Wapp

Check-in [ba52964f32]
Login

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

Overview
Comment:Update the built-in SQLite to the latest 3.47.0 beta.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: ba52964f32850b9064486d223474a6c967988406b2f0520cef4afaa58a80959c
User & Date: drh 2024-10-18 16:07:34.237
Context
2024-11-06
16:24
Show both the SQLite version number and the TCL version number with the -v option to wapptclsh. (check-in: 719ed9a20d user: drh tags: trunk)
2024-10-18
16:07
Update the built-in SQLite to the latest 3.47.0 beta. (check-in: ba52964f32 user: drh tags: trunk)
2024-10-14
11:16
Do not require CRLF endings from clients. (check-in: 2b091c8428 user: drh tags: trunk)
Changes
Unified Diff Ignore Whitespace Patch
Changes to tclsqlite3.c.
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
** the text of this file.  Search for "Begin file sqlite3.h" to find the start
** of the embedded sqlite3.h header file.) Additional code files may be needed
** if you want a wrapper to interface SQLite with your choice of programming
** language. The code for the "sqlite3" command-line shell is also in a
** separate file. This file contains only code for the core SQLite library.
**
** The content in this amalgamation comes from Fossil check-in
** 76b6331e6a705a420a64820a18214f07cf4c.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1
#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
/************** Begin file sqliteInt.h ***************************************/







|







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
** the text of this file.  Search for "Begin file sqlite3.h" to find the start
** of the embedded sqlite3.h header file.) Additional code files may be needed
** if you want a wrapper to interface SQLite with your choice of programming
** language. The code for the "sqlite3" command-line shell is also in a
** separate file. This file contains only code for the core SQLite library.
**
** The content in this amalgamation comes from Fossil check-in
** 5f0cc7f26453faaea20a7bb0a1bcbab381a9.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1
#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
/************** Begin file sqliteInt.h ***************************************/
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.47.0"
#define SQLITE_VERSION_NUMBER 3047000
#define SQLITE_SOURCE_ID      "2024-09-28 19:52:38 76b6331e6a705a420a64820a18214f07cf4c1d5151e7158d6fff09964e63f352"

/*
** CAPI3REF: Run-Time Library Version Numbers
** KEYWORDS: sqlite3_version sqlite3_sourceid
**
** These interfaces provide the same information as the [SQLITE_VERSION],
** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros







|







461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.47.0"
#define SQLITE_VERSION_NUMBER 3047000
#define SQLITE_SOURCE_ID      "2024-10-18 10:51:43 5f0cc7f26453faaea20a7bb0a1bcbab381a9bae7a81e099bb27f4b05fac1cd6c"

/*
** CAPI3REF: Run-Time Library Version Numbers
** KEYWORDS: sqlite3_version sqlite3_sourceid
**
** These interfaces provide the same information as the [SQLITE_VERSION],
** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
** whichever comes first.  ^If nByte is zero, then no prepared
** statement is generated.
** If the caller knows that the supplied string is nul-terminated, then
** there is a small performance advantage to passing an nByte parameter that
** is the number of bytes in the input string <i>including</i>
** the nul-terminator.
** Note that nByte measure the length of the input in bytes, not
** characters, even for the UTF-16 inferfaces.
**
** ^If pzTail is not NULL then *pzTail is made to point to the first byte
** past the end of the first SQL statement in zSql.  These routines only
** compile the first statement in zSql, so *pzTail is left pointing to
** what remains uncompiled.
**
** ^*ppStmt is left pointing to a compiled [prepared statement] that can be







|







4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
** whichever comes first.  ^If nByte is zero, then no prepared
** statement is generated.
** If the caller knows that the supplied string is nul-terminated, then
** there is a small performance advantage to passing an nByte parameter that
** is the number of bytes in the input string <i>including</i>
** the nul-terminator.
** Note that nByte measure the length of the input in bytes, not
** characters, even for the UTF-16 interfaces.
**
** ^If pzTail is not NULL then *pzTail is made to point to the first byte
** past the end of the first SQL statement in zSql.  These routines only
** compile the first statement in zSql, so *pzTail is left pointing to
** what remains uncompiled.
**
** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
**
** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call
** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
** This flag instructs SQLite to omit some corner-case optimizations that
** might disrupt the operation of the [sqlite3_value_subtype()] function,
** causing it to return zero rather than the correct subtype().
** SQL functions that invokes [sqlite3_value_subtype()] should have this
** property.  If the SQLITE_SUBTYPE property is omitted, then the return
** value from [sqlite3_value_subtype()] might sometimes be zero even though
** a non-zero subtype was specified by the function argument expression.
**
** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd>
** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call
** [sqlite3_result_subtype()] to cause a sub-type to be associated with its







|







5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
**
** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call
** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
** This flag instructs SQLite to omit some corner-case optimizations that
** might disrupt the operation of the [sqlite3_value_subtype()] function,
** causing it to return zero rather than the correct subtype().
** All SQL functions that invoke [sqlite3_value_subtype()] should have this
** property.  If the SQLITE_SUBTYPE property is omitted, then the return
** value from [sqlite3_value_subtype()] might sometimes be zero even though
** a non-zero subtype was specified by the function argument expression.
**
** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd>
** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call
** [sqlite3_result_subtype()] to cause a sub-type to be associated with its
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
#define SQLITE_TESTCTRL_RESULT_INTREAL          27
#define SQLITE_TESTCTRL_PRNG_SEED               28
#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
#define SQLITE_TESTCTRL_SEEK_COUNT              30
#define SQLITE_TESTCTRL_TRACEFLAGS              31
#define SQLITE_TESTCTRL_TUNE                    32
#define SQLITE_TESTCTRL_LOGEST                  33
#define SQLITE_TESTCTRL_USELONGDOUBLE           34
#define SQLITE_TESTCTRL_LAST                    34  /* Largest TESTCTRL */

/*
** CAPI3REF: SQL Keyword Checking
**
** These routines provide access to the set of SQL language keywords
** recognized by SQLite.  Applications can uses these routines to determine







|







8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
#define SQLITE_TESTCTRL_RESULT_INTREAL          27
#define SQLITE_TESTCTRL_PRNG_SEED               28
#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
#define SQLITE_TESTCTRL_SEEK_COUNT              30
#define SQLITE_TESTCTRL_TRACEFLAGS              31
#define SQLITE_TESTCTRL_TUNE                    32
#define SQLITE_TESTCTRL_LOGEST                  33
#define SQLITE_TESTCTRL_USELONGDOUBLE           34  /* NOT USED */
#define SQLITE_TESTCTRL_LAST                    34  /* Largest TESTCTRL */

/*
** CAPI3REF: SQL Keyword Checking
**
** These routines provide access to the set of SQL language keywords
** recognized by SQLite.  Applications can uses these routines to determine
9657
9658
9659
9660
9661
9662
9663










9664
9665
9666
9667
9668
9669
9670
**
** The [sqlite3_backup] object itself is partially threadsafe. Multiple
** threads may safely make multiple concurrent calls to sqlite3_backup_step().
** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
** APIs are not strictly speaking threadsafe. If they are invoked at the
** same time as another thread is invoking sqlite3_backup_step() it is
** possible that they return invalid values.










*/
SQLITE_API sqlite3_backup *sqlite3_backup_init(
  sqlite3 *pDest,                        /* Destination database handle */
  const char *zDestName,                 /* Destination database name */
  sqlite3 *pSource,                      /* Source database handle */
  const char *zSourceName                /* Source database name */
);







>
>
>
>
>
>
>
>
>
>







9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
**
** The [sqlite3_backup] object itself is partially threadsafe. Multiple
** threads may safely make multiple concurrent calls to sqlite3_backup_step().
** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
** APIs are not strictly speaking threadsafe. If they are invoked at the
** same time as another thread is invoking sqlite3_backup_step() it is
** possible that they return invalid values.
**
** <b>Alternatives To Using The Backup API</b>
**
** Other techniques for safely creating a consistent backup of an SQLite
** database include:
**
** <ul>
** <li> The [VACUUM INTO] command.
** <li> The [sqlite3_rsync] utility program.
** </ul>
*/
SQLITE_API sqlite3_backup *sqlite3_backup_init(
  sqlite3 *pDest,                        /* Destination database handle */
  const char *zDestName,                 /* Destination database name */
  sqlite3 *pSource,                      /* Source database handle */
  const char *zSourceName                /* Source database name */
);
10855
10856
10857
10858
10859
10860
10861








10862
10863
10864
10865
10866
10867
10868
** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
** new [sqlite3_snapshot] object that records the current state of
** schema S in database connection D.  ^On success, the
** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
** If there is not already a read-transaction open on schema S when
** this function is called, one is opened automatically.








**
** The following must be true for this function to succeed. If any of
** the following statements are false when sqlite3_snapshot_get() is
** called, SQLITE_ERROR is returned. The final value of *P is undefined
** in this case.
**
** <ul>







>
>
>
>
>
>
>
>







10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
** new [sqlite3_snapshot] object that records the current state of
** schema S in database connection D.  ^On success, the
** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
** If there is not already a read-transaction open on schema S when
** this function is called, one is opened automatically.
**
** If a read-transaction is opened by this function, then it is guaranteed
** that the returned snapshot object may not be invalidated by a database
** writer or checkpointer until after the read-transaction is closed. This
** is not guaranteed if a read-transaction is already open when this
** function is called. In that case, any subsequent write or checkpoint
** operation on the database may invalidate the returned snapshot handle,
** even while the read-transaction remains open.
**
** The following must be true for this function to succeed. If any of
** the following statements are false when sqlite3_snapshot_get() is
** called, SQLITE_ERROR is returned. The final value of *P is undefined
** in this case.
**
** <ul>
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538

/*************************************************************************
** CUSTOM TOKENIZERS
**
** Applications may also register custom tokenizer types. A tokenizer
** is registered by providing fts5 with a populated instance of the
** following structure. All structure methods must be defined, setting
**
** any member of the fts5_tokenizer struct to NULL leads to undefined
** behaviour. The structure methods are expected to function as follows:
**
** xCreate:
**   This function is used to allocate and initialize a tokenizer instance.
**   A tokenizer instance is required to actually tokenize text.
**







<







13542
13543
13544
13545
13546
13547
13548

13549
13550
13551
13552
13553
13554
13555

/*************************************************************************
** CUSTOM TOKENIZERS
**
** Applications may also register custom tokenizer types. A tokenizer
** is registered by providing fts5 with a populated instance of the
** following structure. All structure methods must be defined, setting

** any member of the fts5_tokenizer struct to NULL leads to undefined
** behaviour. The structure methods are expected to function as follows:
**
** xCreate:
**   This function is used to allocate and initialize a tokenizer instance.
**   A tokenizer instance is required to actually tokenize text.
**
14812
14813
14814
14815
14816
14817
14818

14819
14820
14821
14822
14823
14824
14825
/************** End of parse.h ***********************************************/
/************** Continuing where we left off in sqliteInt.h ******************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stddef.h>


/*
** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
** This allows better measurements of where memcpy() is used when running
** cachegrind.  But this macro version of memcpy() is very slow so it
** should not be used in production.  This is a performance measurement
** hack only.







>







14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
/************** End of parse.h ***********************************************/
/************** Continuing where we left off in sqliteInt.h ******************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stddef.h>
#include <ctype.h>

/*
** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
** This allows better measurements of where memcpy() is used when running
** cachegrind.  But this macro version of memcpy() is very slow so it
** should not be used in production.  This is a performance measurement
** hack only.
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
** substitute integer for floating-point
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite_int64
# define float sqlite_int64
# define fabs(X) ((X)<0?-(X):(X))
# define sqlite3IsOverflow(X) 0
# define LONGDOUBLE_TYPE sqlite_int64
# ifndef SQLITE_BIG_DBL
#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
# endif
# define SQLITE_OMIT_DATETIME_FUNCS 1
# define SQLITE_OMIT_TRACE 1
# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
# undef SQLITE_HAVE_ISNAN







<







14852
14853
14854
14855
14856
14857
14858

14859
14860
14861
14862
14863
14864
14865
** substitute integer for floating-point
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite_int64
# define float sqlite_int64
# define fabs(X) ((X)<0?-(X):(X))
# define sqlite3IsOverflow(X) 0

# ifndef SQLITE_BIG_DBL
#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
# endif
# define SQLITE_OMIT_DATETIME_FUNCS 1
# define SQLITE_OMIT_TRACE 1
# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
# undef SQLITE_HAVE_ISNAN
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
#ifndef INT8_TYPE
# ifdef HAVE_INT8_T
#  define INT8_TYPE int8_t
# else
#  define INT8_TYPE signed char
# endif
#endif
#ifndef LONGDOUBLE_TYPE
# define LONGDOUBLE_TYPE long double
#endif
typedef sqlite_int64 i64;          /* 8-byte signed integer */
typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
typedef INT16_TYPE i16;            /* 2-byte signed integer */
typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
typedef INT8_TYPE i8;              /* 1-byte signed integer */







<
<
<







15026
15027
15028
15029
15030
15031
15032



15033
15034
15035
15036
15037
15038
15039
#ifndef INT8_TYPE
# ifdef HAVE_INT8_T
#  define INT8_TYPE int8_t
# else
#  define INT8_TYPE signed char
# endif
#endif



typedef sqlite_int64 i64;          /* 8-byte signed integer */
typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
typedef INT16_TYPE i16;            /* 2-byte signed integer */
typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
typedef INT8_TYPE i8;              /* 1-byte signed integer */
16394
16395
16396
16397
16398
16399
16400



16401
16402
16403
16404
16405
16406
16407
  Pgno iTable,                         /* Index of root page */
  int wrFlag,                          /* 1 for writing.  0 for read-only */
  struct KeyInfo*,                     /* First argument to compare function */
  BtCursor *pCursor                    /* Space to write cursor structure */
);
SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);



SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
#ifdef SQLITE_ENABLE_CURSOR_HINTS
SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
#endif

SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);







>
>
>







16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
  Pgno iTable,                         /* Index of root page */
  int wrFlag,                          /* 1 for writing.  0 for read-only */
  struct KeyInfo*,                     /* First argument to compare function */
  BtCursor *pCursor                    /* Space to write cursor structure */
);
SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE int sqlite3BtreeClosesWithCursor(Btree*,BtCursor*);
#endif
SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
#ifdef SQLITE_ENABLE_CURSOR_HINTS
SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
#endif

SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
#define EP_WinFunc   0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
#define EP_Subrtn    0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
#define EP_Quoted    0x4000000 /* TK_ID was originally quoted */
#define EP_Static    0x8000000 /* Held in memory not obtained from malloc() */
#define EP_IsTrue   0x10000000 /* Always has boolean value of TRUE */
#define EP_IsFalse  0x20000000 /* Always has boolean value of FALSE */
#define EP_FromDDL  0x40000000 /* Originates from sqlite_schema */
               /*   0x80000000 // Available */

/* The EP_Propagate mask is a set of properties that automatically propagate
** upwards into parent nodes.
*/
#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)

/* Macros can be used to test, set, or clear bits in the







|







19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
#define EP_WinFunc   0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
#define EP_Subrtn    0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
#define EP_Quoted    0x4000000 /* TK_ID was originally quoted */
#define EP_Static    0x8000000 /* Held in memory not obtained from malloc() */
#define EP_IsTrue   0x10000000 /* Always has boolean value of TRUE */
#define EP_IsFalse  0x20000000 /* Always has boolean value of FALSE */
#define EP_FromDDL  0x40000000 /* Originates from sqlite_schema */
#define EP_SubtArg  0x80000000 /* Is argument to SQLITE_SUBTYPE function */

/* The EP_Propagate mask is a set of properties that automatically propagate
** upwards into parent nodes.
*/
#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)

/* Macros can be used to test, set, or clear bits in the
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
  int bMemstat;                     /* True to enable memory status */
  u8 bCoreMutex;                    /* True to enable core mutexing */
  u8 bFullMutex;                    /* True to enable full mutexing */
  u8 bOpenUri;                      /* True to interpret filenames as URIs */
  u8 bUseCis;                       /* Use covering indices for full-scans */
  u8 bSmallMalloc;                  /* Avoid large memory allocations if true */
  u8 bExtraSchemaChecks;            /* Verify type,name,tbl_name in schema */
  u8 bUseLongDouble;                /* Make use of long double */
#ifdef SQLITE_DEBUG
  u8 bJsonSelfcheck;                /* Double-check JSON parsing */
#endif
  int mxStrlen;                     /* Maximum string length */
  int neverCorrupt;                 /* Database is always well-formed */
  int szLookaside;                  /* Default lookaside buffer size */
  int nLookaside;                   /* Default lookaside buffer count */







<







20396
20397
20398
20399
20400
20401
20402

20403
20404
20405
20406
20407
20408
20409
  int bMemstat;                     /* True to enable memory status */
  u8 bCoreMutex;                    /* True to enable core mutexing */
  u8 bFullMutex;                    /* True to enable full mutexing */
  u8 bOpenUri;                      /* True to interpret filenames as URIs */
  u8 bUseCis;                       /* Use covering indices for full-scans */
  u8 bSmallMalloc;                  /* Avoid large memory allocations if true */
  u8 bExtraSchemaChecks;            /* Verify type,name,tbl_name in schema */

#ifdef SQLITE_DEBUG
  u8 bJsonSelfcheck;                /* Double-check JSON parsing */
#endif
  int mxStrlen;                     /* Maximum string length */
  int neverCorrupt;                 /* Database is always well-formed */
  int szLookaside;                  /* Default lookaside buffer size */
  int nLookaside;                   /* Default lookaside buffer count */
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
*/
#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
# define SQLITE_ENABLE_FTS3 1
#endif

/*
** The ctype.h header is needed for non-ASCII systems.  It is also
** needed by FTS3 when FTS3 is included in the amalgamation.
*/
#if !defined(SQLITE_ASCII) || \
    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
# include <ctype.h>
#endif

/*
** The following macros mimic the standard library functions toupper(),
** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
** sqlite versions only work for ASCII characters, regardless of locale.
*/
#ifdef SQLITE_ASCII
# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))







<
<
<
<
<
<
<
<
<







20770
20771
20772
20773
20774
20775
20776









20777
20778
20779
20780
20781
20782
20783
** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
*/
#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
# define SQLITE_ENABLE_FTS3 1
#endif










/*
** The following macros mimic the standard library functions toupper(),
** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
** sqlite versions only work for ASCII characters, regardless of locale.
*/
#ifdef SQLITE_ASCII
# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   1,                         /* bCoreMutex */
   SQLITE_THREADSAFE==1,      /* bFullMutex */
   SQLITE_USE_URI,            /* bOpenUri */
   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
   0,                         /* bSmallMalloc */
   1,                         /* bExtraSchemaChecks */
   sizeof(LONGDOUBLE_TYPE)>8, /* bUseLongDouble */
#ifdef SQLITE_DEBUG
   0,                         /* bJsonSelfcheck */
#endif
   0x7ffffffe,                /* mxStrlen */
   0,                         /* neverCorrupt */
   SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */







<







23127
23128
23129
23130
23131
23132
23133

23134
23135
23136
23137
23138
23139
23140
   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   1,                         /* bCoreMutex */
   SQLITE_THREADSAFE==1,      /* bFullMutex */
   SQLITE_USE_URI,            /* bOpenUri */
   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
   0,                         /* bSmallMalloc */
   1,                         /* bExtraSchemaChecks */

#ifdef SQLITE_DEBUG
   0,                         /* bJsonSelfcheck */
#endif
   0x7ffffffe,                /* mxStrlen */
   0,                         /* neverCorrupt */
   SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
**     for unicode values 0x80 and greater.  It does not change over-length
**     encodings to 0xfffd as some systems recommend.
*/
#define READ_UTF8(zIn, zTerm, c)                           \
  c = *(zIn++);                                            \
  if( c>=0xc0 ){                                           \
    c = sqlite3Utf8Trans1[c-0xc0];                         \
    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
      c = (c<<6) + (0x3f & *(zIn++));                      \
    }                                                      \
    if( c<0x80                                             \
        || (c&0xFFFFF800)==0xD800                          \
        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
  }
SQLITE_PRIVATE u32 sqlite3Utf8Read(







|







34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
**     for unicode values 0x80 and greater.  It does not change over-length
**     encodings to 0xfffd as some systems recommend.
*/
#define READ_UTF8(zIn, zTerm, c)                           \
  c = *(zIn++);                                            \
  if( c>=0xc0 ){                                           \
    c = sqlite3Utf8Trans1[c-0xc0];                         \
    while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){             \
      c = (c<<6) + (0x3f & *(zIn++));                      \
    }                                                      \
    if( c<0x80                                             \
        || (c&0xFFFFF800)==0xD800                          \
        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
  }
SQLITE_PRIVATE u32 sqlite3Utf8Read(
35678
35679
35680
35681
35682
35683
35684


35685
35686
35687
35688
35689
35690
35691
  u64 s = 0;       /* significand */
  int d = 0;       /* adjust exponent for shifting decimal point */
  int esign = 1;   /* sign of exponent */
  int e = 0;       /* exponent */
  int eValid = 1;  /* True exponent is either not used or is well-formed */
  int nDigit = 0;  /* Number of digits processed */
  int eType = 1;   /* 1: pure integer,  2+: fractional  -1 or less: bad UTF16 */



  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  *pResult = 0.0;   /* Default return value, in case of an error */
  if( length==0 ) return 0;

  if( enc==SQLITE_UTF8 ){
    incr = 1;







>
>







35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
  u64 s = 0;       /* significand */
  int d = 0;       /* adjust exponent for shifting decimal point */
  int esign = 1;   /* sign of exponent */
  int e = 0;       /* exponent */
  int eValid = 1;  /* True exponent is either not used or is well-formed */
  int nDigit = 0;  /* Number of digits processed */
  int eType = 1;   /* 1: pure integer,  2+: fractional  -1 or less: bad UTF16 */
  double rr[2];
  u64 s2;

  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  *pResult = 0.0;   /* Default return value, in case of an error */
  if( length==0 ) return 0;

  if( enc==SQLITE_UTF8 ){
    incr = 1;
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
    e--;
  }
  while( e<0 && (s%10)==0 ){
    s /= 10;
    e++;
  }

  if( e==0 ){
    *pResult = s;
  }else if( sqlite3Config.bUseLongDouble ){
    LONGDOUBLE_TYPE r = (LONGDOUBLE_TYPE)s;
    if( e>0 ){
      while( e>=100  ){ e-=100; r *= 1.0e+100L; }
      while( e>=10   ){ e-=10;  r *= 1.0e+10L;  }
      while( e>=1    ){ e-=1;   r *= 1.0e+01L;  }
    }else{
      while( e<=-100 ){ e+=100; r *= 1.0e-100L; }
      while( e<=-10  ){ e+=10;  r *= 1.0e-10L;  }
      while( e<=-1   ){ e+=1;   r *= 1.0e-01L;  }
    }
    assert( r>=0.0 );
    if( r>+1.7976931348623157081452742373e+308L ){
#ifdef INFINITY
      *pResult = +INFINITY;
#else
      *pResult = 1.0e308*10.0;
#endif
    }else{
      *pResult = (double)r;
    }
  }else{
    double rr[2];
    u64 s2;
    rr[0] = (double)s;
    s2 = (u64)rr[0];
#if defined(_MSC_VER) && _MSC_VER<1700
    if( s2==0x8000000000000000LL ){ s2 = 2*(u64)(0.5*rr[0]); }
#endif
    rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s);
    if( e>0 ){
      while( e>=100  ){
        e -= 100;
        dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
      }
      while( e>=10   ){
        e -= 10;
        dekkerMul2(rr, 1.0e+10, 0.0);
      }
      while( e>=1    ){
        e -= 1;
        dekkerMul2(rr, 1.0e+01, 0.0);
      }
    }else{
      while( e<=-100 ){
        e += 100;
        dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
      }
      while( e<=-10  ){
        e += 10;
        dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
      }
      while( e<=-1   ){
        e += 1;
        dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
      }
    }
    *pResult = rr[0]+rr[1];
    if( sqlite3IsNaN(*pResult) ) *pResult = 1e300*1e300;
  }
  if( sign<0 ) *pResult = -*pResult;
  assert( !sqlite3IsNaN(*pResult) );

atof_return:
  /* return true if number and no extra non-whitespace characters after */
  if( z==zEnd && nDigit>0 && eValid && eType>0 ){
    return eType;







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|

|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<







35797
35798
35799
35800
35801
35802
35803


























35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838

35839
35840
35841
35842
35843
35844
35845
    e--;
  }
  while( e<0 && (s%10)==0 ){
    s /= 10;
    e++;
  }



























  rr[0] = (double)s;
  s2 = (u64)rr[0];
#if defined(_MSC_VER) && _MSC_VER<1700
  if( s2==0x8000000000000000LL ){ s2 = 2*(u64)(0.5*rr[0]); }
#endif
  rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s);
  if( e>0 ){
    while( e>=100  ){
      e -= 100;
      dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
    }
    while( e>=10   ){
      e -= 10;
      dekkerMul2(rr, 1.0e+10, 0.0);
    }
    while( e>=1    ){
      e -= 1;
      dekkerMul2(rr, 1.0e+01, 0.0);
    }
  }else{
    while( e<=-100 ){
      e += 100;
      dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
    }
    while( e<=-10  ){
      e += 10;
      dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
    }
    while( e<=-1   ){
      e += 1;
      dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
    }
  }
  *pResult = rr[0]+rr[1];
  if( sqlite3IsNaN(*pResult) ) *pResult = 1e300*1e300;

  if( sign<0 ) *pResult = -*pResult;
  assert( !sqlite3IsNaN(*pResult) );

atof_return:
  /* return true if number and no extra non-whitespace characters after */
  if( z==zEnd && nDigit>0 && eValid && eType>0 ){
    return eType;
36171
36172
36173
36174
36175
36176
36177


36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
** into the middle of p->zBuf[].  There are p->n significant digits.
** The p->z[] array is *not* zero-terminated.
*/
SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){
  int i;
  u64 v;
  int e, exp = 0;


  p->isSpecial = 0;
  p->z = p->zBuf;

  assert( mxRound>0 );

  /* Convert negative numbers to positive.  Deal with Infinity, 0.0, and
  ** NaN. */
  if( r<0.0 ){
    p->sign = '-';
    r = -r;







>
>


<







36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162

36163
36164
36165
36166
36167
36168
36169
** into the middle of p->zBuf[].  There are p->n significant digits.
** The p->z[] array is *not* zero-terminated.
*/
SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){
  int i;
  u64 v;
  int e, exp = 0;
  double rr[2];

  p->isSpecial = 0;
  p->z = p->zBuf;

  assert( mxRound>0 );

  /* Convert negative numbers to positive.  Deal with Infinity, 0.0, and
  ** NaN. */
  if( r<0.0 ){
    p->sign = '-';
    r = -r;
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
    p->n = 0;
    p->iDP = 0;
    return;
  }

  /* Multiply r by powers of ten until it lands somewhere in between
  ** 1.0e+19 and 1.0e+17.
  */
  if( sqlite3Config.bUseLongDouble ){
    LONGDOUBLE_TYPE rr = r;
    if( rr>=1.0e+19 ){
      while( rr>=1.0e+119L ){ exp+=100; rr *= 1.0e-100L; }
      while( rr>=1.0e+29L  ){ exp+=10;  rr *= 1.0e-10L;  }
      while( rr>=1.0e+19L  ){ exp++;    rr *= 1.0e-1L;   }
    }else{
      while( rr<1.0e-97L   ){ exp-=100; rr *= 1.0e+100L; }
      while( rr<1.0e+07L   ){ exp-=10;  rr *= 1.0e+10L;  }
      while( rr<1.0e+17L   ){ exp--;    rr *= 1.0e+1L;   }
    }
    v = (u64)rr;
  }else{
    /* If high-precision floating point is not available using "long double",
    ** then use Dekker-style double-double computation to increase the
    ** precision.
    **
    ** The error terms on constants like 1.0e+100 computed using the
    ** decimal extension, for example as follows:
    **
    **   SELECT decimal_exp(decimal_sub('1.0e+100',decimal(1.0e+100)));
    */
    double rr[2];
    rr[0] = r;
    rr[1] = 0.0;
    if( rr[0]>9.223372036854774784e+18 ){
      while( rr[0]>9.223372036854774784e+118 ){
        exp += 100;
        dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
      }
      while( rr[0]>9.223372036854774784e+28 ){
        exp += 10;
        dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
      }
      while( rr[0]>9.223372036854774784e+18 ){
        exp += 1;
        dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
      }
    }else{
      while( rr[0]<9.223372036854774784e-83  ){
        exp -= 100;
        dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
      }
      while( rr[0]<9.223372036854774784e+07  ){
        exp -= 10;
        dekkerMul2(rr, 1.0e+10, 0.0);
      }
      while( rr[0]<9.22337203685477478e+17  ){
        exp -= 1;
        dekkerMul2(rr, 1.0e+01, 0.0);
      }
    }
    v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1];
  }


  /* Extract significant digits. */
  i = sizeof(p->zBuf)-1;
  assert( v>0 );
  while( v ){  p->zBuf[i--] = (v%10) + '0'; v /= 10; }
  assert( i>=0 && i<sizeof(p->zBuf)-1 );
  p->n = sizeof(p->zBuf) - 1 - i;







|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<







36183
36184
36185
36186
36187
36188
36189
36190














36191
36192
36193
36194
36195
36196
36197
36198

36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228


36229
36230
36231
36232
36233
36234
36235
    p->n = 0;
    p->iDP = 0;
    return;
  }

  /* Multiply r by powers of ten until it lands somewhere in between
  ** 1.0e+19 and 1.0e+17.
  **














  ** Use Dekker-style double-double computation to increase the
  ** precision.
  **
  ** The error terms on constants like 1.0e+100 computed using the
  ** decimal extension, for example as follows:
  **
  **   SELECT decimal_exp(decimal_sub('1.0e+100',decimal(1.0e+100)));
  */

  rr[0] = r;
  rr[1] = 0.0;
  if( rr[0]>9.223372036854774784e+18 ){
    while( rr[0]>9.223372036854774784e+118 ){
      exp += 100;
      dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
    }
    while( rr[0]>9.223372036854774784e+28 ){
      exp += 10;
      dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
    }
    while( rr[0]>9.223372036854774784e+18 ){
      exp += 1;
      dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
    }
  }else{
    while( rr[0]<9.223372036854774784e-83  ){
      exp -= 100;
      dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
    }
    while( rr[0]<9.223372036854774784e+07  ){
      exp -= 10;
      dekkerMul2(rr, 1.0e+10, 0.0);
    }
    while( rr[0]<9.22337203685477478e+17  ){
      exp -= 1;
      dekkerMul2(rr, 1.0e+01, 0.0);
    }
  }
  v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1];



  /* Extract significant digits. */
  i = sizeof(p->zBuf)-1;
  assert( v>0 );
  while( v ){  p->zBuf[i--] = (v%10) + '0'; v /= 10; }
  assert( i>=0 && i<sizeof(p->zBuf)-1 );
  p->n = sizeof(p->zBuf) - 1 - i;
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066



41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077


41078


41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
*/
static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  int rc = SQLITE_OK;
  int reserved = 0;
  unixFile *pFile = (unixFile*)id;




  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );

  assert( pFile );

  /* Check if a thread in this process holds such a lock */
  if( pFile->eFileLock>SHARED_LOCK ){
    reserved = 1;
  }

  /* Otherwise see if some other process holds it. */


  if( !reserved ){


    /* attempt to get the lock */
    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
    if( !lrc ){
      /* got the lock, unlock it */
      lrc = robust_flock(pFile->h, LOCK_UN);
      if ( lrc ) {
        int tErrno = errno;
        /* unlock failed with an error */
        lrc = SQLITE_IOERR_UNLOCK;
        storeLastErrno(pFile, tErrno);
        rc = lrc;
      }
    } else {
      int tErrno = errno;
      reserved = 1;
      /* someone else might have it reserved */
      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
      if( IS_LOCK_ERROR(lrc) ){
        storeLastErrno(pFile, tErrno);
        rc = lrc;
      }
    }
  }
  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));

#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  if( (rc & 0xff) == SQLITE_IOERR ){
    rc = SQLITE_OK;
    reserved=1;
  }
#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  *pResOut = reserved;
  return rc;
}

/*
** Lock the file with the lock specified by parameter eFileLock - one
** of the following:
**
**     (1) SHARED_LOCK







|
<

>
>
>




<
<
|
<
|
|
<
>
>
|
>
>
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
|
<
|
<
<
|







41022
41023
41024
41025
41026
41027
41028
41029

41030
41031
41032
41033
41034
41035
41036
41037


41038

41039
41040

41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051


















41052


41053

41054


41055
41056
41057
41058
41059
41060
41061
41062
/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, set *pResOut
** to a non-zero value otherwise *pResOut is set to zero.  The return value
** is set to SQLITE_OK unless an I/O error occurs during lock checking.
*/
static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
#ifdef SQLITE_DEBUG

  unixFile *pFile = (unixFile*)id;
#else
  UNUSED_PARAMETER(id);
#endif

  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );

  assert( pFile );


  assert( pFile->eFileLock<=SHARED_LOCK );


  /* The flock VFS only ever takes exclusive locks (see function flockLock).

  ** Therefore, if this connection is holding any lock at all, no other
  ** connection may be holding a RESERVED lock. So set *pResOut to 0
  ** in this case.
  **
  ** Or, this connection may be holding no lock. In that case, set *pResOut to
  ** 0 as well. The caller will then attempt to take an EXCLUSIVE lock on the
  ** db in order to roll the hot journal back. If there is another connection
  ** holding a lock, that attempt will fail and an SQLITE_BUSY returned to
  ** the user. With other VFS, we try to avoid this, in order to allow a reader
  ** to proceed while a writer is preparing its transaction. But that won't
  ** work with the flock VFS - as it always takes EXCLUSIVE locks - so it is


















  ** not a problem in this case.  */


  *pResOut = 0;




  return SQLITE_OK;
}

/*
** Lock the file with the lock specified by parameter eFileLock - one
** of the following:
**
**     (1) SHARED_LOCK
65687
65688
65689
65690
65691
65692
65693

65694
65695
65696
65697
65698
65699
65700
#endif
#ifdef SQLITE_DEBUG
  int nSehTry;               /* Number of nested SEH_TRY{} blocks */
  u8 lockError;              /* True if a locking error has occurred */
#endif
#ifdef SQLITE_ENABLE_SNAPSHOT
  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */

#endif
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  sqlite3 *db;
#endif
};

/*







>







65631
65632
65633
65634
65635
65636
65637
65638
65639
65640
65641
65642
65643
65644
65645
#endif
#ifdef SQLITE_DEBUG
  int nSehTry;               /* Number of nested SEH_TRY{} blocks */
  u8 lockError;              /* True if a locking error has occurred */
#endif
#ifdef SQLITE_ENABLE_SNAPSHOT
  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
  int bGetSnapshot;          /* Transaction opened for sqlite3_get_snapshot() */
#endif
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  sqlite3 *db;
#endif
};

/*
68243
68244
68245
68246
68247
68248
68249
68250
68251
68252
68253
68254
68255
68256
68257

  assert( pWal->nWiData>0 );
  assert( pWal->apWiData[0]!=0 );
  pInfo = walCkptInfo(pWal);
  SEH_INJECT_FAULT;
  if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
#ifdef SQLITE_ENABLE_SNAPSHOT
   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
#endif
  ){
    /* The WAL has been completely backfilled (or it is empty).
    ** and can be safely ignored.
    */
    rc = walLockShared(pWal, WAL_READ_LOCK(0));
    walShmBarrier(pWal);







|







68188
68189
68190
68191
68192
68193
68194
68195
68196
68197
68198
68199
68200
68201
68202

  assert( pWal->nWiData>0 );
  assert( pWal->apWiData[0]!=0 );
  pInfo = walCkptInfo(pWal);
  SEH_INJECT_FAULT;
  if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
#ifdef SQLITE_ENABLE_SNAPSHOT
   && ((pWal->bGetSnapshot==0 && pWal->pSnapshot==0) || pWal->hdr.mxFrame==0)
#endif
  ){
    /* The WAL has been completely backfilled (or it is empty).
    ** and can be safely ignored.
    */
    rc = walLockShared(pWal, WAL_READ_LOCK(0));
    walShmBarrier(pWal);
69643
69644
69645
69646
69647
69648
69649











69650


69651
69652
69653
69654
69655
69656
69657

/* Try to open on pSnapshot when the next read-transaction starts
*/
SQLITE_PRIVATE void sqlite3WalSnapshotOpen(
  Wal *pWal,
  sqlite3_snapshot *pSnapshot
){











  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;


}

/*
** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
*/
SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){







>
>
>
>
>
>
>
>
>
>
>
|
>
>







69588
69589
69590
69591
69592
69593
69594
69595
69596
69597
69598
69599
69600
69601
69602
69603
69604
69605
69606
69607
69608
69609
69610
69611
69612
69613
69614
69615

/* Try to open on pSnapshot when the next read-transaction starts
*/
SQLITE_PRIVATE void sqlite3WalSnapshotOpen(
  Wal *pWal,
  sqlite3_snapshot *pSnapshot
){
  if( pSnapshot && ((WalIndexHdr*)pSnapshot)->iVersion==0 ){
    /* iVersion==0 means that this is a call to sqlite3_snapshot_get().  In
    ** this case set the bGetSnapshot flag so that if the call to
    ** sqlite3_snapshot_get() is about to read transaction on this wal
    ** file, it does not take read-lock 0 if the wal file has been completely
    ** checkpointed. Taking read-lock 0 would work, but then it would be
    ** possible for a subsequent writer to destroy the snapshot even while
    ** this connection is holding its read-transaction open. This is contrary
    ** to user expectations, so we avoid it by not taking read-lock 0. */
    pWal->bGetSnapshot = 1;
  }else{
    pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
    pWal->bGetSnapshot = 0;
  }
}

/*
** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
*/
SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
75523
75524
75525
75526
75527
75528
75529



















75530
75531
75532
75533
75534
75535
75536
** sufficient storage to hold a cursor.  The BtCursor object is opaque
** to users so they cannot do the sizeof() themselves - they must call
** this routine.
*/
SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  return ROUND8(sizeof(BtCursor));
}




















/*
** Initialize memory that will be converted into a BtCursor object.
**
** The simple approach here would be to memset() the entire object
** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
** do not need to be zeroed and they are large, so we can save a lot







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







75481
75482
75483
75484
75485
75486
75487
75488
75489
75490
75491
75492
75493
75494
75495
75496
75497
75498
75499
75500
75501
75502
75503
75504
75505
75506
75507
75508
75509
75510
75511
75512
75513
** sufficient storage to hold a cursor.  The BtCursor object is opaque
** to users so they cannot do the sizeof() themselves - they must call
** this routine.
*/
SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  return ROUND8(sizeof(BtCursor));
}

#ifdef SQLITE_DEBUG
/*
** Return true if and only if the Btree object will be automatically
** closed with the BtCursor closes.  This is used within assert() statements
** only.
*/
SQLITE_PRIVATE int sqlite3BtreeClosesWithCursor(
  Btree *pBtree,       /* the btree object */
  BtCursor *pCur       /* Corresponding cursor */
){
  BtShared *pBt = pBtree->pBt;
  if( (pBt->openFlags & BTREE_SINGLE)==0 ) return 0;
  if( pBt->pCursor!=pCur ) return 0;
  if( pCur->pNext!=0 ) return 0;
  if( pCur->pBtree!=pBtree ) return 0;
  return 1;
}
#endif

/*
** Initialize memory that will be converted into a BtCursor object.
**
** The simple approach here would be to memset() the entire object
** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
** do not need to be zeroed and they are large, so we can save a lot
89591
89592
89593
89594
89595
89596
89597
89598
89599
89600
89601
89602
89603
89604
89605
89606
89607
89608
89609
89610
89611
89612
89613
89614
89615
89616
89617
89618
89619
89620
89621
89622
89623
89624
89625
89626
}

/* The following two functions are used only within testcase() to prove
** test coverage.  These functions do no exist for production builds.
** We must use separate SQLITE_NOINLINE functions here, since otherwise
** optimizer code movement causes gcov to become very confused.
*/
#if  defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
static int SQLITE_NOINLINE doubleLt(double a, double b){ return a<b; }
static int SQLITE_NOINLINE doubleEq(double a, double b){ return a==b; }
#endif

/*
** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
** number.  Return negative, zero, or positive if the first (i64) is less than,
** equal to, or greater than the second (double).
*/
SQLITE_PRIVATE int sqlite3IntFloatCompare(i64 i, double r){
  if( sqlite3IsNaN(r) ){
    /* SQLite considers NaN to be a NULL. And all integer values are greater
    ** than NULL */
    return 1;
  }
  if( sqlite3Config.bUseLongDouble ){
    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
    testcase( x<r );
    testcase( x>r );
    testcase( x==r );
    return (x<r) ? -1 : (x>r);
  }else{
    i64 y;
    if( r<-9223372036854775808.0 ) return +1;
    if( r>=9223372036854775808.0 ) return -1;
    y = (i64)r;
    if( i<y ) return -1;
    if( i>y ) return +1;







|














<
<
<
<
<
<
<







89568
89569
89570
89571
89572
89573
89574
89575
89576
89577
89578
89579
89580
89581
89582
89583
89584
89585
89586
89587
89588
89589







89590
89591
89592
89593
89594
89595
89596
}

/* The following two functions are used only within testcase() to prove
** test coverage.  These functions do no exist for production builds.
** We must use separate SQLITE_NOINLINE functions here, since otherwise
** optimizer code movement causes gcov to become very confused.
*/
#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
static int SQLITE_NOINLINE doubleLt(double a, double b){ return a<b; }
static int SQLITE_NOINLINE doubleEq(double a, double b){ return a==b; }
#endif

/*
** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
** number.  Return negative, zero, or positive if the first (i64) is less than,
** equal to, or greater than the second (double).
*/
SQLITE_PRIVATE int sqlite3IntFloatCompare(i64 i, double r){
  if( sqlite3IsNaN(r) ){
    /* SQLite considers NaN to be a NULL. And all integer values are greater
    ** than NULL */
    return 1;







  }else{
    i64 y;
    if( r<-9223372036854775808.0 ) return +1;
    if( r>=9223372036854775808.0 ) return -1;
    y = (i64)r;
    if( i<y ) return -1;
    if( i>y ) return +1;
97943
97944
97945
97946
97947
97948
97949

97950


97951
97952
97953
97954
97955
97956
97957
          rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
              0, pCx->uc.pCursor);
          pCx->isTable = 1;
        }
      }
      pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
      if( rc ){

        sqlite3BtreeClose(pCx->ub.pBtx);


      }
    }
  }
  if( rc ) goto abort_due_to_error;
  pCx->nullRow = 1;
  break;
}







>

>
>







97913
97914
97915
97916
97917
97918
97919
97920
97921
97922
97923
97924
97925
97926
97927
97928
97929
97930
          rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
              0, pCx->uc.pCursor);
          pCx->isTable = 1;
        }
      }
      pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
      if( rc ){
        assert( !sqlite3BtreeClosesWithCursor(pCx->ub.pBtx, pCx->uc.pCursor) );
        sqlite3BtreeClose(pCx->ub.pBtx);
      }else{
        assert( sqlite3BtreeClosesWithCursor(pCx->ub.pBtx, pCx->uc.pCursor) );
      }
    }
  }
  if( rc ) goto abort_due_to_error;
  pCx->nullRow = 1;
  break;
}
108254
108255
108256
108257
108258
108259
108260


















108261
108262
108263
108264
108265
108266
108267
              pNC->nNcErr++;
            }
            pExpr->op = TK_NULL;
            return WRC_Prune;
          }
        }
#endif


















        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
          /* For the purposes of the EP_ConstFunc flag, date and time
          ** functions and other functions that change slowly are considered
          ** constant because they are constant for the duration of one query.
          ** This allows them to be factored out of inner loops. */
          ExprSetProperty(pExpr,EP_ConstFunc);
        }







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







108227
108228
108229
108230
108231
108232
108233
108234
108235
108236
108237
108238
108239
108240
108241
108242
108243
108244
108245
108246
108247
108248
108249
108250
108251
108252
108253
108254
108255
108256
108257
108258
              pNC->nNcErr++;
            }
            pExpr->op = TK_NULL;
            return WRC_Prune;
          }
        }
#endif

        /* If the function may call sqlite3_value_subtype(), then set the
        ** EP_SubtArg flag on all of its argument expressions. This prevents
        ** where.c from replacing the expression with a value read from an
        ** index on the same expression, which will not have the correct
        ** subtype. Also set the flag if the function expression itself is
        ** an EP_SubtArg expression. In this case subtypes are required as
        ** the function may return a value with a subtype back to its
        ** caller using sqlite3_result_value().  */
        if( (pDef->funcFlags & SQLITE_SUBTYPE)
         || ExprHasProperty(pExpr, EP_SubtArg)
        ){
          int ii;
          for(ii=0; ii<n; ii++){
            ExprSetProperty(pList->a[ii].pExpr, EP_SubtArg);
          }
        }

        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
          /* For the purposes of the EP_ConstFunc flag, date and time
          ** functions and other functions that change slowly are considered
          ** constant because they are constant for the duration of one query.
          ** This allows them to be factored out of inner loops. */
          ExprSetProperty(pExpr,EP_ConstFunc);
        }
113927
113928
113929
113930
113931
113932
113933





















































113934
113935
113936
113937
113938
113939
113940
              (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
      break;
    }
#endif /* !defined(SQLITE_UNTESTABLE) */
  }
  return target;
}






















































/*
** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
** If it is, then resolve the expression by reading from the index and
** return the register into which the value has been read.  If pExpr is
** not an indexed expression, then return negative.
*/







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







113918
113919
113920
113921
113922
113923
113924
113925
113926
113927
113928
113929
113930
113931
113932
113933
113934
113935
113936
113937
113938
113939
113940
113941
113942
113943
113944
113945
113946
113947
113948
113949
113950
113951
113952
113953
113954
113955
113956
113957
113958
113959
113960
113961
113962
113963
113964
113965
113966
113967
113968
113969
113970
113971
113972
113973
113974
113975
113976
113977
113978
113979
113980
113981
113982
113983
113984
              (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
      break;
    }
#endif /* !defined(SQLITE_UNTESTABLE) */
  }
  return target;
}

/*
** Expression Node callback for sqlite3ExprCanReturnSubtype().
**
** Only a function call is able to return a subtype.  So if the node
** is not a function call, return WRC_Prune immediately.
**
** A function call is able to return a subtype if it has the
** SQLITE_RESULT_SUBTYPE property.
**
** Assume that every function is able to pass-through a subtype from
** one of its argument (using sqlite3_result_value()).  Most functions
** are not this way, but we don't have a mechanism to distinguish those
** that are from those that are not, so assume they all work this way.
** That means that if one of its arguments is another function and that
** other function is able to return a subtype, then this function is
** able to return a subtype.
*/
static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){
  int n;
  FuncDef *pDef;
  sqlite3 *db;
  if( pExpr->op!=TK_FUNCTION ){
    return WRC_Prune;
  }
  assert( ExprUseXList(pExpr) );
  db = pWalker->pParse->db;
  n = ALWAYS(pExpr->x.pList) ? pExpr->x.pList->nExpr : 0;
  pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
    pWalker->eCode = 1;
    return WRC_Prune;
  }
  return WRC_Continue;
}

/*
** Return TRUE if expression pExpr is able to return a subtype.
**
** A TRUE return does not guarantee that a subtype will be returned.
** It only indicates that a subtype return is possible.  False positives
** are acceptable as they only disable an optimization.  False negatives,
** on the other hand, can lead to incorrect answers.
*/
static int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){
  Walker w;
  memset(&w, 0, sizeof(w));
  w.pParse = pParse;
  w.xExprCallback = exprNodeCanReturnSubtype;
  sqlite3WalkExpr(&w, pExpr);
  return w.eCode;
}


/*
** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
** If it is, then resolve the expression by reading from the index and
** return the register into which the value has been read.  If pExpr is
** not an indexed expression, then return negative.
*/
113960
113961
113962
113963
113964
113965
113966











113967
113968
113969
113970
113971
113972
113973
     || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
     || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
    ){
      /* Affinity mismatch on a generated column */
      continue;
    }












    v = pParse->pVdbe;
    assert( v!=0 );
    if( p->bMaybeNullRow ){
      /* If the index is on a NULL row due to an outer join, then we
      ** cannot extract the value from the index.  The value must be
      ** computed using the original expression. */
      int addr = sqlite3VdbeCurrentAddr(v);







>
>
>
>
>
>
>
>
>
>
>







114004
114005
114006
114007
114008
114009
114010
114011
114012
114013
114014
114015
114016
114017
114018
114019
114020
114021
114022
114023
114024
114025
114026
114027
114028
     || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
     || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
    ){
      /* Affinity mismatch on a generated column */
      continue;
    }


    /* Functions that might set a subtype should not be replaced by the
    ** value taken from an expression index if they are themselves an
    ** argument to another scalar function or aggregate.
    ** https://sqlite.org/forum/forumpost/68d284c86b082c3e */
    if( ExprHasProperty(pExpr, EP_SubtArg)
     && sqlite3ExprCanReturnSubtype(pParse, pExpr)
    ){
      continue;
    }

    v = pParse->pVdbe;
    assert( v!=0 );
    if( p->bMaybeNullRow ){
      /* If the index is on a NULL row due to an outer join, then we
      ** cannot extract the value from the index.  The value must be
      ** computed using the original expression. */
      int addr = sqlite3VdbeCurrentAddr(v);
120758
120759
120760
120761
120762
120763
120764
120765
120766
120767
120768
120769
120770
120771
120772
120773

  while( sqlite3_step(pStmt)==SQLITE_ROW ){
    int nIdxCol = 1;              /* Number of columns in stat4 records */

    char *zIndex;    /* Index name */
    Index *pIdx;     /* Pointer to the index object */
    int nSample;     /* Number of samples */
    int nByte;       /* Bytes of space required */
    int i;           /* Bytes of space required */
    tRowcnt *pSpace; /* Available allocated memory space */
    u8 *pPtr;        /* Available memory as a u8 for easier manipulation */

    zIndex = (char *)sqlite3_column_text(pStmt, 0);
    if( zIndex==0 ) continue;
    nSample = sqlite3_column_int(pStmt, 1);
    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);







|
|







120813
120814
120815
120816
120817
120818
120819
120820
120821
120822
120823
120824
120825
120826
120827
120828

  while( sqlite3_step(pStmt)==SQLITE_ROW ){
    int nIdxCol = 1;              /* Number of columns in stat4 records */

    char *zIndex;    /* Index name */
    Index *pIdx;     /* Pointer to the index object */
    int nSample;     /* Number of samples */
    i64 nByte;       /* Bytes of space required */
    i64 i;           /* Bytes of space required */
    tRowcnt *pSpace; /* Available allocated memory space */
    u8 *pPtr;        /* Available memory as a u8 for easier manipulation */

    zIndex = (char *)sqlite3_column_text(pStmt, 0);
    if( zIndex==0 ) continue;
    nSample = sqlite3_column_int(pStmt, 1);
    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
131786
131787
131788
131789
131790
131791
131792
131793






131794
131795
131796
131797
131798
131799
131800
}

#ifdef SQLITE_DEBUG
/*
** Implementation of fpdecode(x,y,z) function.
**
** x is a real number that is to be decoded.  y is the precision.
** z is the maximum real precision.






*/
static void fpdecodeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FpDecode s;







|
>
>
>
>
>
>







131841
131842
131843
131844
131845
131846
131847
131848
131849
131850
131851
131852
131853
131854
131855
131856
131857
131858
131859
131860
131861
}

#ifdef SQLITE_DEBUG
/*
** Implementation of fpdecode(x,y,z) function.
**
** x is a real number that is to be decoded.  y is the precision.
** z is the maximum real precision.  Return a string that shows the
** results of the sqlite3FpDecode() function.
**
** Used for testing and debugging only, specifically testing and debugging
** of the sqlite3FpDecode() function.  This SQL function does not appear
** in production builds.  This function is not an API and is subject to
** modification or removal in future versions of SQLite.
*/
static void fpdecodeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  FpDecode s;
131810
131811
131812
131813
131814
131815
131816












































































131817
131818
131819
131820
131821
131822
131823
  sqlite3FpDecode(&s, x, y, z);
  if( s.isSpecial==2 ){
    sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN");
  }else{
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP);
  }
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);












































































}
#endif /* SQLITE_DEBUG */

/*
** All of the FuncDef structures in the aBuiltinFunc[] array above
** to the global function hash table.  This occurs at start-time (as
** a consequence of calling sqlite3_initialize()).







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







131871
131872
131873
131874
131875
131876
131877
131878
131879
131880
131881
131882
131883
131884
131885
131886
131887
131888
131889
131890
131891
131892
131893
131894
131895
131896
131897
131898
131899
131900
131901
131902
131903
131904
131905
131906
131907
131908
131909
131910
131911
131912
131913
131914
131915
131916
131917
131918
131919
131920
131921
131922
131923
131924
131925
131926
131927
131928
131929
131930
131931
131932
131933
131934
131935
131936
131937
131938
131939
131940
131941
131942
131943
131944
131945
131946
131947
131948
131949
131950
131951
131952
131953
131954
131955
131956
131957
131958
131959
131960
  sqlite3FpDecode(&s, x, y, z);
  if( s.isSpecial==2 ){
    sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN");
  }else{
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP);
  }
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
}
#endif /* SQLITE_DEBUG */

#ifdef SQLITE_DEBUG
/*
** Implementation of parseuri(uri,flags) function.
**
** Required Arguments:
**    "uri"        The URI to parse.
**    "flags"      Bitmask of flags, as if to sqlite3_open_v2().
**
** Additional arguments beyond the first two make calls to
** sqlite3_uri_key() for integers and sqlite3_uri_parameter for
** anything else.
**
** The result is a string showing the results of calling sqlite3ParseUri().
**
** Used for testing and debugging only, specifically testing and debugging
** of the sqlite3ParseUri() function.  This SQL function does not appear
** in production builds.  This function is not an API and is subject to
** modification or removal in future versions of SQLite.
*/
static void parseuriFunc(
  sqlite3_context *ctx,
  int argc,
  sqlite3_value **argv
){
  sqlite3_str *pResult;
  const char *zVfs;
  const char *zUri;
  unsigned int flgs;
  int rc;
  sqlite3_vfs *pVfs = 0;
  char *zFile = 0;
  char *zErr = 0;

  if( argc<2 ) return;
  pVfs = sqlite3_vfs_find(0);
  assert( pVfs );
  zVfs = pVfs->zName;
  zUri = (const char*)sqlite3_value_text(argv[0]);
  if( zUri==0 ) return;
  flgs = (unsigned int)sqlite3_value_int(argv[1]);
  rc = sqlite3ParseUri(zVfs, zUri, &flgs, &pVfs, &zFile, &zErr);
  pResult = sqlite3_str_new(0);
  if( pResult ){
    int i;
    sqlite3_str_appendf(pResult, "rc=%d", rc);
    sqlite3_str_appendf(pResult, ", flags=0x%x", flgs);
    sqlite3_str_appendf(pResult, ", vfs=%Q", pVfs ? pVfs->zName: 0);
    sqlite3_str_appendf(pResult, ", err=%Q", zErr);
    sqlite3_str_appendf(pResult, ", file=%Q", zFile);
    if( zFile ){
      const char *z = zFile;
      z += sqlite3Strlen30(z)+1;
      while( z[0] ){
        sqlite3_str_appendf(pResult, ", %Q", z);
        z += sqlite3Strlen30(z)+1;
      }
      for(i=2; i<argc; i++){
        const char *zArg;
        if( sqlite3_value_type(argv[i])==SQLITE_INTEGER ){
          int k = sqlite3_value_int(argv[i]);
          sqlite3_str_appendf(pResult, ", '%d:%q'",k,sqlite3_uri_key(zFile, k));
        }else if( (zArg = (const char*)sqlite3_value_text(argv[i]))!=0 ){
          sqlite3_str_appendf(pResult, ", '%q:%q'",
                 zArg, sqlite3_uri_parameter(zFile,zArg));
        }else{
          sqlite3_str_appendf(pResult, ", NULL");
        }
      }
    }
    sqlite3_result_text(ctx, sqlite3_str_finish(pResult), -1, sqlite3_free);
  }
  sqlite3_free_filename(zFile);
  sqlite3_free(zErr);
}
#endif /* SQLITE_DEBUG */

/*
** All of the FuncDef structures in the aBuiltinFunc[] array above
** to the global function hash table.  This occurs at start-time (as
** a consequence of calling sqlite3_initialize()).
131875
131876
131877
131878
131879
131880
131881
131882

131883
131884
131885
131886
131887
131888
131889
131890
131891
131892

131893
131894
131895
131896
131897
131898
131899
    WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
    FUNCTION(max,                0, 1, 1, 0                ),
    WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
    FUNCTION2(subtype,           1, 0, 0, subtypeFunc, SQLITE_FUNC_TYPEOF),

    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
    FUNCTION2(octet_length,      1, 0, 0, bytelengthFunc,SQLITE_FUNC_BYTELEN),
    FUNCTION(instr,              2, 0, 0, instrFunc        ),
    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
    FUNCTION(format,            -1, 0, 0, printfFunc       ),
    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
    FUNCTION(char,              -1, 0, 0, charFunc         ),
    FUNCTION(abs,                1, 0, 0, absFunc          ),
#ifdef SQLITE_DEBUG
    FUNCTION(fpdecode,           3, 0, 0, fpdecodeFunc     ),

#endif
#ifndef SQLITE_OMIT_FLOATING_POINT
    FUNCTION(round,              1, 0, 0, roundFunc        ),
    FUNCTION(round,              2, 0, 0, roundFunc        ),
#endif
    FUNCTION(upper,              1, 0, 0, upperFunc        ),
    FUNCTION(lower,              1, 0, 0, lowerFunc        ),







|
>










>







132012
132013
132014
132015
132016
132017
132018
132019
132020
132021
132022
132023
132024
132025
132026
132027
132028
132029
132030
132031
132032
132033
132034
132035
132036
132037
132038
    WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
    FUNCTION(max,                0, 1, 1, 0                ),
    WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
    FUNCTION2(subtype,           1, 0, 0, subtypeFunc,
                                           SQLITE_FUNC_TYPEOF|SQLITE_SUBTYPE),
    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
    FUNCTION2(octet_length,      1, 0, 0, bytelengthFunc,SQLITE_FUNC_BYTELEN),
    FUNCTION(instr,              2, 0, 0, instrFunc        ),
    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
    FUNCTION(format,            -1, 0, 0, printfFunc       ),
    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
    FUNCTION(char,              -1, 0, 0, charFunc         ),
    FUNCTION(abs,                1, 0, 0, absFunc          ),
#ifdef SQLITE_DEBUG
    FUNCTION(fpdecode,           3, 0, 0, fpdecodeFunc     ),
    FUNCTION(parseuri,          -1, 0, 0, parseuriFunc     ),
#endif
#ifndef SQLITE_OMIT_FLOATING_POINT
    FUNCTION(round,              1, 0, 0, roundFunc        ),
    FUNCTION(round,              2, 0, 0, roundFunc        ),
#endif
    FUNCTION(upper,              1, 0, 0, upperFunc        ),
    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
131980
131981
131982
131983
131984
131985
131986
131987
131988
131989
131990
131991
131992
131993
131994
    MFUNCTION(acosh,             1, acosh,     math1Func   ),
    MFUNCTION(asinh,             1, asinh,     math1Func   ),
    MFUNCTION(atanh,             1, atanh,     math1Func   ),
#endif
    MFUNCTION(sqrt,              1, sqrt,      math1Func   ),
    MFUNCTION(radians,           1, degToRad,  math1Func   ),
    MFUNCTION(degrees,           1, radToDeg,  math1Func   ),
    FUNCTION(pi,                 0, 0, 0,      piFunc      ),
#endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
    FUNCTION(sign,               1, 0, 0,      signFunc    ),
    INLINE_FUNC(coalesce,       -1, INLINEFUNC_coalesce, 0 ),
    INLINE_FUNC(iif,             3, INLINEFUNC_iif,      0 ),
  };
#ifndef SQLITE_OMIT_ALTERTABLE
  sqlite3AlterFunctions();







|







132119
132120
132121
132122
132123
132124
132125
132126
132127
132128
132129
132130
132131
132132
132133
    MFUNCTION(acosh,             1, acosh,     math1Func   ),
    MFUNCTION(asinh,             1, asinh,     math1Func   ),
    MFUNCTION(atanh,             1, atanh,     math1Func   ),
#endif
    MFUNCTION(sqrt,              1, sqrt,      math1Func   ),
    MFUNCTION(radians,           1, degToRad,  math1Func   ),
    MFUNCTION(degrees,           1, radToDeg,  math1Func   ),
    MFUNCTION(pi,                0, 0,         piFunc      ),
#endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
    FUNCTION(sign,               1, 0, 0,      signFunc    ),
    INLINE_FUNC(coalesce,       -1, INLINEFUNC_coalesce, 0 ),
    INLINE_FUNC(iif,             3, INLINEFUNC_iif,      0 ),
  };
#ifndef SQLITE_OMIT_ALTERTABLE
  sqlite3AlterFunctions();
141114
141115
141116
141117
141118
141119
141120

141121
141122
141123
141124
141125
141126
141127
          aRoot[++cnt] = pIdx->tnum;
        }
      }
      aRoot[0] = cnt;

      /* Make sure sufficient number of registers have been allocated */
      sqlite3TouchRegister(pParse, 8+cnt);

      sqlite3ClearTempRegCache(pParse);

      /* Do the b-tree integrity checks */
      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 1, cnt, 8, (char*)aRoot,P4_INTARRAY);
      sqlite3VdbeChangeP5(v, (u8)i);
      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,







>







141253
141254
141255
141256
141257
141258
141259
141260
141261
141262
141263
141264
141265
141266
141267
          aRoot[++cnt] = pIdx->tnum;
        }
      }
      aRoot[0] = cnt;

      /* Make sure sufficient number of registers have been allocated */
      sqlite3TouchRegister(pParse, 8+cnt);
      sqlite3VdbeAddOp3(v, OP_Null, 0, 8, 8+cnt);
      sqlite3ClearTempRegCache(pParse);

      /* Do the b-tree integrity checks */
      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 1, cnt, 8, (char*)aRoot,P4_INTARRAY);
      sqlite3VdbeChangeP5(v, (u8)i);
      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
161343
161344
161345
161346
161347
161348
161349
161350
161351
161352
161353

161354
161355
161356
161357
161358
161359
161360
161361


161362
161363



161364
161365
161366
161367
161368
161369
161370
161371
161372
161373
161374
161375
161376
161377
161378
161379
161380
161381
161382
    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  }else if( op==TK_STRING ){
    assert( !ExprHasProperty(pRight, EP_IntValue) );
     z = (u8*)pRight->u.zToken;
  }
  if( z ){

    /* Count the number of prefix characters prior to the first wildcard.
    ** If the underlying database has a UTF16LE encoding, then only consider
    ** ASCII characters.  Note that the encoding of z[] is UTF8 - we are

    ** dealing with only UTF8 here in this code, but the database engine
    ** itself might be processing content using a different encoding. */
    cnt = 0;
    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
      cnt++;
      if( c==wc[3] && z[cnt]!=0 ){
        cnt++;
      }else if( c>=0x80 && ENC(db)==SQLITE_UTF16LE ){


         cnt--;
         break;



      }
    }

    /* The optimization is possible only if (1) the pattern does not begin
    ** with a wildcard and if (2) the non-wildcard prefix does not end with
    ** an (illegal 0xff) character, or (3) the pattern does not consist of
    ** a single escape character. The second condition is necessary so
    ** that we can increment the prefix key to find an upper bound for the
    ** range search. The third is because the caller assumes that the pattern
    ** consists of at least one character after all escapes have been
    ** removed.  */
    if( (cnt>1 || (cnt>0 && z[0]!=wc[3])) && 255!=(u8)z[cnt-1] ){
      Expr *pPrefix;

      /* A "complete" match if the pattern ends with "*" or "%" */
      *pisComplete = c==wc[0] && z[cnt+1]==0 && ENC(db)!=SQLITE_UTF16LE;

      /* Get the pattern prefix.  Remove all escapes from the prefix. */
      pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);







<
|
|
|
>
|
|



|

|
>
>
|
|
>
>
>











|







161483
161484
161485
161486
161487
161488
161489

161490
161491
161492
161493
161494
161495
161496
161497
161498
161499
161500
161501
161502
161503
161504
161505
161506
161507
161508
161509
161510
161511
161512
161513
161514
161515
161516
161517
161518
161519
161520
161521
161522
161523
161524
161525
161526
161527
    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  }else if( op==TK_STRING ){
    assert( !ExprHasProperty(pRight, EP_IntValue) );
     z = (u8*)pRight->u.zToken;
  }
  if( z ){

    /* Count the number of prefix bytes prior to the first wildcard.
    ** or U+fffd character.  If the underlying database has a UTF16LE
    ** encoding, then only consider ASCII characters.  Note that the
    ** encoding of z[] is UTF8 - we are dealing with only UTF8 here in
    ** this code, but the database engine itself might be processing
    ** content using a different encoding. */
    cnt = 0;
    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
      cnt++;
      if( c==wc[3] && z[cnt]>0 && z[cnt]<0x80 ){
        cnt++;
      }else if( c>=0x80 ){
        const u8 *z2 = z+cnt-1;
        if( sqlite3Utf8Read(&z2)==0xfffd || ENC(db)==SQLITE_UTF16LE ){
          cnt--;
          break;
        }else{
          cnt = (int)(z2-z);
        }
      }
    }

    /* The optimization is possible only if (1) the pattern does not begin
    ** with a wildcard and if (2) the non-wildcard prefix does not end with
    ** an (illegal 0xff) character, or (3) the pattern does not consist of
    ** a single escape character. The second condition is necessary so
    ** that we can increment the prefix key to find an upper bound for the
    ** range search. The third is because the caller assumes that the pattern
    ** consists of at least one character after all escapes have been
    ** removed.  */
    if( (cnt>1 || (cnt>0 && z[0]!=wc[3])) && ALWAYS(255!=(u8)z[cnt-1]) ){
      Expr *pPrefix;

      /* A "complete" match if the pattern ends with "*" or "%" */
      *pisComplete = c==wc[0] && z[cnt+1]==0 && ENC(db)!=SQLITE_UTF16LE;

      /* Get the pattern prefix.  Remove all escapes from the prefix. */
      pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
169326
169327
169328
169329
169330
169331
169332
169333
169334
169335
169336
169337
169338
169339
169340
169341
169342
169343
169344
169345
169346
169347
169348
169349
169350
169351
169352
169353
169354
169355
169356
169357
169358
169359
169360
169361
169362
169363
169364
169365
169366
169367
169368
169369
169370
169371
169372
169373
169374
169375
169376
169377
169378
169379
169380
169381
169382
169383
169384
169385
169386
169387
169388
169389
169390
169391
      }
    }
    nSearch += pLoop->nOut;
    if( pWInfo->nOutStarDelta ) nSearch += pLoop->rStarDelta;
  }
}

/*
** Expression Node callback for sqlite3ExprCanReturnSubtype().
**
** Only a function call is able to return a subtype.  So if the node
** is not a function call, return WRC_Prune immediately.
**
** A function call is able to return a subtype if it has the
** SQLITE_RESULT_SUBTYPE property.
**
** Assume that every function is able to pass-through a subtype from
** one of its argument (using sqlite3_result_value()).  Most functions
** are not this way, but we don't have a mechanism to distinguish those
** that are from those that are not, so assume they all work this way.
** That means that if one of its arguments is another function and that
** other function is able to return a subtype, then this function is
** able to return a subtype.
*/
static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){
  int n;
  FuncDef *pDef;
  sqlite3 *db;
  if( pExpr->op!=TK_FUNCTION ){
    return WRC_Prune;
  }
  assert( ExprUseXList(pExpr) );
  db = pWalker->pParse->db;
  n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
  pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
  if( pDef==0 || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
    pWalker->eCode = 1;
    return WRC_Prune;
  }
  return WRC_Continue;
}

/*
** Return TRUE if expression pExpr is able to return a subtype.
**
** A TRUE return does not guarantee that a subtype will be returned.
** It only indicates that a subtype return is possible.  False positives
** are acceptable as they only disable an optimization.  False negatives,
** on the other hand, can lead to incorrect answers.
*/
static int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){
  Walker w;
  memset(&w, 0, sizeof(w));
  w.pParse = pParse;
  w.xExprCallback = exprNodeCanReturnSubtype;
  sqlite3WalkExpr(&w, pExpr);
  return w.eCode;
}

/*
** The index pIdx is used by a query and contains one or more expressions.
** In other words pIdx is an index on an expression.  iIdxCur is the cursor
** number for the index and iDataCur is the cursor number for the corresponding
** table.
**
** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







169471
169472
169473
169474
169475
169476
169477




















































169478
169479
169480
169481
169482
169483
169484
      }
    }
    nSearch += pLoop->nOut;
    if( pWInfo->nOutStarDelta ) nSearch += pLoop->rStarDelta;
  }
}





















































/*
** The index pIdx is used by a query and contains one or more expressions.
** In other words pIdx is an index on an expression.  iIdxCur is the cursor
** number for the index and iDataCur is the cursor number for the corresponding
** table.
**
** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for
169411
169412
169413
169414
169415
169416
169417
169418
169419
169420
169421
169422
169423
169424
169425
169426
169427
169428
169429
169430
      pExpr = pIdx->aColExpr->a[i].pExpr;
    }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
      pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
    }else{
      continue;
    }
    if( sqlite3ExprIsConstant(0,pExpr) ) continue;
    if( pExpr->op==TK_FUNCTION && sqlite3ExprCanReturnSubtype(pParse,pExpr) ){
      /* Functions that might set a subtype should not be replaced by the
      ** value taken from an expression index since the index omits the
      ** subtype.  https://sqlite.org/forum/forumpost/68d284c86b082c3e */
      continue;
    }
    p = sqlite3DbMallocRaw(pParse->db,  sizeof(IndexedExpr));
    if( p==0 ) break;
    p->pIENext = pParse->pIdxEpr;
#ifdef WHERETRACE_ENABLED
    if( sqlite3WhereTrace & 0x200 ){
      sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
      if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr);







<
<
<
<
<
<







169504
169505
169506
169507
169508
169509
169510






169511
169512
169513
169514
169515
169516
169517
      pExpr = pIdx->aColExpr->a[i].pExpr;
    }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
      pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
    }else{
      continue;
    }
    if( sqlite3ExprIsConstant(0,pExpr) ) continue;






    p = sqlite3DbMallocRaw(pParse->db,  sizeof(IndexedExpr));
    if( p==0 ) break;
    p->pIENext = pParse->pIdxEpr;
#ifdef WHERETRACE_ENABLED
    if( sqlite3WhereTrace & 0x200 ){
      sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
      if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr);
181160
181161
181162
181163
181164
181165
181166
181167
181168
181169
181170
181171
181172
181173
181174
181175
181176
181177
181178
181179
181180
181181
181182
181183
181184
181185
181186
181187
181188
181189
181190
181191
181192
181193
181194
181195
181196
181197
181198
181199
** If the following global variable points to a string which is the
** name of a directory, then that directory will be used to store
** all database files specified with a relative pathname.
**
** See also the "PRAGMA data_store_directory" SQL command.
*/
SQLITE_API char *sqlite3_data_directory = 0;

/*
** Determine whether or not high-precision (long double) floating point
** math works correctly on CPU currently running.
*/
static SQLITE_NOINLINE int hasHighPrecisionDouble(int rc){
  if( sizeof(LONGDOUBLE_TYPE)<=8 ){
    /* If the size of "long double" is not more than 8, then
    ** high-precision math is not possible. */
    return 0;
  }else{
    /* Just because sizeof(long double)>8 does not mean that the underlying
    ** hardware actually supports high-precision floating point.  For example,
    ** clearing the 0x100 bit in the floating-point control word on Intel
    ** processors will make long double work like double, even though long
    ** double takes up more space.  The only way to determine if long double
    ** actually works is to run an experiment. */
    LONGDOUBLE_TYPE a, b, c;
    rc++;
    a = 1.0+rc*0.1;
    b = 1.0e+18+rc*25.0;
    c = a+b;
    return b!=c;
  }
}


/*
** Initialize SQLite.
**
** This routine must be called to initialize the memory allocation,
** VFS, and mutex subsystems prior to doing any serious work with
** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







181247
181248
181249
181250
181251
181252
181253


























181254
181255
181256
181257
181258
181259
181260
** If the following global variable points to a string which is the
** name of a directory, then that directory will be used to store
** all database files specified with a relative pathname.
**
** See also the "PRAGMA data_store_directory" SQL command.
*/
SQLITE_API char *sqlite3_data_directory = 0;



























/*
** Initialize SQLite.
**
** This routine must be called to initialize the memory allocation,
** VFS, and mutex subsystems prior to doing any serious work with
** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
181381
181382
181383
181384
181385
181386
181387
181388
181389
181390
181391
181392
181393
181394
181395
181396
181397
181398
181399
181400
181401
  */
#ifdef SQLITE_EXTRA_INIT
  if( bRunExtraInit ){
    int SQLITE_EXTRA_INIT(const char*);
    rc = SQLITE_EXTRA_INIT(0);
  }
#endif

  /* Experimentally determine if high-precision floating point is
  ** available. */
#ifndef SQLITE_OMIT_WSD
  sqlite3Config.bUseLongDouble = hasHighPrecisionDouble(rc);
#endif

  return rc;
}

/*
** Undo the effects of sqlite3_initialize().  Must not be called while
** there are outstanding database connections or memory allocations or
** while any part of SQLite is otherwise in use in any thread.  This







<
<
<
<
<
<
<







181442
181443
181444
181445
181446
181447
181448







181449
181450
181451
181452
181453
181454
181455
  */
#ifdef SQLITE_EXTRA_INIT
  if( bRunExtraInit ){
    int SQLITE_EXTRA_INIT(const char*);
    rc = SQLITE_EXTRA_INIT(0);
  }
#endif







  return rc;
}

/*
** Undo the effects of sqlite3_initialize().  Must not be called while
** there are outstanding database connections or memory allocations or
** while any part of SQLite is otherwise in use in any thread.  This
185639
185640
185641
185642
185643
185644
185645
185646
185647
185648
185649
185650
185651
185652
185653
185654
185655
185656
185657
185658
185659
185660
185661
185662
185663
185664
185665
185666
185667
185668
185669
185670
      u64 *pU64 = va_arg(ap,u64*);
      int *pI2 = va_arg(ap,int*);
      *pI1 = rLogEst;
      *pU64 = sqlite3LogEstToInt(rLogEst);
      *pI2 = sqlite3LogEst(*pU64);
      break;
    }

#if !defined(SQLITE_OMIT_WSD)
    /* sqlite3_test_control(SQLITE_TESTCTRL_USELONGDOUBLE, int X);
    **
    **   X<0     Make no changes to the bUseLongDouble.  Just report value.
    **   X==0    Disable bUseLongDouble
    **   X==1    Enable bUseLongDouble
    **   X>=2    Set bUseLongDouble to its default value for this platform
    */
    case SQLITE_TESTCTRL_USELONGDOUBLE: {
      int b = va_arg(ap, int);
      if( b>=2 ) b = hasHighPrecisionDouble(b);
      if( b>=0 ) sqlite3Config.bUseLongDouble = b>0;
      rc = sqlite3Config.bUseLongDouble!=0;
      break;
    }
#endif


#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
    /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
    **
    ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
    ** of the id-th tuning parameter to *piValue.  If "id" is between -1
    ** and -SQLITE_NTUNE, then write the current value of the (-id)-th







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







185693
185694
185695
185696
185697
185698
185699


















185700
185701
185702
185703
185704
185705
185706
      u64 *pU64 = va_arg(ap,u64*);
      int *pI2 = va_arg(ap,int*);
      *pI1 = rLogEst;
      *pU64 = sqlite3LogEstToInt(rLogEst);
      *pI2 = sqlite3LogEst(*pU64);
      break;
    }



















#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
    /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
    **
    ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
    ** of the id-th tuning parameter to *piValue.  If "id" is between -1
    ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
185965
185966
185967
185968
185969
185970
185971



185972

185973
185974
185975
185976
185977
185978
185979
  sqlite3_mutex_enter(db->mutex);

  if( db->autoCommit==0 ){
    int iDb = sqlite3FindDbName(db, zDb);
    if( iDb==0 || iDb>1 ){
      Btree *pBt = db->aDb[iDb].pBt;
      if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){



        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);

        if( rc==SQLITE_OK ){
          rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
        }
      }
    }
  }








>
>
>

>







186001
186002
186003
186004
186005
186006
186007
186008
186009
186010
186011
186012
186013
186014
186015
186016
186017
186018
186019
  sqlite3_mutex_enter(db->mutex);

  if( db->autoCommit==0 ){
    int iDb = sqlite3FindDbName(db, zDb);
    if( iDb==0 || iDb>1 ){
      Btree *pBt = db->aDb[iDb].pBt;
      if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
        Pager *pPager = sqlite3BtreePager(pBt);
        i64 dummy = 0;
        sqlite3PagerSnapshotOpen(pPager, (sqlite3_snapshot*)&dummy);
        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
        sqlite3PagerSnapshotOpen(pPager, 0);
        if( rc==SQLITE_OK ){
          rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
        }
      }
    }
  }

225800
225801
225802
225803
225804
225805
225806
225807
225808
225809
225810
225811
225812
225813
225814
225815
  int iDb;                        /* Index of database to analyze */
  int szPage;                     /* Size of each page in bytes */
};

struct DbpageTable {
  sqlite3_vtab base;              /* Base class.  Must be first */
  sqlite3 *db;                    /* The database */
  int nTrunc;                     /* Entries in aTrunc[] */
  Pgno *aTrunc;                   /* Truncation size for each database */
};

/* Columns */
#define DBPAGE_COLUMN_PGNO    0
#define DBPAGE_COLUMN_DATA    1
#define DBPAGE_COLUMN_SCHEMA  2








|
|







225840
225841
225842
225843
225844
225845
225846
225847
225848
225849
225850
225851
225852
225853
225854
225855
  int iDb;                        /* Index of database to analyze */
  int szPage;                     /* Size of each page in bytes */
};

struct DbpageTable {
  sqlite3_vtab base;              /* Base class.  Must be first */
  sqlite3 *db;                    /* The database */
  int iDbTrunc;                   /* Database to truncate */
  Pgno pgnoTrunc;                 /* Size to truncate to */
};

/* Columns */
#define DBPAGE_COLUMN_PGNO    0
#define DBPAGE_COLUMN_DATA    1
#define DBPAGE_COLUMN_SCHEMA  2

225850
225851
225852
225853
225854
225855
225856
225857
225858
225859
225860
225861
225862
225863
225864
225865
  return rc;
}

/*
** Disconnect from or destroy a dbpagevfs virtual table.
*/
static int dbpageDisconnect(sqlite3_vtab *pVtab){
  DbpageTable *pTab = (DbpageTable *)pVtab;
  sqlite3_free(pTab->aTrunc);
  sqlite3_free(pVtab);
  return SQLITE_OK;
}

/*
** idxNum:
**







<
<







225890
225891
225892
225893
225894
225895
225896


225897
225898
225899
225900
225901
225902
225903
  return rc;
}

/*
** Disconnect from or destroy a dbpagevfs virtual table.
*/
static int dbpageDisconnect(sqlite3_vtab *pVtab){


  sqlite3_free(pVtab);
  return SQLITE_OK;
}

/*
** idxNum:
**
226118
226119
226120
226121
226122
226123
226124
226125
226126
226127
226128
226129
226130
226131
226132
226133
226134
226135
226136

226137
226138
226139
226140
226141
226142
226143
226144
226145
226146
226147
226148
226149

226150
226151
226152
226153
226154
226155
226156
    zErr = "bad page number";
    goto update_fail;
  }
  szPage = sqlite3BtreeGetPageSize(pBt);
  if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
   || sqlite3_value_bytes(argv[3])!=szPage
  ){
    if( sqlite3_value_type(argv[3])==SQLITE_NULL && isInsert ){
      if( iDb>=pTab->nTrunc ){
        testcase( pTab->aTrunc!=0 );
        pTab->aTrunc = sqlite3_realloc(pTab->aTrunc, (iDb+1)*sizeof(Pgno));
        if( pTab->aTrunc ){
          int j;
          for(j=pTab->nTrunc; j<iDb; j++) pTab->aTrunc[j] = 0;
          pTab->nTrunc = iDb+1;
        }else{
          return SQLITE_NOMEM;
        }
      }

      pTab->aTrunc[iDb] = pgno;
    }else{
      zErr = "bad page value";
      goto update_fail;
    }
  }
  pPager = sqlite3BtreePager(pBt);
  rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  if( rc==SQLITE_OK ){
    const void *pData = sqlite3_value_blob(argv[3]);
    if( (rc = sqlite3PagerWrite(pDbPage))==SQLITE_OK && pData ){
      unsigned char *aPage = sqlite3PagerGetData(pDbPage);
      memcpy(aPage, pData, szPage);

    }
  }
  sqlite3PagerUnref(pDbPage);
  return rc;

update_fail:
  sqlite3_free(pVtab->zErrMsg);







|
|
<
<
<
|
<
|
<
<
<
<
>
|












>







226156
226157
226158
226159
226160
226161
226162
226163
226164



226165

226166




226167
226168
226169
226170
226171
226172
226173
226174
226175
226176
226177
226178
226179
226180
226181
226182
226183
226184
226185
226186
226187
226188
    zErr = "bad page number";
    goto update_fail;
  }
  szPage = sqlite3BtreeGetPageSize(pBt);
  if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
   || sqlite3_value_bytes(argv[3])!=szPage
  ){
    if( sqlite3_value_type(argv[3])==SQLITE_NULL && isInsert && pgno>1 ){
      /* "INSERT INTO dbpage($PGNO,NULL)" causes page number $PGNO and



      ** all subsequent pages to be deleted. */

      pTab->iDbTrunc = iDb;




      pgno--;
      pTab->pgnoTrunc = pgno;
    }else{
      zErr = "bad page value";
      goto update_fail;
    }
  }
  pPager = sqlite3BtreePager(pBt);
  rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  if( rc==SQLITE_OK ){
    const void *pData = sqlite3_value_blob(argv[3]);
    if( (rc = sqlite3PagerWrite(pDbPage))==SQLITE_OK && pData ){
      unsigned char *aPage = sqlite3PagerGetData(pDbPage);
      memcpy(aPage, pData, szPage);
      pTab->pgnoTrunc = 0;
    }
  }
  sqlite3PagerUnref(pDbPage);
  return rc;

update_fail:
  sqlite3_free(pVtab->zErrMsg);
226166
226167
226168
226169
226170
226171
226172
226173
226174
226175
226176
226177
226178
226179
226180
226181
226182
226183
226184
226185
226186
226187
226188
226189

226190

226191
226192






226193
226194
226195
226196
226197
226198
226199
226200
226201
226202
  DbpageTable *pTab = (DbpageTable *)pVtab;
  sqlite3 *db = pTab->db;
  int i;
  for(i=0; i<db->nDb; i++){
    Btree *pBt = db->aDb[i].pBt;
    if( pBt ) (void)sqlite3BtreeBeginTrans(pBt, 1, 0);
  }
  if( pTab->nTrunc>0 ){
    memset(pTab->aTrunc, 0, sizeof(pTab->aTrunc[0])*pTab->nTrunc);
  }
  return SQLITE_OK;
}

/* Invoke sqlite3PagerTruncate() as necessary, just prior to COMMIT
*/
static int dbpageSync(sqlite3_vtab *pVtab){
  int iDb;
  DbpageTable *pTab = (DbpageTable *)pVtab;

  for(iDb=0; iDb<pTab->nTrunc; iDb++){
    if( pTab->aTrunc[iDb]>0 ){
      Btree *pBt = pTab->db->aDb[iDb].pBt;
      Pager *pPager = sqlite3BtreePager(pBt);
      sqlite3PagerTruncateImage(pPager, pTab->aTrunc[iDb]);

      pTab->aTrunc[iDb] = 0;

    }
  }






  return SQLITE_OK;
}


/*
** Invoke this routine to register the "dbpage" virtual table module
*/
SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  static sqlite3_module dbpage_module = {
    0,                            /* iVersion */







|
<
<






<

<
<
|
|
|
|
>
|
>
|
|
>
>
>
>
>
>


<







226198
226199
226200
226201
226202
226203
226204
226205


226206
226207
226208
226209
226210
226211

226212


226213
226214
226215
226216
226217
226218
226219
226220
226221
226222
226223
226224
226225
226226
226227
226228
226229

226230
226231
226232
226233
226234
226235
226236
  DbpageTable *pTab = (DbpageTable *)pVtab;
  sqlite3 *db = pTab->db;
  int i;
  for(i=0; i<db->nDb; i++){
    Btree *pBt = db->aDb[i].pBt;
    if( pBt ) (void)sqlite3BtreeBeginTrans(pBt, 1, 0);
  }
  pTab->pgnoTrunc = 0;


  return SQLITE_OK;
}

/* Invoke sqlite3PagerTruncate() as necessary, just prior to COMMIT
*/
static int dbpageSync(sqlite3_vtab *pVtab){

  DbpageTable *pTab = (DbpageTable *)pVtab;


  if( pTab->pgnoTrunc>0 ){
    Btree *pBt = pTab->db->aDb[pTab->iDbTrunc].pBt;
    Pager *pPager = sqlite3BtreePager(pBt);
    sqlite3PagerTruncateImage(pPager, pTab->pgnoTrunc);
  }
  pTab->pgnoTrunc = 0;
  return SQLITE_OK;
}

/* Cancel any pending truncate.
*/
static int dbpageRollbackTo(sqlite3_vtab *pVtab, int notUsed1){
  DbpageTable *pTab = (DbpageTable *)pVtab;
  pTab->pgnoTrunc = 0;
  (void)notUsed1;
  return SQLITE_OK;
}


/*
** Invoke this routine to register the "dbpage" virtual table module
*/
SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  static sqlite3_module dbpage_module = {
    0,                            /* iVersion */
226217
226218
226219
226220
226221
226222
226223
226224
226225
226226
226227
226228
226229
226230
226231
    dbpageSync,                   /* xSync */
    0,                            /* xCommit */
    0,                            /* xRollback */
    0,                            /* xFindMethod */
    0,                            /* xRename */
    0,                            /* xSavepoint */
    0,                            /* xRelease */
    0,                            /* xRollbackTo */
    0,                            /* xShadowName */
    0                             /* xIntegrity */
  };
  return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
}
#elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }







|







226251
226252
226253
226254
226255
226256
226257
226258
226259
226260
226261
226262
226263
226264
226265
    dbpageSync,                   /* xSync */
    0,                            /* xCommit */
    0,                            /* xRollback */
    0,                            /* xFindMethod */
    0,                            /* xRename */
    0,                            /* xSavepoint */
    0,                            /* xRelease */
    dbpageRollbackTo,             /* xRollbackTo */
    0,                            /* xShadowName */
    0                             /* xIntegrity */
  };
  return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
}
#elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
233177
233178
233179
233180
233181
233182
233183
233184
233185
233186
233187
233188
233189
233190
233191

/*************************************************************************
** CUSTOM TOKENIZERS
**
** Applications may also register custom tokenizer types. A tokenizer
** is registered by providing fts5 with a populated instance of the
** following structure. All structure methods must be defined, setting
**
** any member of the fts5_tokenizer struct to NULL leads to undefined
** behaviour. The structure methods are expected to function as follows:
**
** xCreate:
**   This function is used to allocate and initialize a tokenizer instance.
**   A tokenizer instance is required to actually tokenize text.
**







<







233211
233212
233213
233214
233215
233216
233217

233218
233219
233220
233221
233222
233223
233224

/*************************************************************************
** CUSTOM TOKENIZERS
**
** Applications may also register custom tokenizer types. A tokenizer
** is registered by providing fts5 with a populated instance of the
** following structure. All structure methods must be defined, setting

** any member of the fts5_tokenizer struct to NULL leads to undefined
** behaviour. The structure methods are expected to function as follows:
**
** xCreate:
**   This function is used to allocate and initialize a tokenizer instance.
**   A tokenizer instance is required to actually tokenize text.
**
233746
233747
233748
233749
233750
233751
233752

233753
233754
233755
233756
233757
233758
233759
  int nCol;                       /* Number of columns */
  char **azCol;                   /* Column names */
  u8 *abUnindexed;                /* True for unindexed columns */
  int nPrefix;                    /* Number of prefix indexes */
  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
  int eContent;                   /* An FTS5_CONTENT value */
  int bContentlessDelete;         /* "contentless_delete=" option (dflt==0) */

  char *zContent;                 /* content table */
  char *zContentRowid;            /* "content_rowid=" option value */
  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
  int bTokendata;                 /* "tokendata=" option value (dflt==0) */
  int bLocale;                    /* "locale=" option value (dflt==0) */
  int eDetail;                    /* FTS5_DETAIL_XXX value */
  char *zContentExprlist;







>







233779
233780
233781
233782
233783
233784
233785
233786
233787
233788
233789
233790
233791
233792
233793
  int nCol;                       /* Number of columns */
  char **azCol;                   /* Column names */
  u8 *abUnindexed;                /* True for unindexed columns */
  int nPrefix;                    /* Number of prefix indexes */
  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
  int eContent;                   /* An FTS5_CONTENT value */
  int bContentlessDelete;         /* "contentless_delete=" option (dflt==0) */
  int bContentlessUnindexed;      /* "contentless_unindexed=" option (dflt=0) */
  char *zContent;                 /* content table */
  char *zContentRowid;            /* "content_rowid=" option value */
  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
  int bTokendata;                 /* "tokendata=" option value (dflt==0) */
  int bLocale;                    /* "locale=" option value (dflt==0) */
  int eDetail;                    /* FTS5_DETAIL_XXX value */
  char *zContentExprlist;
233784
233785
233786
233787
233788
233789
233790
233791
233792
233793

233794
233795
233796
233797
233798
233799
233800

/* Current expected value of %_config table 'version' field. And
** the expected version if the 'secure-delete' option has ever been
** set on the table.  */
#define FTS5_CURRENT_VERSION               4
#define FTS5_CURRENT_VERSION_SECUREDELETE  5

#define FTS5_CONTENT_NORMAL   0
#define FTS5_CONTENT_NONE     1
#define FTS5_CONTENT_EXTERNAL 2


#define FTS5_DETAIL_FULL      0
#define FTS5_DETAIL_NONE      1
#define FTS5_DETAIL_COLUMNS   2

#define FTS5_PATTERN_NONE     0
#define FTS5_PATTERN_LIKE     65  /* matches SQLITE_INDEX_CONSTRAINT_LIKE */







|
|
|
>







233818
233819
233820
233821
233822
233823
233824
233825
233826
233827
233828
233829
233830
233831
233832
233833
233834
233835

/* Current expected value of %_config table 'version' field. And
** the expected version if the 'secure-delete' option has ever been
** set on the table.  */
#define FTS5_CURRENT_VERSION               4
#define FTS5_CURRENT_VERSION_SECUREDELETE  5

#define FTS5_CONTENT_NORMAL    0
#define FTS5_CONTENT_NONE      1
#define FTS5_CONTENT_EXTERNAL  2
#define FTS5_CONTENT_UNINDEXED 3

#define FTS5_DETAIL_FULL      0
#define FTS5_DETAIL_NONE      1
#define FTS5_DETAIL_COLUMNS   2

#define FTS5_PATTERN_NONE     0
#define FTS5_PATTERN_LIKE     65  /* matches SQLITE_INDEX_CONSTRAINT_LIKE */
234246
234247
234248
234249
234250
234251
234252
234253
234254
234255
234256
234257
234258
234259
234260
static int sqlite3Fts5StorageClose(Fts5Storage *p);
static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);

static int sqlite3Fts5DropAll(Fts5Config*);
static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);

static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**, int);
static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);

static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg);

static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);








|







234281
234282
234283
234284
234285
234286
234287
234288
234289
234290
234291
234292
234293
234294
234295
static int sqlite3Fts5StorageClose(Fts5Storage *p);
static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);

static int sqlite3Fts5DropAll(Fts5Config*);
static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);

static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**, int);
static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, int, sqlite3_value**, i64*);
static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);

static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg);

static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);

237453
237454
237455
237456
237457
237458
237459

237460
237461
237462
237463
237464
237465
237466
  Fts5Config *pConfig,            /* Configuration object to update */
  const char *zCmd,               /* Special command to parse */
  const char *zArg,               /* Argument to parse */
  char **pzErr                    /* OUT: Error message */
){
  int rc = SQLITE_OK;
  int nCmd = (int)strlen(zCmd);

  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
    const char *p;
    int bFirst = 1;
    if( pConfig->aPrefix==0 ){
      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
      if( rc ) return rc;







>







237488
237489
237490
237491
237492
237493
237494
237495
237496
237497
237498
237499
237500
237501
237502
  Fts5Config *pConfig,            /* Configuration object to update */
  const char *zCmd,               /* Special command to parse */
  const char *zArg,               /* Argument to parse */
  char **pzErr                    /* OUT: Error message */
){
  int rc = SQLITE_OK;
  int nCmd = (int)strlen(zCmd);

  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
    const char *p;
    int bFirst = 1;
    if( pConfig->aPrefix==0 ){
      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
      if( rc ) return rc;
237571
237572
237573
237574
237575
237576
237577










237578
237579
237580
237581
237582
237583
237584
      *pzErr = sqlite3_mprintf("malformed contentless_delete=... directive");
      rc = SQLITE_ERROR;
    }else{
      pConfig->bContentlessDelete = (zArg[0]=='1');
    }
    return rc;
  }











  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
    if( pConfig->zContentRowid ){
      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
      rc = SQLITE_ERROR;
    }else{
      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);







>
>
>
>
>
>
>
>
>
>







237607
237608
237609
237610
237611
237612
237613
237614
237615
237616
237617
237618
237619
237620
237621
237622
237623
237624
237625
237626
237627
237628
237629
237630
      *pzErr = sqlite3_mprintf("malformed contentless_delete=... directive");
      rc = SQLITE_ERROR;
    }else{
      pConfig->bContentlessDelete = (zArg[0]=='1');
    }
    return rc;
  }

  if( sqlite3_strnicmp("contentless_unindexed", zCmd, nCmd)==0 ){
    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
      *pzErr = sqlite3_mprintf("malformed contentless_delete=... directive");
      rc = SQLITE_ERROR;
    }else{
      pConfig->bContentlessUnindexed = (zArg[0]=='1');
    }
    return rc;
  }

  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
    if( pConfig->zContentRowid ){
      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
      rc = SQLITE_ERROR;
    }else{
      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
237689
237690
237691
237692
237693
237694
237695
237696

237697
237698
237699
237700
237701
237702
237703
237704
237705
237706

237707
237708
237709
237710
237711
237712
237713
237714
237715
237716
237717
237718
237719
237720
237721
237722
237723
237724
237725
237726




237727
237728
237729


237730
237731
237732
237733
237734
237735
237736
237737
237738
  return zRet;
}

static int fts5ConfigParseColumn(
  Fts5Config *p,
  char *zCol,
  char *zArg,
  char **pzErr

){
  int rc = SQLITE_OK;
  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  ){
    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
    rc = SQLITE_ERROR;
  }else if( zArg ){
    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
      p->abUnindexed[p->nCol] = 1;

    }else{
      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
      rc = SQLITE_ERROR;
    }
  }

  p->azCol[p->nCol++] = zCol;
  return rc;
}

/*
** Populate the Fts5Config.zContentExprlist string.
*/
static int fts5ConfigMakeExprlist(Fts5Config *p){
  int i;
  int rc = SQLITE_OK;
  Fts5Buffer buf = {0, 0, 0};

  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  if( p->eContent!=FTS5_CONTENT_NONE ){




    for(i=0; i<p->nCol; i++){
      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);


      }else{
        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
      }
    }
  }
  if( p->eContent==FTS5_CONTENT_NORMAL && p->bLocale ){
    for(i=0; i<p->nCol; i++){
      if( p->abUnindexed[i]==0 ){
        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.l%d", i);







|
>










>




















>
>
>
>



>
>

|







237735
237736
237737
237738
237739
237740
237741
237742
237743
237744
237745
237746
237747
237748
237749
237750
237751
237752
237753
237754
237755
237756
237757
237758
237759
237760
237761
237762
237763
237764
237765
237766
237767
237768
237769
237770
237771
237772
237773
237774
237775
237776
237777
237778
237779
237780
237781
237782
237783
237784
237785
237786
237787
237788
237789
237790
237791
237792
  return zRet;
}

static int fts5ConfigParseColumn(
  Fts5Config *p,
  char *zCol,
  char *zArg,
  char **pzErr,
  int *pbUnindexed
){
  int rc = SQLITE_OK;
  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  ){
    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
    rc = SQLITE_ERROR;
  }else if( zArg ){
    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
      p->abUnindexed[p->nCol] = 1;
      *pbUnindexed = 1;
    }else{
      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
      rc = SQLITE_ERROR;
    }
  }

  p->azCol[p->nCol++] = zCol;
  return rc;
}

/*
** Populate the Fts5Config.zContentExprlist string.
*/
static int fts5ConfigMakeExprlist(Fts5Config *p){
  int i;
  int rc = SQLITE_OK;
  Fts5Buffer buf = {0, 0, 0};

  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  if( p->eContent!=FTS5_CONTENT_NONE ){
    assert( p->eContent==FTS5_CONTENT_EXTERNAL
         || p->eContent==FTS5_CONTENT_NORMAL
         || p->eContent==FTS5_CONTENT_UNINDEXED
    );
    for(i=0; i<p->nCol; i++){
      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
      }else if( p->eContent==FTS5_CONTENT_NORMAL || p->abUnindexed[i] ){
        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
      }else{
        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", NULL");
      }
    }
  }
  if( p->eContent==FTS5_CONTENT_NORMAL && p->bLocale ){
    for(i=0; i<p->nCol; i++){
      if( p->abUnindexed[i]==0 ){
        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.l%d", i);
237767
237768
237769
237770
237771
237772
237773

237774
237775
237776
237777
237778
237779
237780
  Fts5Config **ppOut,             /* OUT: Results of parse */
  char **pzErr                    /* OUT: Error message */
){
  int rc = SQLITE_OK;             /* Return code */
  Fts5Config *pRet;               /* New object to return */
  int i;
  sqlite3_int64 nByte;


  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  if( pRet==0 ) return SQLITE_NOMEM;
  memset(pRet, 0, sizeof(Fts5Config));
  pRet->pGlobal = pGlobal;
  pRet->db = db;
  pRet->iCookie = -1;







>







237821
237822
237823
237824
237825
237826
237827
237828
237829
237830
237831
237832
237833
237834
237835
  Fts5Config **ppOut,             /* OUT: Results of parse */
  char **pzErr                    /* OUT: Error message */
){
  int rc = SQLITE_OK;             /* Return code */
  Fts5Config *pRet;               /* New object to return */
  int i;
  sqlite3_int64 nByte;
  int bUnindexed = 0;             /* True if there are one or more UNINDEXED */

  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  if( pRet==0 ) return SQLITE_NOMEM;
  memset(pRet, 0, sizeof(Fts5Config));
  pRet->pGlobal = pGlobal;
  pRet->db = db;
  pRet->iCookie = -1;
237826
237827
237828
237829
237830
237831
237832
237833
237834
237835
237836
237837
237838
237839
237840
        if( bOption ){
          rc = fts5ConfigParseSpecial(pRet,
            ALWAYS(zOne)?zOne:"",
            zTwo?zTwo:"",
            pzErr
          );
        }else{
          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
          zOne = 0;
        }
      }
    }

    sqlite3_free(zOne);
    sqlite3_free(zTwo);







|







237881
237882
237883
237884
237885
237886
237887
237888
237889
237890
237891
237892
237893
237894
237895
        if( bOption ){
          rc = fts5ConfigParseSpecial(pRet,
            ALWAYS(zOne)?zOne:"",
            zTwo?zTwo:"",
            pzErr
          );
        }else{
          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr, &bUnindexed);
          zOne = 0;
        }
      }
    }

    sqlite3_free(zOne);
    sqlite3_free(zTwo);
237857
237858
237859
237860
237861
237862
237863













237864
237865
237866
237867
237868
237869
237870
237871



237872
237873
237874
237875
237876
237877
237878
  */
  if( rc==SQLITE_OK && pRet->bContentlessDelete && pRet->bColumnsize==0 ){
    *pzErr = sqlite3_mprintf(
        "contentless_delete=1 is incompatible with columnsize=0"
    );
    rc = SQLITE_ERROR;
  }














  /* If no zContent option was specified, fill in the default values. */
  if( rc==SQLITE_OK && pRet->zContent==0 ){
    const char *zTail = 0;
    assert( pRet->eContent==FTS5_CONTENT_NORMAL
         || pRet->eContent==FTS5_CONTENT_NONE
    );
    if( pRet->eContent==FTS5_CONTENT_NORMAL ){



      zTail = "content";
    }else if( pRet->bColumnsize ){
      zTail = "docsize";
    }

    if( zTail ){
      pRet->zContent = sqlite3Fts5Mprintf(







>
>
>
>
>
>
>
>
>
>
>
>
>








>
>
>







237912
237913
237914
237915
237916
237917
237918
237919
237920
237921
237922
237923
237924
237925
237926
237927
237928
237929
237930
237931
237932
237933
237934
237935
237936
237937
237938
237939
237940
237941
237942
237943
237944
237945
237946
237947
237948
237949
  */
  if( rc==SQLITE_OK && pRet->bContentlessDelete && pRet->bColumnsize==0 ){
    *pzErr = sqlite3_mprintf(
        "contentless_delete=1 is incompatible with columnsize=0"
    );
    rc = SQLITE_ERROR;
  }

  /* We only allow contentless_unindexed=1 if the table is actually a
  ** contentless one.
  */
  if( rc==SQLITE_OK
   && pRet->bContentlessUnindexed
   && pRet->eContent!=FTS5_CONTENT_NONE
  ){
    *pzErr = sqlite3_mprintf(
        "contentless_unindexed=1 requires a contentless table"
    );
    rc = SQLITE_ERROR;
  }

  /* If no zContent option was specified, fill in the default values. */
  if( rc==SQLITE_OK && pRet->zContent==0 ){
    const char *zTail = 0;
    assert( pRet->eContent==FTS5_CONTENT_NORMAL
         || pRet->eContent==FTS5_CONTENT_NONE
    );
    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
      zTail = "content";
    }else if( bUnindexed && pRet->bContentlessUnindexed ){
      pRet->eContent = FTS5_CONTENT_UNINDEXED;
      zTail = "content";
    }else if( pRet->bColumnsize ){
      zTail = "docsize";
    }

    if( zTail ){
      pRet->zContent = sqlite3Fts5Mprintf(
247039
247040
247041
247042
247043
247044
247045





247046
247047
247048
247049
247050
247051
247052
      if( nEntry>0 ){
        int nPercent = (nTomb * 100) / nEntry;
        if( nPercent>=pConfig->nDeleteMerge && nPercent>nBest ){
          iRet = ii;
          nBest = nPercent;
        }
      }





    }
  }
  return iRet;
}

/*
** Do up to nPg pages of automerge work on the index.







>
>
>
>
>







247110
247111
247112
247113
247114
247115
247116
247117
247118
247119
247120
247121
247122
247123
247124
247125
247126
247127
247128
      if( nEntry>0 ){
        int nPercent = (nTomb * 100) / nEntry;
        if( nPercent>=pConfig->nDeleteMerge && nPercent>nBest ){
          iRet = ii;
          nBest = nPercent;
        }
      }

      /* If pLvl is already the input level to an ongoing merge, look no
      ** further for a merge candidate. The caller should be allowed to
      ** continue merging from pLvl first.  */
      if( pLvl->nMerge ) break;
    }
  }
  return iRet;
}

/*
** Do up to nPg pages of automerge work on the index.
250963
250964
250965
250966
250967
250968
250969
250970
250971
250972
250973
250974
250975
250976
250977

  *ppVtab = (sqlite3_vtab*)pNew;
  return rc;
}

/*
** We must have a single struct=? constraint that will be passed through
** into the xFilter method.  If there is no valid stmt=? constraint,
** then return an SQLITE_CONSTRAINT error.
*/
static int fts5structBestIndexMethod(
  sqlite3_vtab *tab,
  sqlite3_index_info *pIdxInfo
){
  int i;







|







251039
251040
251041
251042
251043
251044
251045
251046
251047
251048
251049
251050
251051
251052
251053

  *ppVtab = (sqlite3_vtab*)pNew;
  return rc;
}

/*
** We must have a single struct=? constraint that will be passed through
** into the xFilter method.  If there is no valid struct=? constraint,
** then return an SQLITE_CONSTRAINT error.
*/
static int fts5structBestIndexMethod(
  sqlite3_vtab *tab,
  sqlite3_index_info *pIdxInfo
){
  int i;
251554
251555
251556
251557
251558
251559
251560
251561


251562
251563


251564


251565
251566
251567
251568
251569
251570
251571
  }
}
#else
# define fts5CheckTransactionState(x,y,z)
#endif

/*
** Return true if pTab is a contentless table.


*/
static int fts5IsContentless(Fts5FullTable *pTab){


  return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;


}

/*
** Delete a virtual table handle allocated by fts5InitVtab().
*/
static void fts5FreeVtab(Fts5FullTable *pTab){
  if( pTab ){







|
>
>

|
>
>
|
>
>







251630
251631
251632
251633
251634
251635
251636
251637
251638
251639
251640
251641
251642
251643
251644
251645
251646
251647
251648
251649
251650
251651
251652
251653
  }
}
#else
# define fts5CheckTransactionState(x,y,z)
#endif

/*
** Return true if pTab is a contentless table. If parameter bIncludeUnindexed
** is true, this includes contentless tables that store UNINDEXED columns
** only.
*/
static int fts5IsContentless(Fts5FullTable *pTab, int bIncludeUnindexed){
  int eContent = pTab->p.pConfig->eContent;
  return (
    eContent==FTS5_CONTENT_NONE
    || (bIncludeUnindexed && eContent==FTS5_CONTENT_UNINDEXED)
  );
}

/*
** Delete a virtual table handle allocated by fts5InitVtab().
*/
static void fts5FreeVtab(Fts5FullTable *pTab){
  if( pTab ){
252948
252949
252950
252951
252952
252953
252954
252955
252956
252957
252958
252959
252960
252961
252962
      );
      rc = SQLITE_ERROR;
    }else{
      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
    }
    bLoadConfig = 1;
  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
    if( pConfig->eContent==FTS5_CONTENT_NONE ){
      fts5SetVtabError(pTab,
          "'rebuild' may not be used with a contentless fts5 table"
      );
      rc = SQLITE_ERROR;
    }else{
      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
    }







|







253030
253031
253032
253033
253034
253035
253036
253037
253038
253039
253040
253041
253042
253043
253044
      );
      rc = SQLITE_ERROR;
    }else{
      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
    }
    bLoadConfig = 1;
  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
    if( fts5IsContentless(pTab, 1) ){
      fts5SetVtabError(pTab,
          "'rebuild' may not be used with a contentless fts5 table"
      );
      rc = SQLITE_ERROR;
    }else{
      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
    }
253017
253018
253019
253020
253021
253022
253023
253024
253025
253026
253027
253028
253029
253030





























































253031
253032
253033
253034
253035
253036
253037
  int *pRc,
  Fts5FullTable *pTab,
  sqlite3_value **apVal,
  i64 *piRowid
){
  int rc = *pRc;
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  }
  *pRc = rc;
}






























































/*
** This function is the implementation of the xUpdate callback used by
** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
** inserted, updated or deleted.
**
** A delete specifies a single argument - the rowid of the row to remove.







|






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







253099
253100
253101
253102
253103
253104
253105
253106
253107
253108
253109
253110
253111
253112
253113
253114
253115
253116
253117
253118
253119
253120
253121
253122
253123
253124
253125
253126
253127
253128
253129
253130
253131
253132
253133
253134
253135
253136
253137
253138
253139
253140
253141
253142
253143
253144
253145
253146
253147
253148
253149
253150
253151
253152
253153
253154
253155
253156
253157
253158
253159
253160
253161
253162
253163
253164
253165
253166
253167
253168
253169
253170
253171
253172
253173
253174
253175
253176
253177
253178
253179
253180
  int *pRc,
  Fts5FullTable *pTab,
  sqlite3_value **apVal,
  i64 *piRowid
){
  int rc = *pRc;
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, 0, apVal, piRowid);
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  }
  *pRc = rc;
}

/*
**
** This function is called when the user attempts an UPDATE on a contentless
** table. Parameter bRowidModified is true if the UPDATE statement modifies
** the rowid value. Parameter apVal[] contains the new values for each user
** defined column of the fts5 table. pConfig is the configuration object of the
** table being updated (guaranteed to be contentless). The contentless_delete=1
** and contentless_unindexed=1 options may or may not be set.
**
** This function returns SQLITE_OK if the UPDATE can go ahead, or an SQLite
** error code if it cannot. In this case an error message is also loaded into
** pConfig. Output parameter (*pbContent) is set to true if the caller should
** update the %_content table only - not the FTS index or any other shadow
** table. This occurs when an UPDATE modifies only UNINDEXED columns of the
** table.
**
** An UPDATE may proceed if:
**
**   * The only columns modified are UNINDEXED columns, or
**
**   * The contentless_delete=1 option was specified and all of the indexed
**     columns (not a subset) have been modified.
*/
static int fts5ContentlessUpdate(
  Fts5Config *pConfig,
  sqlite3_value **apVal,
  int bRowidModified,
  int *pbContent
){
  int ii;
  int bSeenIndex = 0;             /* Have seen modified indexed column */
  int bSeenIndexNC = 0;           /* Have seen unmodified indexed column */
  int rc = SQLITE_OK;

  for(ii=0; ii<pConfig->nCol; ii++){
    if( pConfig->abUnindexed[ii]==0 ){
      if( sqlite3_value_nochange(apVal[ii]) ){
        bSeenIndexNC++;
      }else{
        bSeenIndex++;
      }
    }
  }

  if( bSeenIndex==0 && bRowidModified==0 ){
    *pbContent = 1;
  }else{
    if( bSeenIndexNC || pConfig->bContentlessDelete==0 ){
      rc = SQLITE_ERROR;
      sqlite3Fts5ConfigErrmsg(pConfig,
          (pConfig->bContentlessDelete ?
          "%s a subset of columns on fts5 contentless-delete table: %s" :
          "%s contentless fts5 table: %s")
          , "cannot UPDATE", pConfig->zName
      );
    }
  }

  return rc;
}

/*
** This function is the implementation of the xUpdate callback used by
** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
** inserted, updated or deleted.
**
** A delete specifies a single argument - the rowid of the row to remove.
253111
253112
253113
253114
253115
253116
253117


253118
253119
253120
253121
253122
253123
253124
253125
253126
253127
253128
253129
253130
253131
253132
253133
253134
253135
253136

253137
253138
253139
253140
253141
253142
253143
    if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->bContentlessDelete ){
      eConflict = sqlite3_vtab_on_conflict(pConfig->db);
    }

    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
    assert( nArg!=1 || eType0==SQLITE_INTEGER );



    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
    ** This is not suported. Except - they are both supported if the CREATE
    ** VIRTUAL TABLE statement contained "contentless_delete=1". */
    if( eType0==SQLITE_INTEGER
     && pConfig->eContent==FTS5_CONTENT_NONE
     && pConfig->bContentlessDelete==0
    ){
      pTab->p.base.zErrMsg = sqlite3_mprintf(
          "cannot %s contentless fts5 table: %s",
          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
      );
      rc = SQLITE_ERROR;
    }

    /* DELETE */
    else if( nArg==1 ){
      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0, 0);
      bUpdateOrDelete = 1;

    }

    /* INSERT or UPDATE */
    else{
      int eType1 = sqlite3_value_numeric_type(apVal[1]);

      /* It is an error to write an fts5_locale() value to a table without







>
>
|
<
|
<
<
|
<
|
|
<
|
|
|
<
<
<
|
|
|
>







253254
253255
253256
253257
253258
253259
253260
253261
253262
253263

253264


253265

253266
253267

253268
253269
253270



253271
253272
253273
253274
253275
253276
253277
253278
253279
253280
253281
    if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->bContentlessDelete ){
      eConflict = sqlite3_vtab_on_conflict(pConfig->db);
    }

    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
    assert( nArg!=1 || eType0==SQLITE_INTEGER );

    /* DELETE */
    if( nArg==1 ){
      /* It is only possible to DELETE from a contentless table if the

      ** contentless_delete=1 flag is set. */


      if( fts5IsContentless(pTab, 1) && pConfig->bContentlessDelete==0 ){

        fts5SetVtabError(pTab,
            "cannot DELETE from contentless fts5 table: %s", pConfig->zName

        );
        rc = SQLITE_ERROR;
      }else{



        i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0, 0);
        bUpdateOrDelete = 1;
      }
    }

    /* INSERT or UPDATE */
    else{
      int eType1 = sqlite3_value_numeric_type(apVal[1]);

      /* It is an error to write an fts5_locale() value to a table without
253163
253164
253165
253166
253167
253168
253169

253170
253171









253172
253173
253174

253175
253176
253177
253178
253179
253180
253181
253182
253183
253184
253185
253186
253187
253188
253189
253190
253191
253192









253193
253194
253195
253196
253197
253198
253199
253200
253201
253202
253203
253204
253205
          bUpdateOrDelete = 1;
        }
        fts5StorageInsert(&rc, pTab, apVal, pRowid);
      }

      /* UPDATE */
      else{

        i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
        i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */









        if( eType1!=SQLITE_INTEGER ){
          rc = SQLITE_MISMATCH;
        }else if( iOld!=iNew ){

          if( eConflict==SQLITE_REPLACE ){
            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0, 1);
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0, 0);
            }
            fts5StorageInsert(&rc, pTab, apVal, pRowid);
          }else{
            rc = sqlite3Fts5StorageFindDeleteRow(pTab->pStorage, iOld);
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageContentInsert(pTab->pStorage,apVal,pRowid);
            }
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0, 1);
            }
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
            }
          }









        }else{
          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0, 1);
          fts5StorageInsert(&rc, pTab, apVal, pRowid);
        }
        bUpdateOrDelete = 1;
        sqlite3Fts5StorageReleaseDeleteRow(pTab->pStorage);
      }

    }
  }

  if( rc==SQLITE_OK
   && bUpdateOrDelete







>


>
>
>
>
>
>
>
>
>



>

|

|



|

|


|


|


>
>
>
>
>
>
>
>
>

|



|







253301
253302
253303
253304
253305
253306
253307
253308
253309
253310
253311
253312
253313
253314
253315
253316
253317
253318
253319
253320
253321
253322
253323
253324
253325
253326
253327
253328
253329
253330
253331
253332
253333
253334
253335
253336
253337
253338
253339
253340
253341
253342
253343
253344
253345
253346
253347
253348
253349
253350
253351
253352
253353
253354
253355
253356
253357
253358
253359
253360
253361
253362
253363
          bUpdateOrDelete = 1;
        }
        fts5StorageInsert(&rc, pTab, apVal, pRowid);
      }

      /* UPDATE */
      else{
        Fts5Storage *pStorage = pTab->pStorage;
        i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
        i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
        int bContent = 0;         /* Content only update */

        /* If this is a contentless table (including contentless_unindexed=1
        ** tables), check if the UPDATE may proceed.  */
        if( fts5IsContentless(pTab, 1) ){
          rc = fts5ContentlessUpdate(pConfig, &apVal[2], iOld!=iNew, &bContent);
          if( rc!=SQLITE_OK ) goto update_out;
        }

        if( eType1!=SQLITE_INTEGER ){
          rc = SQLITE_MISMATCH;
        }else if( iOld!=iNew ){
          assert( bContent==0 );
          if( eConflict==SQLITE_REPLACE ){
            rc = sqlite3Fts5StorageDelete(pStorage, iOld, 0, 1);
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageDelete(pStorage, iNew, 0, 0);
            }
            fts5StorageInsert(&rc, pTab, apVal, pRowid);
          }else{
            rc = sqlite3Fts5StorageFindDeleteRow(pStorage, iOld);
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageContentInsert(pStorage, 0, apVal, pRowid);
            }
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageDelete(pStorage, iOld, 0, 0);
            }
            if( rc==SQLITE_OK ){
              rc = sqlite3Fts5StorageIndexInsert(pStorage, apVal, *pRowid);
            }
          }
        }else if( bContent ){
          /* This occurs when an UPDATE on a contentless table affects *only*
          ** UNINDEXED columns. This is a no-op for contentless_unindexed=0
          ** tables, or a write to the %_content table only for =1 tables.  */
          assert( fts5IsContentless(pTab, 1) );
          rc = sqlite3Fts5StorageFindDeleteRow(pStorage, iOld);
          if( rc==SQLITE_OK ){
            rc = sqlite3Fts5StorageContentInsert(pStorage, 1, apVal, pRowid);
          }
        }else{
          rc = sqlite3Fts5StorageDelete(pStorage, iOld, 0, 1);
          fts5StorageInsert(&rc, pTab, apVal, pRowid);
        }
        bUpdateOrDelete = 1;
        sqlite3Fts5StorageReleaseDeleteRow(pStorage);
      }

    }
  }

  if( rc==SQLITE_OK
   && bUpdateOrDelete
253392
253393
253394
253395
253396
253397
253398
253399
253400
253401
253402
253403
253404
253405
253406
  int rc = SQLITE_OK;
  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);

  assert( pCsr->ePlan!=FTS5_PLAN_SPECIAL );
  if( iCol<0 || iCol>=pTab->pConfig->nCol ){
    rc = SQLITE_RANGE;
  }else if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab)) ){
    *pz = 0;
    *pn = 0;
  }else{
    rc = fts5SeekCursor(pCsr, 0);
    if( rc==SQLITE_OK ){
      rc = fts5TextFromStmt(pTab->pConfig, pCsr->pStmt, iCol, pz, pn);
      sqlite3Fts5ClearLocale(pTab->pConfig);







|







253550
253551
253552
253553
253554
253555
253556
253557
253558
253559
253560
253561
253562
253563
253564
  int rc = SQLITE_OK;
  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);

  assert( pCsr->ePlan!=FTS5_PLAN_SPECIAL );
  if( iCol<0 || iCol>=pTab->pConfig->nCol ){
    rc = SQLITE_RANGE;
  }else if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab), 0) ){
    *pz = 0;
    *pn = 0;
  }else{
    rc = fts5SeekCursor(pCsr, 0);
    if( rc==SQLITE_OK ){
      rc = fts5TextFromStmt(pTab->pConfig, pCsr->pStmt, iCol, pz, pn);
      sqlite3Fts5ClearLocale(pTab->pConfig);
253425
253426
253427
253428
253429
253430
253431
253432
253433
253434
253435
253436
253437
253438
253439
  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  int rc = SQLITE_OK;
  int bLive = (pCsr->pSorter==0);

  if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){
    rc = SQLITE_RANGE;
  }else if( pConfig->eDetail!=FTS5_DETAIL_FULL
         && pConfig->eContent==FTS5_CONTENT_NONE
  ){
    *pa = 0;
    *pn = 0;
    return SQLITE_OK;
  }else if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
      Fts5PoslistPopulator *aPopulator;







|







253583
253584
253585
253586
253587
253588
253589
253590
253591
253592
253593
253594
253595
253596
253597
  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  int rc = SQLITE_OK;
  int bLive = (pCsr->pSorter==0);

  if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){
    rc = SQLITE_RANGE;
  }else if( pConfig->eDetail!=FTS5_DETAIL_FULL
         && fts5IsContentless((Fts5FullTable*)pCsr->base.pVtab, 1)
  ){
    *pa = 0;
    *pn = 0;
    return SQLITE_OK;
  }else if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
      Fts5PoslistPopulator *aPopulator;
253621
253622
253623
253624
253625
253626
253627
253628
253629
253630
253631
253632
253633
253634
253635
  Fts5Config *pConfig = pTab->p.pConfig;
  int rc = SQLITE_OK;

  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
    if( pConfig->bColumnsize ){
      i64 iRowid = fts5CursorRowid(pCsr);
      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
    }else if( pConfig->zContent==0 ){
      int i;
      for(i=0; i<pConfig->nCol; i++){
        if( pConfig->abUnindexed[i]==0 ){
          pCsr->aColumnSize[i] = -1;
        }
      }
    }else{







|







253779
253780
253781
253782
253783
253784
253785
253786
253787
253788
253789
253790
253791
253792
253793
  Fts5Config *pConfig = pTab->p.pConfig;
  int rc = SQLITE_OK;

  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
    if( pConfig->bColumnsize ){
      i64 iRowid = fts5CursorRowid(pCsr);
      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
    }else if( !pConfig->zContent || pConfig->eContent==FTS5_CONTENT_UNINDEXED ){
      int i;
      for(i=0; i<pConfig->nCol; i++){
        if( pConfig->abUnindexed[i]==0 ){
          pCsr->aColumnSize[i] = -1;
        }
      }
    }else{
253909
253910
253911
253912
253913
253914
253915
253916
253917
253918
253919
253920
253921
253922
253923
  *pnLocale = 0;

  assert( pCsr->ePlan!=FTS5_PLAN_SPECIAL );
  if( iCol<0 || iCol>=pConfig->nCol ){
    rc = SQLITE_RANGE;
  }else if(
      pConfig->abUnindexed[iCol]==0
   && pConfig->eContent!=FTS5_CONTENT_NONE
   && pConfig->bLocale
  ){
    rc = fts5SeekCursor(pCsr, 0);
    if( rc==SQLITE_OK ){
      const char *zDummy = 0;
      int nDummy = 0;
      rc = fts5TextFromStmt(pConfig, pCsr->pStmt, iCol, &zDummy, &nDummy);







|







254067
254068
254069
254070
254071
254072
254073
254074
254075
254076
254077
254078
254079
254080
254081
  *pnLocale = 0;

  assert( pCsr->ePlan!=FTS5_PLAN_SPECIAL );
  if( iCol<0 || iCol>=pConfig->nCol ){
    rc = SQLITE_RANGE;
  }else if(
      pConfig->abUnindexed[iCol]==0
   && 0==fts5IsContentless((Fts5FullTable*)pCsr->base.pVtab, 1)
   && pConfig->bLocale
  ){
    rc = fts5SeekCursor(pCsr, 0);
    if( rc==SQLITE_OK ){
      const char *zDummy = 0;
      int nDummy = 0;
      rc = fts5TextFromStmt(pConfig, pCsr->pStmt, iCol, &zDummy, &nDummy);
254184
254185
254186
254187
254188
254189
254190
254191
254192
254193
254194
254195
254196
254197
254198
254199
254200
254201
254202
254203
254204
254205
254206
254207
     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
    ){
      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
      }
    }
  }else{
    /* A column created by the user containing values. */
    int bNochange = sqlite3_vtab_nochange(pCtx);

    if( fts5IsContentless(pTab) ){
      if( bNochange && pConfig->bContentlessDelete ){
        fts5ResultError(pCtx, "cannot UPDATE a subset of "
            "columns on fts5 contentless-delete table: %s", pConfig->zName
        );
      }
    }else if( bNochange==0 || pConfig->eContent!=FTS5_CONTENT_NORMAL ){
      pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
      rc = fts5SeekCursor(pCsr, 1);
      if( rc==SQLITE_OK ){
        sqlite3_value *pVal = sqlite3_column_value(pCsr->pStmt, iCol+1);
        if( pConfig->bLocale
         && pConfig->eContent==FTS5_CONTENT_EXTERNAL
         && sqlite3Fts5IsLocaleValue(pConfig, pVal)







<
|
<
<
<
<
<
<
<
<







254342
254343
254344
254345
254346
254347
254348

254349








254350
254351
254352
254353
254354
254355
254356
     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
    ){
      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
      }
    }
  }else{

    if( !sqlite3_vtab_nochange(pCtx) && pConfig->eContent!=FTS5_CONTENT_NONE ){








      pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
      rc = fts5SeekCursor(pCsr, 1);
      if( rc==SQLITE_OK ){
        sqlite3_value *pVal = sqlite3_column_value(pCsr->pStmt, iCol+1);
        if( pConfig->bLocale
         && pConfig->eContent==FTS5_CONTENT_EXTERNAL
         && sqlite3Fts5IsLocaleValue(pConfig, pVal)
254736
254737
254738
254739
254740
254741
254742
254743
254744
254745
254746
254747
254748
254749
254750
static void fts5SourceIdFunc(
  sqlite3_context *pCtx,          /* Function call context */
  int nArg,                       /* Number of args */
  sqlite3_value **apUnused        /* Function arguments */
){
  assert( nArg==0 );
  UNUSED_PARAM2(nArg, apUnused);
  sqlite3_result_text(pCtx, "fts5: 2024-09-26 19:38:34 f97f9944b829a49da12786f934da0a5ad51591afd6d8a19a4a0835f51bbdbff2", -1, SQLITE_TRANSIENT);
}

/*
** Implementation of fts5_locale(LOCALE, TEXT) function.
**
** If parameter LOCALE is NULL, or a zero-length string, then a copy of
** TEXT is returned. Otherwise, both LOCALE and TEXT are interpreted as







|







254885
254886
254887
254888
254889
254890
254891
254892
254893
254894
254895
254896
254897
254898
254899
static void fts5SourceIdFunc(
  sqlite3_context *pCtx,          /* Function call context */
  int nArg,                       /* Number of args */
  sqlite3_value **apUnused        /* Function arguments */
){
  assert( nArg==0 );
  UNUSED_PARAM2(nArg, apUnused);
  sqlite3_result_text(pCtx, "fts5: 2024-10-18 10:51:43 5f0cc7f26453faaea20a7bb0a1bcbab381a9bae7a81e099bb27f4b05fac1cd6c", -1, SQLITE_TRANSIENT);
}

/*
** Implementation of fts5_locale(LOCALE, TEXT) function.
**
** If parameter LOCALE is NULL, or a zero-length string, then a copy of
** TEXT is returned. Otherwise, both LOCALE and TEXT are interpreted as
255064
255065
255066
255067
255068
255069
255070
255071
255072
255073
255074
255075
255076
255077
255078
255079
255080
255081
255082
255083
255084
255085
255086
255087
255088
255089
255090
255091
255092
255093
255094
255095
255096
255097
255098
255099
255100
255101
#define FTS5_STMT_DELETE_CONTENT  6
#define FTS5_STMT_REPLACE_DOCSIZE 7
#define FTS5_STMT_DELETE_DOCSIZE  8
#define FTS5_STMT_LOOKUP_DOCSIZE  9
#define FTS5_STMT_REPLACE_CONFIG 10
#define FTS5_STMT_SCAN           11

/*
** Return a pointer to a buffer obtained from sqlite3_malloc() that contains
** nBind comma-separated question marks. e.g. if nBind is passed 5, this
** function returns "?,?,?,?,?".
**
** If *pRc is not SQLITE_OK when this function is called, it is a no-op and
** NULL is returned immediately. Or, if the attempt to malloc a buffer
** fails, then *pRc is set to SQLITE_NOMEM and NULL is returned. Otherwise,
** if it is SQLITE_OK when this function is called and the malloc() succeeds,
** *pRc is left unchanged.
*/
static char *fts5BindingsList(int *pRc, int nBind){
  char *zBind = sqlite3Fts5MallocZero(pRc, 1 + nBind*2);
  if( zBind ){
    int ii;
    for(ii=0; ii<nBind; ii++){
      zBind[ii*2] = '?';
      zBind[ii*2 + 1] = ',';
    }
    zBind[ii*2-1] = '\0';
  }
  return zBind;
}

/*
** Prepare the two insert statements - Fts5Storage.pInsertContent and
** Fts5Storage.pInsertDocsize - if they have not already been prepared.
** Return SQLITE_OK if successful, or an SQLite error code if an error
** occurs.
*/
static int fts5StorageGetStmt(







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







255213
255214
255215
255216
255217
255218
255219
























255220
255221
255222
255223
255224
255225
255226
#define FTS5_STMT_DELETE_CONTENT  6
#define FTS5_STMT_REPLACE_DOCSIZE 7
#define FTS5_STMT_DELETE_DOCSIZE  8
#define FTS5_STMT_LOOKUP_DOCSIZE  9
#define FTS5_STMT_REPLACE_CONFIG 10
#define FTS5_STMT_SCAN           11

























/*
** Prepare the two insert statements - Fts5Storage.pInsertContent and
** Fts5Storage.pInsertDocsize - if they have not already been prepared.
** Return SQLITE_OK if successful, or an SQLite error code if an error
** occurs.
*/
static int fts5StorageGetStmt(
255156
255157
255158
255159
255160
255161
255162
255163
255164
255165
255166
255167



255168












255169
255170
255171

255172
255173
255174
255175
255176
255177
255178
255179
255180
255181
255182
255183
255184
255185
255186
      case FTS5_STMT_LOOKUP:
      case FTS5_STMT_LOOKUP2:
        zSql = sqlite3_mprintf(azStmt[eStmt],
            pC->zContentExprlist, pC->zContent, pC->zContentRowid
        );
        break;

      case FTS5_STMT_INSERT_CONTENT: {
        int nCol = 0;
        char *zBind;
        int i;




        nCol = 1 + pC->nCol;












        if( pC->bLocale ){
          for(i=0; i<pC->nCol; i++){
            if( pC->abUnindexed[i]==0 ) nCol++;

          }
        }

        zBind = fts5BindingsList(&rc, nCol);
        if( zBind ){
          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
          sqlite3_free(zBind);
        }
        break;
      }

      case FTS5_STMT_REPLACE_DOCSIZE:
        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName,
          (pC->bContentlessDelete ? ",?" : "")
        );







|
|
|


>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
>
|
|
|
|
<
|
|
<







255281
255282
255283
255284
255285
255286
255287
255288
255289
255290
255291
255292
255293
255294
255295
255296
255297
255298
255299
255300
255301
255302
255303
255304
255305
255306
255307
255308
255309
255310
255311
255312
255313
255314
255315
255316

255317
255318

255319
255320
255321
255322
255323
255324
255325
      case FTS5_STMT_LOOKUP:
      case FTS5_STMT_LOOKUP2:
        zSql = sqlite3_mprintf(azStmt[eStmt],
            pC->zContentExprlist, pC->zContent, pC->zContentRowid
        );
        break;

      case FTS5_STMT_INSERT_CONTENT:
      case FTS5_STMT_REPLACE_CONTENT: {
        char *zBind = 0;
        int i;

        assert( pC->eContent==FTS5_CONTENT_NORMAL
             || pC->eContent==FTS5_CONTENT_UNINDEXED
        );

        /* Add bindings for the "c*" columns - those that store the actual
        ** table content. If eContent==NORMAL, then there is one binding
        ** for each column. Or, if eContent==UNINDEXED, then there are only
        ** bindings for the UNINDEXED columns. */
        for(i=0; rc==SQLITE_OK && i<(pC->nCol+1); i++){
          if( !i || pC->eContent==FTS5_CONTENT_NORMAL || pC->abUnindexed[i-1] ){
            zBind = sqlite3Fts5Mprintf(&rc, "%z%s?%d", zBind, zBind?",":"",i+1);
          }
        }

        /* Add bindings for any "l*" columns. Only non-UNINDEXED columns
        ** require these.  */
        if( pC->bLocale && pC->eContent==FTS5_CONTENT_NORMAL ){
          for(i=0; rc==SQLITE_OK && i<pC->nCol; i++){
            if( pC->abUnindexed[i]==0 ){
              zBind = sqlite3Fts5Mprintf(&rc, "%z,?%d", zBind, pC->nCol+i+2);
            }
          }
        }


        zSql = sqlite3Fts5Mprintf(&rc, azStmt[eStmt], pC->zDb, pC->zName,zBind);
        sqlite3_free(zBind);

        break;
      }

      case FTS5_STMT_REPLACE_DOCSIZE:
        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName,
          (pC->bContentlessDelete ? ",?" : "")
        );
255358
255359
255360
255361
255362
255363
255364
255365


255366
255367
255368
255369
255370
255371
255372
255373
255374
255375



255376
255377

255378
255379
255380
255381
255382
255383
255384

  memset(p, 0, (size_t)nByte);
  p->aTotalSize = (i64*)&p[1];
  p->pConfig = pConfig;
  p->pIndex = pIndex;

  if( bCreate ){
    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){


      int nDefn = 32 + pConfig->nCol*10;
      char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 20);
      if( zDefn==0 ){
        rc = SQLITE_NOMEM;
      }else{
        int i;
        int iOff;
        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
        iOff = (int)strlen(zDefn);
        for(i=0; i<pConfig->nCol; i++){



          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
          iOff += (int)strlen(&zDefn[iOff]);

        }
        if( pConfig->bLocale ){
          for(i=0; i<pConfig->nCol; i++){
            if( pConfig->abUnindexed[i]==0 ){
              sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", l%d", i);
              iOff += (int)strlen(&zDefn[iOff]);
            }







|
>
>










>
>
>
|
|
>







255497
255498
255499
255500
255501
255502
255503
255504
255505
255506
255507
255508
255509
255510
255511
255512
255513
255514
255515
255516
255517
255518
255519
255520
255521
255522
255523
255524
255525
255526
255527
255528
255529

  memset(p, 0, (size_t)nByte);
  p->aTotalSize = (i64*)&p[1];
  p->pConfig = pConfig;
  p->pIndex = pIndex;

  if( bCreate ){
    if( pConfig->eContent==FTS5_CONTENT_NORMAL
     || pConfig->eContent==FTS5_CONTENT_UNINDEXED
    ){
      int nDefn = 32 + pConfig->nCol*10;
      char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 20);
      if( zDefn==0 ){
        rc = SQLITE_NOMEM;
      }else{
        int i;
        int iOff;
        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
        iOff = (int)strlen(zDefn);
        for(i=0; i<pConfig->nCol; i++){
          if( pConfig->eContent==FTS5_CONTENT_NORMAL
           || pConfig->abUnindexed[i]
          ){
            sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
            iOff += (int)strlen(&zDefn[iOff]);
          }
        }
        if( pConfig->bLocale ){
          for(i=0; i<pConfig->nCol; i++){
            if( pConfig->abUnindexed[i]==0 ){
              sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", l%d", i);
              iOff += (int)strlen(&zDefn[iOff]);
            }
255608
255609
255610
255611
255612
255613
255614
255615


255616
255617
255618
255619
255620
255621
255622
*/
static int fts5StorageContentlessDelete(Fts5Storage *p, i64 iDel){
  i64 iOrigin = 0;
  sqlite3_stmt *pLookup = 0;
  int rc = SQLITE_OK;

  assert( p->pConfig->bContentlessDelete );
  assert( p->pConfig->eContent==FTS5_CONTENT_NONE );



  /* Look up the origin of the document in the %_docsize table. Store
  ** this in stack variable iOrigin.  */
  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  if( rc==SQLITE_OK ){
    sqlite3_bind_int64(pLookup, 1, iDel);
    if( SQLITE_ROW==sqlite3_step(pLookup) ){







|
>
>







255753
255754
255755
255756
255757
255758
255759
255760
255761
255762
255763
255764
255765
255766
255767
255768
255769
*/
static int fts5StorageContentlessDelete(Fts5Storage *p, i64 iDel){
  i64 iOrigin = 0;
  sqlite3_stmt *pLookup = 0;
  int rc = SQLITE_OK;

  assert( p->pConfig->bContentlessDelete );
  assert( p->pConfig->eContent==FTS5_CONTENT_NONE
       || p->pConfig->eContent==FTS5_CONTENT_UNINDEXED
  );

  /* Look up the origin of the document in the %_docsize table. Store
  ** this in stack variable iOrigin.  */
  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  if( rc==SQLITE_OK ){
    sqlite3_bind_int64(pLookup, 1, iDel);
    if( SQLITE_ROW==sqlite3_step(pLookup) ){
255732
255733
255734
255735
255736
255737
255738






255739
255740
255741
255742
255743
255744
255745
255746
255747
255748
255749
255750
255751
255752
255753
255754
255755


255756
255757
255758
255759
255760
255761
255762
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  }

  if( rc==SQLITE_OK ){
    if( p->pConfig->bContentlessDelete ){
      rc = fts5StorageContentlessDelete(p, iDel);






    }else{
      rc = fts5StorageDeleteFromIndex(p, iDel, apVal, bSaveRow);
    }
  }

  /* Delete the %_docsize record */
  if( rc==SQLITE_OK && pConfig->bColumnsize ){
    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
    if( rc==SQLITE_OK ){
      sqlite3_bind_int64(pDel, 1, iDel);
      sqlite3_step(pDel);
      rc = sqlite3_reset(pDel);
    }
  }

  /* Delete the %_content record */
  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){


    if( rc==SQLITE_OK ){
      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
    }
    if( rc==SQLITE_OK ){
      sqlite3_bind_int64(pDel, 1, iDel);
      sqlite3_step(pDel);
      rc = sqlite3_reset(pDel);







>
>
>
>
>
>
















|
>
>







255879
255880
255881
255882
255883
255884
255885
255886
255887
255888
255889
255890
255891
255892
255893
255894
255895
255896
255897
255898
255899
255900
255901
255902
255903
255904
255905
255906
255907
255908
255909
255910
255911
255912
255913
255914
255915
255916
255917
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  }

  if( rc==SQLITE_OK ){
    if( p->pConfig->bContentlessDelete ){
      rc = fts5StorageContentlessDelete(p, iDel);
      if( rc==SQLITE_OK
       && bSaveRow
       && p->pConfig->eContent==FTS5_CONTENT_UNINDEXED
      ){
        rc = sqlite3Fts5StorageFindDeleteRow(p, iDel);
      }
    }else{
      rc = fts5StorageDeleteFromIndex(p, iDel, apVal, bSaveRow);
    }
  }

  /* Delete the %_docsize record */
  if( rc==SQLITE_OK && pConfig->bColumnsize ){
    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
    if( rc==SQLITE_OK ){
      sqlite3_bind_int64(pDel, 1, iDel);
      sqlite3_step(pDel);
      rc = sqlite3_reset(pDel);
    }
  }

  /* Delete the %_content record */
  if( pConfig->eContent==FTS5_CONTENT_NORMAL
   || pConfig->eContent==FTS5_CONTENT_UNINDEXED
  ){
    if( rc==SQLITE_OK ){
      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
    }
    if( rc==SQLITE_OK ){
      sqlite3_bind_int64(pDel, 1, iDel);
      sqlite3_step(pDel);
      rc = sqlite3_reset(pDel);
255780
255781
255782
255783
255784
255785
255786
255787





255788
255789
255790
255791
255792
255793
255794
255795
      "DELETE FROM %Q.'%q_data';"
      "DELETE FROM %Q.'%q_idx';",
      pConfig->zDb, pConfig->zName,
      pConfig->zDb, pConfig->zName
  );
  if( rc==SQLITE_OK && pConfig->bColumnsize ){
    rc = fts5ExecPrintf(pConfig->db, 0,
        "DELETE FROM %Q.'%q_docsize';",





        pConfig->zDb, pConfig->zName
    );
  }

  /* Reinitialize the %_data table. This call creates the initial structure
  ** and averages records.  */
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5IndexReinit(p->pIndex);







|
>
>
>
>
>
|







255935
255936
255937
255938
255939
255940
255941
255942
255943
255944
255945
255946
255947
255948
255949
255950
255951
255952
255953
255954
255955
      "DELETE FROM %Q.'%q_data';"
      "DELETE FROM %Q.'%q_idx';",
      pConfig->zDb, pConfig->zName,
      pConfig->zDb, pConfig->zName
  );
  if( rc==SQLITE_OK && pConfig->bColumnsize ){
    rc = fts5ExecPrintf(pConfig->db, 0,
        "DELETE FROM %Q.'%q_docsize';", pConfig->zDb, pConfig->zName
    );
  }

  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_UNINDEXED ){
    rc = fts5ExecPrintf(pConfig->db, 0,
        "DELETE FROM %Q.'%q_content';", pConfig->zDb, pConfig->zName
    );
  }

  /* Reinitialize the %_data table. This call creates the initial structure
  ** and averages records.  */
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5IndexReinit(p->pIndex);
255917
255918
255919
255920
255921
255922
255923

255924
255925
255926
255927
255928
255929
255930
255931


255932
255933
255934
255935
255936
255937
255938
255939
255940


255941
255942
255943
255944
255945
255946
255947
255948
255949
255950

255951
255952
255953
255954
255955
255956
255957
255958
255959
255960
255961
255962
255963
255964
255965
255966
255967
255968
255969
255970
255971
255972
255973
255974
255975
255976
255977
255978
255979
255980
255981
255982

255983
255984
255985
255986
255987
255988
255989
}

/*
** Insert a new row into the FTS content table.
*/
static int sqlite3Fts5StorageContentInsert(
  Fts5Storage *p,

  sqlite3_value **apVal,
  i64 *piRowid
){
  Fts5Config *pConfig = p->pConfig;
  int rc = SQLITE_OK;

  /* Insert the new row into the %_content table. */
  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){


    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
      *piRowid = sqlite3_value_int64(apVal[1]);
    }else{
      rc = fts5StorageNewRowid(p, piRowid);
    }
  }else{
    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
    int i;                        /* Counter variable */
    int nIndexed = 0;             /* Number indexed columns seen */


    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
    if( pInsert ) sqlite3_clear_bindings(pInsert);

    /* Bind the rowid value */
    sqlite3_bind_value(pInsert, 1, apVal[1]);

    /* Loop through values for user-defined columns. i=2 is the leftmost
    ** user-defined column. As is column 1 of pSavedRow.  */
    for(i=2; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
      int bUnindexed = pConfig->abUnindexed[i-2];

      sqlite3_value *pVal = apVal[i];

      nIndexed += !bUnindexed;
      if( sqlite3_value_nochange(pVal) && p->pSavedRow ){
        /* This is an UPDATE statement, and column (i-2) was not modified.
        ** Retrieve the value from Fts5Storage.pSavedRow instead. */
        pVal = sqlite3_column_value(p->pSavedRow, i-1);
        if( pConfig->bLocale && bUnindexed==0 ){
          sqlite3_bind_value(pInsert, pConfig->nCol + 1 + nIndexed,
              sqlite3_column_value(p->pSavedRow, pConfig->nCol + i - 1)
          );
        }
      }else if( sqlite3Fts5IsLocaleValue(pConfig, pVal) ){
        const char *pText = 0;
        const char *pLoc = 0;
        int nText = 0;
        int nLoc = 0;
        assert( pConfig->bLocale );

        rc = sqlite3Fts5DecodeLocaleValue(pVal, &pText, &nText, &pLoc, &nLoc);
        if( rc==SQLITE_OK ){
          sqlite3_bind_text(pInsert, i, pText, nText, SQLITE_TRANSIENT);
          if( bUnindexed==0 ){
            int iLoc = pConfig->nCol + 1 + nIndexed;
            sqlite3_bind_text(pInsert, iLoc, pLoc, nLoc, SQLITE_TRANSIENT);
          }
        }

        continue;
      }

      rc = sqlite3_bind_value(pInsert, i, pVal);

    }
    if( rc==SQLITE_OK ){
      sqlite3_step(pInsert);
      rc = sqlite3_reset(pInsert);
    }
    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  }







>







|
>
>








|
>
>
|









>
|

<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|

|
|

|
>







256077
256078
256079
256080
256081
256082
256083
256084
256085
256086
256087
256088
256089
256090
256091
256092
256093
256094
256095
256096
256097
256098
256099
256100
256101
256102
256103
256104
256105
256106
256107
256108
256109
256110
256111
256112
256113
256114
256115
256116
256117
256118

256119
256120
256121
256122
256123
256124
256125
256126
256127
256128
256129
256130
256131
256132
256133
256134
256135
256136
256137
256138
256139
256140
256141
256142
256143
256144
256145
256146
256147
256148
256149
256150
256151
256152
256153
256154
256155
}

/*
** Insert a new row into the FTS content table.
*/
static int sqlite3Fts5StorageContentInsert(
  Fts5Storage *p,
  int bReplace,                   /* True to use REPLACE instead of INSERT */
  sqlite3_value **apVal,
  i64 *piRowid
){
  Fts5Config *pConfig = p->pConfig;
  int rc = SQLITE_OK;

  /* Insert the new row into the %_content table. */
  if( pConfig->eContent!=FTS5_CONTENT_NORMAL
   && pConfig->eContent!=FTS5_CONTENT_UNINDEXED
  ){
    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
      *piRowid = sqlite3_value_int64(apVal[1]);
    }else{
      rc = fts5StorageNewRowid(p, piRowid);
    }
  }else{
    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
    int i;                        /* Counter variable */

    assert( FTS5_STMT_INSERT_CONTENT+1==FTS5_STMT_REPLACE_CONTENT );
    assert( bReplace==0 || bReplace==1 );
    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT+bReplace, &pInsert, 0);
    if( pInsert ) sqlite3_clear_bindings(pInsert);

    /* Bind the rowid value */
    sqlite3_bind_value(pInsert, 1, apVal[1]);

    /* Loop through values for user-defined columns. i=2 is the leftmost
    ** user-defined column. As is column 1 of pSavedRow.  */
    for(i=2; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
      int bUnindexed = pConfig->abUnindexed[i-2];
      if( pConfig->eContent==FTS5_CONTENT_NORMAL || bUnindexed ){
        sqlite3_value *pVal = apVal[i];


        if( sqlite3_value_nochange(pVal) && p->pSavedRow ){
          /* This is an UPDATE statement, and user-defined column (i-2) was not
          ** modified.  Retrieve the value from Fts5Storage.pSavedRow.  */
          pVal = sqlite3_column_value(p->pSavedRow, i-1);
          if( pConfig->bLocale && bUnindexed==0 ){
            sqlite3_bind_value(pInsert, pConfig->nCol + i,
                sqlite3_column_value(p->pSavedRow, pConfig->nCol + i - 1)
            );
          }
        }else if( sqlite3Fts5IsLocaleValue(pConfig, pVal) ){
          const char *pText = 0;
          const char *pLoc = 0;
          int nText = 0;
          int nLoc = 0;
          assert( pConfig->bLocale );

          rc = sqlite3Fts5DecodeLocaleValue(pVal, &pText, &nText, &pLoc, &nLoc);
          if( rc==SQLITE_OK ){
            sqlite3_bind_text(pInsert, i, pText, nText, SQLITE_TRANSIENT);
            if( bUnindexed==0 ){
              int iLoc = pConfig->nCol + i;
              sqlite3_bind_text(pInsert, iLoc, pLoc, nLoc, SQLITE_TRANSIENT);
            }
          }

          continue;
        }

        rc = sqlite3_bind_value(pInsert, i, pVal);
      }
    }
    if( rc==SQLITE_OK ){
      sqlite3_step(pInsert);
      rc = sqlite3_reset(pInsert);
    }
    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  }
256685
256686
256687
256688
256689
256690
256691
256692
256693
256694
256695
256696
256697
256698
256699
  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
};

#define READ_UTF8(zIn, zTerm, c)                           \
  c = *(zIn++);                                            \
  if( c>=0xc0 ){                                           \
    c = sqlite3Utf8Trans1[c-0xc0];                         \
    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
      c = (c<<6) + (0x3f & *(zIn++));                      \
    }                                                      \
    if( c<0x80                                             \
        || (c&0xFFFFF800)==0xD800                          \
        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
  }








|







256851
256852
256853
256854
256855
256856
256857
256858
256859
256860
256861
256862
256863
256864
256865
  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
};

#define READ_UTF8(zIn, zTerm, c)                           \
  c = *(zIn++);                                            \
  if( c>=0xc0 ){                                           \
    c = sqlite3Utf8Trans1[c-0xc0];                         \
    while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){             \
      c = (c<<6) + (0x3f & *(zIn++));                      \
    }                                                      \
    if( c<0x80                                             \
        || (c&0xFFFFF800)==0xD800                          \
        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
  }

264251
264252
264253
264254
264255
264256
264257
264258
264259
264260
264261
264262
264263
264264
264265
** 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);







|







264417
264418
264419
264420
264421
264422
264423
264424
264425
264426
264427
264428
264429
264430
264431
** 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.5-", 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);
264307
264308
264309
264310
264311
264312
264313














264314
264315
264316
264317
264318
264319
264320
/* 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"







>
>
>
>
>
>
>
>
>
>
>
>
>
>







264473
264474
264475
264476
264477
264478
264479
264480
264481
264482
264483
264484
264485
264486
264487
264488
264489
264490
264491
264492
264493
264494
264495
264496
264497
264498
264499
264500
/* 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"
#ifdef WIN32
      "set new [list]\n"
      "foreach arg $argv {\n"
        "if {[file exists $arg]} {\n"
          "lappend new $arg\n"
        "} else {\n"
          "foreach match [lsort [glob -nocomplain $arg]] {\n"
            "lappend new $match\n"
          "}\n"
        "}\n"
      "}\n"
      "set argv $new\n"
      "unset new\n"
#endif
      "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"