SQLite Android Bindings

Check-in [bd50a651bd]
Login

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

Overview
Comment:Update this project to version 3.42.0.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: bd50a651bdf944ab04996b5123bcd06a9e927700
User & Date: dan 2023-05-16 13:46:22.550
Context
2023-08-24
14:01
Upgrade to 3.43.0. (check-in: 2c57345f44 user: dan tags: trunk)
2023-05-16
13:46
Update this project to version 3.42.0. (check-in: bd50a651bd user: dan tags: trunk)
2023-03-10
13:59
Update to version 3.41.1. (check-in: 3cf8726532 user: dan tags: trunk)
Changes
Unified Diff Ignore Whitespace Patch
Changes to sqlite3/src/main/jni/sqlite/sqlite3.c.
1
2
3
4
5
6
7
8
9
10
/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version 3.41.1.  By combining all the individual C code files into this
** single large file, the entire code can be compiled as a single translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% or more are commonly seen when SQLite is compiled as a single
** translation unit.
**
** This file is all you need to compile SQLite.  To use SQLite in other


|







1
2
3
4
5
6
7
8
9
10
/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version 3.42.0.  By combining all the individual C code files into this
** single large file, the entire code can be compiled as a single translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% or more are commonly seen when SQLite is compiled as a single
** translation unit.
**
** This file is all you need to compile SQLite.  To use SQLite in other
119
120
121
122
123
124
125




126
127
128
129
130
131
132
#endif /* defined(_MSC_VER) */

#if defined(_MSC_VER) && !defined(_WIN64)
#undef SQLITE_4_BYTE_ALIGNED_MALLOC
#define SQLITE_4_BYTE_ALIGNED_MALLOC
#endif /* defined(_MSC_VER) && !defined(_WIN64) */





#endif /* SQLITE_MSVC_H */

/************** End of msvc.h ************************************************/
/************** Continuing where we left off in sqliteInt.h ******************/

/*
** Special setup for VxWorks







>
>
>
>







119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#endif /* defined(_MSC_VER) */

#if defined(_MSC_VER) && !defined(_WIN64)
#undef SQLITE_4_BYTE_ALIGNED_MALLOC
#define SQLITE_4_BYTE_ALIGNED_MALLOC
#endif /* defined(_MSC_VER) && !defined(_WIN64) */

#if !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800
#define HAVE_LOG2 0
#endif /* !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 */

#endif /* SQLITE_MSVC_H */

/************** End of msvc.h ************************************************/
/************** Continuing where we left off in sqliteInt.h ******************/

/*
** Special setup for VxWorks
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.41.1"
#define SQLITE_VERSION_NUMBER 3041001
#define SQLITE_SOURCE_ID      "2023-03-10 12:13:52 20399f3eda5ec249d147ba9e48da6e87f969d7966a9a896764ca437ff7e737ff"

/*
** 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







|
|
|







452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.42.0"
#define SQLITE_VERSION_NUMBER 3042000
#define SQLITE_SOURCE_ID      "2023-05-16 12:36:15 831d0fb2836b71c9bc51067c49fee4b8f18047814f2ff22d817d25195cf350b0"

/*
** 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
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976











1977
1978
1979
1980
1981
1982
1983
** applications and so this routine is usually not necessary.  It is
** provided to support rare applications with unusual needs.
**
** <b>The sqlite3_config() interface is not threadsafe. The application
** must ensure that no other SQLite interfaces are invoked by other
** threads while sqlite3_config() is running.</b>
**
** The sqlite3_config() interface
** may only be invoked prior to library initialization using
** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
** Note, however, that ^sqlite3_config() can be called as part of the
** implementation of an application-defined [sqlite3_os_init()].
**
** The first argument to sqlite3_config() is an integer
** [configuration option] that determines
** what property of SQLite is to be configured.  Subsequent arguments
** vary depending on the [configuration option]
** in the first argument.











**
** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
** ^If the option is unknown or SQLite is unable to set the option
** then this routine returns a non-zero [error code].
*/
SQLITE_API int sqlite3_config(int, ...);








<
<
<
<
<
<
<
<





>
>
>
>
>
>
>
>
>
>
>







1961
1962
1963
1964
1965
1966
1967








1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
** applications and so this routine is usually not necessary.  It is
** provided to support rare applications with unusual needs.
**
** <b>The sqlite3_config() interface is not threadsafe. The application
** must ensure that no other SQLite interfaces are invoked by other
** threads while sqlite3_config() is running.</b>
**








** The first argument to sqlite3_config() is an integer
** [configuration option] that determines
** what property of SQLite is to be configured.  Subsequent arguments
** vary depending on the [configuration option]
** in the first argument.
**
** For most configuration options, the sqlite3_config() interface
** may only be invoked prior to library initialization using
** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
** The exceptional configuration options that may be invoked at any time
** are called "anytime configuration options".
** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
** [sqlite3_shutdown()] with a first argument that is not an anytime
** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE.
** Note, however, that ^sqlite3_config() can be called as part of the
** implementation of an application-defined [sqlite3_os_init()].
**
** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
** ^If the option is unknown or SQLite is unable to set the option
** then this routine returns a non-zero [error code].
*/
SQLITE_API int sqlite3_config(int, ...);

2077
2078
2079
2080
2081
2082
2083

















2084
2085
2086
2087
2088
2089
2090

/*
** CAPI3REF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
** can be passed as the first argument to the [sqlite3_config()] interface.

















**
** New configuration options may be added in future releases of SQLite.
** Existing configuration options might be discontinued.  Applications
** should check the return code from [sqlite3_config()] to make sure that
** the call worked.  The [sqlite3_config()] interface will return a
** non-zero [error code] if a discontinued or unsupported configuration option
** is invoked.







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







2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114

/*
** CAPI3REF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
** can be passed as the first argument to the [sqlite3_config()] interface.
**
** Most of the configuration options for sqlite3_config()
** will only work if invoked prior to [sqlite3_initialize()] or after
** [sqlite3_shutdown()].  The few exceptions to this rule are called
** "anytime configuration options".
** ^Calling [sqlite3_config()] with a first argument that is not an
** anytime configuration option in between calls to [sqlite3_initialize()] and
** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE.
**
** The set of anytime configuration options can change (by insertions
** and/or deletions) from one release of SQLite to the next.
** As of SQLite version 3.42.0, the complete set of anytime configuration
** options is:
** <ul>
** <li> SQLITE_CONFIG_LOG
** <li> SQLITE_CONFIG_PCACHE_HDRSZ
** </ul>
**
** New configuration options may be added in future releases of SQLite.
** Existing configuration options might be discontinued.  Applications
** should check the return code from [sqlite3_config()] to make sure that
** the call worked.  The [sqlite3_config()] interface will return a
** non-zero [error code] if a discontinued or unsupported configuration option
** is invoked.
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
** size can be adjusted up or down for individual databases using the
** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this
** configuration setting is never used, then the default maximum is determined
** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that
** compile-time option is not set, then the default maximum is 1073741824.
** </dl>
*/
#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_SCRATCH       6  /* No longer used */
#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
#define SQLITE_CONFIG_PCACHE       14  /* no-op */
#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
#define SQLITE_CONFIG_URI          17  /* int */
#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */
#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|







2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
** size can be adjusted up or down for individual databases using the
** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this
** configuration setting is never used, then the default maximum is determined
** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that
** compile-time option is not set, then the default maximum is 1073741824.
** </dl>
*/
#define SQLITE_CONFIG_SINGLETHREAD         1  /* nil */
#define SQLITE_CONFIG_MULTITHREAD          2  /* nil */
#define SQLITE_CONFIG_SERIALIZED           3  /* nil */
#define SQLITE_CONFIG_MALLOC               4  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_GETMALLOC            5  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_SCRATCH              6  /* No longer used */
#define SQLITE_CONFIG_PAGECACHE            7  /* void*, int sz, int N */
#define SQLITE_CONFIG_HEAP                 8  /* void*, int nByte, int min */
#define SQLITE_CONFIG_MEMSTATUS            9  /* boolean */
#define SQLITE_CONFIG_MUTEX               10  /* sqlite3_mutex_methods* */
#define SQLITE_CONFIG_GETMUTEX            11  /* sqlite3_mutex_methods* */
/* previously SQLITE_CONFIG_CHUNKALLOC    12 which is now unused. */
#define SQLITE_CONFIG_LOOKASIDE           13  /* int int */
#define SQLITE_CONFIG_PCACHE              14  /* no-op */
#define SQLITE_CONFIG_GETPCACHE           15  /* no-op */
#define SQLITE_CONFIG_LOG                 16  /* xFunc, void* */
#define SQLITE_CONFIG_URI                 17  /* int */
#define SQLITE_CONFIG_PCACHE2             18  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_GETPCACHE2          19  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
#define SQLITE_CONFIG_SQLLOG              21  /* xSqllog, void* */
#define SQLITE_CONFIG_MMAP_SIZE           22  /* sqlite3_int64, sqlite3_int64 */
#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */
#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
































2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764


2765
2766
2767
2768
2769
2770
2771
2772
** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the
** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
** additional information. This feature can also be turned on and off
** using the [PRAGMA legacy_alter_table] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DML]]
** <dt>SQLITE_DBCONFIG_DQS_DML</td>
** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DML statements
** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DDL]]
** <dt>SQLITE_DBCONFIG_DQS_DDL</td>
** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DDL statements,
** such as CREATE TABLE and CREATE INDEX. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
** assume that database schemas are untainted by malicious content.
** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
** takes additional defensive steps to protect the application from harm
** including:
** <ul>
** <li> Prohibit the use of SQL functions inside triggers, views,
** CHECK constraints, DEFAULT clauses, expression indexes,
** partial indexes, or generated columns
** unless those functions are tagged with [SQLITE_INNOCUOUS].
** <li> Prohibit the use of virtual tables inside of triggers or views
** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
** </ul>
** This setting defaults to "on" for legacy compatibility, however
** all applications are advised to turn it off if possible. This setting
** can also be controlled using the [PRAGMA trusted_schema] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
** the legacy file format flag.  When activated, this flag causes all newly
** created database file to have a schema format version number (the 4-byte
** integer found at offset 44 into the database header) of 1.  This in turn
** means that the resulting database file will be readable and writable by
** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,
** newly created databases are generally not understandable by SQLite versions
** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there
** is now scarcely any need to generated database files that are compatible
** all the way back to version 3.0.0, and so this setting is of little
** practical use, but is provided so that SQLite can continue to claim the
** ability to generate new database files that are compatible with  version
** 3.0.0.
** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
** the [VACUUM] command will fail with an obscure error when attempting to
** process a table with generated columns and a descending index.  This is
** not considered a bug since SQLite versions 3.3.0 and earlier do not support
** either generated columns or decending indexes.
** </dd>
































** </dl>
*/
#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */
#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */
#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */
#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */
#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */


#define SQLITE_DBCONFIG_MAX                   1017 /* Largest DBCONFIG */

/*
** CAPI3REF: Enable Or Disable Extended Result Codes
** METHOD: sqlite3
**
** ^The sqlite3_extended_result_codes() routine enables or disables the
** [extended result codes] feature of SQLite. ^The extended result







|








|








|



















|








|










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




















>
>
|







2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the
** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
** additional information. This feature can also be turned on and off
** using the [PRAGMA legacy_alter_table] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DML]]
** <dt>SQLITE_DBCONFIG_DQS_DML</dt>
** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DML statements
** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DDL]]
** <dt>SQLITE_DBCONFIG_DQS_DDL</dt>
** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DDL statements,
** such as CREATE TABLE and CREATE INDEX. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</dt>
** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
** assume that database schemas are untainted by malicious content.
** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
** takes additional defensive steps to protect the application from harm
** including:
** <ul>
** <li> Prohibit the use of SQL functions inside triggers, views,
** CHECK constraints, DEFAULT clauses, expression indexes,
** partial indexes, or generated columns
** unless those functions are tagged with [SQLITE_INNOCUOUS].
** <li> Prohibit the use of virtual tables inside of triggers or views
** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
** </ul>
** This setting defaults to "on" for legacy compatibility, however
** all applications are advised to turn it off if possible. This setting
** can also be controlled using the [PRAGMA trusted_schema] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt>
** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
** the legacy file format flag.  When activated, this flag causes all newly
** created database file to have a schema format version number (the 4-byte
** integer found at offset 44 into the database header) of 1.  This in turn
** means that the resulting database file will be readable and writable by
** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,
** newly created databases are generally not understandable by SQLite versions
** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there
** is now scarcely any need to generate database files that are compatible
** all the way back to version 3.0.0, and so this setting is of little
** practical use, but is provided so that SQLite can continue to claim the
** ability to generate new database files that are compatible with  version
** 3.0.0.
** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
** the [VACUUM] command will fail with an obscure error when attempting to
** process a table with generated columns and a descending index.  This is
** not considered a bug since SQLite versions 3.3.0 and earlier do not support
** either generated columns or decending indexes.
** </dd>
**
** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]]
** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt>
** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in
** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears
** a flag that enables collection of the sqlite3_stmt_scanstatus_v2()
** statistics. For statistics to be collected, the flag must be set on
** the database handle both when the SQL statement is prepared and when it
** is stepped. The flag is set (collection of statistics is enabled)
** by default.  This option takes two arguments: an integer and a pointer to
** an integer..  The first argument is 1, 0, or -1 to enable, disable, or
** leave unchanged the statement scanstatus option.  If the second argument
** is not NULL, then the value of the statement scanstatus setting after
** processing the first argument is written into the integer that the second
** argument points to.
** </dd>
**
** [[SQLITE_DBCONFIG_REVERSE_SCANORDER]]
** <dt>SQLITE_DBCONFIG_REVERSE_SCANORDER</dt>
** <dd>The SQLITE_DBCONFIG_REVERSE_SCANORDER option changes the default order
** in which tables and indexes are scanned so that the scans start at the end
** and work toward the beginning rather than starting at the beginning and
** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the
** same as setting [PRAGMA reverse_unordered_selects].  This option takes
** two arguments which are an integer and a pointer to an integer.  The first
** argument is 1, 0, or -1 to enable, disable, or leave unchanged the
** reverse scan order flag, respectively.  If the second argument is not NULL,
** then 0 or 1 is written into the integer that the second argument points to
** depending on if the reverse scan order flag is set after processing the
** first argument.
** </dd>
**
** </dl>
*/
#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */
#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */
#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */
#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */
#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */
#define SQLITE_DBCONFIG_STMT_SCANSTATUS       1018 /* int int* */
#define SQLITE_DBCONFIG_REVERSE_SCANORDER     1019 /* int int* */
#define SQLITE_DBCONFIG_MAX                   1019 /* Largest DBCONFIG */

/*
** CAPI3REF: Enable Or Disable Extended Result Codes
** METHOD: sqlite3
**
** ^The sqlite3_extended_result_codes() routine enables or disables the
** [extended result codes] feature of SQLite. ^The extended result
6503
6504
6505
6506
6507
6508
6509







6510
6511
6512
6513
6514
6515
6516
** requested from the operating system is returned.
**
** ^SQLite implements this interface by calling the xSleep()
** method of the default [sqlite3_vfs] object.  If the xSleep() method
** of the default VFS is not implemented correctly, or not implemented at
** all, then the behavior of sqlite3_sleep() may deviate from the description
** in the previous paragraphs.







*/
SQLITE_API int sqlite3_sleep(int);

/*
** CAPI3REF: Name Of The Folder Holding Temporary Files
**
** ^(If this global variable is made to point to a string which is







>
>
>
>
>
>
>







6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
** requested from the operating system is returned.
**
** ^SQLite implements this interface by calling the xSleep()
** method of the default [sqlite3_vfs] object.  If the xSleep() method
** of the default VFS is not implemented correctly, or not implemented at
** all, then the behavior of sqlite3_sleep() may deviate from the description
** in the previous paragraphs.
**
** If a negative argument is passed to sqlite3_sleep() the results vary by
** VFS and operating system.  Some system treat a negative argument as an
** instruction to sleep forever.  Others understand it to mean do not sleep
** at all. ^In SQLite version 3.42.0 and later, a negative
** argument passed into sqlite3_sleep() is changed to zero before it is relayed
** down into the xSleep method of the VFS.
*/
SQLITE_API int sqlite3_sleep(int);

/*
** CAPI3REF: Name Of The Folder Holding Temporary Files
**
** ^(If this global variable is made to point to a string which is
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
** behavior.)^
**
** ^The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.   The behavior
** is undefined if the mutex is not currently entered by the
** calling thread or is not currently allocated.
**
** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
** sqlite3_mutex_leave() is a NULL pointer, then all three routines
** behave as no-ops.
**
** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
*/
SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);







|
|
|







8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
** behavior.)^
**
** ^The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.   The behavior
** is undefined if the mutex is not currently entered by the
** calling thread or is not currently allocated.
**
** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(),
** sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer,
** then any of the four routines behaves as a no-op.
**
** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
*/
SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879









9880
9881
9882
9883
9884

9885
9886
9887
9888
9889
9890
9891
** prohibits that virtual table from being used from within triggers and
** views.
** </dd>
**
** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
** <dd>Calls of the form
** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
** identify that virtual table as being safe to use from within triggers
** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
** virtual table can do no serious harm even if it is controlled by a
** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
** flag unless absolutely necessary.
** </dd>









** </dl>
*/
#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
#define SQLITE_VTAB_INNOCUOUS          2
#define SQLITE_VTAB_DIRECTONLY         3


/*
** CAPI3REF: Determine The Virtual Table Conflict Policy
**
** This function may only be called from within a call to the [xUpdate] method
** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],







|






>
>
>
>
>
>
>
>
>





>







9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
** prohibits that virtual table from being used from within triggers and
** views.
** </dd>
**
** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
** <dd>Calls of the form
** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
** the [xConnect] or [xCreate] methods of a [virtual table] implementation
** identify that virtual table as being safe to use from within triggers
** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
** virtual table can do no serious harm even if it is controlled by a
** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
** flag unless absolutely necessary.
** </dd>
**
** [[SQLITE_VTAB_USES_ALL_SCHEMAS]]<dt>SQLITE_VTAB_USES_ALL_SCHEMAS</dt>
** <dd>Calls of the form
** [sqlite3_vtab_config](db,SQLITE_VTAB_USES_ALL_SCHEMA) from within the
** the [xConnect] or [xCreate] methods of a [virtual table] implementation
** instruct the query planner to begin at least a read transaction on
** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the
** virtual table is used.
** </dd>
** </dl>
*/
#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
#define SQLITE_VTAB_INNOCUOUS          2
#define SQLITE_VTAB_DIRECTONLY         3
#define SQLITE_VTAB_USES_ALL_SCHEMAS   4

/*
** CAPI3REF: Determine The Virtual Table Conflict Policy
**
** This function may only be called from within a call to the [xUpdate] method
** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065




11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086

11087







11088
11089

11090
11091
11092
11093
11094
11095
11096
** Session objects must be deleted before the database handle to which they
** are attached is closed. Refer to the documentation for
** [sqlite3session_create()] for details.
*/
SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);

/*
** CAPIREF: Conigure a Session Object
** METHOD: sqlite3_session
**
** This method is used to configure a session object after it has been
** created. At present the only valid value for the second parameter is
** [SQLITE_SESSION_OBJCONFIG_SIZE].
**




** Arguments for sqlite3session_object_config()
**
** The following values may passed as the the 4th parameter to
** sqlite3session_object_config().
**
** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
**   This option is used to set, clear or query the flag that enables
**   the [sqlite3session_changeset_size()] API. Because it imposes some
**   computational overhead, this API is disabled by default. Argument
**   pArg must point to a value of type (int). If the value is initially
**   0, then the sqlite3session_changeset_size() API is disabled. If it
**   is greater than 0, then the same API is enabled. Or, if the initial
**   value is less than zero, no change is made. In all cases the (int)
**   variable is set to 1 if the sqlite3session_changeset_size() API is
**   enabled following the current call, or 0 otherwise.
**
**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
**   the first table has been attached to the session object.
*/
SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);


/*







*/
#define SQLITE_SESSION_OBJCONFIG_SIZE 1


/*
** CAPI3REF: Enable Or Disable A Session Object
** METHOD: sqlite3_session
**
** Enable or disable the recording of changes by a session object. When
** enabled, a session object records changes made to the database. When







|



|
|

>
>
>
>
|

|















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

|
>







11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
** Session objects must be deleted before the database handle to which they
** are attached is closed. Refer to the documentation for
** [sqlite3session_create()] for details.
*/
SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);

/*
** CAPI3REF: Configure a Session Object
** METHOD: sqlite3_session
**
** This method is used to configure a session object after it has been
** created. At present the only valid values for the second parameter are
** [SQLITE_SESSION_OBJCONFIG_SIZE] and [SQLITE_SESSION_OBJCONFIG_ROWID].
**
*/
SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);

/*
** CAPI3REF: Options for sqlite3session_object_config
**
** The following values may passed as the the 2nd parameter to
** sqlite3session_object_config().
**
** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
**   This option is used to set, clear or query the flag that enables
**   the [sqlite3session_changeset_size()] API. Because it imposes some
**   computational overhead, this API is disabled by default. Argument
**   pArg must point to a value of type (int). If the value is initially
**   0, then the sqlite3session_changeset_size() API is disabled. If it
**   is greater than 0, then the same API is enabled. Or, if the initial
**   value is less than zero, no change is made. In all cases the (int)
**   variable is set to 1 if the sqlite3session_changeset_size() API is
**   enabled following the current call, or 0 otherwise.
**
**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
**   the first table has been attached to the session object.
**
** <dt>SQLITE_SESSION_OBJCONFIG_ROWID <dd>
**   This option is used to set, clear or query the flag that enables
**   collection of data for tables with no explicit PRIMARY KEY.
**
**   Normally, tables with no explicit PRIMARY KEY are simply ignored
**   by the sessions module. However, if this flag is set, it behaves
**   as if such tables have a column "_rowid_ INTEGER PRIMARY KEY" inserted
**   as their leftmost columns.
**
**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
**   the first table has been attached to the session object.
*/
#define SQLITE_SESSION_OBJCONFIG_SIZE  1
#define SQLITE_SESSION_OBJCONFIG_ROWID 2

/*
** CAPI3REF: Enable Or Disable A Session Object
** METHOD: sqlite3_session
**
** Enable or disable the recording of changes by a session object. When
** enabled, a session object records changes made to the database. When
12215
12216
12217
12218
12219
12220
12221













12222
12223
12224

12225
12226
12227
12228
12229
12230
12231
**   caller has an open transaction or savepoint when apply_v2() is called,
**   it may revert the partially applied changeset by rolling it back.
**
** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
**   Invert the changeset before applying it. This is equivalent to inverting
**   a changeset using sqlite3changeset_invert() before applying it. It is
**   an error to specify this flag with a patchset.













*/
#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
#define SQLITE_CHANGESETAPPLY_INVERT        0x0002


/*
** CAPI3REF: Constants Passed To The Conflict Handler
**
** Values that may be passed as the second argument to a conflict-handler.
**
** <dl>







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



>







12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
**   caller has an open transaction or savepoint when apply_v2() is called,
**   it may revert the partially applied changeset by rolling it back.
**
** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
**   Invert the changeset before applying it. This is equivalent to inverting
**   a changeset using sqlite3changeset_invert() before applying it. It is
**   an error to specify this flag with a patchset.
**
** <dt>SQLITE_CHANGESETAPPLY_IGNORENOOP <dd>
**   Do not invoke the conflict handler callback for any changes that
**   would not actually modify the database even if they were applied.
**   Specifically, this means that the conflict handler is not invoked
**   for:
**    <ul>
**    <li>a delete change if the row being deleted cannot be found,
**    <li>an update change if the modified fields are already set to
**        their new values in the conflicting row, or
**    <li>an insert change if all fields of the conflicting row match
**        the row being inserted.
**    </ul>
*/
#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
#define SQLITE_CHANGESETAPPLY_INVERT        0x0002
#define SQLITE_CHANGESETAPPLY_IGNORENOOP    0x0004

/*
** CAPI3REF: Constants Passed To The Conflict Handler
**
** Values that may be passed as the second argument to a conflict-handler.
**
** <dl>
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
#pragma warn -ccc /* Condition is always true or false */
#pragma warn -aus /* Assigned value is never used */
#pragma warn -csu /* Comparing signed and unsigned */
#pragma warn -spa /* Suspicious pointer arithmetic */
#endif

/*
** WAL mode depends on atomic aligned 32-bit loads and stores in a few
** places.  The following macros try to make this explicit.
*/
#ifndef __has_extension
# define __has_extension(x) 0     /* compatibility with non-clang compilers */
#endif
#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
# define SQLITE_ATOMIC_INTRINSICS 1
# define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)







|
|







13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
#pragma warn -ccc /* Condition is always true or false */
#pragma warn -aus /* Assigned value is never used */
#pragma warn -csu /* Comparing signed and unsigned */
#pragma warn -spa /* Suspicious pointer arithmetic */
#endif

/*
** A few places in the code require atomic load/store of aligned
** integer values.
*/
#ifndef __has_extension
# define __has_extension(x) 0     /* compatibility with non-clang compilers */
#endif
#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
# define SQLITE_ATOMIC_INTRINSICS 1
# define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582

13583
13584

13585
13586





13587
13588
13589
13590
13591
13592
13593
# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
#else                          /* Generates a warning - but it always works */
# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(X))
#endif

/*
** A macro to hint to the compiler that a function should not be
** inlined.
*/
#if defined(__GNUC__)
#  define SQLITE_NOINLINE  __attribute__((noinline))

#elif defined(_MSC_VER) && _MSC_VER>=1310
#  define SQLITE_NOINLINE  __declspec(noinline)

#else
#  define SQLITE_NOINLINE





#endif

/*
** Make sure that the compiler intrinsics we desire are enabled when
** compiling with an appropriate version of MSVC unless prevented by
** the SQLITE_DISABLE_INTRINSIC define.
*/







|




>


>


>
>
>
>
>







13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
#else                          /* Generates a warning - but it always works */
# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(X))
#endif

/*
** Macros to hint to the compiler that a function should or should not be
** inlined.
*/
#if defined(__GNUC__)
#  define SQLITE_NOINLINE  __attribute__((noinline))
#  define SQLITE_INLINE    __attribute__((always_inline)) inline
#elif defined(_MSC_VER) && _MSC_VER>=1310
#  define SQLITE_NOINLINE  __declspec(noinline)
#  define SQLITE_INLINE    __forceinline
#else
#  define SQLITE_NOINLINE
#  define SQLITE_INLINE
#endif
#if defined(SQLITE_COVERAGE_TEST) || defined(__STRICT_ANSI__)
# undef SQLITE_INLINE
# define SQLITE_INLINE
#endif

/*
** Make sure that the compiler intrinsics we desire are enabled when
** compiling with an appropriate version of MSVC unless prevented by
** the SQLITE_DISABLE_INTRINSIC define.
*/
16539
16540
16541
16542
16543
16544
16545




16546
16547
16548
16549
16550
16551
16552
# define sqlite3VdbeScanStatusRange(a,b,c,d)
# define sqlite3VdbeScanStatusCounters(a,b,c,d)
#endif

#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
#endif





#endif /* SQLITE_VDBE_H */

/************** End of vdbe.h ************************************************/
/************** Continuing where we left off in sqliteInt.h ******************/
/************** Include pcache.h in the middle of sqliteInt.h ****************/
/************** Begin file pcache.h ******************************************/







>
>
>
>







16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
# define sqlite3VdbeScanStatusRange(a,b,c,d)
# define sqlite3VdbeScanStatusCounters(a,b,c,d)
#endif

#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
#endif

#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
SQLITE_PRIVATE int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr);
#endif

#endif /* SQLITE_VDBE_H */

/************** End of vdbe.h ************************************************/
/************** Continuing where we left off in sqliteInt.h ******************/
/************** Include pcache.h in the middle of sqliteInt.h ****************/
/************** Begin file pcache.h ******************************************/
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
  u16 flags;                     /* PGHDR flags defined below */

  /**********************************************************************
  ** Elements above, except pCache, are public.  All that follow are
  ** private to pcache.c and should not be accessed by other modules.
  ** pCache is grouped with the public elements for efficiency.
  */
  i16 nRef;                      /* Number of users of this page */
  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
                          /* NB: pDirtyNext and pDirtyPrev are undefined if the
                          ** PgHdr object is not dirty */
};

/* Bit values for PgHdr.flags */







|







16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
  u16 flags;                     /* PGHDR flags defined below */

  /**********************************************************************
  ** Elements above, except pCache, are public.  All that follow are
  ** private to pcache.c and should not be accessed by other modules.
  ** pCache is grouped with the public elements for efficiency.
  */
  i64 nRef;                      /* Number of users of this page */
  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
                          /* NB: pDirtyNext and pDirtyPrev are undefined if the
                          ** PgHdr object is not dirty */
};

/* Bit values for PgHdr.flags */
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
/* Clear flags from pages of the page cache */
SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);

/* Discard the contents of the cache */
SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);

/* Return the total number of outstanding page references */
SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);

/* Increment the reference count of an existing page */
SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);

SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);

/* Return the total number of pages stored in the cache */
SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);

#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
/* Iterate through all dirty pages currently stored in the cache. This
** interface is only available if SQLITE_CHECK_PAGES is defined when the







|




|







16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
/* Clear flags from pages of the page cache */
SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);

/* Discard the contents of the cache */
SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);

/* Return the total number of outstanding page references */
SQLITE_PRIVATE i64 sqlite3PcacheRefCount(PCache*);

/* Increment the reference count of an existing page */
SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);

SQLITE_PRIVATE i64 sqlite3PcachePageRefcount(PgHdr*);

/* Return the total number of pages stored in the cache */
SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);

#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
/* Iterate through all dirty pages currently stored in the cache. This
** interface is only available if SQLITE_CHECK_PAGES is defined when the
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
#define SQLITE_TrustedSchema  0x00000080  /* Allow unsafe functions and
                                          ** vtabs in the schema definition */
#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
                                          /*   result set is empty */
#define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
#define SQLITE_ReadUncommit   0x00000400  /* READ UNCOMMITTED in shared-cache */
#define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
#define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
#define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
#define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
#define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
#define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
#define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */







|







17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
#define SQLITE_TrustedSchema  0x00000080  /* Allow unsafe functions and
                                          ** vtabs in the schema definition */
#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
                                          /*   result set is empty */
#define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
#define SQLITE_StmtScanStatus 0x00000400  /* Enable stmt_scanstats() counters */
#define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
#define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
#define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
#define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
#define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
#define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
#define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */
17275
17276
17277
17278
17279
17280
17281

17282
17283
17284
17285
17286
17287
17288
#define SQLITE_DqsDDL         0x20000000  /* dbl-quoted strings allowed in DDL*/
#define SQLITE_DqsDML         0x40000000  /* dbl-quoted strings allowed in DML*/
#define SQLITE_EnableView     0x80000000  /* Enable the use of views */
#define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */
                                          /*   DELETE, or UPDATE and return */
                                          /*   the count using a callback. */
#define SQLITE_CorruptRdOnly  HI(0x00002) /* Prohibit writes due to error */


/* Flags used only if debugging */
#ifdef SQLITE_DEBUG
#define SQLITE_SqlTrace       HI(0x0100000) /* Debug print SQL as it executes */
#define SQLITE_VdbeListing    HI(0x0200000) /* Debug listings of VDBE progs */
#define SQLITE_VdbeTrace      HI(0x0400000) /* True to trace VDBE execution */
#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */







>







17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
#define SQLITE_DqsDDL         0x20000000  /* dbl-quoted strings allowed in DDL*/
#define SQLITE_DqsDML         0x40000000  /* dbl-quoted strings allowed in DML*/
#define SQLITE_EnableView     0x80000000  /* Enable the use of views */
#define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */
                                          /*   DELETE, or UPDATE and return */
                                          /*   the count using a callback. */
#define SQLITE_CorruptRdOnly  HI(0x00002) /* Prohibit writes due to error */
#define SQLITE_ReadUncommit   HI(0x00004) /* READ UNCOMMITTED in shared-cache */

/* Flags used only if debugging */
#ifdef SQLITE_DEBUG
#define SQLITE_SqlTrace       HI(0x0100000) /* Debug print SQL as it executes */
#define SQLITE_VdbeListing    HI(0x0200000) /* Debug listings of VDBE progs */
#define SQLITE_VdbeTrace      HI(0x0400000) /* True to trace VDBE execution */
#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */
17331
17332
17333
17334
17335
17336
17337

17338
17339
17340
17341
17342
17343
17344
#define SQLITE_BloomPulldown  0x00100000 /* Run Bloom filters early */
#define SQLITE_BalancedMerge  0x00200000 /* Balance multi-way merges */
#define SQLITE_ReleaseReg     0x00400000 /* Use OP_ReleaseReg for testing */
#define SQLITE_FlttnUnionAll  0x00800000 /* Disable the UNION ALL flattener */
   /* TH3 expects this value  ^^^^^^^^^^ See flatten04.test */
#define SQLITE_IndexedExpr    0x01000000 /* Pull exprs from index when able */
#define SQLITE_Coroutines     0x02000000 /* Co-routines for subqueries */

#define SQLITE_AllOpts        0xffffffff /* All optimizations */

/*
** Macros for testing whether or not optimizations are enabled or disabled.
*/
#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)







>







17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
#define SQLITE_BloomPulldown  0x00100000 /* Run Bloom filters early */
#define SQLITE_BalancedMerge  0x00200000 /* Balance multi-way merges */
#define SQLITE_ReleaseReg     0x00400000 /* Use OP_ReleaseReg for testing */
#define SQLITE_FlttnUnionAll  0x00800000 /* Disable the UNION ALL flattener */
   /* TH3 expects this value  ^^^^^^^^^^ See flatten04.test */
#define SQLITE_IndexedExpr    0x01000000 /* Pull exprs from index when able */
#define SQLITE_Coroutines     0x02000000 /* Co-routines for subqueries */
#define SQLITE_NullUnusedCols 0x04000000 /* NULL unused columns in subqueries */
#define SQLITE_AllOpts        0xffffffff /* All optimizations */

/*
** Macros for testing whether or not optimizations are enabled or disabled.
*/
#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
17802
17803
17804
17805
17806
17807
17808

17809
17810
17811
17812
17813
17814
17815
*/
struct VTable {
  sqlite3 *db;              /* Database connection associated with this table */
  Module *pMod;             /* Pointer to module implementation */
  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
  int nRef;                 /* Number of pointers to this structure */
  u8 bConstraint;           /* True if constraints are supported */

  u8 eVtabRisk;             /* Riskiness of allowing hacker access */
  int iSavepoint;           /* Depth of the SAVEPOINT stack */
  VTable *pNext;            /* Next in linked list (see above) */
};

/* Allowed values for VTable.eVtabRisk
*/







>







17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
*/
struct VTable {
  sqlite3 *db;              /* Database connection associated with this table */
  Module *pMod;             /* Pointer to module implementation */
  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
  int nRef;                 /* Number of pointers to this structure */
  u8 bConstraint;           /* True if constraints are supported */
  u8 bAllSchemas;           /* True if might use any attached schema */
  u8 eVtabRisk;             /* Riskiness of allowing hacker access */
  int iSavepoint;           /* Depth of the SAVEPOINT stack */
  VTable *pNext;            /* Next in linked list (see above) */
};

/* Allowed values for VTable.eVtabRisk
*/
18182
18183
18184
18185
18186
18187
18188

18189
18190
18191
18192
18193
18194
18195
  unsigned bNoQuery:1;     /* Do not use this index to optimize queries */
  unsigned bAscKeyBug:1;   /* True if the bba7b69f9849b5bf bug applies */
  unsigned bHasVCol:1;     /* Index references one or more VIRTUAL columns */
  unsigned bHasExpr:1;     /* Index contains an expression, either a literal
                           ** expression, or a reference to a VIRTUAL column */
#ifdef SQLITE_ENABLE_STAT4
  int nSample;             /* Number of elements in aSample[] */

  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
  IndexSample *aSample;    /* Samples of the left-most key */
  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
#endif
  Bitmask colNotIdxed;     /* Unindexed columns in pTab */







>







18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
  unsigned bNoQuery:1;     /* Do not use this index to optimize queries */
  unsigned bAscKeyBug:1;   /* True if the bba7b69f9849b5bf bug applies */
  unsigned bHasVCol:1;     /* Index references one or more VIRTUAL columns */
  unsigned bHasExpr:1;     /* Index contains an expression, either a literal
                           ** expression, or a reference to a VIRTUAL column */
#ifdef SQLITE_ENABLE_STAT4
  int nSample;             /* Number of elements in aSample[] */
  int mxSample;            /* Number of slots allocated to aSample[] */
  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
  IndexSample *aSample;    /* Samples of the left-most key */
  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
#endif
  Bitmask colNotIdxed;     /* Unindexed columns in pTab */
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
#define NC_AllowAgg  0x000001 /* Aggregate functions are allowed here */
#define NC_PartIdx   0x000002 /* True if resolving a partial index WHERE */
#define NC_IsCheck   0x000004 /* True if resolving a CHECK constraint */
#define NC_GenCol    0x000008 /* True for a GENERATED ALWAYS AS clause */
#define NC_HasAgg    0x000010 /* One or more aggregate functions seen */
#define NC_IdxExpr   0x000020 /* True if resolving columns of CREATE INDEX */
#define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
#define NC_VarSelect 0x000040 /* A correlated subquery has been seen */
#define NC_UEList    0x000080 /* True if uNC.pEList is used */
#define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */
#define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */
#define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */
#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */
#define NC_Complex   0x002000 /* True if a function or subquery seen */
#define NC_AllowWin  0x004000 /* Window functions are allowed here */







|







18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
#define NC_AllowAgg  0x000001 /* Aggregate functions are allowed here */
#define NC_PartIdx   0x000002 /* True if resolving a partial index WHERE */
#define NC_IsCheck   0x000004 /* True if resolving a CHECK constraint */
#define NC_GenCol    0x000008 /* True for a GENERATED ALWAYS AS clause */
#define NC_HasAgg    0x000010 /* One or more aggregate functions seen */
#define NC_IdxExpr   0x000020 /* True if resolving columns of CREATE INDEX */
#define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
#define NC_Subquery  0x000040 /* A subquery has been seen */
#define NC_UEList    0x000080 /* True if uNC.pEList is used */
#define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */
#define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */
#define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */
#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */
#define NC_Complex   0x002000 /* True if a function or subquery seen */
#define NC_AllowWin  0x004000 /* Window functions are allowed here */
19205
19206
19207
19208
19209
19210
19211



19212
19213
19214
19215
19216
19217
19218
  u8 okConstFactor;    /* OK to factor out constants */
  u8 disableLookaside; /* Number of times lookaside has been disabled */
  u8 prepFlags;        /* SQLITE_PREPARE_* flags */
  u8 withinRJSubrtn;   /* Nesting level for RIGHT JOIN body subroutines */
#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  u8 earlyCleanup;     /* OOM inside sqlite3ParserAddCleanup() */
#endif



  int nRangeReg;       /* Size of the temporary register block */
  int iRangeReg;       /* First register in temporary register block */
  int nErr;            /* Number of errors seen */
  int nTab;            /* Number of previously allocated VDBE cursors */
  int nMem;            /* Number of memory cells used so far */
  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
  int iSelfTab;        /* Table associated with an index on expr, or negative







>
>
>







19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
  u8 okConstFactor;    /* OK to factor out constants */
  u8 disableLookaside; /* Number of times lookaside has been disabled */
  u8 prepFlags;        /* SQLITE_PREPARE_* flags */
  u8 withinRJSubrtn;   /* Nesting level for RIGHT JOIN body subroutines */
#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  u8 earlyCleanup;     /* OOM inside sqlite3ParserAddCleanup() */
#endif
#ifdef SQLITE_DEBUG
  u8 ifNotExists;      /* Might be true if IF NOT EXISTS.  Assert()s only */
#endif
  int nRangeReg;       /* Size of the temporary register block */
  int iRangeReg;       /* First register in temporary register block */
  int nErr;            /* Number of errors seen */
  int nTab;            /* Number of previously allocated VDBE cursors */
  int nMem;            /* Number of memory cells used so far */
  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
  int iSelfTab;        /* Table associated with an index on expr, or negative
19665
19666
19667
19668
19669
19670
19671

19672
19673
19674
19675
19676
19677
19678
    struct WindowRewrite *pRewrite;           /* Window rewrite context */
    struct WhereConst *pConst;                /* WHERE clause constants */
    struct RenameCtx *pRename;                /* RENAME COLUMN context */
    struct Table *pTab;                       /* Table of generated column */
    struct CoveringIndexCheck *pCovIdxCk;     /* Check for covering index */
    SrcItem *pSrcItem;                        /* A single FROM clause item */
    DbFixer *pFix;                            /* See sqlite3FixSelect() */

  } u;
};

/*
** The following structure contains information used by the sqliteFix...
** routines as they walk the parse tree to make database references
** explicit.







>







19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
    struct WindowRewrite *pRewrite;           /* Window rewrite context */
    struct WhereConst *pConst;                /* WHERE clause constants */
    struct RenameCtx *pRename;                /* RENAME COLUMN context */
    struct Table *pTab;                       /* Table of generated column */
    struct CoveringIndexCheck *pCovIdxCk;     /* Check for covering index */
    SrcItem *pSrcItem;                        /* A single FROM clause item */
    DbFixer *pFix;                            /* See sqlite3FixSelect() */
    Mem *aMem;                                /* See sqlite3BtreeCursorHint() */
  } u;
};

/*
** The following structure contains information used by the sqliteFix...
** routines as they walk the parse tree to make database references
** explicit.
19934
19935
19936
19937
19938
19939
19940


19941
19942
19943
19944
19945
19946
19947
19948
19949


19950
19951
19952
19953
19954
19955
19956
# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)


#else
# define sqlite3Toupper(x)   toupper((unsigned char)(x))
# define sqlite3Isspace(x)   isspace((unsigned char)(x))
# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
# define sqlite3Tolower(x)   tolower((unsigned char)(x))
# define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')


#endif
SQLITE_PRIVATE int sqlite3IsIdChar(u8);

/*
** Internal function prototypes
*/
SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);







>
>









>
>







20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
# define sqlite3JsonId1(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x42)
# define sqlite3JsonId2(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x46)
#else
# define sqlite3Toupper(x)   toupper((unsigned char)(x))
# define sqlite3Isspace(x)   isspace((unsigned char)(x))
# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
# define sqlite3Tolower(x)   tolower((unsigned char)(x))
# define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
# define sqlite3JsonId1(x)   (sqlite3IsIdChar(x)&&(x)<'0')
# define sqlite3JsonId2(x)   sqlite3IsIdChar(x)
#endif
SQLITE_PRIVATE int sqlite3IsIdChar(u8);

/*
** Internal function prototypes
*/
SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
20136
20137
20138
20139
20140
20141
20142




20143
20144
20145
20146
20147
20148
20149
SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*);
SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);




#ifdef SQLITE_DEBUG
SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
#endif
SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);







>
>
>
>







20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*);
SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
SQLITE_PRIVATE void sqlite3TouchRegister(Parse*,int);
#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
SQLITE_PRIVATE int sqlite3FirstAvailableRegister(Parse*,int);
#endif
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
#endif
SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
                          Expr*, int, int, u8);
SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
                         Expr*,ExprList*,u32,Expr*);
SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
#endif
SQLITE_PRIVATE void sqlite3CodeChangeCount(Vdbe*,int,const char*);
SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,







|







20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
                          Expr*, int, int, u8);
SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
                         Expr*,ExprList*,u32,Expr*);
SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, Trigger*);
SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
#endif
SQLITE_PRIVATE void sqlite3CodeChangeCount(Vdbe*,int,const char*);
SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
SQLITE_PRIVATE int sqlite3ExprIsTableConstraint(Expr*,const SrcItem*);
#ifdef SQLITE_ENABLE_CURSOR_HINTS
SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
#endif
SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*);
SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
SQLITE_PRIVATE int sqlite3IsRowid(const char*);







|







20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int);
#ifdef SQLITE_ENABLE_CURSOR_HINTS
SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
#endif
SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*);
SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
SQLITE_PRIVATE int sqlite3IsRowid(const char*);
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);

SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
    && !defined(SQLITE_OMIT_VIRTUALTABLE)
SQLITE_PRIVATE   void sqlite3VtabUsesAllSchemas(sqlite3_index_info*);
#endif
SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse*,sqlite3*);
SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse*);
SQLITE_PRIVATE void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
#ifdef SQLITE_ENABLE_NORMALIZE







<
<
|
<







20952
20953
20954
20955
20956
20957
20958


20959

20960
20961
20962
20963
20964
20965
20966
SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);

SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);


SQLITE_PRIVATE void sqlite3VtabUsesAllSchemas(Parse*);

SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse*,sqlite3*);
SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse*);
SQLITE_PRIVATE void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
#ifdef SQLITE_ENABLE_NORMALIZE
21072
21073
21074
21075
21076
21077
21078






21079
21080
21081
21082
21083
21084
21085
#endif

#if defined(VDBE_PROFILE) \
 || defined(SQLITE_PERFORMANCE_TRACE) \
 || defined(SQLITE_ENABLE_STMT_SCANSTATUS)
SQLITE_PRIVATE sqlite3_uint64 sqlite3Hwtime(void);
#endif







#endif /* SQLITEINT_H */

/************** End of sqliteInt.h *******************************************/
/************** Begin file os_common.h ***************************************/
/*
** 2004 May 22







>
>
>
>
>
>







21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
#endif

#if defined(VDBE_PROFILE) \
 || defined(SQLITE_PERFORMANCE_TRACE) \
 || defined(SQLITE_ENABLE_STMT_SCANSTATUS)
SQLITE_PRIVATE sqlite3_uint64 sqlite3Hwtime(void);
#endif

#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
# define IS_STMT_SCANSTATUS(db) (db->flags & SQLITE_StmtScanStatus)
#else
# define IS_STMT_SCANSTATUS(db) 0
#endif

#endif /* SQLITEINT_H */

/************** End of sqliteInt.h *******************************************/
/************** Begin file os_common.h ***************************************/
/*
** 2004 May 22
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
**
**   isspace()                        0x01
**   isalpha()                        0x02
**   isdigit()                        0x04
**   isalnum()                        0x06
**   isxdigit()                       0x08
**   toupper()                        0x20
**   SQLite identifier character      0x40
**   Quote character                  0x80
**
** Bit 0x20 is set if the mapped character requires translation to upper
** case. i.e. if the character is a lower-case ASCII character.
** If x is a lower-case ASCII character, then its upper-case equivalent
** is (x - 0x20). Therefore toupper() can be implemented as:
**







|







22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
**
**   isspace()                        0x01
**   isalpha()                        0x02
**   isdigit()                        0x04
**   isalnum()                        0x06
**   isxdigit()                       0x08
**   toupper()                        0x20
**   SQLite identifier character      0x40   $, _, or non-ascii
**   Quote character                  0x80
**
** Bit 0x20 is set if the mapped character requires translation to upper
** case. i.e. if the character is a lower-case ASCII character.
** If x is a lower-case ASCII character, then its upper-case equivalent
** is (x - 0x20). Therefore toupper() can be implemented as:
**
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
#endif
   0,                         /* bLocaltimeFault */
   0,                         /* xAltLocaltime */
   0x7ffffffe,                /* iOnceResetThreshold */
   SQLITE_DEFAULT_SORTERREF_SIZE,   /* szSorterRef */
   0,                         /* iPrngSeed */
#ifdef SQLITE_DEBUG
   {0,0,0,0,0,0}              /* aTune */
#endif
};

/*
** Hash table for global functions - functions common to all
** database connections.  After initialization, this table is
** read-only.







|







22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
#endif
   0,                         /* bLocaltimeFault */
   0,                         /* xAltLocaltime */
   0x7ffffffe,                /* iOnceResetThreshold */
   SQLITE_DEFAULT_SORTERREF_SIZE,   /* szSorterRef */
   0,                         /* iPrngSeed */
#ifdef SQLITE_DEBUG
   {0,0,0,0,0,0},             /* aTune */
#endif
};

/*
** Hash table for global functions - functions common to all
** database connections.  After initialization, this table is
** read-only.
23561
23562
23563
23564
23565
23566
23567

23568
23569
23570
23571
23572
23573
23574
  char validJD;       /* True (1) if iJD is valid */
  char rawS;          /* Raw numeric value stored in s */
  char validYMD;      /* True (1) if Y,M,D are valid */
  char validHMS;      /* True (1) if h,m,s are valid */
  char validTZ;       /* True (1) if tz is valid */
  char tzSet;         /* Timezone was set explicitly */
  char isError;       /* An overflow has occurred */

};


/*
** Convert zDate into one or more integers according to the conversion
** specifier zFormat.
**







>







23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
  char validJD;       /* True (1) if iJD is valid */
  char rawS;          /* Raw numeric value stored in s */
  char validYMD;      /* True (1) if Y,M,D are valid */
  char validHMS;      /* True (1) if h,m,s are valid */
  char validTZ;       /* True (1) if tz is valid */
  char tzSet;         /* Timezone was set explicitly */
  char isError;       /* An overflow has occurred */
  char useSubsec;     /* Display subsecond precision */
};


/*
** Convert zDate into one or more integers according to the conversion
** specifier zFormat.
**
23875
23876
23877
23878
23879
23880
23881





23882
23883
23884
23885
23886
23887
23888
  }else if( parseHhMmSs(zDate, p)==0 ){
    return 0;
  }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
    return setDateTimeToCurrent(context, p);
  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
    setRawDateNumber(p, r);
    return 0;





  }
  return 1;
}

/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
** Multiplying this by 86400000 gives 464269060799999 as the maximum value
** for DateTime.iJD.







>
>
>
>
>







24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
  }else if( parseHhMmSs(zDate, p)==0 ){
    return 0;
  }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
    return setDateTimeToCurrent(context, p);
  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
    setRawDateNumber(p, r);
    return 0;
  }else if( (sqlite3StrICmp(zDate,"subsec")==0
             || sqlite3StrICmp(zDate,"subsecond")==0)
           && sqlite3NotPureFunc(context) ){
    p->useSubsec = 1;
    return setDateTimeToCurrent(context, p);
  }
  return 1;
}

/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
** Multiplying this by 86400000 gives 464269060799999 as the maximum value
** for DateTime.iJD.
24289
24290
24291
24292
24293
24294
24295






24296
24297








24298
24299
24300
24301
24302
24303
24304
    }
    case 's': {
      /*
      **    start of TTTTT
      **
      ** Move the date backwards to the beginning of the current day,
      ** or month or year.






      */
      if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;








      if( !p->validJD && !p->validYMD && !p->validHMS ) break;
      z += 9;
      computeYMD(p);
      p->validHMS = 1;
      p->h = p->m = 0;
      p->s = 0.0;
      p->rawS = 0;







>
>
>
>
>
>

|
>
>
>
>
>
>
>
>







24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
    }
    case 's': {
      /*
      **    start of TTTTT
      **
      ** Move the date backwards to the beginning of the current day,
      ** or month or year.
      **
      **    subsecond
      **    subsec
      **
      ** Show subsecond precision in the output of datetime() and
      ** unixepoch() and strftime('%s').
      */
      if( sqlite3_strnicmp(z, "start of ", 9)!=0 ){
        if( sqlite3_stricmp(z, "subsec")==0
         || sqlite3_stricmp(z, "subsecond")==0
        ){
          p->useSubsec = 1;
          rc = 0;
        }
        break;
      }
      if( !p->validJD && !p->validYMD && !p->validHMS ) break;
      z += 9;
      computeYMD(p);
      p->validHMS = 1;
      p->h = p->m = 0;
      p->s = 0.0;
      p->rawS = 0;
24488
24489
24490
24491
24492
24493
24494



24495

24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532











24533
24534
24535
24536


24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566











24567
24568
24569
24570


24571
24572
24573
24574
24575
24576
24577
24578
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    computeJD(&x);



    sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000);

  }
}

/*
**    datetime( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD HH:MM:SS
*/
static void datetimeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    int Y, s;
    char zBuf[24];
    computeYMD_HMS(&x);
    Y = x.Y;
    if( Y<0 ) Y = -Y;
    zBuf[1] = '0' + (Y/1000)%10;
    zBuf[2] = '0' + (Y/100)%10;
    zBuf[3] = '0' + (Y/10)%10;
    zBuf[4] = '0' + (Y)%10;
    zBuf[5] = '-';
    zBuf[6] = '0' + (x.M/10)%10;
    zBuf[7] = '0' + (x.M)%10;
    zBuf[8] = '-';
    zBuf[9] = '0' + (x.D/10)%10;
    zBuf[10] = '0' + (x.D)%10;
    zBuf[11] = ' ';
    zBuf[12] = '0' + (x.h/10)%10;
    zBuf[13] = '0' + (x.h)%10;
    zBuf[14] = ':';
    zBuf[15] = '0' + (x.m/10)%10;
    zBuf[16] = '0' + (x.m)%10;
    zBuf[17] = ':';











    s = (int)x.s;
    zBuf[18] = '0' + (s/10)%10;
    zBuf[19] = '0' + (s)%10;
    zBuf[20] = 0;


    if( x.Y<0 ){
      zBuf[0] = '-';
      sqlite3_result_text(context, zBuf, 20, SQLITE_TRANSIENT);
    }else{
      sqlite3_result_text(context, &zBuf[1], 19, SQLITE_TRANSIENT);
    }
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
*/
static void timeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    int s;
    char zBuf[16];
    computeHMS(&x);
    zBuf[0] = '0' + (x.h/10)%10;
    zBuf[1] = '0' + (x.h)%10;
    zBuf[2] = ':';
    zBuf[3] = '0' + (x.m/10)%10;
    zBuf[4] = '0' + (x.m)%10;
    zBuf[5] = ':';











    s = (int)x.s;
    zBuf[6] = '0' + (s/10)%10;
    zBuf[7] = '0' + (s)%10;
    zBuf[8] = 0;


    sqlite3_result_text(context, zBuf, 8, SQLITE_TRANSIENT);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD







>
>
>
|
>















|
|




















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


|

|
















|








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







24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    computeJD(&x);
    if( x.useSubsec ){
      sqlite3_result_double(context, (x.iJD - 21086676*(i64)10000000)/1000.0);
    }else{
      sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000);
    }
  }
}

/*
**    datetime( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD HH:MM:SS
*/
static void datetimeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    int Y, s, n;
    char zBuf[32];
    computeYMD_HMS(&x);
    Y = x.Y;
    if( Y<0 ) Y = -Y;
    zBuf[1] = '0' + (Y/1000)%10;
    zBuf[2] = '0' + (Y/100)%10;
    zBuf[3] = '0' + (Y/10)%10;
    zBuf[4] = '0' + (Y)%10;
    zBuf[5] = '-';
    zBuf[6] = '0' + (x.M/10)%10;
    zBuf[7] = '0' + (x.M)%10;
    zBuf[8] = '-';
    zBuf[9] = '0' + (x.D/10)%10;
    zBuf[10] = '0' + (x.D)%10;
    zBuf[11] = ' ';
    zBuf[12] = '0' + (x.h/10)%10;
    zBuf[13] = '0' + (x.h)%10;
    zBuf[14] = ':';
    zBuf[15] = '0' + (x.m/10)%10;
    zBuf[16] = '0' + (x.m)%10;
    zBuf[17] = ':';
    if( x.useSubsec ){
      s = (int)1000.0*x.s;
      zBuf[18] = '0' + (s/10000)%10;
      zBuf[19] = '0' + (s/1000)%10;
      zBuf[20] = '.';
      zBuf[21] = '0' + (s/100)%10;
      zBuf[22] = '0' + (s/10)%10;
      zBuf[23] = '0' + (s)%10;
      zBuf[24] = 0;
      n = 24;
    }else{
      s = (int)x.s;
      zBuf[18] = '0' + (s/10)%10;
      zBuf[19] = '0' + (s)%10;
      zBuf[20] = 0;
      n = 20;
    }
    if( x.Y<0 ){
      zBuf[0] = '-';
      sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
    }else{
      sqlite3_result_text(context, &zBuf[1], n-1, SQLITE_TRANSIENT);
    }
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
*/
static void timeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    int s, n;
    char zBuf[16];
    computeHMS(&x);
    zBuf[0] = '0' + (x.h/10)%10;
    zBuf[1] = '0' + (x.h)%10;
    zBuf[2] = ':';
    zBuf[3] = '0' + (x.m/10)%10;
    zBuf[4] = '0' + (x.m)%10;
    zBuf[5] = ':';
    if( x.useSubsec ){
      s = (int)1000.0*x.s;
      zBuf[6] = '0' + (s/10000)%10;
      zBuf[7] = '0' + (s/1000)%10;
      zBuf[8] = '.';
      zBuf[9] = '0' + (s/100)%10;
      zBuf[10] = '0' + (s/10)%10;
      zBuf[11] = '0' + (s)%10;
      zBuf[12] = 0;
      n = 12;
    }else{
      s = (int)x.s;
      zBuf[6] = '0' + (s/10)%10;
      zBuf[7] = '0' + (s)%10;
      zBuf[8] = 0;
      n = 8;
    }
    sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD
24695
24696
24697
24698
24699
24700
24701




24702
24703

24704
24705
24706
24707
24708
24709
24710
        break;
      }
      case 'M': {
        sqlite3_str_appendf(&sRes,"%02d",x.m);
        break;
      }
      case 's': {




        i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
        sqlite3_str_appendf(&sRes,"%lld",iS);

        break;
      }
      case 'S': {
        sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
        break;
      }
      case 'w': {







>
>
>
>
|
|
>







24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
        break;
      }
      case 'M': {
        sqlite3_str_appendf(&sRes,"%02d",x.m);
        break;
      }
      case 's': {
        if( x.useSubsec ){
          sqlite3_str_appendf(&sRes,"%.3f",
                (x.iJD - 21086676*(i64)10000000)/1000.0);
        }else{
          i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
          sqlite3_str_appendf(&sRes,"%lld",iS);
        }
        break;
      }
      case 'S': {
        sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
        break;
      }
      case 'w': {
30067
30068
30069
30070
30071
30072
30073














30074
30075
30076
30077
30078
30079
30080
  d = digit;
  digit += '0';
  *val = (*val - d)*10.0;
  return (char)digit;
}
#endif /* SQLITE_OMIT_FLOATING_POINT */















/*
** Set the StrAccum object to an error mode.
*/
SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum *p, u8 eError){
  assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
  p->accError = eError;
  if( p->mxAlloc ) sqlite3_str_reset(p);







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







30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
  d = digit;
  digit += '0';
  *val = (*val - d)*10.0;
  return (char)digit;
}
#endif /* SQLITE_OMIT_FLOATING_POINT */

#ifndef SQLITE_OMIT_FLOATING_POINT
/*
** "*val" is a u64.  *msd is a divisor used to extract the
** most significant digit of *val.  Extract that most significant
** digit and return it.
*/
static char et_getdigit_int(u64 *val, u64 *msd){
  u64 x = (*val)/(*msd);
  *val -= x*(*msd);
  if( *msd>=10 ) *msd /= 10;
  return '0' + (char)(x & 15);
}
#endif /* SQLITE_OMIT_FLOATING_POINT */

/*
** Set the StrAccum object to an error mode.
*/
SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum *p, u8 eError){
  assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
  p->accError = eError;
  if( p->mxAlloc ) sqlite3_str_reset(p);
30159
30160
30161
30162
30163
30164
30165


30166
30167
30168
30169
30170
30171
30172
  etByte done;               /* Loop termination flag */
  etByte cThousand;          /* Thousands separator for %d and %u */
  etByte xtype = etINVALID;  /* Conversion paradigm */
  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
  sqlite_uint64 longvalue;   /* Value for integer types */
  LONGDOUBLE_TYPE realvalue; /* Value for real types */


  const et_info *infop;      /* Pointer to the appropriate info structure */
  char *zOut;                /* Rendering buffer */
  int nOut;                  /* Size of the rendering buffer */
  char *zExtra = 0;          /* Malloced memory used by some conversion */
#ifndef SQLITE_OMIT_FLOATING_POINT
  int  exp, e2;              /* exponent of real numbers */
  int nsd;                   /* Number of significant digits returned */







>
>







30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
  etByte done;               /* Loop termination flag */
  etByte cThousand;          /* Thousands separator for %d and %u */
  etByte xtype = etINVALID;  /* Conversion paradigm */
  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
  sqlite_uint64 longvalue;   /* Value for integer types */
  LONGDOUBLE_TYPE realvalue; /* Value for real types */
  sqlite_uint64 msd;         /* Divisor to get most-significant-digit
                             ** of longvalue */
  const et_info *infop;      /* Pointer to the appropriate info structure */
  char *zOut;                /* Rendering buffer */
  int nOut;                  /* Size of the rendering buffer */
  char *zExtra = 0;          /* Malloced memory used by some conversion */
#ifndef SQLITE_OMIT_FLOATING_POINT
  int  exp, e2;              /* exponent of real numbers */
  int nsd;                   /* Number of significant digits returned */
30465
30466
30467
30468
30469
30470
30471

30472
30473














30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488




30489
30490

30491
30492


30493
30494
30495
30496
30497
30498
30499
30500
30501




30502
30503
30504
30505
30506
30507
30508






30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533


30534
30535
30536

30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551





30552
30553
30554

30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567

30568




30569

30570
30571
30572
30573
30574
30575
30576
#endif
        if( realvalue<0.0 ){
          realvalue = -realvalue;
          prefix = '-';
        }else{
          prefix = flag_prefix;
        }

        if( xtype==etGENERIC && precision>0 ) precision--;
        testcase( precision>0xfff );














        idx = precision & 0xfff;
        rounder = arRound[idx%10];
        while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
        if( xtype==etFLOAT ){
          double rx = (double)realvalue;
          sqlite3_uint64 u;
          int ex;
          memcpy(&u, &rx, sizeof(u));
          ex = -1023 + (int)((u>>52)&0x7ff);
          if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
          realvalue += rounder;
        }
        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
        exp = 0;
        if( sqlite3IsNaN((double)realvalue) ){




          bufpt = "NaN";
          length = 3;

          break;
        }


        if( realvalue>0.0 ){
          LONGDOUBLE_TYPE scale = 1.0;
          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
          while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
          realvalue /= scale;
          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
          if( exp>350 ){




            bufpt = buf;
            buf[0] = prefix;
            memcpy(buf+(prefix!=0),"Inf",4);
            length = 3+(prefix!=0);
            break;
          }
        }






        bufpt = buf;
        /*
        ** If the field type is etGENERIC, then convert to either etEXP
        ** or etFLOAT, as appropriate.
        */
        if( xtype!=etFLOAT ){
          realvalue += rounder;
          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
        }
        if( xtype==etGENERIC ){
          flag_rtz = !flag_alternateform;
          if( exp<-4 || exp>precision ){
            xtype = etEXP;
          }else{
            precision = precision - exp;
            xtype = etFLOAT;
          }
        }else{
          flag_rtz = flag_altform2;
        }
        if( xtype==etEXP ){
          e2 = 0;
        }else{
          e2 = exp;
        }


        {
          i64 szBufNeeded;           /* Size of a temporary buffer needed */
          szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;

          if( szBufNeeded > etBUFSIZE ){
            bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
            if( bufpt==0 ) return;
          }
        }
        zOut = bufpt;
        nsd = 16 + flag_altform2*10;
        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
        /* The sign in front of the number */
        if( prefix ){
          *(bufpt++) = prefix;
        }
        /* Digits prior to the decimal point */
        if( e2<0 ){
          *(bufpt++) = '0';





        }else{
          for(; e2>=0; e2--){
            *(bufpt++) = et_getdigit(&realvalue,&nsd);

          }
        }
        /* The decimal point */
        if( flag_dp ){
          *(bufpt++) = '.';
        }
        /* "0" digits after the decimal point but before the first
        ** significant digit of the number */
        for(e2++; e2<0; precision--, e2++){
          assert( precision>0 );
          *(bufpt++) = '0';
        }
        /* Significant digits after the decimal point */

        while( (precision--)>0 ){




          *(bufpt++) = et_getdigit(&realvalue,&nsd);

        }
        /* Remove trailing zeros and the "." if no digits follow the "." */
        if( flag_rtz && flag_dp ){
          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
          assert( bufpt>zOut );
          if( bufpt[-1]=='.' ){
            if( flag_altform2 ){







>


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




<
<
<
<
















>
>



>






<








>
>
>
>
>



>













>
|
>
>
>
>
|
>







30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703


30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746




30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774

30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
#endif
        if( realvalue<0.0 ){
          realvalue = -realvalue;
          prefix = '-';
        }else{
          prefix = flag_prefix;
        }
        exp = 0;
        if( xtype==etGENERIC && precision>0 ) precision--;
        testcase( precision>0xfff );
        if( realvalue<1.0e+16
         && realvalue==(LONGDOUBLE_TYPE)(longvalue = (u64)realvalue)
        ){
          /* Number is a pure integer that can be represented as u64 */
          for(msd=1; msd*10<=longvalue; msd *= 10, exp++){}
          if( exp>precision && xtype!=etFLOAT ){
            u64 rnd = msd/2;
            int kk = precision;
            while( kk-- > 0 ){  rnd /= 10; }
            longvalue += rnd;
          }
        }else{
          msd = 0;
          longvalue = 0;  /* To prevent a compiler warning */
          idx = precision & 0xfff;
          rounder = arRound[idx%10];
          while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
          if( xtype==etFLOAT ){
            double rx = (double)realvalue;
            sqlite3_uint64 u;
            int ex;
            memcpy(&u, &rx, sizeof(u));
            ex = -1023 + (int)((u>>52)&0x7ff);
            if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
            realvalue += rounder;
          }


          if( sqlite3IsNaN((double)realvalue) ){
            if( flag_zeropad ){
              bufpt = "null";
              length = 4;
            }else{
              bufpt = "NaN";
              length = 3;
            }
            break;
          }

          /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
          if( ALWAYS(realvalue>0.0) ){
            LONGDOUBLE_TYPE scale = 1.0;
            while( realvalue>=1e100*scale && exp<=350){ scale*=1e100;exp+=100;}
            while( realvalue>=1e10*scale && exp<=350 ){ scale*=1e10; exp+=10; }
            while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
            realvalue /= scale;
            while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
            while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
            if( exp>350 ){
              if( flag_zeropad ){
                realvalue = 9.0;
                exp = 999;
              }else{
                bufpt = buf;
                buf[0] = prefix;
                memcpy(buf+(prefix!=0),"Inf",4);
                length = 3+(prefix!=0);
                break;
              }
            }
            if( xtype!=etFLOAT ){
              realvalue += rounder;
              if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
            }
          }
        }

        /*
        ** If the field type is etGENERIC, then convert to either etEXP
        ** or etFLOAT, as appropriate.
        */




        if( xtype==etGENERIC ){
          flag_rtz = !flag_alternateform;
          if( exp<-4 || exp>precision ){
            xtype = etEXP;
          }else{
            precision = precision - exp;
            xtype = etFLOAT;
          }
        }else{
          flag_rtz = flag_altform2;
        }
        if( xtype==etEXP ){
          e2 = 0;
        }else{
          e2 = exp;
        }
        nsd = 16 + flag_altform2*10;
        bufpt = buf;
        {
          i64 szBufNeeded;           /* Size of a temporary buffer needed */
          szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
          if( cThousand && e2>0 ) szBufNeeded += (e2+2)/3;
          if( szBufNeeded > etBUFSIZE ){
            bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
            if( bufpt==0 ) return;
          }
        }
        zOut = bufpt;

        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
        /* The sign in front of the number */
        if( prefix ){
          *(bufpt++) = prefix;
        }
        /* Digits prior to the decimal point */
        if( e2<0 ){
          *(bufpt++) = '0';
        }else if( msd>0 ){
          for(; e2>=0; e2--){
            *(bufpt++) = et_getdigit_int(&longvalue,&msd);
            if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ',';
          }
        }else{
          for(; e2>=0; e2--){
            *(bufpt++) = et_getdigit(&realvalue,&nsd);
            if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ',';
          }
        }
        /* The decimal point */
        if( flag_dp ){
          *(bufpt++) = '.';
        }
        /* "0" digits after the decimal point but before the first
        ** significant digit of the number */
        for(e2++; e2<0; precision--, e2++){
          assert( precision>0 );
          *(bufpt++) = '0';
        }
        /* Significant digits after the decimal point */
        if( msd>0 ){
          while( (precision--)>0 ){
            *(bufpt++) = et_getdigit_int(&longvalue,&msd);
          }
        }else{
          while( (precision--)>0 ){
            *(bufpt++) = et_getdigit(&realvalue,&nsd);
          }
        }
        /* Remove trailing zeros and the "." if no digits follow the "." */
        if( flag_rtz && flag_dp ){
          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
          assert( bufpt>zOut );
          if( bufpt[-1]=='.' ){
            if( flag_altform2 ){
31243
31244
31245
31246
31247
31248
31249
31250
31251









31252
31253
31254

31255
31256
31257
31258
31259
31260
31261
31262
#endif
  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  sqlite3_str_vappendf(&acc, zFormat, ap);
  zBuf[acc.nChar] = 0;
  return zBuf;
}
SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  char *z;
  va_list ap;









  va_start(ap,zFormat);
  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  va_end(ap);

  return z;
}

/*
** This is the routine that actually formats the sqlite3_log() message.
** We house it in a separate routine from sqlite3_log() to avoid using
** stack space on small-stack systems when logging is disabled.
**







|

>
>
>
>
>
>
>
>
>

|

>
|







31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
#endif
  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  sqlite3_str_vappendf(&acc, zFormat, ap);
  zBuf[acc.nChar] = 0;
  return zBuf;
}
SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  StrAccum acc;
  va_list ap;
  if( n<=0 ) return zBuf;
#ifdef SQLITE_ENABLE_API_ARMOR
  if( zBuf==0 || zFormat==0 ) {
    (void)SQLITE_MISUSE_BKPT;
    if( zBuf ) zBuf[0] = 0;
    return zBuf;
  }
#endif
  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  va_start(ap,zFormat);
  sqlite3_str_vappendf(&acc, zFormat, ap);
  va_end(ap);
  zBuf[acc.nChar] = 0;
  return zBuf;
}

/*
** This is the routine that actually formats the sqlite3_log() message.
** We house it in a separate routine from sqlite3_log() to avoid using
** stack space on small-stack systems when logging is disabled.
**
34278
34279
34280
34281
34282
34283
34284
34285

34286
34287
34288


34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
  if( v<0 ){
    x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
  }else{
    x = v;
  }
  i = sizeof(zTemp)-2;
  zTemp[sizeof(zTemp)-1] = 0;
  do{

    zTemp[i--] = (x%10) + '0';
    x = x/10;
  }while( x );


  if( v<0 ) zTemp[i--] = '-';
  memcpy(zOut, &zTemp[i+1], sizeof(zTemp)-1-i);
  return sizeof(zTemp)-2-i;
}

/*
** Compare the 19-character string zNum against the text representation
** value 2^63:  9223372036854775808.  Return negative, zero, or positive
** if zNum is less than, equal to, or greater than the string.
** Note that zNum must contain exactly 19 characters.







<
>
|

|
>
>
|
|
|







34531
34532
34533
34534
34535
34536
34537

34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
  if( v<0 ){
    x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
  }else{
    x = v;
  }
  i = sizeof(zTemp)-2;
  zTemp[sizeof(zTemp)-1] = 0;

  while( 1 /*exit-by-break*/ ){
    zTemp[i] = (x%10) + '0';
    x = x/10;
    if( x==0 ) break;
    i--;
  };
  if( v<0 ) zTemp[--i] = '-';
  memcpy(zOut, &zTemp[i], sizeof(zTemp)-i);
  return sizeof(zTemp)-1-i;
}

/*
** Compare the 19-character string zNum against the text representation
** value 2^63:  9223372036854775808.  Return negative, zero, or positive
** if zNum is less than, equal to, or greater than the string.
** Note that zNum must contain exactly 19 characters.
34449
34450
34451
34452
34453
34454
34455


34456
34457
34458
34459
34460
34461
34462
34463
    u64 u = 0;
    int i, k;
    for(i=2; z[i]=='0'; i++){}
    for(k=i; sqlite3Isxdigit(z[k]); k++){
      u = u*16 + sqlite3HexToInt(z[k]);
    }
    memcpy(pOut, &u, 8);


    return (z[k]==0 && k-i<=16) ? 0 : 2;
  }else
#endif /* SQLITE_OMIT_HEX_INTEGER */
  {
    return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  }
}








>
>
|







34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
    u64 u = 0;
    int i, k;
    for(i=2; z[i]=='0'; i++){}
    for(k=i; sqlite3Isxdigit(z[k]); k++){
      u = u*16 + sqlite3HexToInt(z[k]);
    }
    memcpy(pOut, &u, 8);
    if( k-i>16 ) return 2;
    if( z[k]!=0 ) return 1;
    return 0;
  }else
#endif /* SQLITE_OMIT_HEX_INTEGER */
  {
    return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  }
}

34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
  else if( zNum[0]=='0'
        && (zNum[1]=='x' || zNum[1]=='X')
        && sqlite3Isxdigit(zNum[2])
  ){
    u32 u = 0;
    zNum += 2;
    while( zNum[0]=='0' ) zNum++;
    for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
      u = u*16 + sqlite3HexToInt(zNum[i]);
    }
    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
      memcpy(pValue, &u, 4);
      return 1;
    }else{
      return 0;







|







34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
  else if( zNum[0]=='0'
        && (zNum[1]=='x' || zNum[1]=='X')
        && sqlite3Isxdigit(zNum[2])
  ){
    u32 u = 0;
    zNum += 2;
    while( zNum[0]=='0' ) zNum++;
    for(i=0; i<8 && sqlite3Isxdigit(zNum[i]); i++){
      u = u*16 + sqlite3HexToInt(zNum[i]);
    }
    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
      memcpy(pValue, &u, 4);
      return 1;
    }else{
      return 0;
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
#    define SQLITE_ENABLE_LOCKING_STYLE 1
#  else
#    define SQLITE_ENABLE_LOCKING_STYLE 0
#  endif
#endif

/* Use pread() and pwrite() if they are available */
#if defined(__APPLE__)
# define HAVE_PREAD 1
# define HAVE_PWRITE 1
#endif
#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
# undef USE_PREAD
# define USE_PREAD64 1
#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)







|







37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
#    define SQLITE_ENABLE_LOCKING_STYLE 1
#  else
#    define SQLITE_ENABLE_LOCKING_STYLE 0
#  endif
#endif

/* Use pread() and pwrite() if they are available */
#if defined(__APPLE__) || defined(__linux__)
# define HAVE_PREAD 1
# define HAVE_PWRITE 1
#endif
#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
# undef USE_PREAD
# define USE_PREAD64 1
#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
** are gather together into this division.
*/

/*
** Seek to the offset passed as the second argument, then read cnt
** bytes into pBuf. Return the number of bytes actually read.
**
** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
** one system to another.  Since SQLite does not define USE_PREAD
** in any form by default, we will not attempt to define _XOPEN_SOURCE.
** See tickets #2741 and #2681.
**
** To avoid stomping the errno value on a failed read the lastErrno value
** is set before returning.
*/
static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  int got;
  int prior = 0;
#if (!defined(USE_PREAD) && !defined(USE_PREAD64))







<
<
<
<
<
<







40488
40489
40490
40491
40492
40493
40494






40495
40496
40497
40498
40499
40500
40501
** are gather together into this division.
*/

/*
** Seek to the offset passed as the second argument, then read cnt
** bytes into pBuf. Return the number of bytes actually read.
**






** To avoid stomping the errno value on a failed read the lastErrno value
** is set before returning.
*/
static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  int got;
  int prior = 0;
#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
                        dwShareMode,
                        dwCreationDisposition,
                        &extendedParameters);
      if( h!=INVALID_HANDLE_VALUE ) break;
      if( isReadWrite ){
        int rc2, isRO = 0;
        sqlite3BeginBenignMalloc();
        rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
        sqlite3EndBenignMalloc();
        if( rc2==SQLITE_OK && isRO ) break;
      }
    }while( winRetryIoerr(&cnt, &lastErrno) );
#else
    do{
      h = osCreateFileW((LPCWSTR)zConverted,
                        dwDesiredAccess,
                        dwShareMode, NULL,
                        dwCreationDisposition,
                        dwFlagsAndAttributes,
                        NULL);
      if( h!=INVALID_HANDLE_VALUE ) break;
      if( isReadWrite ){
        int rc2, isRO = 0;
        sqlite3BeginBenignMalloc();
        rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
        sqlite3EndBenignMalloc();
        if( rc2==SQLITE_OK && isRO ) break;
      }
    }while( winRetryIoerr(&cnt, &lastErrno) );
#endif
  }
#ifdef SQLITE_WIN32_HAS_ANSI
  else{
    do{
      h = osCreateFileA((LPCSTR)zConverted,
                        dwDesiredAccess,
                        dwShareMode, NULL,
                        dwCreationDisposition,
                        dwFlagsAndAttributes,
                        NULL);
      if( h!=INVALID_HANDLE_VALUE ) break;
      if( isReadWrite ){
        int rc2, isRO = 0;
        sqlite3BeginBenignMalloc();
        rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
        sqlite3EndBenignMalloc();
        if( rc2==SQLITE_OK && isRO ) break;
      }
    }while( winRetryIoerr(&cnt, &lastErrno) );
  }
#endif
  winLogIoerr(cnt, __LINE__);







|
















|



















|







50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
                        dwShareMode,
                        dwCreationDisposition,
                        &extendedParameters);
      if( h!=INVALID_HANDLE_VALUE ) break;
      if( isReadWrite ){
        int rc2, isRO = 0;
        sqlite3BeginBenignMalloc();
        rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
        sqlite3EndBenignMalloc();
        if( rc2==SQLITE_OK && isRO ) break;
      }
    }while( winRetryIoerr(&cnt, &lastErrno) );
#else
    do{
      h = osCreateFileW((LPCWSTR)zConverted,
                        dwDesiredAccess,
                        dwShareMode, NULL,
                        dwCreationDisposition,
                        dwFlagsAndAttributes,
                        NULL);
      if( h!=INVALID_HANDLE_VALUE ) break;
      if( isReadWrite ){
        int rc2, isRO = 0;
        sqlite3BeginBenignMalloc();
        rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
        sqlite3EndBenignMalloc();
        if( rc2==SQLITE_OK && isRO ) break;
      }
    }while( winRetryIoerr(&cnt, &lastErrno) );
#endif
  }
#ifdef SQLITE_WIN32_HAS_ANSI
  else{
    do{
      h = osCreateFileA((LPCSTR)zConverted,
                        dwDesiredAccess,
                        dwShareMode, NULL,
                        dwCreationDisposition,
                        dwFlagsAndAttributes,
                        NULL);
      if( h!=INVALID_HANDLE_VALUE ) break;
      if( isReadWrite ){
        int rc2, isRO = 0;
        sqlite3BeginBenignMalloc();
        rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
        sqlite3EndBenignMalloc();
        if( rc2==SQLITE_OK && isRO ) break;
      }
    }while( winRetryIoerr(&cnt, &lastErrno) );
  }
#endif
  winLogIoerr(cnt, __LINE__);
50522
50523
50524
50525
50526
50527
50528







50529
50530
50531
50532
50533
50534
50535
  DWORD lastErrno = 0;
  void *zConverted;
  UNUSED_PARAMETER(pVfs);

  SimulateIOError( return SQLITE_IOERR_ACCESS; );
  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
           zFilename, flags, pResOut));








  zConverted = winConvertFromUtf8Filename(zFilename);
  if( zConverted==0 ){
    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
    return SQLITE_IOERR_NOMEM_BKPT;
  }
  if( osIsNT() ){







>
>
>
>
>
>
>







50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
  DWORD lastErrno = 0;
  void *zConverted;
  UNUSED_PARAMETER(pVfs);

  SimulateIOError( return SQLITE_IOERR_ACCESS; );
  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
           zFilename, flags, pResOut));

  if( zFilename==0 ){
    *pResOut = 0;
    OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
             zFilename, pResOut, *pResOut));
    return SQLITE_OK;
  }

  zConverted = winConvertFromUtf8Filename(zFilename);
  if( zConverted==0 ){
    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
    return SQLITE_IOERR_NOMEM_BKPT;
  }
  if( osIsNT() ){
52650
52651
52652
52653
52654
52655
52656
52657
52658
52659
52660
52661
52662
52663
52664
**   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
**   (so that the right page to eject can be found by following pDirtyPrev
**   pointers).
*/
struct PCache {
  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
  PgHdr *pSynced;                     /* Last synced page in dirty page list */
  int nRefSum;                        /* Sum of ref counts over all pages */
  int szCache;                        /* Configured cache size */
  int szSpill;                        /* Size before spilling occurs */
  int szPage;                         /* Size of every page in this cache */
  int szExtra;                        /* Size of extra space for each page */
  u8 bPurgeable;                      /* True if pages are on backing store */
  u8 eCreate;                         /* eCreate value for for xFetch() */
  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */







|







52908
52909
52910
52911
52912
52913
52914
52915
52916
52917
52918
52919
52920
52921
52922
**   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
**   (so that the right page to eject can be found by following pDirtyPrev
**   pointers).
*/
struct PCache {
  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
  PgHdr *pSynced;                     /* Last synced page in dirty page list */
  i64 nRefSum;                        /* Sum of ref counts over all pages */
  int szCache;                        /* Configured cache size */
  int szSpill;                        /* Size before spilling occurs */
  int szPage;                         /* Size of every page in this cache */
  int szExtra;                        /* Size of extra space for each page */
  u8 bPurgeable;                      /* True if pages are on backing store */
  u8 eCreate;                         /* eCreate value for for xFetch() */
  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
52679
52680
52681
52682
52683
52684
52685



52686
52687
52688
52689
52690

52691
52692
52693
52694
52695
52696
52697
52698
52699
52700
52701
52702
52703
52704
52705
52706
52707
52708
52709
52710
52711
52712
  int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
  int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  static void pcachePageTrace(int i, sqlite3_pcache_page *pLower){
    PgHdr *pPg;
    unsigned char *a;
    int j;



    pPg = (PgHdr*)pLower->pExtra;
    printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
    a = (unsigned char *)pLower->pBuf;
    for(j=0; j<12; j++) printf("%02x", a[j]);
    printf(" ptr %p\n", pPg);

  }
  static void pcacheDump(PCache *pCache){
    int N;
    int i;
    sqlite3_pcache_page *pLower;

    if( sqlite3PcacheTrace<2 ) return;
    if( pCache->pCache==0 ) return;
    N = sqlite3PcachePagecount(pCache);
    if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
    for(i=1; i<=N; i++){
       pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
       if( pLower==0 ) continue;
       pcachePageTrace(i, pLower);
       if( ((PgHdr*)pLower)->pPage==0 ){
         sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
       }
    }
  }
#else
# define pcacheTrace(X)
# define pcachePageTrace(PGNO, X)







>
>
>
|
|
|
|
|
>












<

|







52937
52938
52939
52940
52941
52942
52943
52944
52945
52946
52947
52948
52949
52950
52951
52952
52953
52954
52955
52956
52957
52958
52959
52960
52961
52962
52963
52964

52965
52966
52967
52968
52969
52970
52971
52972
52973
  int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
  int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  static void pcachePageTrace(int i, sqlite3_pcache_page *pLower){
    PgHdr *pPg;
    unsigned char *a;
    int j;
    if( pLower==0 ){
      printf("%3d: NULL\n", i);
    }else{
      pPg = (PgHdr*)pLower->pExtra;
      printf("%3d: nRef %2lld flgs %02x data ", i, pPg->nRef, pPg->flags);
      a = (unsigned char *)pLower->pBuf;
      for(j=0; j<12; j++) printf("%02x", a[j]);
      printf(" ptr %p\n", pPg);
    }
  }
  static void pcacheDump(PCache *pCache){
    int N;
    int i;
    sqlite3_pcache_page *pLower;

    if( sqlite3PcacheTrace<2 ) return;
    if( pCache->pCache==0 ) return;
    N = sqlite3PcachePagecount(pCache);
    if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
    for(i=1; i<=N; i++){
       pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);

       pcachePageTrace(i, pLower);
       if( pLower && ((PgHdr*)pLower)->pPage==0 ){
         sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
       }
    }
  }
#else
# define pcacheTrace(X)
# define pcachePageTrace(PGNO, X)
53424
53425
53426
53427
53428
53429
53430
53431
53432
53433
53434
53435
53436
53437
53438
53439
53440
53441
53442
53443
53444
53445

/*
** Return the total number of references to all pages held by the cache.
**
** This is not the total number of pages referenced, but the sum of the
** reference count for all pages.
*/
SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  return pCache->nRefSum;
}

/*
** Return the number of references to the page supplied as an argument.
*/
SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  return p->nRef;
}

/*
** Return the total number of pages in the cache.
*/
SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){







|






|







53685
53686
53687
53688
53689
53690
53691
53692
53693
53694
53695
53696
53697
53698
53699
53700
53701
53702
53703
53704
53705
53706

/*
** Return the total number of references to all pages held by the cache.
**
** This is not the total number of pages referenced, but the sum of the
** reference count for all pages.
*/
SQLITE_PRIVATE i64 sqlite3PcacheRefCount(PCache *pCache){
  return pCache->nRefSum;
}

/*
** Return the number of references to the page supplied as an argument.
*/
SQLITE_PRIVATE i64 sqlite3PcachePageRefcount(PgHdr *p){
  return p->nRef;
}

/*
** Return the total number of pages in the cache.
*/
SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
58086
58087
58088
58089
58090
58091
58092


58093
58094
58095
58096
58097
58098
58099
** If successful, return SQLITE_OK. If an IO error occurs while modifying
** the database file, return the error code to the caller.
*/
static int pager_truncate(Pager *pPager, Pgno nPage){
  int rc = SQLITE_OK;
  assert( pPager->eState!=PAGER_ERROR );
  assert( pPager->eState!=PAGER_READER );



  if( isOpen(pPager->fd)
   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  ){
    i64 currentSize, newSize;
    int szPage = pPager->pageSize;
    assert( pPager->eLock==EXCLUSIVE_LOCK );







>
>







58347
58348
58349
58350
58351
58352
58353
58354
58355
58356
58357
58358
58359
58360
58361
58362
** If successful, return SQLITE_OK. If an IO error occurs while modifying
** the database file, return the error code to the caller.
*/
static int pager_truncate(Pager *pPager, Pgno nPage){
  int rc = SQLITE_OK;
  assert( pPager->eState!=PAGER_ERROR );
  assert( pPager->eState!=PAGER_READER );
  PAGERTRACE(("Truncate %d npage %u\n", PAGERID(pPager), nPage));


  if( isOpen(pPager->fd)
   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  ){
    i64 currentSize, newSize;
    int szPage = pPager->pageSize;
    assert( pPager->eLock==EXCLUSIVE_LOCK );
61003
61004
61005
61006
61007
61008
61009




61010
61011
61012
61013
61014
61015
61016

    pPg->pPager = pPager;

    assert( !isOpen(pPager->fd) || !MEMDB );
    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
      if( pgno>pPager->mxPgno ){
        rc = SQLITE_FULL;




        goto pager_acquire_err;
      }
      if( noContent ){
        /* Failure to set the bits in the InJournal bit-vectors is benign.
        ** It merely means that we might do some extra work to journal a
        ** page that does not need to be journaled.  Nevertheless, be sure
        ** to test the case where a malloc error occurs while trying to set







>
>
>
>







61266
61267
61268
61269
61270
61271
61272
61273
61274
61275
61276
61277
61278
61279
61280
61281
61282
61283

    pPg->pPager = pPager;

    assert( !isOpen(pPager->fd) || !MEMDB );
    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
      if( pgno>pPager->mxPgno ){
        rc = SQLITE_FULL;
        if( pgno<=pPager->dbSize ){
          sqlite3PcacheRelease(pPg);
          pPg = 0;
        }
        goto pager_acquire_err;
      }
      if( noContent ){
        /* Failure to set the bits in the InJournal bit-vectors is benign.
        ** It merely means that we might do some extra work to journal a
        ** page that does not need to be journaled.  Nevertheless, be sure
        ** to test the case where a malloc error occurs while trying to set
61167
61168
61169
61170
61171
61172
61173
61174
61175
61176
61177


61178
61179
61180
61181
61182
61183
61184
61185
61186
61187
61188
61189
61190
61191
61192
61193
61194
61195
61196
61197
61198
61199
61200
  if( pPage==0 ) return 0;
  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
}

/*
** Release a page reference.
**
** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
** used if we know that the page being released is not the last page.
** The btree layer always holds page1 open until the end, so these first
** to routines can be used to release any page other than BtShared.pPage1.


**
** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine
** checks the total number of outstanding pages and if the number of
** pages reaches zero it drops the database lock.
*/
SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  TESTONLY( Pager *pPager = pPg->pPager; )
  assert( pPg!=0 );
  if( pPg->flags & PGHDR_MMAP ){
    assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */
    pagerReleaseMapPage(pPg);
  }else{
    sqlite3PcacheRelease(pPg);
  }
  /* Do not use this routine to release the last reference to page1 */
  assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
}
SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
}
SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  Pager *pPager;
  assert( pPg!=0 );







|
|

|
>
>















|







61434
61435
61436
61437
61438
61439
61440
61441
61442
61443
61444
61445
61446
61447
61448
61449
61450
61451
61452
61453
61454
61455
61456
61457
61458
61459
61460
61461
61462
61463
61464
61465
61466
61467
61468
61469
  if( pPage==0 ) return 0;
  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
}

/*
** Release a page reference.
**
** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be used
** if we know that the page being released is not the last reference to page1.
** The btree layer always holds page1 open until the end, so these first
** two routines can be used to release any page other than BtShared.pPage1.
** The assert() at tag-20230419-2 proves that this constraint is always
** honored.
**
** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine
** checks the total number of outstanding pages and if the number of
** pages reaches zero it drops the database lock.
*/
SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  TESTONLY( Pager *pPager = pPg->pPager; )
  assert( pPg!=0 );
  if( pPg->flags & PGHDR_MMAP ){
    assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */
    pagerReleaseMapPage(pPg);
  }else{
    sqlite3PcacheRelease(pPg);
  }
  /* Do not use this routine to release the last reference to page1 */
  assert( sqlite3PcacheRefCount(pPager->pPCache)>0 ); /* tag-20230419-2 */
}
SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
}
SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  Pager *pPager;
  assert( pPg!=0 );
62946
62947
62948
62949
62950
62951
62952

62953
62954

62955
62956
62957
62958
62959
62960
62961
62962
62963
62964
62965
62966

/*
** Attempt to take an exclusive lock on the database file. If a PENDING lock
** is obtained instead, immediately release it.
*/
static int pagerExclusiveLock(Pager *pPager){
  int rc;                         /* Return code */


  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );

  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  if( rc!=SQLITE_OK ){
    /* If the attempt to grab the exclusive lock failed, release the
    ** pending lock that may have been obtained instead.  */
    pagerUnlockDb(pPager, SHARED_LOCK);
  }

  return rc;
}

/*
** Call sqlite3WalOpen() to open the WAL handle. If the pager is in







>

|
>




|







63215
63216
63217
63218
63219
63220
63221
63222
63223
63224
63225
63226
63227
63228
63229
63230
63231
63232
63233
63234
63235
63236
63237

/*
** Attempt to take an exclusive lock on the database file. If a PENDING lock
** is obtained instead, immediately release it.
*/
static int pagerExclusiveLock(Pager *pPager){
  int rc;                         /* Return code */
  u8 eOrigLock;                   /* Original lock */

  assert( pPager->eLock>=SHARED_LOCK );
  eOrigLock = pPager->eLock;
  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  if( rc!=SQLITE_OK ){
    /* If the attempt to grab the exclusive lock failed, release the
    ** pending lock that may have been obtained instead.  */
    pagerUnlockDb(pPager, eOrigLock);
  }

  return rc;
}

/*
** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
63957
63958
63959
63960
63961
63962
63963

63964
63965
63966
63967
63968
63969
63970
63971
63972
63973
63974
63975
























63976

63977
63978
63979
63980
63981
63982
63983
  }else{
    s1 = s2 = 0;
  }

  assert( nByte>=8 );
  assert( (nByte&0x00000007)==0 );
  assert( nByte<=65536 );


  if( nativeCksum ){
    do {
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
    }while( aData<aEnd );
  }else{
    do {
      s1 += BYTESWAP32(aData[0]) + s2;
      s2 += BYTESWAP32(aData[1]) + s1;
      aData += 2;
    }while( aData<aEnd );
























  }


  aOut[0] = s1;
  aOut[1] = s2;
}

/*
** If there is the possibility of concurrent access to the SHM file







>

|
<
<
<
<
<





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

>







64228
64229
64230
64231
64232
64233
64234
64235
64236
64237





64238
64239
64240
64241
64242
64243
64244
64245
64246
64247
64248
64249
64250
64251
64252
64253
64254
64255
64256
64257
64258
64259
64260
64261
64262
64263
64264
64265
64266
64267
64268
64269
64270
64271
64272
64273
64274
64275
  }else{
    s1 = s2 = 0;
  }

  assert( nByte>=8 );
  assert( (nByte&0x00000007)==0 );
  assert( nByte<=65536 );
  assert( nByte%4==0 );

  if( !nativeCksum ){





    do {
      s1 += BYTESWAP32(aData[0]) + s2;
      s2 += BYTESWAP32(aData[1]) + s1;
      aData += 2;
    }while( aData<aEnd );
  }else if( nByte%64==0 ){
    do {
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
    }while( aData<aEnd );
  }else{
    do {
      s1 += *aData++ + s2;
      s2 += *aData++ + s1;
    }while( aData<aEnd );
  }
  assert( aData==aEnd );

  aOut[0] = s1;
  aOut[1] = s2;
}

/*
** If there is the possibility of concurrent access to the SHM file
66900
66901
66902
66903
66904
66905
66906
66907


66908
66909
66910
66911
66912
66913
66914
    **     https://sqlite.org/src/info/ff5be73dee
    */
    if( pWal->syncHeader ){
      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
      if( rc ) return rc;
    }
  }
  assert( (int)pWal->szPage==szPage );



  /* Setup information needed to write frames into the WAL */
  w.pWal = pWal;
  w.pFd = pWal->pWalFd;
  w.iSyncPoint = 0;
  w.syncFlags = sync_flags;
  w.szPage = szPage;







|
>
>







67192
67193
67194
67195
67196
67197
67198
67199
67200
67201
67202
67203
67204
67205
67206
67207
67208
    **     https://sqlite.org/src/info/ff5be73dee
    */
    if( pWal->syncHeader ){
      rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
      if( rc ) return rc;
    }
  }
  if( (int)pWal->szPage!=szPage ){
    return SQLITE_CORRUPT_BKPT;  /* TH3 test case: cov1/corrupt155.test */
  }

  /* Setup information needed to write frames into the WAL */
  w.pWal = pWal;
  w.pFd = pWal->pWalFd;
  w.iSyncPoint = 0;
  w.syncFlags = sync_flags;
  w.szPage = szPage;
67560
67561
67562
67563
67564
67565
67566
67567
67568
67569
67570
67571
67572
67573
67574
** contiguous or in order, but cell pointers are contiguous and in order.
**
** Cell content makes use of variable length integers.  A variable
** length integer is 1 to 9 bytes where the lower 7 bits of each
** byte are used.  The integer consists of all bytes that have bit 8 set and
** the first byte with bit 8 clear.  The most significant byte of the integer
** appears first.  A variable-length integer may not be more than 9 bytes long.
** As a special case, all 8 bytes of the 9th byte are used as data.  This
** allows a 64-bit integer to be encoded in 9 bytes.
**
**    0x00                      becomes  0x00000000
**    0x7f                      becomes  0x0000007f
**    0x81 0x00                 becomes  0x00000080
**    0x82 0x00                 becomes  0x00000100
**    0x80 0x7f                 becomes  0x0000007f







|







67854
67855
67856
67857
67858
67859
67860
67861
67862
67863
67864
67865
67866
67867
67868
** contiguous or in order, but cell pointers are contiguous and in order.
**
** Cell content makes use of variable length integers.  A variable
** length integer is 1 to 9 bytes where the lower 7 bits of each
** byte are used.  The integer consists of all bytes that have bit 8 set and
** the first byte with bit 8 clear.  The most significant byte of the integer
** appears first.  A variable-length integer may not be more than 9 bytes long.
** As a special case, all 8 bits of the 9th byte are used as data.  This
** allows a 64-bit integer to be encoded in 9 bytes.
**
**    0x00                      becomes  0x00000000
**    0x7f                      becomes  0x0000007f
**    0x81 0x00                 becomes  0x00000080
**    0x82 0x00                 becomes  0x00000100
**    0x80 0x7f                 becomes  0x0000007f
67944
67945
67946
67947
67948
67949
67950
67951
67952
67953
67954
67955
67956
67957
67958

/*
** Legal values for BtCursor.curFlags
*/
#define BTCF_WriteFlag    0x01   /* True if a write cursor */
#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
#define BTCF_Pinned       0x40   /* Cursor is busy and cannot be moved */

/*
** Potential values for BtCursor.eState.
**







|







68238
68239
68240
68241
68242
68243
68244
68245
68246
68247
68248
68249
68250
68251
68252

/*
** Legal values for BtCursor.curFlags
*/
#define BTCF_WriteFlag    0x01   /* True if a write cursor */
#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
#define BTCF_AtLast       0x08   /* Cursor is pointing to the last entry */
#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
#define BTCF_Pinned       0x40   /* Cursor is busy and cannot be moved */

/*
** Potential values for BtCursor.eState.
**
68089
68090
68091
68092
68093
68094
68095
68096

68097
68098
68099
68100
68101
68102
68103
68104
  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
  Pgno nPage;       /* Number of pages in the database */
  int mxErr;        /* Stop accumulating errors when this reaches zero */
  int nErr;         /* Number of messages written to zErrMsg so far */
  int rc;           /* SQLITE_OK, SQLITE_NOMEM, or SQLITE_INTERRUPT */
  u32 nStep;        /* Number of steps into the integrity_check process */
  const char *zPfx; /* Error message prefix */
  Pgno v1;          /* Value for first %u substitution in zPfx */

  int v2;           /* Value for second %d substitution in zPfx */
  StrAccum errMsg;  /* Accumulate the error message text here */
  u32 *heap;        /* Min-heap used for analyzing cell coverage */
  sqlite3 *db;      /* Database connection running the check */
};

/*
** Routines to read or write a two- and four-byte big-endian integer values.







|
>
|







68383
68384
68385
68386
68387
68388
68389
68390
68391
68392
68393
68394
68395
68396
68397
68398
68399
  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
  Pgno nPage;       /* Number of pages in the database */
  int mxErr;        /* Stop accumulating errors when this reaches zero */
  int nErr;         /* Number of messages written to zErrMsg so far */
  int rc;           /* SQLITE_OK, SQLITE_NOMEM, or SQLITE_INTERRUPT */
  u32 nStep;        /* Number of steps into the integrity_check process */
  const char *zPfx; /* Error message prefix */
  Pgno v0;          /* Value for first %u substitution in zPfx (root page) */
  Pgno v1;          /* Value for second %u substitution in zPfx (current pg) */
  int v2;           /* Value for third %d substitution in zPfx */
  StrAccum errMsg;  /* Accumulate the error message text here */
  u32 *heap;        /* Min-heap used for analyzing cell coverage */
  sqlite3 *db;      /* Database connection running the check */
};

/*
** Routines to read or write a two- and four-byte big-endian integer values.
68553
68554
68555
68556
68557
68558
68559
68560
68561
68562
68563
68564
68565
68566
68567
68568
** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
** with the page number and filename associated with the (MemPage*).
*/
#ifdef SQLITE_DEBUG
int corruptPageError(int lineno, MemPage *p){
  char *zMsg;
  sqlite3BeginBenignMalloc();
  zMsg = sqlite3_mprintf("database corruption page %d of %s",
      (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  );
  sqlite3EndBenignMalloc();
  if( zMsg ){
    sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  }
  sqlite3_free(zMsg);
  return SQLITE_CORRUPT_BKPT;







|
|







68848
68849
68850
68851
68852
68853
68854
68855
68856
68857
68858
68859
68860
68861
68862
68863
** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
** with the page number and filename associated with the (MemPage*).
*/
#ifdef SQLITE_DEBUG
int corruptPageError(int lineno, MemPage *p){
  char *zMsg;
  sqlite3BeginBenignMalloc();
  zMsg = sqlite3_mprintf("database corruption page %u of %s",
             p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  );
  sqlite3EndBenignMalloc();
  if( zMsg ){
    sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  }
  sqlite3_free(zMsg);
  return SQLITE_CORRUPT_BKPT;
69363
69364
69365
69366
69367
69368
69369














69370
69371



69372
69373
69374
69375
69376
69377
69378
/*
** Provide hints to the cursor.  The particular hint given (and the type
** and number of the varargs parameters) is determined by the eHintType
** parameter.  See the definitions of the BTREE_HINT_* macros for details.
*/
SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  /* Used only by system that substitute their own storage engine */














}
#endif




/*
** Provide flag hints to the cursor.
*/
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  pCur->hints = x;







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







69658
69659
69660
69661
69662
69663
69664
69665
69666
69667
69668
69669
69670
69671
69672
69673
69674
69675
69676
69677
69678
69679
69680
69681
69682
69683
69684
69685
69686
69687
69688
69689
69690
/*
** Provide hints to the cursor.  The particular hint given (and the type
** and number of the varargs parameters) is determined by the eHintType
** parameter.  See the definitions of the BTREE_HINT_* macros for details.
*/
SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  /* Used only by system that substitute their own storage engine */
#ifdef SQLITE_DEBUG
  if( ALWAYS(eHintType==BTREE_HINT_RANGE) ){
    va_list ap;
    Expr *pExpr;
    Walker w;
    memset(&w, 0, sizeof(w));
    w.xExprCallback = sqlite3CursorRangeHintExprCheck;
    va_start(ap, eHintType);
    pExpr = va_arg(ap, Expr*);
    w.u.aMem = va_arg(ap, Mem*);
    va_end(ap);
    assert( pExpr!=0 );
    assert( w.u.aMem!=0 );
    sqlite3WalkExpr(&w, pExpr);
  }
#endif /* SQLITE_DEBUG */
}
#endif /* SQLITE_ENABLE_CURSOR_HINTS */


/*
** Provide flag hints to the cursor.
*/
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  pCur->hints = x;
69449
69450
69451
69452
69453
69454
69455
69456
69457
69458
69459
69460
69461
69462
69463
    *pRC = SQLITE_CORRUPT_BKPT;
    goto ptrmap_exit;
  }
  assert( offset <= (int)pBt->usableSize-5 );
  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);

  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
    *pRC= rc = sqlite3PagerWrite(pDbPage);
    if( rc==SQLITE_OK ){
      pPtrmap[offset] = eType;
      put4byte(&pPtrmap[offset+1], parent);
    }
  }








|







69761
69762
69763
69764
69765
69766
69767
69768
69769
69770
69771
69772
69773
69774
69775
    *pRC = SQLITE_CORRUPT_BKPT;
    goto ptrmap_exit;
  }
  assert( offset <= (int)pBt->usableSize-5 );
  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);

  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
    TRACE(("PTRMAP_UPDATE: %u->(%u,%u)\n", key, eType, parent));
    *pRC= rc = sqlite3PagerWrite(pDbPage);
    if( rc==SQLITE_OK ){
      pPtrmap[offset] = eType;
      put4byte(&pPtrmap[offset+1], parent);
    }
  }

69648
69649
69650
69651
69652
69653
69654
69655
69656
69657
69658
69659
69660
69661
69662
69663
69664
69665
69666
69667
69668
69669
69670
69671
69672
69673
69674


69675


69676
69677
69678
69679
69680
69681
69682
  **
  ** The code is inlined and the loop is unrolled for performance.
  ** This routine is a high-runner.
  */
  iKey = *pIter;
  if( iKey>=0x80 ){
    u8 x;
    iKey = ((iKey&0x7f)<<7) | ((x = *++pIter) & 0x7f);
    if( x>=0x80 ){
      iKey = (iKey<<7) | ((x =*++pIter) & 0x7f);
      if( x>=0x80 ){
        iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
        if( x>=0x80 ){
          iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
          if( x>=0x80 ){
            iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
            if( x>=0x80 ){
              iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
              if( x>=0x80 ){
                iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
                if( x>=0x80 ){
                  iKey = (iKey<<8) | (*++pIter);
                }
              }
            }
          }
        }


      }


    }
  }
  pIter++;

  pInfo->nKey = *(i64*)&iKey;
  pInfo->nPayload = nPayload;
  pInfo->pPayload = pIter;







|

|

|

|

|

|

|

|





>
>

>
>







69960
69961
69962
69963
69964
69965
69966
69967
69968
69969
69970
69971
69972
69973
69974
69975
69976
69977
69978
69979
69980
69981
69982
69983
69984
69985
69986
69987
69988
69989
69990
69991
69992
69993
69994
69995
69996
69997
69998
  **
  ** The code is inlined and the loop is unrolled for performance.
  ** This routine is a high-runner.
  */
  iKey = *pIter;
  if( iKey>=0x80 ){
    u8 x;
    iKey = (iKey<<7) ^ (x = *++pIter);
    if( x>=0x80 ){
      iKey = (iKey<<7) ^ (x = *++pIter);
      if( x>=0x80 ){
        iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++pIter);
        if( x>=0x80 ){
          iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
          if( x>=0x80 ){
            iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
            if( x>=0x80 ){
              iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
              if( x>=0x80 ){
                iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
                if( x>=0x80 ){
                  iKey = (iKey<<8) ^ 0x8000 ^ (*++pIter);
                }
              }
            }
          }
        }
      }else{
        iKey ^= 0x204000;
      }
    }else{
      iKey ^= 0x4000;
    }
  }
  pIter++;

  pInfo->nKey = *(i64*)&iKey;
  pInfo->nPayload = nPayload;
  pInfo->pPayload = pIter;
69745
69746
69747
69748
69749
69750
69751
69752

69753
69754
69755










































69756
69757
69758
69759
69760
69761
69762
69763
69764
69765
69766
69767

69768
69769
69770
69771
69772
69773
69774
** Compute the total number of bytes that a Cell needs in the cell
** data area of the btree-page.  The return number includes the cell
** data header and the local payload, but not any overflow page or
** the space used by the cell pointer.
**
** cellSizePtrNoPayload()    =>   table internal nodes
** cellSizePtrTableLeaf()    =>   table leaf nodes
** cellSizePtr()             =>   all index nodes & table leaf nodes

*/
static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */










































  u8 *pEnd;                                /* End mark for a varint */
  u32 nSize;                               /* Size value to return */

#ifdef SQLITE_DEBUG
  /* The value returned by this function should always be the same as
  ** the (CellInfo.nSize) value found by doing a full parse of the
  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  ** this function verifies that this invariant is not violated. */
  CellInfo debuginfo;
  pPage->xParseCell(pPage, pCell, &debuginfo);
#endif


  nSize = *pIter;
  if( nSize>=0x80 ){
    pEnd = &pIter[8];
    nSize &= 0x7f;
    do{
      nSize = (nSize<<7) | (*++pIter & 0x7f);
    }while( *(pIter)>=0x80 && pIter<pEnd );







|
>


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












>







70061
70062
70063
70064
70065
70066
70067
70068
70069
70070
70071
70072
70073
70074
70075
70076
70077
70078
70079
70080
70081
70082
70083
70084
70085
70086
70087
70088
70089
70090
70091
70092
70093
70094
70095
70096
70097
70098
70099
70100
70101
70102
70103
70104
70105
70106
70107
70108
70109
70110
70111
70112
70113
70114
70115
70116
70117
70118
70119
70120
70121
70122
70123
70124
70125
70126
70127
70128
70129
70130
70131
70132
70133
70134
** Compute the total number of bytes that a Cell needs in the cell
** data area of the btree-page.  The return number includes the cell
** data header and the local payload, but not any overflow page or
** the space used by the cell pointer.
**
** cellSizePtrNoPayload()    =>   table internal nodes
** cellSizePtrTableLeaf()    =>   table leaf nodes
** cellSizePtr()             =>   index internal nodes
** cellSizeIdxLeaf()         =>   index leaf nodes
*/
static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  u8 *pIter = pCell + 4;                   /* For looping over bytes of pCell */
  u8 *pEnd;                                /* End mark for a varint */
  u32 nSize;                               /* Size value to return */

#ifdef SQLITE_DEBUG
  /* The value returned by this function should always be the same as
  ** the (CellInfo.nSize) value found by doing a full parse of the
  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  ** this function verifies that this invariant is not violated. */
  CellInfo debuginfo;
  pPage->xParseCell(pPage, pCell, &debuginfo);
#endif

  assert( pPage->childPtrSize==4 );
  nSize = *pIter;
  if( nSize>=0x80 ){
    pEnd = &pIter[8];
    nSize &= 0x7f;
    do{
      nSize = (nSize<<7) | (*++pIter & 0x7f);
    }while( *(pIter)>=0x80 && pIter<pEnd );
  }
  pIter++;
  testcase( nSize==pPage->maxLocal );
  testcase( nSize==(u32)pPage->maxLocal+1 );
  if( nSize<=pPage->maxLocal ){
    nSize += (u32)(pIter - pCell);
    assert( nSize>4 );
  }else{
    int minLocal = pPage->minLocal;
    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
    testcase( nSize==pPage->maxLocal );
    testcase( nSize==(u32)pPage->maxLocal+1 );
    if( nSize>pPage->maxLocal ){
      nSize = minLocal;
    }
    nSize += 4 + (u16)(pIter - pCell);
  }
  assert( nSize==debuginfo.nSize || CORRUPT_DB );
  return (u16)nSize;
}
static u16 cellSizePtrIdxLeaf(MemPage *pPage, u8 *pCell){
  u8 *pIter = pCell;                       /* For looping over bytes of pCell */
  u8 *pEnd;                                /* End mark for a varint */
  u32 nSize;                               /* Size value to return */

#ifdef SQLITE_DEBUG
  /* The value returned by this function should always be the same as
  ** the (CellInfo.nSize) value found by doing a full parse of the
  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  ** this function verifies that this invariant is not violated. */
  CellInfo debuginfo;
  pPage->xParseCell(pPage, pCell, &debuginfo);
#endif

  assert( pPage->childPtrSize==0 );
  nSize = *pIter;
  if( nSize>=0x80 ){
    pEnd = &pIter[8];
    nSize &= 0x7f;
    do{
      nSize = (nSize<<7) | (*++pIter & 0x7f);
    }while( *(pIter)>=0x80 && pIter<pEnd );
69997
69998
69999
70000
70001
70002
70003
70004
70005
70006
70007
70008
70009
70010
70011
70012
70013
70014
      pAddr = &data[cellOffset + i*2];
      pc = get2byte(pAddr);
      testcase( pc==iCellFirst );
      testcase( pc==iCellLast );
      /* These conditions have already been verified in btreeInitPage()
      ** if PRAGMA cell_size_check=ON.
      */
      if( pc<iCellStart || pc>iCellLast ){
        return SQLITE_CORRUPT_PAGE(pPage);
      }
      assert( pc>=iCellStart && pc<=iCellLast );
      size = pPage->xCellSize(pPage, &src[pc]);
      cbrk -= size;
      if( cbrk<iCellStart || pc+size>usableSize ){
        return SQLITE_CORRUPT_PAGE(pPage);
      }
      assert( cbrk+size<=usableSize && cbrk>=iCellStart );
      testcase( cbrk+size==usableSize );







|


|







70357
70358
70359
70360
70361
70362
70363
70364
70365
70366
70367
70368
70369
70370
70371
70372
70373
70374
      pAddr = &data[cellOffset + i*2];
      pc = get2byte(pAddr);
      testcase( pc==iCellFirst );
      testcase( pc==iCellLast );
      /* These conditions have already been verified in btreeInitPage()
      ** if PRAGMA cell_size_check=ON.
      */
      if( pc>iCellLast ){
        return SQLITE_CORRUPT_PAGE(pPage);
      }
      assert( pc>=0 && pc<=iCellLast );
      size = pPage->xCellSize(pPage, &src[pc]);
      cbrk -= size;
      if( cbrk<iCellStart || pc+size>usableSize ){
        return SQLITE_CORRUPT_PAGE(pPage);
      }
      assert( cbrk+size<=usableSize && cbrk>=iCellStart );
      testcase( cbrk+size==usableSize );
70115
70116
70117
70118
70119
70120
70121
70122
70123
70124
70125
70126
70127
70128
70129
** The caller guarantees that there is sufficient space to make the
** allocation.  This routine might need to defragment in order to bring
** all the space together, however.  This routine will avoid using
** the first two bytes past the cell pointer area since presumably this
** allocation is being made in order to insert a new cell, so we will
** also end up needing a new cell pointer.
*/
static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
  int top;                             /* First byte of cell content area */
  int rc = SQLITE_OK;                  /* Integer return code */
  u8 *pTmp;                            /* Temp ptr into data[] */
  int gap;        /* First byte of gap between cell pointers and cell content */








|







70475
70476
70477
70478
70479
70480
70481
70482
70483
70484
70485
70486
70487
70488
70489
** The caller guarantees that there is sufficient space to make the
** allocation.  This routine might need to defragment in order to bring
** all the space together, however.  This routine will avoid using
** the first two bytes past the cell pointer area since presumably this
** allocation is being made in order to insert a new cell, so we will
** also end up needing a new cell pointer.
*/
static SQLITE_INLINE int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
  int top;                             /* First byte of cell content area */
  int rc = SQLITE_OK;                  /* Integer return code */
  u8 *pTmp;                            /* Temp ptr into data[] */
  int gap;        /* First byte of gap between cell pointers and cell content */

70141
70142
70143
70144
70145
70146
70147
70148
70149
70150
70151
70152
70153
70154


70155
70156
70157
70158
70159
70160
70161
  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  ** and the reserved space is zero (the usual value for reserved space)
  ** then the cell content offset of an empty page wants to be 65536.
  ** However, that integer is too large to be stored in a 2-byte unsigned
  ** integer, so a value of 0 is used in its place. */
  pTmp = &data[hdr+5];
  top = get2byte(pTmp);
  assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
  if( gap>top ){
    if( top==0 && pPage->pBt->usableSize==65536 ){
      top = 65536;
    }else{
      return SQLITE_CORRUPT_PAGE(pPage);
    }


  }

  /* If there is enough space between gap and top for one more cell pointer,
  ** and if the freelist is not empty, then search the
  ** freelist looking for a slot big enough to satisfy the request.
  */
  testcase( gap+2==top );







<






>
>







70501
70502
70503
70504
70505
70506
70507

70508
70509
70510
70511
70512
70513
70514
70515
70516
70517
70518
70519
70520
70521
70522
  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  ** and the reserved space is zero (the usual value for reserved space)
  ** then the cell content offset of an empty page wants to be 65536.
  ** However, that integer is too large to be stored in a 2-byte unsigned
  ** integer, so a value of 0 is used in its place. */
  pTmp = &data[hdr+5];
  top = get2byte(pTmp);

  if( gap>top ){
    if( top==0 && pPage->pBt->usableSize==65536 ){
      top = 65536;
    }else{
      return SQLITE_CORRUPT_PAGE(pPage);
    }
  }else if( top>(int)pPage->pBt->usableSize ){
    return SQLITE_CORRUPT_PAGE(pPage);
  }

  /* If there is enough space between gap and top for one more cell pointer,
  ** and if the freelist is not empty, then search the
  ** freelist looking for a slot big enough to satisfy the request.
  */
  testcase( gap+2==top );
70230
70231
70232
70233
70234
70235
70236
70237
70238
70239
70240
70241
70242
70243
70244

  assert( pPage->pBt!=0 );
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( iSize>=4 );   /* Minimum cell size is 4 */
  assert( iStart<=pPage->pBt->usableSize-4 );

  /* The list of freeblocks must be in ascending order.  Find the
  ** spot on the list where iStart should be inserted.
  */
  hdr = pPage->hdrOffset;
  iPtr = hdr + 1;
  if( data[iPtr+1]==0 && data[iPtr]==0 ){







|







70591
70592
70593
70594
70595
70596
70597
70598
70599
70600
70601
70602
70603
70604
70605

  assert( pPage->pBt!=0 );
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( iSize>=4 );   /* Minimum cell size is 4 */
  assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 );

  /* The list of freeblocks must be in ascending order.  Find the
  ** spot on the list where iStart should be inserted.
  */
  hdr = pPage->hdrOffset;
  iPtr = hdr + 1;
  if( data[iPtr+1]==0 && data[iPtr]==0 ){
70287
70288
70289
70290
70291
70292
70293





70294
70295
70296
70297
70298
70299
70300
70301
70302
70303
70304
70305
70306
70307
70308
70309
70310
70311
70312

70313
70314
70315
70316
70317
70318
70319
      }
    }
    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
    data[hdr+7] -= nFrag;
  }
  pTmp = &data[hdr+5];
  x = get2byte(pTmp);





  if( iStart<=x ){
    /* The new freeblock is at the beginning of the cell content area,
    ** so just extend the cell content area rather than create another
    ** freelist entry */
    if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
    put2byte(&data[hdr+1], iFreeBlk);
    put2byte(&data[hdr+5], iEnd);
  }else{
    /* Insert the new freeblock into the freelist */
    put2byte(&data[iPtr], iStart);
  }
  if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
    /* Overwrite deleted information with zeros when the secure_delete
    ** option is enabled */
    memset(&data[iStart], 0, iSize);
  }
  put2byte(&data[iStart], iFreeBlk);
  put2byte(&data[iStart+2], iSize);

  pPage->nFree += iOrigSize;
  return SQLITE_OK;
}

/*
** Decode the flags byte (the first byte of the header) for a page
** and initialize fields of the MemPage structure accordingly.







>
>
>
>
>











<
<
<
<
<
<
|
|
>







70648
70649
70650
70651
70652
70653
70654
70655
70656
70657
70658
70659
70660
70661
70662
70663
70664
70665
70666
70667
70668
70669
70670






70671
70672
70673
70674
70675
70676
70677
70678
70679
70680
      }
    }
    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
    data[hdr+7] -= nFrag;
  }
  pTmp = &data[hdr+5];
  x = get2byte(pTmp);
  if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
    /* Overwrite deleted information with zeros when the secure_delete
    ** option is enabled */
    memset(&data[iStart], 0, iSize);
  }
  if( iStart<=x ){
    /* The new freeblock is at the beginning of the cell content area,
    ** so just extend the cell content area rather than create another
    ** freelist entry */
    if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
    put2byte(&data[hdr+1], iFreeBlk);
    put2byte(&data[hdr+5], iEnd);
  }else{
    /* Insert the new freeblock into the freelist */
    put2byte(&data[iPtr], iStart);






    put2byte(&data[iStart], iFreeBlk);
    put2byte(&data[iStart+2], iSize);
  }
  pPage->nFree += iOrigSize;
  return SQLITE_OK;
}

/*
** Decode the flags byte (the first byte of the header) for a page
** and initialize fields of the MemPage structure accordingly.
70342
70343
70344
70345
70346
70347
70348
70349
70350
70351
70352
70353
70354
70355
70356
70357
70358
70359
70360
70361
70362
70363
      pPage->xParseCell = btreeParseCellPtr;
      pPage->intKey = 1;
      pPage->maxLocal = pBt->maxLeaf;
      pPage->minLocal = pBt->minLeaf;
    }else if( flagByte==(PTF_ZERODATA | PTF_LEAF) ){
      pPage->intKey = 0;
      pPage->intKeyLeaf = 0;
      pPage->xCellSize = cellSizePtr;
      pPage->xParseCell = btreeParseCellPtrIndex;
      pPage->maxLocal = pBt->maxLocal;
      pPage->minLocal = pBt->minLocal;
    }else{
      pPage->intKey = 0;
      pPage->intKeyLeaf = 0;
      pPage->xCellSize = cellSizePtr;
      pPage->xParseCell = btreeParseCellPtrIndex;
      return SQLITE_CORRUPT_PAGE(pPage);
    }
  }else{
    pPage->childPtrSize = 4;
    pPage->leaf = 0;
    if( flagByte==(PTF_ZERODATA) ){







|






|







70703
70704
70705
70706
70707
70708
70709
70710
70711
70712
70713
70714
70715
70716
70717
70718
70719
70720
70721
70722
70723
70724
      pPage->xParseCell = btreeParseCellPtr;
      pPage->intKey = 1;
      pPage->maxLocal = pBt->maxLeaf;
      pPage->minLocal = pBt->minLeaf;
    }else if( flagByte==(PTF_ZERODATA | PTF_LEAF) ){
      pPage->intKey = 0;
      pPage->intKeyLeaf = 0;
      pPage->xCellSize = cellSizePtrIdxLeaf;
      pPage->xParseCell = btreeParseCellPtrIndex;
      pPage->maxLocal = pBt->maxLocal;
      pPage->minLocal = pBt->minLocal;
    }else{
      pPage->intKey = 0;
      pPage->intKeyLeaf = 0;
      pPage->xCellSize = cellSizePtrIdxLeaf;
      pPage->xParseCell = btreeParseCellPtrIndex;
      return SQLITE_CORRUPT_PAGE(pPage);
    }
  }else{
    pPage->childPtrSize = 4;
    pPage->leaf = 0;
    if( flagByte==(PTF_ZERODATA) ){
72215
72216
72217
72218
72219
72220
72221
72222
72223
72224
72225
72226
72227
72228
72229
  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( pDbPage->pBt==pBt );
  if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;

  /* Move page iDbPage from its current location to page number iFreePage */
  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
      iDbPage, iFreePage, iPtrPage, eType));
  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pDbPage->pgno = iFreePage;








|







72576
72577
72578
72579
72580
72581
72582
72583
72584
72585
72586
72587
72588
72589
72590
  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( pDbPage->pBt==pBt );
  if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;

  /* Move page iDbPage from its current location to page number iFreePage */
  TRACE(("AUTOVACUUM: Moving %u to free page %u (ptr page %u type %u)\n",
      iDbPage, iFreePage, iPtrPage, eType));
  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  pDbPage->pgno = iFreePage;

74501
74502
74503
74504
74505
74506
74507
74508

74509
74510
74511
74512
74513
74514
74515
      pCur->eState = CURSOR_VALID;
      if( pCur->skipNext>0 ) return SQLITE_OK;
    }
  }

  pPage = pCur->pPage;
  idx = ++pCur->ix;
  if( NEVER(!pPage->isInit) || sqlite3FaultSim(412) ){

    return SQLITE_CORRUPT_BKPT;
  }

  if( idx>=pPage->nCell ){
    if( !pPage->leaf ){
      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
      if( rc ) return rc;







|
>







74862
74863
74864
74865
74866
74867
74868
74869
74870
74871
74872
74873
74874
74875
74876
74877
      pCur->eState = CURSOR_VALID;
      if( pCur->skipNext>0 ) return SQLITE_OK;
    }
  }

  pPage = pCur->pPage;
  idx = ++pCur->ix;
  if( sqlite3FaultSim(412) ) pPage->isInit = 0;
  if( !pPage->isInit ){
    return SQLITE_CORRUPT_BKPT;
  }

  if( idx>=pPage->nCell ){
    if( !pPage->leaf ){
      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
      if( rc ) return rc;
74764
74765
74766
74767
74768
74769
74770
74771
74772
74773
74774
74775
74776
74777
74778
        if( rc ){
          goto end_allocate_page;
        }
        *pPgno = iTrunk;
        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
        *ppPage = pTrunk;
        pTrunk = 0;
        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
        /* Value of k is out of range.  Database corruption */
        rc = SQLITE_CORRUPT_PGNO(iTrunk);
        goto end_allocate_page;
#ifndef SQLITE_OMIT_AUTOVACUUM
      }else if( searchList
            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))







|







75126
75127
75128
75129
75130
75131
75132
75133
75134
75135
75136
75137
75138
75139
75140
        if( rc ){
          goto end_allocate_page;
        }
        *pPgno = iTrunk;
        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
        *ppPage = pTrunk;
        pTrunk = 0;
        TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
        /* Value of k is out of range.  Database corruption */
        rc = SQLITE_CORRUPT_PGNO(iTrunk);
        goto end_allocate_page;
#ifndef SQLITE_OMIT_AUTOVACUUM
      }else if( searchList
            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
74830
74831
74832
74833
74834
74835
74836
74837
74838
74839
74840
74841
74842
74843
74844
            if( rc ){
              goto end_allocate_page;
            }
            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
          }
        }
        pTrunk = 0;
        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
#endif
      }else if( k>0 ){
        /* Extract a leaf from the trunk */
        u32 closest;
        Pgno iPage;
        unsigned char *aData = pTrunk->aData;
        if( nearby>0 ){







|







75192
75193
75194
75195
75196
75197
75198
75199
75200
75201
75202
75203
75204
75205
75206
            if( rc ){
              goto end_allocate_page;
            }
            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
          }
        }
        pTrunk = 0;
        TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
#endif
      }else if( k>0 ){
        /* Extract a leaf from the trunk */
        u32 closest;
        Pgno iPage;
        unsigned char *aData = pTrunk->aData;
        if( nearby>0 ){
74875
74876
74877
74878
74879
74880
74881
74882
74883
74884
74885
74886
74887
74888
74889
74890
        }
        testcase( iPage==mxPage );
        if( !searchList
         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
        ){
          int noContent;
          *pPgno = iPage;
          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
                 ": %d more free pages\n",
                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
          rc = sqlite3PagerWrite(pTrunk->pDbPage);
          if( rc ) goto end_allocate_page;
          if( closest<k-1 ){
            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
          }
          put4byte(&aData[4], k-1);







|
|







75237
75238
75239
75240
75241
75242
75243
75244
75245
75246
75247
75248
75249
75250
75251
75252
        }
        testcase( iPage==mxPage );
        if( !searchList
         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
        ){
          int noContent;
          *pPgno = iPage;
          TRACE(("ALLOCATE: %u was leaf %u of %u on trunk %u"
                 ": %u more free pages\n",
                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
          rc = sqlite3PagerWrite(pTrunk->pDbPage);
          if( rc ) goto end_allocate_page;
          if( closest<k-1 ){
            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
          }
          put4byte(&aData[4], k-1);
74932
74933
74934
74935
74936
74937
74938
74939
74940
74941
74942
74943
74944
74945
74946
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
      /* If *pPgno refers to a pointer-map page, allocate two new pages
      ** at the end of the file instead of one. The first allocated page
      ** becomes a new pointer-map page, the second is used by the caller.
      */
      MemPage *pPg = 0;
      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
      if( rc==SQLITE_OK ){
        rc = sqlite3PagerWrite(pPg->pDbPage);
        releasePage(pPg);
      }
      if( rc ) return rc;







|







75294
75295
75296
75297
75298
75299
75300
75301
75302
75303
75304
75305
75306
75307
75308
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
      /* If *pPgno refers to a pointer-map page, allocate two new pages
      ** at the end of the file instead of one. The first allocated page
      ** becomes a new pointer-map page, the second is used by the caller.
      */
      MemPage *pPg = 0;
      TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage));
      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
      if( rc==SQLITE_OK ){
        rc = sqlite3PagerWrite(pPg->pDbPage);
        releasePage(pPg);
      }
      if( rc ) return rc;
74955
74956
74957
74958
74959
74960
74961
74962
74963
74964
74965
74966
74967
74968
74969
    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
    if( rc ) return rc;
    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
    if( rc!=SQLITE_OK ){
      releasePage(*ppPage);
      *ppPage = 0;
    }
    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  }

  assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );

end_allocate_page:
  releasePage(pTrunk);
  releasePage(pPrevTrunk);







|







75317
75318
75319
75320
75321
75322
75323
75324
75325
75326
75327
75328
75329
75330
75331
    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
    if( rc ) return rc;
    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
    if( rc!=SQLITE_OK ){
      releasePage(*ppPage);
      *ppPage = 0;
    }
    TRACE(("ALLOCATE: %u from end of file\n", *pPgno));
  }

  assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );

end_allocate_page:
  releasePage(pTrunk);
  releasePage(pPrevTrunk);
75083
75084
75085
75086
75087
75088
75089
75090
75091
75092
75093
75094
75095
75096
75097
75098
75099
75100
75101
75102
75103
75104
75105
75106
75107
75108
75109
75110
75111
75112
75113
75114
75115
75116
75117
75118
        put4byte(&pTrunk->aData[4], nLeaf+1);
        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
          sqlite3PagerDontWrite(pPage->pDbPage);
        }
        rc = btreeSetHasContent(pBt, iPage);
      }
      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
      goto freepage_out;
    }
  }

  /* If control flows to this point, then it was not possible to add the
  ** the page being freed as a leaf page of the first trunk in the free-list.
  ** Possibly because the free-list is empty, or possibly because the
  ** first trunk in the free-list is full. Either way, the page being freed
  ** will become the new first trunk page in the free-list.
  */
  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
    goto freepage_out;
  }
  rc = sqlite3PagerWrite(pPage->pDbPage);
  if( rc!=SQLITE_OK ){
    goto freepage_out;
  }
  put4byte(pPage->aData, iTrunk);
  put4byte(&pPage->aData[4], 0);
  put4byte(&pPage1->aData[32], iPage);
  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));

freepage_out:
  if( pPage ){
    pPage->isInit = 0;
  }
  releasePage(pPage);
  releasePage(pTrunk);







|




















|







75445
75446
75447
75448
75449
75450
75451
75452
75453
75454
75455
75456
75457
75458
75459
75460
75461
75462
75463
75464
75465
75466
75467
75468
75469
75470
75471
75472
75473
75474
75475
75476
75477
75478
75479
75480
        put4byte(&pTrunk->aData[4], nLeaf+1);
        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
          sqlite3PagerDontWrite(pPage->pDbPage);
        }
        rc = btreeSetHasContent(pBt, iPage);
      }
      TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno));
      goto freepage_out;
    }
  }

  /* If control flows to this point, then it was not possible to add the
  ** the page being freed as a leaf page of the first trunk in the free-list.
  ** Possibly because the free-list is empty, or possibly because the
  ** first trunk in the free-list is full. Either way, the page being freed
  ** will become the new first trunk page in the free-list.
  */
  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
    goto freepage_out;
  }
  rc = sqlite3PagerWrite(pPage->pDbPage);
  if( rc!=SQLITE_OK ){
    goto freepage_out;
  }
  put4byte(pPage->aData, iTrunk);
  put4byte(&pPage->aData[4], 0);
  put4byte(&pPage1->aData[32], iPage);
  TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk));

freepage_out:
  if( pPage ){
    pPage->isInit = 0;
  }
  releasePage(pPage);
  releasePage(pTrunk);
75463
75464
75465
75466
75467
75468
75469








75470
75471
75472
75473
75474
75475
75476
** If the cell content will fit on the page, then put it there.  If it
** will not fit, then make a copy of the cell content into pTemp if
** pTemp is not null.  Regardless of pTemp, allocate a new entry
** in pPage->apOvfl[] and make it point to the cell content (either
** in pTemp or the original pCell) and also record its index.
** Allocating a new entry in pPage->aCell[] implies that
** pPage->nOverflow is incremented.








*/
static int insertCell(
  MemPage *pPage,   /* Page into which we are copying */
  int i,            /* New cell becomes the i-th cell of the page */
  u8 *pCell,        /* Content of the new cell */
  int sz,           /* Bytes of content in pCell */
  u8 *pTemp,        /* Temp storage space for pCell, if needed */







>
>
>
>
>
>
>
>







75825
75826
75827
75828
75829
75830
75831
75832
75833
75834
75835
75836
75837
75838
75839
75840
75841
75842
75843
75844
75845
75846
** If the cell content will fit on the page, then put it there.  If it
** will not fit, then make a copy of the cell content into pTemp if
** pTemp is not null.  Regardless of pTemp, allocate a new entry
** in pPage->apOvfl[] and make it point to the cell content (either
** in pTemp or the original pCell) and also record its index.
** Allocating a new entry in pPage->aCell[] implies that
** pPage->nOverflow is incremented.
**
** The insertCellFast() routine below works exactly the same as
** insertCell() except that it lacks the pTemp and iChild parameters
** which are assumed zero.  Other than that, the two routines are the
** same.
**
** Fixes or enhancements to this routine should be reflected in
** insertCellFast()!
*/
static int insertCell(
  MemPage *pPage,   /* Page into which we are copying */
  int i,            /* New cell becomes the i-th cell of the page */
  u8 *pCell,        /* Content of the new cell */
  int sz,           /* Bytes of content in pCell */
  u8 *pTemp,        /* Temp storage space for pCell, if needed */
75485
75486
75487
75488
75489
75490
75491

75492
75493
75494
75495
75496
75497
75498







75499


















































































75500
75501
75502
75503
75504
75505
75506
  assert( MX_CELL(pPage->pBt)<=10921 );
  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
  assert( pPage->nFree>=0 );

  if( pPage->nOverflow || sz+2>pPage->nFree ){
    if( pTemp ){
      memcpy(pTemp, pCell, sz);
      pCell = pTemp;
    }
    if( iChild ){
      put4byte(pCell, iChild);







    }


















































































    j = pPage->nOverflow++;
    /* Comparison against ArraySize-1 since we hold back one extra slot
    ** as a contingency.  In other words, never need more than 3 overflow
    ** slots but 4 are allocated, just to be safe. */
    assert( j < ArraySize(pPage->apOvfl)-1 );
    pPage->apOvfl[j] = pCell;
    pPage->aiOvfl[j] = (u16)i;







>





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







75855
75856
75857
75858
75859
75860
75861
75862
75863
75864
75865
75866
75867

75868
75869
75870
75871
75872
75873
75874
75875
75876
75877
75878
75879
75880
75881
75882
75883
75884
75885
75886
75887
75888
75889
75890
75891
75892
75893
75894
75895
75896
75897
75898
75899
75900
75901
75902
75903
75904
75905
75906
75907
75908
75909
75910
75911
75912
75913
75914
75915
75916
75917
75918
75919
75920
75921
75922
75923
75924
75925
75926
75927
75928
75929
75930
75931
75932
75933
75934
75935
75936
75937
75938
75939
75940
75941
75942
75943
75944
75945
75946
75947
75948
75949
75950
75951
75952
75953
75954
75955
75956
75957
75958
75959
75960
75961
75962
75963
75964
75965
  assert( MX_CELL(pPage->pBt)<=10921 );
  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
  assert( pPage->nFree>=0 );
  assert( iChild>0 );
  if( pPage->nOverflow || sz+2>pPage->nFree ){
    if( pTemp ){
      memcpy(pTemp, pCell, sz);
      pCell = pTemp;
    }

    put4byte(pCell, iChild);
    j = pPage->nOverflow++;
    /* Comparison against ArraySize-1 since we hold back one extra slot
    ** as a contingency.  In other words, never need more than 3 overflow
    ** slots but 4 are allocated, just to be safe. */
    assert( j < ArraySize(pPage->apOvfl)-1 );
    pPage->apOvfl[j] = pCell;
    pPage->aiOvfl[j] = (u16)i;

    /* When multiple overflows occur, they are always sequential and in
    ** sorted order.  This invariants arise because multiple overflows can
    ** only occur when inserting divider cells into the parent page during
    ** balancing, and the dividers are adjacent and sorted.
    */
    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
  }else{
    int rc = sqlite3PagerWrite(pPage->pDbPage);
    if( NEVER(rc!=SQLITE_OK) ){
      return rc;
    }
    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
    data = pPage->aData;
    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
    rc = allocateSpace(pPage, sz, &idx);
    if( rc ){ return rc; }
    /* The allocateSpace() routine guarantees the following properties
    ** if it returns successfully */
    assert( idx >= 0 );
    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
    assert( idx+sz <= (int)pPage->pBt->usableSize );
    pPage->nFree -= (u16)(2 + sz);
    /* In a corrupt database where an entry in the cell index section of
    ** a btree page has a value of 3 or less, the pCell value might point
    ** as many as 4 bytes in front of the start of the aData buffer for
    ** the source page.  Make sure this does not cause problems by not
    ** reading the first 4 bytes */
    memcpy(&data[idx+4], pCell+4, sz-4);
    put4byte(&data[idx], iChild);
    pIns = pPage->aCellIdx + i*2;
    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
    put2byte(pIns, idx);
    pPage->nCell++;
    /* increment the cell count */
    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pPage->pBt->autoVacuum ){
      int rc2 = SQLITE_OK;
      /* The cell may contain a pointer to an overflow page. If so, write
      ** the entry for the overflow page into the pointer map.
      */
      ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
      if( rc2 ) return rc2;
    }
#endif
  }
  return SQLITE_OK;
}

/*
** This variant of insertCell() assumes that the pTemp and iChild
** parameters are both zero.  Use this variant in sqlite3BtreeInsert()
** for performance improvement, and also so that this variant is only
** called from that one place, and is thus inlined, and thus runs must
** faster.
**
** Fixes or enhancements to this routine should be reflected into
** the insertCell() routine.
*/
static int insertCellFast(
  MemPage *pPage,   /* Page into which we are copying */
  int i,            /* New cell becomes the i-th cell of the page */
  u8 *pCell,        /* Content of the new cell */
  int sz            /* Bytes of content in pCell */
){
  int idx = 0;      /* Where to write new cell content in data[] */
  int j;            /* Loop counter */
  u8 *data;         /* The content of the whole page */
  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */

  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  assert( MX_CELL(pPage->pBt)<=10921 );
  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
  assert( pPage->nFree>=0 );
  assert( pPage->nOverflow==0 );
  if( sz+2>pPage->nFree ){
    j = pPage->nOverflow++;
    /* Comparison against ArraySize-1 since we hold back one extra slot
    ** as a contingency.  In other words, never need more than 3 overflow
    ** slots but 4 are allocated, just to be safe. */
    assert( j < ArraySize(pPage->apOvfl)-1 );
    pPage->apOvfl[j] = pCell;
    pPage->aiOvfl[j] = (u16)i;
75524
75525
75526
75527
75528
75529
75530
75531
75532
75533
75534
75535
75536
75537
75538
75539
75540
75541
75542
75543
75544
75545
75546
75547
75548
    if( rc ){ return rc; }
    /* The allocateSpace() routine guarantees the following properties
    ** if it returns successfully */
    assert( idx >= 0 );
    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
    assert( idx+sz <= (int)pPage->pBt->usableSize );
    pPage->nFree -= (u16)(2 + sz);
    if( iChild ){
      /* In a corrupt database where an entry in the cell index section of
      ** a btree page has a value of 3 or less, the pCell value might point
      ** as many as 4 bytes in front of the start of the aData buffer for
      ** the source page.  Make sure this does not cause problems by not
      ** reading the first 4 bytes */
      memcpy(&data[idx+4], pCell+4, sz-4);
      put4byte(&data[idx], iChild);
    }else{
      memcpy(&data[idx], pCell, sz);
    }
    pIns = pPage->aCellIdx + i*2;
    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
    put2byte(pIns, idx);
    pPage->nCell++;
    /* increment the cell count */
    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );







<
<
<
<
<
<
<
<
<
|
<







75983
75984
75985
75986
75987
75988
75989









75990

75991
75992
75993
75994
75995
75996
75997
    if( rc ){ return rc; }
    /* The allocateSpace() routine guarantees the following properties
    ** if it returns successfully */
    assert( idx >= 0 );
    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
    assert( idx+sz <= (int)pPage->pBt->usableSize );
    pPage->nFree -= (u16)(2 + sz);









    memcpy(&data[idx], pCell, sz);

    pIns = pPage->aCellIdx + i*2;
    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
    put2byte(pIns, idx);
    pPage->nCell++;
    /* increment the cell count */
    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
75719
75720
75721
75722
75723
75724
75725
75726
75727
75728
75729
75730
75731
75732
75733
  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  u8 *pData;
  int k;                          /* Current slot in pCArray->apEnd[] */
  u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */

  assert( i<iEnd );
  j = get2byte(&aData[hdr+5]);
  if( j>(u32)usableSize ){ j = 0; }
  memcpy(&pTmp[j], &aData[j], usableSize - j);

  for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  pSrcEnd = pCArray->apEnd[k];

  pData = pEnd;
  while( 1/*exit by break*/ ){







|







76168
76169
76170
76171
76172
76173
76174
76175
76176
76177
76178
76179
76180
76181
76182
  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  u8 *pData;
  int k;                          /* Current slot in pCArray->apEnd[] */
  u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */

  assert( i<iEnd );
  j = get2byte(&aData[hdr+5]);
  if( NEVER(j>(u32)usableSize) ){ j = 0; }
  memcpy(&pTmp[j], &aData[j], usableSize - j);

  for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  pSrcEnd = pCArray->apEnd[k];

  pData = pEnd;
  while( 1/*exit by break*/ ){
75863
75864
75865
75866
75867
75868
75869
75870
75871
75872
75873

75874
75875
75876
75877
75878


75879
75880
75881
75882
75883










75884

75885
75886
75887
75888
75889
75890
75891
75892
75893
75894
75895
75896
75897

75898
75899
75900
75901
75902
75903
75904
75905
75906
75907
75908
75909
75910
75911
75912
  int nCell,                      /* Cells to delete */
  CellArray *pCArray              /* Array of cells */
){
  u8 * const aData = pPg->aData;
  u8 * const pEnd = &aData[pPg->pBt->usableSize];
  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  int nRet = 0;
  int i;
  int iEnd = iFirst + nCell;
  u8 *pFree = 0;                  /* \__ Parameters for pending call to */
  int szFree = 0;                 /* /   freeSpace()                    */


  for(i=iFirst; i<iEnd; i++){
    u8 *pCell = pCArray->apCell[i];
    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
      int sz;


      /* No need to use cachedCellSize() here.  The sizes of all cells that
      ** are to be freed have already been computing while deciding which
      ** cells need freeing */
      sz = pCArray->szCell[i];  assert( sz>0 );
      if( pFree!=(pCell + sz) ){










        if( pFree ){

          assert( pFree>aData && (pFree - aData)<65536 );
          freeSpace(pPg, (u16)(pFree - aData), szFree);
        }
        pFree = pCell;
        szFree = sz;
        if( pFree+sz>pEnd ){
          return 0;
        }
      }else{
        /* The current cell is adjacent to and before the pFree cell.
        ** Combine the two regions into one to reduce the number of calls
        ** to freeSpace(). */
        pFree = pCell;

        szFree += sz;
      }
      nRet++;
    }
  }
  if( pFree ){
    assert( pFree>aData && (pFree - aData)<65536 );
    freeSpace(pPg, (u16)(pFree - aData), szFree);
  }
  return nRet;
}

/*
** pCArray contains pointers to and sizes of all cells in the page being
** balanced.  The current page, pPg, has pPg->nCell cells starting with







|

|
|
>





>
>




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

<
<
<
|
|
>
|




|
<
|







76312
76313
76314
76315
76316
76317
76318
76319
76320
76321
76322
76323
76324
76325
76326
76327
76328
76329
76330
76331
76332
76333
76334
76335
76336
76337
76338
76339
76340
76341
76342
76343
76344
76345
76346
76347
76348
76349
76350

76351


76352



76353
76354
76355
76356
76357
76358
76359
76360
76361

76362
76363
76364
76365
76366
76367
76368
76369
  int nCell,                      /* Cells to delete */
  CellArray *pCArray              /* Array of cells */
){
  u8 * const aData = pPg->aData;
  u8 * const pEnd = &aData[pPg->pBt->usableSize];
  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  int nRet = 0;
  int i, j;
  int iEnd = iFirst + nCell;
  int nFree = 0;
  int aOfst[10];
  int aAfter[10];

  for(i=iFirst; i<iEnd; i++){
    u8 *pCell = pCArray->apCell[i];
    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
      int sz;
      int iAfter;
      int iOfst;
      /* No need to use cachedCellSize() here.  The sizes of all cells that
      ** are to be freed have already been computing while deciding which
      ** cells need freeing */
      sz = pCArray->szCell[i];  assert( sz>0 );
      iOfst = (u16)(pCell - aData);
      iAfter = iOfst+sz;
      for(j=0; j<nFree; j++){
        if( aOfst[j]==iAfter ){
          aOfst[j] = iOfst;
          break;
        }else if( aAfter[j]==iOfst ){
          aAfter[j] = iAfter;
          break;
        }
      }
      if( j>=nFree ){
        if( nFree>=(int)(sizeof(aOfst)/sizeof(aOfst[0])) ){
          for(j=0; j<nFree; j++){
            freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
          }

          nFree = 0;


        }



        aOfst[nFree] = iOfst;
        aAfter[nFree] = iAfter;
        if( &aData[iAfter]>pEnd ) return 0;
        nFree++;
      }
      nRet++;
    }
  }
  for(j=0; j<nFree; j++){

    freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
  }
  return nRet;
}

/*
** pCArray contains pointers to and sizes of all cells in the page being
** balanced.  The current page, pPg, has pPg->nCell cells starting with
75951
75952
75953
75954
75955
75956
75957
75958
75959
75960
75961
75962
75963
75964
75965
75966
75967
  }
  if( iNewEnd < iOldEnd ){
    int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
    assert( nCell>=nTail );
    nCell -= nTail;
  }

  pData = &aData[get2byteNotZero(&aData[hdr+5])];
  if( pData<pBegin ) goto editpage_fail;
  if( pData>pPg->aDataEnd ) goto editpage_fail;

  /* Add cells to the start of the page */
  if( iNew<iOld ){
    int nAdd = MIN(nNew,iOld-iNew);
    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
    assert( nAdd>=0 );
    pCellptr = pPg->aCellIdx;







|

|







76408
76409
76410
76411
76412
76413
76414
76415
76416
76417
76418
76419
76420
76421
76422
76423
76424
  }
  if( iNewEnd < iOldEnd ){
    int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
    assert( nCell>=nTail );
    nCell -= nTail;
  }

  pData = &aData[get2byte(&aData[hdr+5])];
  if( pData<pBegin ) goto editpage_fail;
  if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;

  /* Add cells to the start of the page */
  if( iNew<iOld ){
    int nAdd = MIN(nNew,iOld-iNew);
    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
    assert( nAdd>=0 );
    pCellptr = pPg->aCellIdx;
76690
76691
76692
76693
76694
76695
76696
76697
76698
76699
76700
76701
76702
76703
76704
  ** must be true:
  **    (1) We found one or more cells (cntNew[0])>0), or
  **    (2) pPage is a virtual root page.  A virtual root page is when
  **        the real root page is page 1 and we are the only child of
  **        that page.
  */
  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
    apOld[0]->pgno, apOld[0]->nCell,
    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  ));

  /*
  ** Allocate k new pages.  Reuse old pages where possible.







|







77147
77148
77149
77150
77151
77152
77153
77154
77155
77156
77157
77158
77159
77160
77161
  ** must be true:
  **    (1) We found one or more cells (cntNew[0])>0), or
  **    (2) pPage is a virtual root page.  A virtual root page is when
  **        the real root page is page 1 and we are the only child of
  **        that page.
  */
  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  TRACE(("BALANCE: old: %u(nc=%u) %u(nc=%u) %u(nc=%u)\n",
    apOld[0]->pgno, apOld[0]->nCell,
    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  ));

  /*
  ** Allocate k new pages.  Reuse old pages where possible.
76774
76775
76776
76777
76778
76779
76780
76781
76782
76783
76784
76785
76786
76787
76788
76789
      sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
      sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
      apNew[i]->pgno = pgnoB;
      apNew[iB]->pgno = pgnoA;
    }
  }

  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
         "%d(%d nc=%d) %d(%d nc=%d)\n",
    apNew[0]->pgno, szNew[0], cntNew[0],
    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,







|
|







77231
77232
77233
77234
77235
77236
77237
77238
77239
77240
77241
77242
77243
77244
77245
77246
      sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
      sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
      apNew[i]->pgno = pgnoB;
      apNew[iB]->pgno = pgnoA;
    }
  }

  TRACE(("BALANCE: new: %u(%u nc=%u) %u(%u nc=%u) %u(%u nc=%u) "
         "%u(%u nc=%u) %u(%u nc=%u)\n",
    apNew[0]->pgno, szNew[0], cntNew[0],
    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
77020
77021
77022
77023
77024
77025
77026
77027
77028
77029
77030
77031
77032
77033
77034
    for(i=0; i<nNew; i++){
      u32 key = get4byte(&apNew[i]->aData[8]);
      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
    }
  }

  assert( pParent->isInit );
  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
          nOld, nNew, b.nCell));

  /* Free any old pages that were not reused as new pages.
  */
  for(i=nNew; i<nOld; i++){
    freePage(apOld[i], &rc);
  }







|







77477
77478
77479
77480
77481
77482
77483
77484
77485
77486
77487
77488
77489
77490
77491
    for(i=0; i<nNew; i++){
      u32 key = get4byte(&apNew[i]->aData[8]);
      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
    }
  }

  assert( pParent->isInit );
  TRACE(("BALANCE: finished: old=%u new=%u cells=%u\n",
          nOld, nNew, b.nCell));

  /* Free any old pages that were not reused as new pages.
  */
  for(i=nNew; i<nOld; i++){
    freePage(apOld[i], &rc);
  }
77105
77106
77107
77108
77109
77110
77111
77112
77113
77114
77115
77116
77117
77118
77119
    releasePage(pChild);
    return rc;
  }
  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );

  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));

  /* Copy the overflow cells from pRoot to pChild */
  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  memcpy(pChild->apOvfl, pRoot->apOvfl,
         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  pChild->nOverflow = pRoot->nOverflow;







|







77562
77563
77564
77565
77566
77567
77568
77569
77570
77571
77572
77573
77574
77575
77576
    releasePage(pChild);
    return rc;
  }
  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );

  TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno));

  /* Copy the overflow cells from pRoot to pChild */
  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  memcpy(pChild->apOvfl, pRoot->apOvfl,
         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  pChild->nOverflow = pRoot->nOverflow;
77588
77589
77590
77591
77592
77593
77594
77595
77596
77597
77598
77599
77600
77601
77602
77603
77604
77605
77606
77607
77608
77609
77610
77611
77612
77613
77614
77615
77616
77617
        x2.nData = pX->nKey;
        x2.nZero = 0;
        return btreeOverwriteCell(pCur, &x2);
      }
    }
  }
  assert( pCur->eState==CURSOR_VALID
       || (pCur->eState==CURSOR_INVALID && loc) );

  pPage = pCur->pPage;
  assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
  assert( pPage->leaf || !pPage->intKey );
  if( pPage->nFree<0 ){
    if( NEVER(pCur->eState>CURSOR_INVALID) ){
     /* ^^^^^--- due to the moveToRoot() call above */
      rc = SQLITE_CORRUPT_BKPT;
    }else{
      rc = btreeComputeFreeSpace(pPage);
    }
    if( rc ) return rc;
  }

  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
          loc==0 ? "overwrite" : "new entry"));
  assert( pPage->isInit || CORRUPT_DB );
  newCell = p->pBt->pTmpSpace;
  assert( newCell!=0 );
  assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
  if( flags & BTREE_PREFORMAT ){







|














|







78045
78046
78047
78048
78049
78050
78051
78052
78053
78054
78055
78056
78057
78058
78059
78060
78061
78062
78063
78064
78065
78066
78067
78068
78069
78070
78071
78072
78073
78074
        x2.nData = pX->nKey;
        x2.nZero = 0;
        return btreeOverwriteCell(pCur, &x2);
      }
    }
  }
  assert( pCur->eState==CURSOR_VALID
       || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB );

  pPage = pCur->pPage;
  assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
  assert( pPage->leaf || !pPage->intKey );
  if( pPage->nFree<0 ){
    if( NEVER(pCur->eState>CURSOR_INVALID) ){
     /* ^^^^^--- due to the moveToRoot() call above */
      rc = SQLITE_CORRUPT_BKPT;
    }else{
      rc = btreeComputeFreeSpace(pPage);
    }
    if( rc ) return rc;
  }

  TRACE(("INSERT: table=%u nkey=%lld ndata=%u page=%u %s\n",
          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
          loc==0 ? "overwrite" : "new entry"));
  assert( pPage->isInit || CORRUPT_DB );
  newCell = p->pBt->pTmpSpace;
  assert( newCell!=0 );
  assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
  if( flags & BTREE_PREFORMAT ){
77630
77631
77632
77633
77634
77635
77636

77637
77638
77639
77640
77641
77642
77643
  }else{
    rc = fillInCell(pPage, newCell, pX, &szNew);
    if( rc ) goto end_insert;
  }
  assert( szNew==pPage->xCellSize(pPage, newCell) );
  assert( szNew <= MX_CELL_SIZE(p->pBt) );
  idx = pCur->ix;

  if( loc==0 ){
    CellInfo info;
    assert( idx>=0 );
    if( idx>=pPage->nCell ){
      return SQLITE_CORRUPT_BKPT;
    }
    rc = sqlite3PagerWrite(pPage->pDbPage);







>







78087
78088
78089
78090
78091
78092
78093
78094
78095
78096
78097
78098
78099
78100
78101
  }else{
    rc = fillInCell(pPage, newCell, pX, &szNew);
    if( rc ) goto end_insert;
  }
  assert( szNew==pPage->xCellSize(pPage, newCell) );
  assert( szNew <= MX_CELL_SIZE(p->pBt) );
  idx = pCur->ix;
  pCur->info.nSize = 0;
  if( loc==0 ){
    CellInfo info;
    assert( idx>=0 );
    if( idx>=pPage->nCell ){
      return SQLITE_CORRUPT_BKPT;
    }
    rc = sqlite3PagerWrite(pPage->pDbPage);
77678
77679
77680
77681
77682
77683
77684
77685
77686
77687
77688
77689
77690
77691
77692
  }else if( loc<0 && pPage->nCell>0 ){
    assert( pPage->leaf );
    idx = ++pCur->ix;
    pCur->curFlags &= ~BTCF_ValidNKey;
  }else{
    assert( pPage->leaf );
  }
  rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );

  /* If no error has occurred and pPage has an overflow cell, call balance()
  ** to redistribute the cells within the tree. Since balance() may move
  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  ** variables.







|







78136
78137
78138
78139
78140
78141
78142
78143
78144
78145
78146
78147
78148
78149
78150
  }else if( loc<0 && pPage->nCell>0 ){
    assert( pPage->leaf );
    idx = ++pCur->ix;
    pCur->curFlags &= ~BTCF_ValidNKey;
  }else{
    assert( pPage->leaf );
  }
  rc = insertCellFast(pPage, idx, newCell, szNew);
  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );

  /* If no error has occurred and pPage has an overflow cell, call balance()
  ** to redistribute the cells within the tree. Since balance() may move
  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  ** variables.
77702
77703
77704
77705
77706
77707
77708
77709
77710
77711
77712
77713
77714
77715
77716
  ** happen while processing an "INSERT INTO ... SELECT" statement), it
  ** is advantageous to leave the cursor pointing to the last entry in
  ** the b-tree if possible. If the cursor is left pointing to the last
  ** entry in the table, and the next row inserted has an integer key
  ** larger than the largest existing key, it is possible to insert the
  ** row without seeking the cursor. This can be a big performance boost.
  */
  pCur->info.nSize = 0;
  if( pPage->nOverflow ){
    assert( rc==SQLITE_OK );
    pCur->curFlags &= ~(BTCF_ValidNKey);
    rc = balance(pCur);

    /* Must make sure nOverflow is reset to zero even if the balance()
    ** fails. Internal data structure corruption will result otherwise.







<







78160
78161
78162
78163
78164
78165
78166

78167
78168
78169
78170
78171
78172
78173
  ** happen while processing an "INSERT INTO ... SELECT" statement), it
  ** is advantageous to leave the cursor pointing to the last entry in
  ** the b-tree if possible. If the cursor is left pointing to the last
  ** entry in the table, and the next row inserted has an integer key
  ** larger than the largest existing key, it is possible to insert the
  ** row without seeking the cursor. This can be a big performance boost.
  */

  if( pPage->nOverflow ){
    assert( rc==SQLITE_OK );
    pCur->curFlags &= ~(BTCF_ValidNKey);
    rc = balance(pCur);

    /* Must make sure nOverflow is reset to zero even if the balance()
    ** fails. Internal data structure corruption will result otherwise.
77902
77903
77904
77905
77906
77907
77908



77909
77910
77911
77912
77913
77914
77915
  pPage = pCur->pPage;
  if( pPage->nCell<=iCellIdx ){
    return SQLITE_CORRUPT_BKPT;
  }
  pCell = findCell(pPage, iCellIdx);
  if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
    return SQLITE_CORRUPT_BKPT;



  }

  /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
  ** be preserved following this delete operation. If the current delete
  ** will cause a b-tree rebalance, then this is done by saving the cursor
  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  ** returning.







>
>
>







78359
78360
78361
78362
78363
78364
78365
78366
78367
78368
78369
78370
78371
78372
78373
78374
78375
  pPage = pCur->pPage;
  if( pPage->nCell<=iCellIdx ){
    return SQLITE_CORRUPT_BKPT;
  }
  pCell = findCell(pPage, iCellIdx);
  if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
    return SQLITE_CORRUPT_BKPT;
  }
  if( pCell<&pPage->aCellIdx[pPage->nCell] ){
    return SQLITE_CORRUPT_BKPT;
  }

  /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
  ** be preserved following this delete operation. If the current delete
  ** will cause a b-tree rebalance, then this is done by saving the cursor
  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  ** returning.
78651
78652
78653
78654
78655
78656
78657
78658

78659
78660
78661
78662
78663
78664
78665
  pCheck->mxErr--;
  pCheck->nErr++;
  va_start(ap, zFormat);
  if( pCheck->errMsg.nChar ){
    sqlite3_str_append(&pCheck->errMsg, "\n", 1);
  }
  if( pCheck->zPfx ){
    sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);

  }
  sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
  va_end(ap);
  if( pCheck->errMsg.accError==SQLITE_NOMEM ){
    checkOom(pCheck);
  }
}







|
>







79111
79112
79113
79114
79115
79116
79117
79118
79119
79120
79121
79122
79123
79124
79125
79126
  pCheck->mxErr--;
  pCheck->nErr++;
  va_start(ap, zFormat);
  if( pCheck->errMsg.nChar ){
    sqlite3_str_append(&pCheck->errMsg, "\n", 1);
  }
  if( pCheck->zPfx ){
    sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx,
                        pCheck->v0, pCheck->v1, pCheck->v2);
  }
  sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
  va_end(ap);
  if( pCheck->errMsg.accError==SQLITE_NOMEM ){
    checkOom(pCheck);
  }
}
78691
78692
78693
78694
78695
78696
78697
78698
78699
78700
78701
78702
78703
78704
78705
78706
78707
78708
78709
** Return 1 if there are 2 or more references to the page and 0 if
** if this is the first reference to the page.
**
** Also check that the page number is in bounds.
*/
static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  if( iPage>pCheck->nPage || iPage==0 ){
    checkAppendMsg(pCheck, "invalid page number %d", iPage);
    return 1;
  }
  if( getPageReferenced(pCheck, iPage) ){
    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
    return 1;
  }
  setPageReferenced(pCheck, iPage);
  return 0;
}

#ifndef SQLITE_OMIT_AUTOVACUUM







|



|







79152
79153
79154
79155
79156
79157
79158
79159
79160
79161
79162
79163
79164
79165
79166
79167
79168
79169
79170
** Return 1 if there are 2 or more references to the page and 0 if
** if this is the first reference to the page.
**
** Also check that the page number is in bounds.
*/
static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  if( iPage>pCheck->nPage || iPage==0 ){
    checkAppendMsg(pCheck, "invalid page number %u", iPage);
    return 1;
  }
  if( getPageReferenced(pCheck, iPage) ){
    checkAppendMsg(pCheck, "2nd reference to page %u", iPage);
    return 1;
  }
  setPageReferenced(pCheck, iPage);
  return 0;
}

#ifndef SQLITE_OMIT_AUTOVACUUM
78721
78722
78723
78724
78725
78726
78727
78728
78729
78730
78731
78732
78733
78734
78735
78736
78737
78738
78739
78740
78741
  int rc;
  u8 ePtrmapType;
  Pgno iPtrmapParent;

  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
    return;
  }

  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
    checkAppendMsg(pCheck,
      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  }
}
#endif

/*
** Check the integrity of the freelist or of an overflow page list.







|





|







79182
79183
79184
79185
79186
79187
79188
79189
79190
79191
79192
79193
79194
79195
79196
79197
79198
79199
79200
79201
79202
  int rc;
  u8 ePtrmapType;
  Pgno iPtrmapParent;

  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
    checkAppendMsg(pCheck, "Failed to read ptrmap key=%u", iChild);
    return;
  }

  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
    checkAppendMsg(pCheck,
      "Bad ptr map entry key=%u expected=(%u,%u) got=(%u,%u)",
      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  }
}
#endif

/*
** Check the integrity of the freelist or of an overflow page list.
78752
78753
78754
78755
78756
78757
78758
78759
78760
78761
78762
78763
78764
78765
78766
78767
78768
78769
78770
78771
78772
78773
78774
78775
78776
78777
78778
78779
  int nErrAtStart = pCheck->nErr;
  while( iPage!=0 && pCheck->mxErr ){
    DbPage *pOvflPage;
    unsigned char *pOvflData;
    if( checkRef(pCheck, iPage) ) break;
    N--;
    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
      checkAppendMsg(pCheck, "failed to get page %d", iPage);
      break;
    }
    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
    if( isFreeList ){
      u32 n = (u32)get4byte(&pOvflData[4]);
#ifndef SQLITE_OMIT_AUTOVACUUM
      if( pCheck->pBt->autoVacuum ){
        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
      }
#endif
      if( n>pCheck->pBt->usableSize/4-2 ){
        checkAppendMsg(pCheck,
           "freelist leaf count too big on page %d", iPage);
        N--;
      }else{
        for(i=0; i<(int)n; i++){
          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
#ifndef SQLITE_OMIT_AUTOVACUUM
          if( pCheck->pBt->autoVacuum ){
            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);







|












|







79213
79214
79215
79216
79217
79218
79219
79220
79221
79222
79223
79224
79225
79226
79227
79228
79229
79230
79231
79232
79233
79234
79235
79236
79237
79238
79239
79240
  int nErrAtStart = pCheck->nErr;
  while( iPage!=0 && pCheck->mxErr ){
    DbPage *pOvflPage;
    unsigned char *pOvflData;
    if( checkRef(pCheck, iPage) ) break;
    N--;
    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
      checkAppendMsg(pCheck, "failed to get page %u", iPage);
      break;
    }
    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
    if( isFreeList ){
      u32 n = (u32)get4byte(&pOvflData[4]);
#ifndef SQLITE_OMIT_AUTOVACUUM
      if( pCheck->pBt->autoVacuum ){
        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
      }
#endif
      if( n>pCheck->pBt->usableSize/4-2 ){
        checkAppendMsg(pCheck,
           "freelist leaf count too big on page %u", iPage);
        N--;
      }else{
        for(i=0; i<(int)n; i++){
          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
#ifndef SQLITE_OMIT_AUTOVACUUM
          if( pCheck->pBt->autoVacuum ){
            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
78797
78798
78799
78800
78801
78802
78803
78804
78805
78806
78807
78808
78809
78810
78811
    }
#endif
    iPage = get4byte(pOvflData);
    sqlite3PagerUnref(pOvflPage);
  }
  if( N && nErrAtStart==pCheck->nErr ){
    checkAppendMsg(pCheck,
      "%s is %d but should be %d",
      isFreeList ? "size" : "overflow list length",
      expected-N, expected);
  }
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

/*







|







79258
79259
79260
79261
79262
79263
79264
79265
79266
79267
79268
79269
79270
79271
79272
    }
#endif
    iPage = get4byte(pOvflData);
    sqlite3PagerUnref(pOvflPage);
  }
  if( N && nErrAtStart==pCheck->nErr ){
    checkAppendMsg(pCheck,
      "%s is %u but should be %u",
      isFreeList ? "size" : "overflow list length",
      expected-N, expected);
  }
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

/*
78912
78913
78914
78915
78916
78917
78918
78919
78920
78921
78922
78923
78924
78925
78926
78927
  */
  checkProgress(pCheck);
  if( pCheck->mxErr==0 ) goto end_of_check;
  pBt = pCheck->pBt;
  usableSize = pBt->usableSize;
  if( iPage==0 ) return 0;
  if( checkRef(pCheck, iPage) ) return 0;
  pCheck->zPfx = "Page %u: ";
  pCheck->v1 = iPage;
  if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
    checkAppendMsg(pCheck,
       "unable to get the page. error code=%d", rc);
    goto end_of_check;
  }

  /* Clear MemPage.isInit to make sure the corruption detection code in







|
|







79373
79374
79375
79376
79377
79378
79379
79380
79381
79382
79383
79384
79385
79386
79387
79388
  */
  checkProgress(pCheck);
  if( pCheck->mxErr==0 ) goto end_of_check;
  pBt = pCheck->pBt;
  usableSize = pBt->usableSize;
  if( iPage==0 ) return 0;
  if( checkRef(pCheck, iPage) ) return 0;
  pCheck->zPfx = "Tree %u page %u: ";
  pCheck->v0 = pCheck->v1 = iPage;
  if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
    checkAppendMsg(pCheck,
       "unable to get the page. error code=%d", rc);
    goto end_of_check;
  }

  /* Clear MemPage.isInit to make sure the corruption detection code in
78939
78940
78941
78942
78943
78944
78945
78946
78947
78948
78949
78950
78951
78952
78953
78954
78955
78956
78957
78958
78959
78960
78961
78962
78963
78964
78965
78966
78967
78968
78969
78970
78971
78972
78973
    checkAppendMsg(pCheck, "free space corruption", rc);
    goto end_of_check;
  }
  data = pPage->aData;
  hdr = pPage->hdrOffset;

  /* Set up for cell analysis */
  pCheck->zPfx = "On tree page %u cell %d: ";
  contentOffset = get2byteNotZero(&data[hdr+5]);
  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */

  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  ** number of cells on the page. */
  nCell = get2byte(&data[hdr+3]);
  assert( pPage->nCell==nCell );

  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  ** immediately follows the b-tree page header. */
  cellStart = hdr + 12 - 4*pPage->leaf;
  assert( pPage->aCellIdx==&data[cellStart] );
  pCellIdx = &data[cellStart + 2*(nCell-1)];

  if( !pPage->leaf ){
    /* Analyze the right-child page of internal pages */
    pgno = get4byte(&data[hdr+8]);
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum ){
      pCheck->zPfx = "On page %u at right child: ";
      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
    }
#endif
    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
    keyCanBeEqual = 0;
  }else{
    /* For leaf pages, the coverage check will occur in the same loop







|



















|







79400
79401
79402
79403
79404
79405
79406
79407
79408
79409
79410
79411
79412
79413
79414
79415
79416
79417
79418
79419
79420
79421
79422
79423
79424
79425
79426
79427
79428
79429
79430
79431
79432
79433
79434
    checkAppendMsg(pCheck, "free space corruption", rc);
    goto end_of_check;
  }
  data = pPage->aData;
  hdr = pPage->hdrOffset;

  /* Set up for cell analysis */
  pCheck->zPfx = "Tree %u page %u cell %u: ";
  contentOffset = get2byteNotZero(&data[hdr+5]);
  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */

  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  ** number of cells on the page. */
  nCell = get2byte(&data[hdr+3]);
  assert( pPage->nCell==nCell );

  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  ** immediately follows the b-tree page header. */
  cellStart = hdr + 12 - 4*pPage->leaf;
  assert( pPage->aCellIdx==&data[cellStart] );
  pCellIdx = &data[cellStart + 2*(nCell-1)];

  if( !pPage->leaf ){
    /* Analyze the right-child page of internal pages */
    pgno = get4byte(&data[hdr+8]);
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum ){
      pCheck->zPfx = "Tree %u page %u right child: ";
      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
    }
#endif
    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
    keyCanBeEqual = 0;
  }else{
    /* For leaf pages, the coverage check will occur in the same loop
78983
78984
78985
78986
78987
78988
78989
78990
78991
78992
78993
78994
78995
78996
78997

    /* Check cell size */
    pCheck->v2 = i;
    assert( pCellIdx==&data[cellStart + i*2] );
    pc = get2byteAligned(pCellIdx);
    pCellIdx -= 2;
    if( pc<contentOffset || pc>usableSize-4 ){
      checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
                             pc, contentOffset, usableSize-4);
      doCoverageCheck = 0;
      continue;
    }
    pCell = &data[pc];
    pPage->xParseCell(pPage, pCell, &info);
    if( pc+info.nSize>usableSize ){







|







79444
79445
79446
79447
79448
79449
79450
79451
79452
79453
79454
79455
79456
79457
79458

    /* Check cell size */
    pCheck->v2 = i;
    assert( pCellIdx==&data[cellStart + i*2] );
    pc = get2byteAligned(pCellIdx);
    pCellIdx -= 2;
    if( pc<contentOffset || pc>usableSize-4 ){
      checkAppendMsg(pCheck, "Offset %u out of range %u..%u",
                             pc, contentOffset, usableSize-4);
      doCoverageCheck = 0;
      continue;
    }
    pCell = &data[pc];
    pPage->xParseCell(pPage, pCell, &info);
    if( pc+info.nSize>usableSize ){
79115
79116
79117
79118
79119
79120
79121
79122
79123
79124
79125
79126
79127
79128
79129
    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
    ** is stored in the fifth field of the b-tree page header.
    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
    ** number of fragmented free bytes within the cell content area.
    */
    if( heap[0]==0 && nFrag!=data[hdr+7] ){
      checkAppendMsg(pCheck,
          "Fragmentation of %d bytes reported as %d on page %u",
          nFrag, data[hdr+7], iPage);
    }
  }

end_of_check:
  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  releasePage(pPage);







|







79576
79577
79578
79579
79580
79581
79582
79583
79584
79585
79586
79587
79588
79589
79590
    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
    ** is stored in the fifth field of the b-tree page header.
    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
    ** number of fragmented free bytes within the cell content area.
    */
    if( heap[0]==0 && nFrag!=data[hdr+7] ){
      checkAppendMsg(pCheck,
          "Fragmentation of %u bytes reported as %u on page %u",
          nFrag, data[hdr+7], iPage);
    }
  }

end_of_check:
  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  releasePage(pPage);
79212
79213
79214
79215
79216
79217
79218
79219
79220
79221
79222
79223
79224
79225
79226
79227
79228
79229
79230
79231
79232
79233
79234
79235
79236
79237
79238
79239
79240
79241
79242
79243

  i = PENDING_BYTE_PAGE(pBt);
  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);

  /* Check the integrity of the freelist
  */
  if( bCkFreelist ){
    sCheck.zPfx = "Main freelist: ";
    checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
              get4byte(&pBt->pPage1->aData[36]));
    sCheck.zPfx = 0;
  }

  /* Check all the tables.
  */
#ifndef SQLITE_OMIT_AUTOVACUUM
  if( !bPartial ){
    if( pBt->autoVacuum ){
      Pgno mx = 0;
      Pgno mxInHdr;
      for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
      mxInHdr = get4byte(&pBt->pPage1->aData[52]);
      if( mx!=mxInHdr ){
        checkAppendMsg(&sCheck,
          "max rootpage (%d) disagrees with header (%d)",
          mx, mxInHdr
        );
      }
    }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
      checkAppendMsg(&sCheck,
        "incremental_vacuum enabled with a max rootpage of zero"
      );







|
















|







79673
79674
79675
79676
79677
79678
79679
79680
79681
79682
79683
79684
79685
79686
79687
79688
79689
79690
79691
79692
79693
79694
79695
79696
79697
79698
79699
79700
79701
79702
79703
79704

  i = PENDING_BYTE_PAGE(pBt);
  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);

  /* Check the integrity of the freelist
  */
  if( bCkFreelist ){
    sCheck.zPfx = "Freelist: ";
    checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
              get4byte(&pBt->pPage1->aData[36]));
    sCheck.zPfx = 0;
  }

  /* Check all the tables.
  */
#ifndef SQLITE_OMIT_AUTOVACUUM
  if( !bPartial ){
    if( pBt->autoVacuum ){
      Pgno mx = 0;
      Pgno mxInHdr;
      for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
      mxInHdr = get4byte(&pBt->pPage1->aData[52]);
      if( mx!=mxInHdr ){
        checkAppendMsg(&sCheck,
          "max rootpage (%u) disagrees with header (%u)",
          mx, mxInHdr
        );
      }
    }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
      checkAppendMsg(&sCheck,
        "incremental_vacuum enabled with a max rootpage of zero"
      );
79260
79261
79262
79263
79264
79265
79266
79267
79268
79269
79270
79271
79272
79273
79274
79275
79276
79277
79278
79279
79280
79281
79282
79283
79284
79285
79286

  /* Make sure every page in the file is referenced
  */
  if( !bPartial ){
    for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
#ifdef SQLITE_OMIT_AUTOVACUUM
      if( getPageReferenced(&sCheck, i)==0 ){
        checkAppendMsg(&sCheck, "Page %d is never used", i);
      }
#else
      /* If the database supports auto-vacuum, make sure no tables contain
      ** references to pointer-map pages.
      */
      if( getPageReferenced(&sCheck, i)==0 &&
         (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
        checkAppendMsg(&sCheck, "Page %d is never used", i);
      }
      if( getPageReferenced(&sCheck, i)!=0 &&
         (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
        checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
      }
#endif
    }
  }

  /* Clean  up and report errors.
  */







|







|



|







79721
79722
79723
79724
79725
79726
79727
79728
79729
79730
79731
79732
79733
79734
79735
79736
79737
79738
79739
79740
79741
79742
79743
79744
79745
79746
79747

  /* Make sure every page in the file is referenced
  */
  if( !bPartial ){
    for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
#ifdef SQLITE_OMIT_AUTOVACUUM
      if( getPageReferenced(&sCheck, i)==0 ){
        checkAppendMsg(&sCheck, "Page %u: never used", i);
      }
#else
      /* If the database supports auto-vacuum, make sure no tables contain
      ** references to pointer-map pages.
      */
      if( getPageReferenced(&sCheck, i)==0 &&
         (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
        checkAppendMsg(&sCheck, "Page %u: never used", i);
      }
      if( getPageReferenced(&sCheck, i)!=0 &&
         (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
        checkAppendMsg(&sCheck, "Page %u: pointer map referenced", i);
      }
#endif
    }
  }

  /* Clean  up and report errors.
  */
79834
79835
79836
79837
79838
79839
79840
79841
79842
79843
79844
79845
79846
79847
79848
79849
79850
79851
79852
79853
79854
  i64 iOff;

  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  assert( p->bDestLocked );
  assert( !isFatalError(p->rc) );
  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  assert( zSrcData );

  /* Catch the case where the destination is an in-memory database and the
  ** page sizes of the source and destination differ.
  */
  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
    rc = SQLITE_READONLY;
  }

  /* This loop runs once for each destination page spanned by the source
  ** page. For each iteration, variable iOff is set to the byte offset
  ** of the destination page.
  */
  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
    DbPage *pDestPg = 0;







<
<
<
<
|
<
<







80295
80296
80297
80298
80299
80300
80301




80302


80303
80304
80305
80306
80307
80308
80309
  i64 iOff;

  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  assert( p->bDestLocked );
  assert( !isFatalError(p->rc) );
  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  assert( zSrcData );




  assert( nSrcPgsz==nDestPgsz || sqlite3PagerIsMemdb(pDestPager)==0 );



  /* This loop runs once for each destination page spanned by the source
  ** page. For each iteration, variable iOff is set to the byte offset
  ** of the destination page.
  */
  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
    DbPage *pDestPg = 0;
79973
79974
79975
79976
79977
79978
79979
79980



79981
79982
79983
79984
79985
79986
79987
    }

    /* Do not allow backup if the destination database is in WAL mode
    ** and the page sizes are different between source and destination */
    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){



      rc = SQLITE_READONLY;
    }

    /* Now that there is a read-lock on the source database, query the
    ** source pager for the number of pages in the database.
    */
    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);







|
>
>
>







80428
80429
80430
80431
80432
80433
80434
80435
80436
80437
80438
80439
80440
80441
80442
80443
80444
80445
    }

    /* Do not allow backup if the destination database is in WAL mode
    ** and the page sizes are different between source and destination */
    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
    if( SQLITE_OK==rc
     && (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager))
     && pgszSrc!=pgszDest
    ){
      rc = SQLITE_READONLY;
    }

    /* Now that there is a read-lock on the source database, query the
    ** source pager for the number of pages in the database.
    */
    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
80522
80523
80524
80525
80526
80527
80528

80529
80530
80531
80532
80533
80534
80535
*/
SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){
  Mem tmp;
  char zBuf[100];
  char *z;
  int i, j, incr;
  if( (p->flags & MEM_Str)==0 ) return 1;

  if( p->flags & MEM_Term ){
    /* Insure that the string is properly zero-terminated.  Pay particular
    ** attention to the case where p->n is odd */
    if( p->szMalloc>0 && p->z==p->zMalloc ){
      assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
      assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
    }







>







80980
80981
80982
80983
80984
80985
80986
80987
80988
80989
80990
80991
80992
80993
80994
*/
SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){
  Mem tmp;
  char zBuf[100];
  char *z;
  int i, j, incr;
  if( (p->flags & MEM_Str)==0 ) return 1;
  if( p->db && p->db->mallocFailed ) return 1;
  if( p->flags & MEM_Term ){
    /* Insure that the string is properly zero-terminated.  Pay particular
    ** attention to the case where p->n is odd */
    if( p->szMalloc>0 && p->z==p->zMalloc ){
      assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
      assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
    }
80804
80805
80806
80807
80808
80809
80810
80811
80812
80813
80814
80815
80816
80817
80818
  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
    pMem->enc = 0;
    return SQLITE_NOMEM_BKPT;
  }

  vdbeMemRenderNum(nByte, pMem->z, pMem);
  assert( pMem->z!=0 );
  assert( pMem->n==sqlite3Strlen30NN(pMem->z) );
  pMem->enc = SQLITE_UTF8;
  pMem->flags |= MEM_Str|MEM_Term;
  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
  sqlite3VdbeChangeEncoding(pMem, enc);
  return SQLITE_OK;
}








|







81263
81264
81265
81266
81267
81268
81269
81270
81271
81272
81273
81274
81275
81276
81277
  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
    pMem->enc = 0;
    return SQLITE_NOMEM_BKPT;
  }

  vdbeMemRenderNum(nByte, pMem->z, pMem);
  assert( pMem->z!=0 );
  assert( pMem->n==(int)sqlite3Strlen30NN(pMem->z) );
  pMem->enc = SQLITE_UTF8;
  pMem->flags |= MEM_Str|MEM_Term;
  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
  sqlite3VdbeChangeEncoding(pMem, enc);
  return SQLITE_OK;
}

81848
81849
81850
81851
81852
81853
81854



81855
81856
81857
81858
81859
81860
81861
  assert( pCtx!=0 );
  assert( (p->flags & EP_TokenOnly)==0 );
  assert( ExprUseXList(p) );
  pList = p->x.pList;
  if( pList ) nVal = pList->nExpr;
  assert( !ExprHasProperty(p, EP_IntValue) );
  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);



  assert( pFunc );
  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  ){
    return SQLITE_OK;
  }








>
>
>







82307
82308
82309
82310
82311
82312
82313
82314
82315
82316
82317
82318
82319
82320
82321
82322
82323
  assert( pCtx!=0 );
  assert( (p->flags & EP_TokenOnly)==0 );
  assert( ExprUseXList(p) );
  pList = p->x.pList;
  if( pList ) nVal = pList->nExpr;
  assert( !ExprHasProperty(p, EP_IntValue) );
  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  if( pFunc==0 ) return SQLITE_OK;
#endif
  assert( pFunc );
  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  ){
    return SQLITE_OK;
  }

81884
81885
81886
81887
81888
81889
81890
81891
81892
81893
81894
81895
81896
81897
81898
81899
81900
81901
81902
81903
81904
81905
81906
81907
  pFunc->xSFunc(&ctx, nVal, apVal);
  if( ctx.isError ){
    rc = ctx.isError;
    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  }else{
    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
    assert( rc==SQLITE_OK );
    assert( enc==pVal->enc
         || (pVal->flags & MEM_Str)==0
         || db->mallocFailed  );
#if 0  /* Not reachable except after a prior failure */
    rc = sqlite3VdbeChangeEncoding(pVal, enc);
    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
      rc = SQLITE_TOOBIG;
      pCtx->pParse->nErr++;
    }
#endif
  }

 value_from_function_out:
  if( rc!=SQLITE_OK ){
    pVal = 0;
    pCtx->pParse->rc = rc;
  }







<
<
<
<

|



<







82346
82347
82348
82349
82350
82351
82352




82353
82354
82355
82356
82357

82358
82359
82360
82361
82362
82363
82364
  pFunc->xSFunc(&ctx, nVal, apVal);
  if( ctx.isError ){
    rc = ctx.isError;
    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  }else{
    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
    assert( rc==SQLITE_OK );




    rc = sqlite3VdbeChangeEncoding(pVal, enc);
    if( NEVER(rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal)) ){
      rc = SQLITE_TOOBIG;
      pCtx->pParse->nErr++;
    }

  }

 value_from_function_out:
  if( rc!=SQLITE_OK ){
    pVal = 0;
    pCtx->pParse->rc = rc;
  }
81957
81958
81959
81960
81961
81962
81963







81964
81965
81966
81967
81968
81969
81970
  if( op==TK_CAST ){
    u8 aff;
    assert( !ExprHasProperty(pExpr, EP_IntValue) );
    aff = sqlite3AffinityType(pExpr->u.zToken,0);
    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
    testcase( rc!=SQLITE_OK );
    if( *ppVal ){







      sqlite3VdbeMemCast(*ppVal, aff, enc);
      sqlite3ValueApplyAffinity(*ppVal, affinity, enc);
    }
    return rc;
  }

  /* Handle negative integers in a single step.  This is needed in the







>
>
>
>
>
>
>







82414
82415
82416
82417
82418
82419
82420
82421
82422
82423
82424
82425
82426
82427
82428
82429
82430
82431
82432
82433
82434
  if( op==TK_CAST ){
    u8 aff;
    assert( !ExprHasProperty(pExpr, EP_IntValue) );
    aff = sqlite3AffinityType(pExpr->u.zToken,0);
    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
    testcase( rc!=SQLITE_OK );
    if( *ppVal ){
#ifdef SQLITE_ENABLE_STAT4
      rc = ExpandBlob(*ppVal);
#else
      /* zero-blobs only come from functions, not literal values.  And
      ** functions are only processed under STAT4 */
      assert( (ppVal[0][0].flags & MEM_Zero)==0 );
#endif
      sqlite3VdbeMemCast(*ppVal, aff, enc);
      sqlite3ValueApplyAffinity(*ppVal, affinity, enc);
    }
    return rc;
  }

  /* Handle negative integers in a single step.  This is needed in the
82803
82804
82805
82806
82807
82808
82809
82810
82811
82812
82813
82814
82815
82816
82817
82818
82819
82820
** Add a new OP_Explain opcode.
**
** If the bPush flag is true, then make this opcode the parent for
** subsequent Explains until sqlite3VdbeExplainPop() is called.
*/
SQLITE_PRIVATE int sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
  int addr = 0;
#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
  ** But omit them (for performance) during production builds */
  if( pParse->explain==2 )
#endif
  {
    char *zMsg;
    Vdbe *v;
    va_list ap;
    int iThis;
    va_start(ap, zFmt);







|


|







83267
83268
83269
83270
83271
83272
83273
83274
83275
83276
83277
83278
83279
83280
83281
83282
83283
83284
** Add a new OP_Explain opcode.
**
** If the bPush flag is true, then make this opcode the parent for
** subsequent Explains until sqlite3VdbeExplainPop() is called.
*/
SQLITE_PRIVATE int sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
  int addr = 0;
#if !defined(SQLITE_DEBUG)
  /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
  ** But omit them (for performance) during production builds */
  if( pParse->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
#endif
  {
    char *zMsg;
    Vdbe *v;
    va_list ap;
    int iThis;
    va_start(ap, zFmt);
83180
83181
83182
83183
83184
83185
83186


83187
83188
83189
83190
83191
83192
83193
** coordinated with changes to mkopcodeh.tcl.
*/
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  int nMaxArgs = *pMaxFuncArgs;
  Op *pOp;
  Parse *pParse = p->pParse;
  int *aLabel = pParse->aLabel;


  p->readOnly = 1;
  p->bIsReader = 0;
  pOp = &p->aOp[p->nOp-1];
  assert( p->aOp[0].opcode==OP_Init );
  while( 1 /* Loop termates when it reaches the OP_Init opcode */ ){
    /* Only JUMP opcodes and the short list of special opcodes in the switch
    ** below need to be considered.  The mkopcodeh.tcl generator script groups







>
>







83644
83645
83646
83647
83648
83649
83650
83651
83652
83653
83654
83655
83656
83657
83658
83659
** coordinated with changes to mkopcodeh.tcl.
*/
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  int nMaxArgs = *pMaxFuncArgs;
  Op *pOp;
  Parse *pParse = p->pParse;
  int *aLabel = pParse->aLabel;

  assert( pParse->db->mallocFailed==0 ); /* tag-20230419-1 */
  p->readOnly = 1;
  p->bIsReader = 0;
  pOp = &p->aOp[p->nOp-1];
  assert( p->aOp[0].opcode==OP_Init );
  while( 1 /* Loop termates when it reaches the OP_Init opcode */ ){
    /* Only JUMP opcodes and the short list of special opcodes in the switch
    ** below need to be considered.  The mkopcodeh.tcl generator script groups
83239
83240
83241
83242
83243
83244
83245

83246
83247
83248
83249
83250
83251
83252
        default: {
          if( pOp->p2<0 ){
            /* The mkopcodeh.tcl script has so arranged things that the only
            ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
            ** have non-negative values for P2. */
            assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
            assert( ADDR(pOp->p2)<-pParse->nLabel );

            pOp->p2 = aLabel[ADDR(pOp->p2)];
          }
          break;
        }
      }
      /* The mkopcodeh.tcl script has so arranged things that the only
      ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to







>







83705
83706
83707
83708
83709
83710
83711
83712
83713
83714
83715
83716
83717
83718
83719
        default: {
          if( pOp->p2<0 ){
            /* The mkopcodeh.tcl script has so arranged things that the only
            ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
            ** have non-negative values for P2. */
            assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
            assert( ADDR(pOp->p2)<-pParse->nLabel );
            assert( aLabel!=0 );  /* True because of tag-20230419-1 */
            pOp->p2 = aLabel[ADDR(pOp->p2)];
          }
          break;
        }
      }
      /* The mkopcodeh.tcl script has so arranged things that the only
      ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
83482
83483
83484
83485
83486
83487
83488

83489
83490
83491
83492
83493
83494
83495
83496
83497
83498
83499
83500

83501
83502
83503
83504
83505
83506
83507
83508
83509
83510
83511
83512
83513
83514
83515
83516

83517
83518
83519
83520
83521
83522
83523
83524
83525
83526
83527
83528
83529
83530

83531
83532
83533
83534
83535
83536
83537
83538
83539
83540
83541
83542
83543
83544
83545
83546

83547
83548
83549
83550
83551
83552
83553
83554
83555
83556
83557
83558

83559
83560
83561
83562
83563
83564
83565
83566
  Vdbe *p,                        /* VM to add scanstatus() to */
  int addrExplain,                /* Address of OP_Explain (or 0) */
  int addrLoop,                   /* Address of loop counter */
  int addrVisit,                  /* Address of rows visited counter */
  LogEst nEst,                    /* Estimated number of output rows */
  const char *zName               /* Name of table or index being scanned */
){

  sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
  ScanStatus *aNew;
  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  if( aNew ){
    ScanStatus *pNew = &aNew[p->nScan++];
    memset(pNew, 0, sizeof(ScanStatus));
    pNew->addrExplain = addrExplain;
    pNew->addrLoop = addrLoop;
    pNew->addrVisit = addrVisit;
    pNew->nEst = nEst;
    pNew->zName = sqlite3DbStrDup(p->db, zName);
    p->aScan = aNew;

  }
}

/*
** Add the range of instructions from addrStart to addrEnd (inclusive) to
** the set of those corresponding to the sqlite3_stmt_scanstatus() counters
** associated with the OP_Explain instruction at addrExplain. The
** sum of the sqlite3Hwtime() values for each of these instructions
** will be returned for SQLITE_SCANSTAT_NCYCLE requests.
*/
SQLITE_PRIVATE void sqlite3VdbeScanStatusRange(
  Vdbe *p,
  int addrExplain,
  int addrStart,
  int addrEnd
){

  ScanStatus *pScan = 0;
  int ii;
  for(ii=p->nScan-1; ii>=0; ii--){
    pScan = &p->aScan[ii];
    if( pScan->addrExplain==addrExplain ) break;
    pScan = 0;
  }
  if( pScan ){
    if( addrEnd<0 ) addrEnd = sqlite3VdbeCurrentAddr(p)-1;
    for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
      if( pScan->aAddrRange[ii]==0 ){
        pScan->aAddrRange[ii] = addrStart;
        pScan->aAddrRange[ii+1] = addrEnd;
        break;

      }
    }
  }
}

/*
** Set the addresses for the SQLITE_SCANSTAT_NLOOP and SQLITE_SCANSTAT_NROW
** counters for the query element associated with the OP_Explain at
** addrExplain.
*/
SQLITE_PRIVATE void sqlite3VdbeScanStatusCounters(
  Vdbe *p,
  int addrExplain,
  int addrLoop,
  int addrVisit
){

  ScanStatus *pScan = 0;
  int ii;
  for(ii=p->nScan-1; ii>=0; ii--){
    pScan = &p->aScan[ii];
    if( pScan->addrExplain==addrExplain ) break;
    pScan = 0;
  }
  if( pScan ){
    pScan->addrLoop = addrLoop;
    pScan->addrVisit = addrVisit;
  }
}

#endif


/*
** Change the value of the opcode, or P1, P2, P3, or P5 operands
** for a specific instruction.
*/
SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){







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
















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
















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







83949
83950
83951
83952
83953
83954
83955
83956
83957
83958
83959
83960
83961
83962
83963
83964
83965
83966
83967
83968
83969
83970
83971
83972
83973
83974
83975
83976
83977
83978
83979
83980
83981
83982
83983
83984
83985
83986
83987
83988
83989
83990
83991
83992
83993
83994
83995
83996
83997
83998
83999
84000
84001
84002
84003
84004
84005
84006
84007
84008
84009
84010
84011
84012
84013
84014
84015
84016
84017
84018
84019
84020
84021
84022
84023
84024
84025
84026
84027
84028
84029
84030
84031
84032
84033
84034
84035
84036
84037
84038
84039
  Vdbe *p,                        /* VM to add scanstatus() to */
  int addrExplain,                /* Address of OP_Explain (or 0) */
  int addrLoop,                   /* Address of loop counter */
  int addrVisit,                  /* Address of rows visited counter */
  LogEst nEst,                    /* Estimated number of output rows */
  const char *zName               /* Name of table or index being scanned */
){
  if( IS_STMT_SCANSTATUS(p->db) ){
    sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
    ScanStatus *aNew;
    aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
    if( aNew ){
      ScanStatus *pNew = &aNew[p->nScan++];
      memset(pNew, 0, sizeof(ScanStatus));
      pNew->addrExplain = addrExplain;
      pNew->addrLoop = addrLoop;
      pNew->addrVisit = addrVisit;
      pNew->nEst = nEst;
      pNew->zName = sqlite3DbStrDup(p->db, zName);
      p->aScan = aNew;
    }
  }
}

/*
** Add the range of instructions from addrStart to addrEnd (inclusive) to
** the set of those corresponding to the sqlite3_stmt_scanstatus() counters
** associated with the OP_Explain instruction at addrExplain. The
** sum of the sqlite3Hwtime() values for each of these instructions
** will be returned for SQLITE_SCANSTAT_NCYCLE requests.
*/
SQLITE_PRIVATE void sqlite3VdbeScanStatusRange(
  Vdbe *p,
  int addrExplain,
  int addrStart,
  int addrEnd
){
  if( IS_STMT_SCANSTATUS(p->db) ){
    ScanStatus *pScan = 0;
    int ii;
    for(ii=p->nScan-1; ii>=0; ii--){
      pScan = &p->aScan[ii];
      if( pScan->addrExplain==addrExplain ) break;
      pScan = 0;
    }
    if( pScan ){
      if( addrEnd<0 ) addrEnd = sqlite3VdbeCurrentAddr(p)-1;
      for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
        if( pScan->aAddrRange[ii]==0 ){
          pScan->aAddrRange[ii] = addrStart;
          pScan->aAddrRange[ii+1] = addrEnd;
          break;
        }
      }
    }
  }
}

/*
** Set the addresses for the SQLITE_SCANSTAT_NLOOP and SQLITE_SCANSTAT_NROW
** counters for the query element associated with the OP_Explain at
** addrExplain.
*/
SQLITE_PRIVATE void sqlite3VdbeScanStatusCounters(
  Vdbe *p,
  int addrExplain,
  int addrLoop,
  int addrVisit
){
  if( IS_STMT_SCANSTATUS(p->db) ){
    ScanStatus *pScan = 0;
    int ii;
    for(ii=p->nScan-1; ii>=0; ii--){
      pScan = &p->aScan[ii];
      if( pScan->addrExplain==addrExplain ) break;
      pScan = 0;
    }
    if( pScan ){
      pScan->addrLoop = addrLoop;
      pScan->addrVisit = addrVisit;
    }
  }
}
#endif /* defined(SQLITE_ENABLE_STMT_SCANSTATUS) */


/*
** Change the value of the opcode, or P1, P2, P3, or P5 operands
** for a specific instruction.
*/
SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
83976
83977
83978
83979
83980
83981
83982
83983
83984
83985
83986
83987
83988
83989
83990
  }else{
    return &p->aOp[addr];
  }
}

/* Return the most recently added opcode
*/
VdbeOp * sqlite3VdbeGetLastOp(Vdbe *p){
  return sqlite3VdbeGetOp(p, p->nOp - 1);
}

#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
/*
** Return an integer value for one of the parameters to the opcode pOp
** determined by character c.







|







84449
84450
84451
84452
84453
84454
84455
84456
84457
84458
84459
84460
84461
84462
84463
  }else{
    return &p->aOp[addr];
  }
}

/* Return the most recently added opcode
*/
SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetLastOp(Vdbe *p){
  return sqlite3VdbeGetOp(p, p->nOp - 1);
}

#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
/*
** Return an integer value for one of the parameters to the opcode pOp
** determined by character c.
85680
85681
85682
85683
85684
85685
85686


85687
85688
85689
85690
85691
85692
85693
          p->nChange = 0;
        }else{
          db->nDeferredCons = 0;
          db->nDeferredImmCons = 0;
          db->flags &= ~(u64)SQLITE_DeferFKs;
          sqlite3CommitInternalChanges(db);
        }


      }else{
        sqlite3RollbackAll(db, SQLITE_OK);
        p->nChange = 0;
      }
      db->nStatement = 0;
    }else if( eStatementOp==0 ){
      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){







>
>







86153
86154
86155
86156
86157
86158
86159
86160
86161
86162
86163
86164
86165
86166
86167
86168
          p->nChange = 0;
        }else{
          db->nDeferredCons = 0;
          db->nDeferredImmCons = 0;
          db->flags &= ~(u64)SQLITE_DeferFKs;
          sqlite3CommitInternalChanges(db);
        }
      }else if( p->rc==SQLITE_SCHEMA && db->nVdbeActive>1 ){
        p->nChange = 0;
      }else{
        sqlite3RollbackAll(db, SQLITE_OK);
        p->nChange = 0;
      }
      db->nStatement = 0;
    }else if( eStatementOp==0 ){
      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
85998
85999
86000
86001
86002
86003
86004
86005
86006
86007
86008
86009
86010
86011
86012
86013
86014
    if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
  }
  vdbeFreeOpArray(db, p->aOp, p->nOp);
  if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
#ifdef SQLITE_ENABLE_NORMALIZE
  sqlite3DbFree(db, p->zNormSql);
  {
    DblquoteStr *pThis, *pNext;
    for(pThis=p->pDblStr; pThis; pThis=pNext){
      pNext = pThis->pNextStr;
      sqlite3DbFree(db, pThis);
    }
  }
#endif
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  {
    int i;







|
|
|







86473
86474
86475
86476
86477
86478
86479
86480
86481
86482
86483
86484
86485
86486
86487
86488
86489
    if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
  }
  vdbeFreeOpArray(db, p->aOp, p->nOp);
  if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
#ifdef SQLITE_ENABLE_NORMALIZE
  sqlite3DbFree(db, p->zNormSql);
  {
    DblquoteStr *pThis, *pNxt;
    for(pThis=p->pDblStr; pThis; pThis=pNxt){
      pNxt = pThis->pNextStr;
      sqlite3DbFree(db, pThis);
    }
  }
#endif
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  {
    int i;
87627
87628
87629
87630
87631
87632
87633














87634
87635
87636
87637
87638
87639
87640
    sqlite3_result_error(pCtx, zMsg, -1);
    sqlite3_free(zMsg);
    return 0;
  }
  return 1;
}















#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
** in memory obtained from sqlite3DbMalloc).
*/
SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){







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







88102
88103
88104
88105
88106
88107
88108
88109
88110
88111
88112
88113
88114
88115
88116
88117
88118
88119
88120
88121
88122
88123
88124
88125
88126
88127
88128
88129
    sqlite3_result_error(pCtx, zMsg, -1);
    sqlite3_free(zMsg);
    return 0;
  }
  return 1;
}

#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
/*
** This Walker callback is used to help verify that calls to
** sqlite3BtreeCursorHint() with opcode BTREE_HINT_RANGE have
** byte-code register values correctly initialized.
*/
SQLITE_PRIVATE int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr){
  if( pExpr->op==TK_REGISTER ){
    assert( (pWalker->u.aMem[pExpr->iTable].flags & MEM_Undefined)==0 );
  }
  return WRC_Continue;
}
#endif /* SQLITE_ENABLE_CURSOR_HINTS && SQLITE_DEBUG */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
** in memory obtained from sqlite3DbMalloc).
*/
SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
87689
87690
87691
87692
87693
87694
87695










87696
87697
87698
87699
87700
87701
87702
87703
87704
87705
87706
87707
87708
87709
87710
87711
87712
87713
87714
87715
87716
87717
87718
87719
87720
  int iBlobWrite
){
  sqlite3 *db = v->db;
  i64 iKey2;
  PreUpdate preupdate;
  const char *zTbl = pTab->zName;
  static const u8 fakeSortOrder = 0;











  assert( db->pPreUpdate==0 );
  memset(&preupdate, 0, sizeof(PreUpdate));
  if( HasRowid(pTab)==0 ){
    iKey1 = iKey2 = 0;
    preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  }else{
    if( op==SQLITE_UPDATE ){
      iKey2 = v->aMem[iReg].u.i;
    }else{
      iKey2 = iKey1;
    }
  }

  assert( pCsr!=0 );
  assert( pCsr->eCurType==CURTYPE_BTREE );
  assert( pCsr->nField==pTab->nCol
       || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  );

  preupdate.v = v;
  preupdate.pCsr = pCsr;
  preupdate.op = op;
  preupdate.iNewReg = iReg;
  preupdate.keyinfo.db = db;







>
>
>
>
>
>
>
>
>
>
















|
|







88178
88179
88180
88181
88182
88183
88184
88185
88186
88187
88188
88189
88190
88191
88192
88193
88194
88195
88196
88197
88198
88199
88200
88201
88202
88203
88204
88205
88206
88207
88208
88209
88210
88211
88212
88213
88214
88215
88216
88217
88218
88219
  int iBlobWrite
){
  sqlite3 *db = v->db;
  i64 iKey2;
  PreUpdate preupdate;
  const char *zTbl = pTab->zName;
  static const u8 fakeSortOrder = 0;
#ifdef SQLITE_DEBUG
  int nRealCol;
  if( pTab->tabFlags & TF_WithoutRowid ){
    nRealCol = sqlite3PrimaryKeyIndex(pTab)->nColumn;
  }else if( pTab->tabFlags & TF_HasVirtual ){
    nRealCol = pTab->nNVCol;
  }else{
    nRealCol = pTab->nCol;
  }
#endif

  assert( db->pPreUpdate==0 );
  memset(&preupdate, 0, sizeof(PreUpdate));
  if( HasRowid(pTab)==0 ){
    iKey1 = iKey2 = 0;
    preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  }else{
    if( op==SQLITE_UPDATE ){
      iKey2 = v->aMem[iReg].u.i;
    }else{
      iKey2 = iKey1;
    }
  }

  assert( pCsr!=0 );
  assert( pCsr->eCurType==CURTYPE_BTREE );
  assert( pCsr->nField==nRealCol
       || (pCsr->nField==nRealCol+1 && op==SQLITE_DELETE && iReg==-1)
  );

  preupdate.v = v;
  preupdate.pCsr = pCsr;
  preupdate.op = op;
  preupdate.iNewReg = iReg;
  preupdate.keyinfo.db = db;
88013
88014
88015
88016
88017
88018
88019
88020
88021
88022
88023
88024
88025
88026
88027
     SQLITE_NULL,     /* 0x1b (not possible) */
     SQLITE_INTEGER,  /* 0x1c (not possible) */
     SQLITE_NULL,     /* 0x1d (not possible) */
     SQLITE_INTEGER,  /* 0x1e (not possible) */
     SQLITE_NULL,     /* 0x1f (not possible) */
     SQLITE_FLOAT,    /* 0x20 INTREAL */
     SQLITE_NULL,     /* 0x21 (not possible) */
     SQLITE_TEXT,     /* 0x22 INTREAL + TEXT */
     SQLITE_NULL,     /* 0x23 (not possible) */
     SQLITE_FLOAT,    /* 0x24 (not possible) */
     SQLITE_NULL,     /* 0x25 (not possible) */
     SQLITE_FLOAT,    /* 0x26 (not possible) */
     SQLITE_NULL,     /* 0x27 (not possible) */
     SQLITE_FLOAT,    /* 0x28 (not possible) */
     SQLITE_NULL,     /* 0x29 (not possible) */







|







88512
88513
88514
88515
88516
88517
88518
88519
88520
88521
88522
88523
88524
88525
88526
     SQLITE_NULL,     /* 0x1b (not possible) */
     SQLITE_INTEGER,  /* 0x1c (not possible) */
     SQLITE_NULL,     /* 0x1d (not possible) */
     SQLITE_INTEGER,  /* 0x1e (not possible) */
     SQLITE_NULL,     /* 0x1f (not possible) */
     SQLITE_FLOAT,    /* 0x20 INTREAL */
     SQLITE_NULL,     /* 0x21 (not possible) */
     SQLITE_FLOAT,    /* 0x22 INTREAL + TEXT */
     SQLITE_NULL,     /* 0x23 (not possible) */
     SQLITE_FLOAT,    /* 0x24 (not possible) */
     SQLITE_NULL,     /* 0x25 (not possible) */
     SQLITE_FLOAT,    /* 0x26 (not possible) */
     SQLITE_NULL,     /* 0x27 (not possible) */
     SQLITE_FLOAT,    /* 0x28 (not possible) */
     SQLITE_NULL,     /* 0x29 (not possible) */
89079
89080
89081
89082
89083
89084
89085

89086
89087
89088
89089
89090
89091
89092
89093
89094
89095
89096
89097
89098
89099

89100
89101
89102
89103
89104
89105
89106
89107
#endif
  ret = 0;
  p = (Vdbe *)pStmt;
  db = p->db;
  assert( db!=0 );
  n = sqlite3_column_count(pStmt);
  if( N<n && N>=0 ){

    N += useType*n;
    sqlite3_mutex_enter(db->mutex);
    assert( db->mallocFailed==0 );
#ifndef SQLITE_OMIT_UTF16
    if( useUtf16 ){
      ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
    }else
#endif
    {
      ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
    }
    /* A malloc may have failed inside of the _text() call. If this
    ** is the case, clear the mallocFailed flag and return NULL.
    */

    if( db->mallocFailed ){
      sqlite3OomClear(db);
      ret = 0;
    }
    sqlite3_mutex_leave(db->mutex);
  }
  return ret;
}







>


<











>
|







89578
89579
89580
89581
89582
89583
89584
89585
89586
89587

89588
89589
89590
89591
89592
89593
89594
89595
89596
89597
89598
89599
89600
89601
89602
89603
89604
89605
89606
89607
#endif
  ret = 0;
  p = (Vdbe *)pStmt;
  db = p->db;
  assert( db!=0 );
  n = sqlite3_column_count(pStmt);
  if( N<n && N>=0 ){
    u8 prior_mallocFailed = db->mallocFailed;
    N += useType*n;
    sqlite3_mutex_enter(db->mutex);

#ifndef SQLITE_OMIT_UTF16
    if( useUtf16 ){
      ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
    }else
#endif
    {
      ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
    }
    /* A malloc may have failed inside of the _text() call. If this
    ** is the case, clear the mallocFailed flag and return NULL.
    */
    assert( db->mallocFailed==0 || db->mallocFailed==1 );
    if( db->mallocFailed > prior_mallocFailed ){
      sqlite3OomClear(db);
      ret = 0;
    }
    sqlite3_mutex_leave(db->mutex);
  }
  return ret;
}
89880
89881
89882
89883
89884
89885
89886


89887
89888







89889
89890
89891
89892
89893
89894
89895
89896
89897
89898
89899
89900
89901
89902
  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
  int iScan,                      /* Index of loop to report on */
  int iScanStatusOp,              /* Which metric to return */
  int flags,
  void *pOut                      /* OUT: Write the answer here */
){
  Vdbe *p = (Vdbe*)pStmt;


  ScanStatus *pScan;
  int idx;








  if( iScan<0 ){
    int ii;
    if( iScanStatusOp==SQLITE_SCANSTAT_NCYCLE ){
      i64 res = 0;
      for(ii=0; ii<p->nOp; ii++){
        res += p->aOp[ii].nCycle;
      }
      *(i64*)pOut = res;
      return 0;
    }
    return 1;
  }
  if( flags & SQLITE_SCANSTAT_COMPLEX ){







>
>
|

>
>
>
>
>
>
>





|
|







90380
90381
90382
90383
90384
90385
90386
90387
90388
90389
90390
90391
90392
90393
90394
90395
90396
90397
90398
90399
90400
90401
90402
90403
90404
90405
90406
90407
90408
90409
90410
90411
  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
  int iScan,                      /* Index of loop to report on */
  int iScanStatusOp,              /* Which metric to return */
  int flags,
  void *pOut                      /* OUT: Write the answer here */
){
  Vdbe *p = (Vdbe*)pStmt;
  VdbeOp *aOp = p->aOp;
  int nOp = p->nOp;
  ScanStatus *pScan = 0;
  int idx;

  if( p->pFrame ){
    VdbeFrame *pFrame;
    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
    aOp = pFrame->aOp;
    nOp = pFrame->nOp;
  }

  if( iScan<0 ){
    int ii;
    if( iScanStatusOp==SQLITE_SCANSTAT_NCYCLE ){
      i64 res = 0;
      for(ii=0; ii<nOp; ii++){
        res += aOp[ii].nCycle;
      }
      *(i64*)pOut = res;
      return 0;
    }
    return 1;
  }
  if( flags & SQLITE_SCANSTAT_COMPLEX ){
89914
89915
89916
89917
89918
89919
89920
89921
89922
89923
89924
89925
89926
89927
89928
89929
89930
89931
89932
89933
89934
89935
89936
    }
  }
  if( idx>=p->nScan ) return 1;

  switch( iScanStatusOp ){
    case SQLITE_SCANSTAT_NLOOP: {
      if( pScan->addrLoop>0 ){
        *(sqlite3_int64*)pOut = p->aOp[pScan->addrLoop].nExec;
      }else{
        *(sqlite3_int64*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_NVISIT: {
      if( pScan->addrVisit>0 ){
        *(sqlite3_int64*)pOut = p->aOp[pScan->addrVisit].nExec;
      }else{
        *(sqlite3_int64*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_EST: {
      double r = 1.0;







|







|







90423
90424
90425
90426
90427
90428
90429
90430
90431
90432
90433
90434
90435
90436
90437
90438
90439
90440
90441
90442
90443
90444
90445
    }
  }
  if( idx>=p->nScan ) return 1;

  switch( iScanStatusOp ){
    case SQLITE_SCANSTAT_NLOOP: {
      if( pScan->addrLoop>0 ){
        *(sqlite3_int64*)pOut = aOp[pScan->addrLoop].nExec;
      }else{
        *(sqlite3_int64*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_NVISIT: {
      if( pScan->addrVisit>0 ){
        *(sqlite3_int64*)pOut = aOp[pScan->addrVisit].nExec;
      }else{
        *(sqlite3_int64*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_EST: {
      double r = 1.0;
89944
89945
89946
89947
89948
89949
89950
89951
89952
89953
89954
89955
89956
89957
89958
89959
89960
89961
89962
89963
89964
89965
89966
89967
89968
89969
89970
89971
89972
89973
89974
89975
89976
89977
89978
89979
89980
89981
89982
89983
89984
89985
89986
89987
89988
89989
89990
89991
89992
89993
89994
89995
89996
89997
89998
89999
90000
90001
90002
90003
    }
    case SQLITE_SCANSTAT_NAME: {
      *(const char**)pOut = pScan->zName;
      break;
    }
    case SQLITE_SCANSTAT_EXPLAIN: {
      if( pScan->addrExplain ){
        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
      }else{
        *(const char**)pOut = 0;
      }
      break;
    }
    case SQLITE_SCANSTAT_SELECTID: {
      if( pScan->addrExplain ){
        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
      }else{
        *(int*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_PARENTID: {
      if( pScan->addrExplain ){
        *(int*)pOut = p->aOp[ pScan->addrExplain ].p2;
      }else{
        *(int*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_NCYCLE: {
      i64 res = 0;
      if( pScan->aAddrRange[0]==0 ){
        res = -1;
      }else{
        int ii;
        for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
          int iIns = pScan->aAddrRange[ii];
          int iEnd = pScan->aAddrRange[ii+1];
          if( iIns==0 ) break;
          if( iIns>0 ){
            while( iIns<=iEnd ){
              res += p->aOp[iIns].nCycle;
              iIns++;
            }
          }else{
            int iOp;
            for(iOp=0; iOp<p->nOp; iOp++){
              Op *pOp = &p->aOp[iOp];
              if( pOp->p1!=iEnd ) continue;
              if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
                continue;
              }
              res += p->aOp[iOp].nCycle;
            }
          }
        }
      }
      *(i64*)pOut = res;
      break;
    }







|







|







|

















|




|
|




|







90453
90454
90455
90456
90457
90458
90459
90460
90461
90462
90463
90464
90465
90466
90467
90468
90469
90470
90471
90472
90473
90474
90475
90476
90477
90478
90479
90480
90481
90482
90483
90484
90485
90486
90487
90488
90489
90490
90491
90492
90493
90494
90495
90496
90497
90498
90499
90500
90501
90502
90503
90504
90505
90506
90507
90508
90509
90510
90511
90512
    }
    case SQLITE_SCANSTAT_NAME: {
      *(const char**)pOut = pScan->zName;
      break;
    }
    case SQLITE_SCANSTAT_EXPLAIN: {
      if( pScan->addrExplain ){
        *(const char**)pOut = aOp[ pScan->addrExplain ].p4.z;
      }else{
        *(const char**)pOut = 0;
      }
      break;
    }
    case SQLITE_SCANSTAT_SELECTID: {
      if( pScan->addrExplain ){
        *(int*)pOut = aOp[ pScan->addrExplain ].p1;
      }else{
        *(int*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_PARENTID: {
      if( pScan->addrExplain ){
        *(int*)pOut = aOp[ pScan->addrExplain ].p2;
      }else{
        *(int*)pOut = -1;
      }
      break;
    }
    case SQLITE_SCANSTAT_NCYCLE: {
      i64 res = 0;
      if( pScan->aAddrRange[0]==0 ){
        res = -1;
      }else{
        int ii;
        for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
          int iIns = pScan->aAddrRange[ii];
          int iEnd = pScan->aAddrRange[ii+1];
          if( iIns==0 ) break;
          if( iIns>0 ){
            while( iIns<=iEnd ){
              res += aOp[iIns].nCycle;
              iIns++;
            }
          }else{
            int iOp;
            for(iOp=0; iOp<nOp; iOp++){
              Op *pOp = &aOp[iOp];
              if( pOp->p1!=iEnd ) continue;
              if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
                continue;
              }
              res += aOp[iOp].nCycle;
            }
          }
        }
      }
      *(i64*)pOut = res;
      break;
    }
90912
90913
90914
90915
90916
90917
90918


90919

90920
90921
90922
90923
90924
90925
90926
  for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
    const Mem *p = &aMem[i];
    if( p->flags & (MEM_Int|MEM_IntReal) ){
      h += p->u.i;
    }else if( p->flags & MEM_Real ){
      h += sqlite3VdbeIntValue(p);
    }else if( p->flags & (MEM_Str|MEM_Blob) ){


      /* no-op */

    }
  }
  return h;
}

/*
** Return the symbolic name for the data type of a pMem







>
>
|
>







91421
91422
91423
91424
91425
91426
91427
91428
91429
91430
91431
91432
91433
91434
91435
91436
91437
91438
  for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
    const Mem *p = &aMem[i];
    if( p->flags & (MEM_Int|MEM_IntReal) ){
      h += p->u.i;
    }else if( p->flags & MEM_Real ){
      h += sqlite3VdbeIntValue(p);
    }else if( p->flags & (MEM_Str|MEM_Blob) ){
      /* All strings have the same hash and all blobs have the same hash,
      ** though, at least, those hashes are different from each other and
      ** from NULL. */
      h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
    }
  }
  return h;
}

/*
** Return the symbolic name for the data type of a pMem
90962
90963
90964
90965
90966
90967
90968

90969
90970
90971
90972
90973
90974
90975
  Mem *aMem = p->aMem;       /* Copy of p->aMem */
  Mem *pIn1 = 0;             /* 1st input operand */
  Mem *pIn2 = 0;             /* 2nd input operand */
  Mem *pIn3 = 0;             /* 3rd input operand */
  Mem *pOut = 0;             /* Output operand */
#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
  u64 *pnCycle = 0;

#endif
  /*** INSERT STACK UNION HERE ***/

  assert( p->eVdbeState==VDBE_RUN_STATE );  /* sqlite3_step() verifies this */
  if( DbMaskNonZero(p->lockMask) ){
    sqlite3VdbeEnter(p);
  }







>







91474
91475
91476
91477
91478
91479
91480
91481
91482
91483
91484
91485
91486
91487
91488
  Mem *aMem = p->aMem;       /* Copy of p->aMem */
  Mem *pIn1 = 0;             /* 1st input operand */
  Mem *pIn2 = 0;             /* 2nd input operand */
  Mem *pIn3 = 0;             /* 3rd input operand */
  Mem *pOut = 0;             /* Output operand */
#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
  u64 *pnCycle = 0;
  int bStmtScanStatus = IS_STMT_SCANSTATUS(db)!=0;
#endif
  /*** INSERT STACK UNION HERE ***/

  assert( p->eVdbeState==VDBE_RUN_STATE );  /* sqlite3_step() verifies this */
  if( DbMaskNonZero(p->lockMask) ){
    sqlite3VdbeEnter(p);
  }
91026
91027
91028
91029
91030
91031
91032

91033
91034
91035
91036
91037

91038


91039

91040
91041
91042
91043
91044
91045
91046
  for(pOp=&aOp[p->pc]; 1; pOp++){
    /* Errors are detected by individual opcodes, with an immediate
    ** jumps to abort_due_to_error. */
    assert( rc==SQLITE_OK );

    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
    nVmStep++;

#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
    pOp->nExec++;
    pnCycle = &pOp->nCycle;
# ifdef VDBE_PROFILE
    if( sqlite3NProfileCnt==0 )

# endif


      *pnCycle -= sqlite3Hwtime();

#endif

    /* Only allow tracing if SQLITE_DEBUG is defined.
    */
#ifdef SQLITE_DEBUG
    if( db->flags & SQLITE_VdbeTrace ){
      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);







>
|


<
|
>
|
>
>

>







91539
91540
91541
91542
91543
91544
91545
91546
91547
91548
91549

91550
91551
91552
91553
91554
91555
91556
91557
91558
91559
91560
91561
91562
91563
  for(pOp=&aOp[p->pc]; 1; pOp++){
    /* Errors are detected by individual opcodes, with an immediate
    ** jumps to abort_due_to_error. */
    assert( rc==SQLITE_OK );

    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
    nVmStep++;

#if defined(VDBE_PROFILE)
    pOp->nExec++;
    pnCycle = &pOp->nCycle;

    if( sqlite3NProfileCnt==0 ) *pnCycle -= sqlite3Hwtime();
#elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
    if( bStmtScanStatus ){
      pOp->nExec++;
      pnCycle = &pOp->nCycle;
      *pnCycle -= sqlite3Hwtime();
    }
#endif

    /* Only allow tracing if SQLITE_DEBUG is defined.
    */
#ifdef SQLITE_DEBUG
    if( db->flags & SQLITE_VdbeTrace ){
      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
92620
92621
92622
92623
92624
92625
92626
92627
92628
92629
92630
92631
92632
92633
92634
  assert( pOp[1].opcode==OP_Jump );
  break;
}

/* Opcode: Jump P1 P2 P3 * *
**
** Jump to the instruction at address P1, P2, or P3 depending on whether
** in the most recent OP_Compare instruction the P1 vector was less than
** equal to, or greater than the P2 vector, respectively.
**
** This opcode must immediately follow an OP_Compare opcode.
*/
case OP_Jump: {             /* jump */
  assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
  assert( iCompareIsInit );







|







93137
93138
93139
93140
93141
93142
93143
93144
93145
93146
93147
93148
93149
93150
93151
  assert( pOp[1].opcode==OP_Jump );
  break;
}

/* Opcode: Jump P1 P2 P3 * *
**
** Jump to the instruction at address P1, P2, or P3 depending on whether
** in the most recent OP_Compare instruction the P1 vector was less than,
** equal to, or greater than the P2 vector, respectively.
**
** This opcode must immediately follow an OP_Compare opcode.
*/
case OP_Jump: {             /* jump */
  assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
  assert( iCompareIsInit );
92847
92848
92849
92850
92851
92852
92853






92854
92855
92856
92857
92858
92859
92860
** If P1 is -1, then P3 is a register number and the datatype is taken
** from the value in that register.
**
** P5 is a bitmask of data types.  SQLITE_INTEGER is the least significant
** (0x01) bit. SQLITE_FLOAT is the 0x02 bit. SQLITE_TEXT is 0x04.
** SQLITE_BLOB is 0x08.  SQLITE_NULL is 0x10.
**






** Take the jump to address P2 if and only if the datatype of the
** value determined by P1 and P3 corresponds to one of the bits in the
** P5 bitmask.
**
*/
case OP_IsType: {        /* jump */
  VdbeCursor *pC;







>
>
>
>
>
>







93364
93365
93366
93367
93368
93369
93370
93371
93372
93373
93374
93375
93376
93377
93378
93379
93380
93381
93382
93383
** If P1 is -1, then P3 is a register number and the datatype is taken
** from the value in that register.
**
** P5 is a bitmask of data types.  SQLITE_INTEGER is the least significant
** (0x01) bit. SQLITE_FLOAT is the 0x02 bit. SQLITE_TEXT is 0x04.
** SQLITE_BLOB is 0x08.  SQLITE_NULL is 0x10.
**
** WARNING: This opcode does not reliably distinguish between NULL and REAL
** when P1>=0.  If the database contains a NaN value, this opcode will think
** that the datatype is REAL when it should be NULL.  When P1<0 and the value
** is already stored in register P3, then this opcode does reliably
** distinguish between NULL and REAL.  The problem only arises then P1>=0.
**
** Take the jump to address P2 if and only if the datatype of the
** value determined by P1 and P3 corresponds to one of the bits in the
** P5 bitmask.
**
*/
case OP_IsType: {        /* jump */
  VdbeCursor *pC;
92960
92961
92962
92963
92964
92965
92966
92967
92968
92969
92970
92971
92972
92973
92974
**
** If P1 is not an open cursor, then this opcode is a no-op.
*/
case OP_IfNullRow: {         /* jump */
  VdbeCursor *pC;
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  if( ALWAYS(pC) && pC->nullRow ){
    sqlite3VdbeMemSetNull(aMem + pOp->p3);
    goto jump_to_p2;
  }
  break;
}

#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC







|







93483
93484
93485
93486
93487
93488
93489
93490
93491
93492
93493
93494
93495
93496
93497
**
** If P1 is not an open cursor, then this opcode is a no-op.
*/
case OP_IfNullRow: {         /* jump */
  VdbeCursor *pC;
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  pC = p->apCsr[pOp->p1];
  if( pC && pC->nullRow ){
    sqlite3VdbeMemSetNull(aMem + pOp->p3);
    goto jump_to_p2;
  }
  break;
}

#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
93455
93456
93457
93458
93459
93460
93461
93462
93463
93464
93465
93466
93467
93468
93469
      testcase( pIn1->u.i==-140737488355329LL );
      if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
        pIn1->flags |= MEM_IntReal;
        pIn1->flags &= ~MEM_Int;
      }else{
        pIn1->u.r = (double)pIn1->u.i;
        pIn1->flags |= MEM_Real;
        pIn1->flags &= ~MEM_Int;
      }
    }
    REGISTER_TRACE((int)(pIn1-aMem), pIn1);
    zAffinity++;
    if( zAffinity[0]==0 ) break;
    pIn1++;
  }







|







93978
93979
93980
93981
93982
93983
93984
93985
93986
93987
93988
93989
93990
93991
93992
      testcase( pIn1->u.i==-140737488355329LL );
      if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
        pIn1->flags |= MEM_IntReal;
        pIn1->flags &= ~MEM_Int;
      }else{
        pIn1->u.r = (double)pIn1->u.i;
        pIn1->flags |= MEM_Real;
        pIn1->flags &= ~(MEM_Int|MEM_Str);
      }
    }
    REGISTER_TRACE((int)(pIn1-aMem), pIn1);
    zAffinity++;
    if( zAffinity[0]==0 ) break;
    pIn1++;
  }
95194
95195
95196
95197
95198
95199
95200

95201
95202
95203
95204
95205
95206
95207
        printf("... fall through after %d steps\n", pOp->p1);
      }
#endif
      VdbeBranchTaken(0,3);
      break;
    }
    nStep--;

    rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
    if( rc ){
      if( rc==SQLITE_DONE ){
        rc = SQLITE_OK;
        goto seekscan_search_fail;
      }else{
        goto abort_due_to_error;







>







95717
95718
95719
95720
95721
95722
95723
95724
95725
95726
95727
95728
95729
95730
95731
        printf("... fall through after %d steps\n", pOp->p1);
      }
#endif
      VdbeBranchTaken(0,3);
      break;
    }
    nStep--;
    pC->cacheStatus = CACHE_STALE;
    rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
    if( rc ){
      if( rc==SQLITE_DONE ){
        rc = SQLITE_OK;
        goto seekscan_search_fail;
      }else{
        goto abort_due_to_error;
97846
97847
97848
97849
97850
97851
97852

97853
97854
97855
97856
97857
97858
97859

  if( rc ){
    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
    goto abort_due_to_error;
  }
  sqlite3VdbeChangeEncoding(pMem, encoding);
  UPDATE_MAX_BLOBSIZE(pMem);

  break;
}

#ifndef SQLITE_OMIT_WAL
/* Opcode: Checkpoint P1 P2 P3 * *
**
** Checkpoint database P1. This is a no-op if P1 is not currently in







>







98370
98371
98372
98373
98374
98375
98376
98377
98378
98379
98380
98381
98382
98383
98384

  if( rc ){
    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
    goto abort_due_to_error;
  }
  sqlite3VdbeChangeEncoding(pMem, encoding);
  UPDATE_MAX_BLOBSIZE(pMem);
  REGISTER_TRACE((int)(pMem-aMem), pMem);
  break;
}

#ifndef SQLITE_OMIT_WAL
/* Opcode: Checkpoint P1 P2 P3 * *
**
** Checkpoint database P1. This is a no-op if P1 is not currently in
98984
98985
98986
98987
98988
98989
98990

98991
98992

98993
98994
98995
98996
98997
98998
98999
*****************************************************************************/
    }

#if defined(VDBE_PROFILE)
    *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
    pnCycle = 0;
#elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)

    *pnCycle += sqlite3Hwtime();
    pnCycle = 0;

#endif

    /* The following code adds nothing to the actual functionality
    ** of the program.  It is only here for testing and debugging.
    ** On the other hand, it does burn CPU cycles every time through
    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
    */







>
|
|
>







99509
99510
99511
99512
99513
99514
99515
99516
99517
99518
99519
99520
99521
99522
99523
99524
99525
99526
*****************************************************************************/
    }

#if defined(VDBE_PROFILE)
    *pnCycle += sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
    pnCycle = 0;
#elif defined(SQLITE_ENABLE_STMT_SCANSTATUS)
    if( pnCycle ){
      *pnCycle += sqlite3Hwtime();
      pnCycle = 0;
    }
#endif

    /* The following code adds nothing to the actual functionality
    ** of the program.  It is only here for testing and debugging.
    ** On the other hand, it does burn CPU cycles every time through
    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
    */
99464
99465
99466
99467
99468
99469
99470
99471
99472
99473
99474
99475
99476
99477
99478
blob_open_out:
  if( rc==SQLITE_OK && db->mallocFailed==0 ){
    *ppBlob = (sqlite3_blob *)pBlob;
  }else{
    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
    sqlite3DbFree(db, pBlob);
  }
  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  sqlite3DbFree(db, zErr);
  sqlite3ParseObjectReset(&sParse);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}








|







99991
99992
99993
99994
99995
99996
99997
99998
99999
100000
100001
100002
100003
100004
100005
blob_open_out:
  if( rc==SQLITE_OK && db->mallocFailed==0 ){
    *ppBlob = (sqlite3_blob *)pBlob;
  }else{
    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
    sqlite3DbFree(db, pBlob);
  }
  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : (char*)0), zErr);
  sqlite3DbFree(db, zErr);
  sqlite3ParseObjectReset(&sParse);
  rc = sqlite3ApiExit(db, rc);
  sqlite3_mutex_leave(db->mutex);
  return rc;
}

99623
99624
99625
99626
99627
99628
99629
99630
99631
99632
99633
99634
99635
99636
99637
    */
    rc = SQLITE_ABORT;
  }else{
    char *zErr;
    ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
    rc = blobSeekToRow(p, iRow, &zErr);
    if( rc!=SQLITE_OK ){
      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
      sqlite3DbFree(db, zErr);
    }
    assert( rc!=SQLITE_SCHEMA );
  }

  rc = sqlite3ApiExit(db, rc);
  assert( rc==SQLITE_OK || p->pStmt==0 );







|







100150
100151
100152
100153
100154
100155
100156
100157
100158
100159
100160
100161
100162
100163
100164
    */
    rc = SQLITE_ABORT;
  }else{
    char *zErr;
    ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
    rc = blobSeekToRow(p, iRow, &zErr);
    if( rc!=SQLITE_OK ){
      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : (char*)0), zErr);
      sqlite3DbFree(db, zErr);
    }
    assert( rc!=SQLITE_SCHEMA );
  }

  rc = sqlite3ApiExit(db, rc);
  assert( rc==SQLITE_OK || p->pStmt==0 );
104011
104012
104013
104014
104015
104016
104017

104018
104019
104020
104021
104022
104023
104024
104025
      pTab = 0;
#ifndef SQLITE_OMIT_TRIGGER
      if( pParse->pTriggerTab!=0 ){
        int op = pParse->eTriggerOp;
        assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
        if( pParse->bReturning ){
          if( (pNC->ncFlags & NC_UBaseReg)!=0

           && (zTab==0 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0)
          ){
            pExpr->iTable = op!=TK_DELETE;
            pTab = pParse->pTriggerTab;
          }
        }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
          pExpr->iTable = 1;
          pTab = pParse->pTriggerTab;







>
|







104538
104539
104540
104541
104542
104543
104544
104545
104546
104547
104548
104549
104550
104551
104552
104553
      pTab = 0;
#ifndef SQLITE_OMIT_TRIGGER
      if( pParse->pTriggerTab!=0 ){
        int op = pParse->eTriggerOp;
        assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
        if( pParse->bReturning ){
          if( (pNC->ncFlags & NC_UBaseReg)!=0
           && ALWAYS(zTab==0
                     || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0)
          ){
            pExpr->iTable = op!=TK_DELETE;
            pTab = pParse->pTriggerTab;
          }
        }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
          pExpr->iTable = 1;
          pTab = pParse->pTriggerTab;
104796
104797
104798
104799
104800
104801
104802
104803
104804

104805
104806
104807
104808
104809
104810
104811
          notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
        }else{
          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
        }
        assert( pNC->nRef>=nRef );
        if( nRef!=pNC->nRef ){
          ExprSetProperty(pExpr, EP_VarSelect);
          pNC->ncFlags |= NC_VarSelect;
        }

      }
      break;
    }
    case TK_VARIABLE: {
      testcase( pNC->ncFlags & NC_IsCheck );
      testcase( pNC->ncFlags & NC_PartIdx );
      testcase( pNC->ncFlags & NC_IdxExpr );







<

>







105324
105325
105326
105327
105328
105329
105330

105331
105332
105333
105334
105335
105336
105337
105338
105339
          notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
        }else{
          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
        }
        assert( pNC->nRef>=nRef );
        if( nRef!=pNC->nRef ){
          ExprSetProperty(pExpr, EP_VarSelect);

        }
        pNC->ncFlags |= NC_Subquery;
      }
      break;
    }
    case TK_VARIABLE: {
      testcase( pNC->ncFlags & NC_IsCheck );
      testcase( pNC->ncFlags & NC_PartIdx );
      testcase( pNC->ncFlags & NC_IdxExpr );
105985
105986
105987
105988
105989
105990
105991
105992
105993
105994
105995
105996
105997
105998
105999
106000
106001
106002
106003
    }
    if( p->flags & EP_Collate ){
      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
        p = p->pLeft;
      }else{
        Expr *pNext  = p->pRight;
        /* The Expr.x union is never used at the same time as Expr.pRight */
        assert( ExprUseXList(p) );
        assert( p->x.pList==0 || p->pRight==0 );
        if( p->x.pList!=0 && !db->mallocFailed ){
          int i;
          for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
              pNext = p->x.pList->a[i].pExpr;
              break;
            }
          }
        }
        p = pNext;







<
|
|

|







106513
106514
106515
106516
106517
106518
106519

106520
106521
106522
106523
106524
106525
106526
106527
106528
106529
106530
    }
    if( p->flags & EP_Collate ){
      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
        p = p->pLeft;
      }else{
        Expr *pNext  = p->pRight;
        /* The Expr.x union is never used at the same time as Expr.pRight */

        assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
        if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
          int i;
          for(i=0; i<p->x.pList->nExpr; i++){
            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
              pNext = p->x.pList->a[i].pExpr;
              break;
            }
          }
        }
        p = pNext;
106821
106822
106823
106824
106825
106826
106827
106828
106829
106830
106831
106832
106833
106834
106835
106836
106837
106838


106839
106840
106841
106842
106843
106844
106845

106846
106847
106848
106849
106850
106851
106852
  return pRet;
}

/*
** Join two expressions using an AND operator.  If either expression is
** NULL, then just return the other expression.
**
** If one side or the other of the AND is known to be false, then instead
** of returning an AND expression, just return a constant expression with
** a value of false.
*/
SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
  sqlite3 *db = pParse->db;
  if( pLeft==0  ){
    return pRight;
  }else if( pRight==0 ){
    return pLeft;
  }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))


         && !IN_RENAME_OBJECT
  ){
    sqlite3ExprDeferredDelete(pParse, pLeft);
    sqlite3ExprDeferredDelete(pParse, pRight);
    return sqlite3Expr(db, TK_INTEGER, "0");
  }else{
    return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);

  }
}

/*
** Construct a new expression node for a function with multiple
** arguments.
*/







|
|
|







|
>
>
|
|
|
|
|
|
|
>







107348
107349
107350
107351
107352
107353
107354
107355
107356
107357
107358
107359
107360
107361
107362
107363
107364
107365
107366
107367
107368
107369
107370
107371
107372
107373
107374
107375
107376
107377
107378
107379
107380
107381
107382
  return pRet;
}

/*
** Join two expressions using an AND operator.  If either expression is
** NULL, then just return the other expression.
**
** If one side or the other of the AND is known to be false, and neither side
** is part of an ON clause, then instead of returning an AND expression,
** just return a constant expression with a value of false.
*/
SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
  sqlite3 *db = pParse->db;
  if( pLeft==0  ){
    return pRight;
  }else if( pRight==0 ){
    return pLeft;
  }else{
    u32 f = pLeft->flags | pRight->flags;
    if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse
     && !IN_RENAME_OBJECT
    ){
      sqlite3ExprDeferredDelete(pParse, pLeft);
      sqlite3ExprDeferredDelete(pParse, pRight);
      return sqlite3Expr(db, TK_INTEGER, "0");
    }else{
      return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
    }
  }
}

/*
** Construct a new expression node for a function with multiple
** arguments.
*/
108083
108084
108085
108086
108087
108088
108089
108090





108091
108092
108093
108094
108095
108096
108097
108098
108099
108100
108101
108102
108103
108104
108105
108106
108107
108108
108109
108110













108111
108112





108113
108114
108115
108116
108117
108118
108119
108120













108121
108122
108123
108124
108125
108126
108127
** table other than iCur.
*/
SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  return exprIsConst(p, 3, iCur);
}

/*
** Check pExpr to see if it is an invariant constraint on data source pSrc.





** This is an optimization.  False negatives will perhaps cause slower
** queries, but false positives will yield incorrect answers.  So when in
** doubt, return 0.
**
** To be an invariant constraint, the following must be true:
**
**   (1)  pExpr cannot refer to any table other than pSrc->iCursor.
**
**   (2)  pExpr cannot use subqueries or non-deterministic functions.
**
**   (3)  pSrc cannot be part of the left operand for a RIGHT JOIN.
**        (Is there some way to relax this constraint?)
**
**   (4)  If pSrc is the right operand of a LEFT JOIN, then...
**         (4a)  pExpr must come from an ON clause..
           (4b)  and specifically the ON clause associated with the LEFT JOIN.
**
**   (5)  If pSrc is not the right operand of a LEFT JOIN or the left
**        operand of a RIGHT JOIN, then pExpr must be from the WHERE
**        clause, not an ON clause.













*/
SQLITE_PRIVATE int sqlite3ExprIsTableConstraint(Expr *pExpr, const SrcItem *pSrc){





  if( pSrc->fg.jointype & JT_LTORJ ){
    return 0;  /* rule (3) */
  }
  if( pSrc->fg.jointype & JT_LEFT ){
    if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0;   /* rule (4a) */
    if( pExpr->w.iJoin!=pSrc->iCursor ) return 0;         /* rule (4b) */
  }else{
    if( ExprHasProperty(pExpr, EP_OuterON) ) return 0;    /* rule (5) */













  }
  return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor); /* rules (1), (2) */
}


/*
** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().







|
>
>
>
>
>




|










|




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

|
>
>
>
>
>








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







108613
108614
108615
108616
108617
108618
108619
108620
108621
108622
108623
108624
108625
108626
108627
108628
108629
108630
108631
108632
108633
108634
108635
108636
108637
108638
108639
108640
108641
108642
108643
108644
108645
108646
108647
108648
108649
108650
108651
108652
108653
108654
108655
108656
108657
108658
108659
108660
108661
108662
108663
108664
108665
108666
108667
108668
108669
108670
108671
108672
108673
108674
108675
108676
108677
108678
108679
108680
108681
108682
108683
108684
108685
108686
108687
108688
108689
108690
108691
108692
108693
** table other than iCur.
*/
SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  return exprIsConst(p, 3, iCur);
}

/*
** Check pExpr to see if it is an constraint on the single data source
** pSrc = &pSrcList->a[iSrc].  In other words, check to see if pExpr
** constrains pSrc but does not depend on any other tables or data
** sources anywhere else in the query.  Return true (non-zero) if pExpr
** is a constraint on pSrc only.
**
** This is an optimization.  False negatives will perhaps cause slower
** queries, but false positives will yield incorrect answers.  So when in
** doubt, return 0.
**
** To be an single-source constraint, the following must be true:
**
**   (1)  pExpr cannot refer to any table other than pSrc->iCursor.
**
**   (2)  pExpr cannot use subqueries or non-deterministic functions.
**
**   (3)  pSrc cannot be part of the left operand for a RIGHT JOIN.
**        (Is there some way to relax this constraint?)
**
**   (4)  If pSrc is the right operand of a LEFT JOIN, then...
**         (4a)  pExpr must come from an ON clause..
**         (4b)  and specifically the ON clause associated with the LEFT JOIN.
**
**   (5)  If pSrc is not the right operand of a LEFT JOIN or the left
**        operand of a RIGHT JOIN, then pExpr must be from the WHERE
**        clause, not an ON clause.
**
**   (6) Either:
**
**       (6a) pExpr does not originate in an ON or USING clause, or
**
**       (6b) The ON or USING clause from which pExpr is derived is
**            not to the left of a RIGHT JOIN (or FULL JOIN).
**
**       Without this restriction, accepting pExpr as a single-table
**       constraint might move the the ON/USING filter expression
**       from the left side of a RIGHT JOIN over to the right side,
**       which leads to incorrect answers.  See also restriction (9)
**       on push-down.
*/
SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(
  Expr *pExpr,                 /* The constraint */
  const SrcList *pSrcList,     /* Complete FROM clause */
  int iSrc                     /* Which element of pSrcList to use */
){
  const SrcItem *pSrc = &pSrcList->a[iSrc];
  if( pSrc->fg.jointype & JT_LTORJ ){
    return 0;  /* rule (3) */
  }
  if( pSrc->fg.jointype & JT_LEFT ){
    if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0;   /* rule (4a) */
    if( pExpr->w.iJoin!=pSrc->iCursor ) return 0;         /* rule (4b) */
  }else{
    if( ExprHasProperty(pExpr, EP_OuterON) ) return 0;    /* rule (5) */
  }
  if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)  /* (6a) */
   && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0     /* Fast pre-test of (6b) */
  ){
    int jj;
    for(jj=0; jj<iSrc; jj++){
      if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
        if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
          return 0;  /* restriction (6) */
        }
        break;
      }
    }
  }
  return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor); /* rules (1), (2) */
}


/*
** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
108357
108358
108359
108360
108361
108362
108363
108364
108365
108366
108367
108368
108369
108370
108371
  return 0;
}

/*
** pX is the RHS of an IN operator.  If pX is a SELECT statement
** that can be simplified to a direct table access, then return
** a pointer to the SELECT statement.  If pX is not a SELECT statement,
** or if the SELECT statement needs to be manifested into a transient
** table, then return NULL.
*/
#ifndef SQLITE_OMIT_SUBQUERY
static Select *isCandidateForInOpt(const Expr *pX){
  Select *p;
  SrcList *pSrc;
  ExprList *pEList;







|







108923
108924
108925
108926
108927
108928
108929
108930
108931
108932
108933
108934
108935
108936
108937
  return 0;
}

/*
** pX is the RHS of an IN operator.  If pX is a SELECT statement
** that can be simplified to a direct table access, then return
** a pointer to the SELECT statement.  If pX is not a SELECT statement,
** or if the SELECT statement needs to be materialized into a transient
** table, then return NULL.
*/
#ifndef SQLITE_OMIT_SUBQUERY
static Select *isCandidateForInOpt(const Expr *pX){
  Select *p;
  SrcList *pSrc;
  ExprList *pEList;
108643
108644
108645
108646
108647
108648
108649
108650
108651
108652
108653
108654
108655
108656
108657
          colUsed = 0;   /* Columns of index used so far */
          for(i=0; i<nExpr; i++){
            Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
            Expr *pRhs = pEList->a[i].pExpr;
            CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
            int j;

            assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
            for(j=0; j<nExpr; j++){
              if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
              assert( pIdx->azColl[j] );
              if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
                continue;
              }
              break;







<







109209
109210
109211
109212
109213
109214
109215

109216
109217
109218
109219
109220
109221
109222
          colUsed = 0;   /* Columns of index used so far */
          for(i=0; i<nExpr; i++){
            Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
            Expr *pRhs = pEList->a[i].pExpr;
            CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
            int j;


            for(j=0; j<nExpr; j++){
              if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
              assert( pIdx->azColl[j] );
              if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
                continue;
              }
              break;
109546
109547
109548
109549
109550
109551
109552

109553
109554
109555
109556
109557
109558
109559
109560
109561
109562
109563
109564

109565
109566
109567
109568
109569
109570
109571
109572
109573
109574
109575
109576
109577
109578
109579
109580

109581
109582
109583
109584
109585
109586
109587
  Parse *pParse,     /* Parsing context */
  Table *pTab,       /* Table containing the generated column */
  Column *pCol,      /* The generated column */
  int regOut         /* Put the result in this register */
){
  int iAddr;
  Vdbe *v = pParse->pVdbe;

  assert( v!=0 );
  assert( pParse->iSelfTab!=0 );
  if( pParse->iSelfTab>0 ){
    iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
  }else{
    iAddr = 0;
  }
  sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
  if( pCol->affinity>=SQLITE_AFF_TEXT ){
    sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
  }
  if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);

}
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */

/*
** Generate code to extract the value of the iCol-th column of a table.
*/
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  Vdbe *v,        /* Parsing context */
  Table *pTab,    /* The table containing the value */
  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
  int iCol,       /* Index of the column to extract */
  int regOut      /* Extract the value into this register */
){
  Column *pCol;
  assert( v!=0 );
  assert( pTab!=0 );

  if( iCol<0 || iCol==pTab->iPKey ){
    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
    VdbeComment((v, "%s.rowid", pTab->zName));
  }else{
    int op;
    int x;
    if( IsVirtual(pTab) ){







>












>
















>







110111
110112
110113
110114
110115
110116
110117
110118
110119
110120
110121
110122
110123
110124
110125
110126
110127
110128
110129
110130
110131
110132
110133
110134
110135
110136
110137
110138
110139
110140
110141
110142
110143
110144
110145
110146
110147
110148
110149
110150
110151
110152
110153
110154
110155
  Parse *pParse,     /* Parsing context */
  Table *pTab,       /* Table containing the generated column */
  Column *pCol,      /* The generated column */
  int regOut         /* Put the result in this register */
){
  int iAddr;
  Vdbe *v = pParse->pVdbe;
  int nErr = pParse->nErr;
  assert( v!=0 );
  assert( pParse->iSelfTab!=0 );
  if( pParse->iSelfTab>0 ){
    iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
  }else{
    iAddr = 0;
  }
  sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
  if( pCol->affinity>=SQLITE_AFF_TEXT ){
    sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
  }
  if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
  if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
}
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */

/*
** Generate code to extract the value of the iCol-th column of a table.
*/
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  Vdbe *v,        /* Parsing context */
  Table *pTab,    /* The table containing the value */
  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
  int iCol,       /* Index of the column to extract */
  int regOut      /* Extract the value into this register */
){
  Column *pCol;
  assert( v!=0 );
  assert( pTab!=0 );
  assert( iCol!=XN_EXPR );
  if( iCol<0 || iCol==pTab->iPKey ){
    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
    VdbeComment((v, "%s.rowid", pTab->zName));
  }else{
    int op;
    int x;
    if( IsVirtual(pTab) ){
109926
109927
109928
109929
109930
109931
109932
109933












109934
109935
109936
109937
109938
109939
109940
    op = pExpr->op;
  }
  switch( op ){
    case TK_AGG_COLUMN: {
      AggInfo *pAggInfo = pExpr->pAggInfo;
      struct AggInfo_col *pCol;
      assert( pAggInfo!=0 );
      assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );












      pCol = &pAggInfo->aCol[pExpr->iAgg];
      if( !pAggInfo->directMode ){
        return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
      }else if( pAggInfo->useSortingIdx ){
        Table *pTab = pCol->pTab;
        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
                              pCol->iSorterColumn, target);







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







110494
110495
110496
110497
110498
110499
110500
110501
110502
110503
110504
110505
110506
110507
110508
110509
110510
110511
110512
110513
110514
110515
110516
110517
110518
110519
110520
    op = pExpr->op;
  }
  switch( op ){
    case TK_AGG_COLUMN: {
      AggInfo *pAggInfo = pExpr->pAggInfo;
      struct AggInfo_col *pCol;
      assert( pAggInfo!=0 );
      assert( pExpr->iAgg>=0 );
      if( pExpr->iAgg>=pAggInfo->nColumn ){
        /* Happens when the left table of a RIGHT JOIN is null and
        ** is using an expression index */
        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
#ifdef SQLITE_VDBE_COVERAGE
        /* Verify that the OP_Null above is exercised by tests
        ** tag-20230325-2 */
        sqlite3VdbeAddOp2(v, OP_NotNull, target, 1);
        VdbeCoverageNeverTaken(v);
#endif
        break;
      }
      pCol = &pAggInfo->aCol[pExpr->iAgg];
      if( !pAggInfo->directMode ){
        return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
      }else if( pAggInfo->useSortingIdx ){
        Table *pTab = pCol->pTab;
        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
                              pCol->iSorterColumn, target);
110101
110102
110103
110104
110105
110106
110107
110108
110109
110110
110111
110112
110113
110114
110115
110116
110117
110118
110119
    }
    case TK_REGISTER: {
      return pExpr->iTable;
    }
#ifndef SQLITE_OMIT_CAST
    case TK_CAST: {
      /* Expressions of the form:   CAST(pLeft AS token) */
      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
      if( inReg!=target ){
        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
        inReg = target;
      }
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      sqlite3VdbeAddOp2(v, OP_Cast, target,
                        sqlite3AffinityType(pExpr->u.zToken, 0));
      return inReg;
    }
#endif /* SQLITE_OMIT_CAST */
    case TK_IS:







|
|
<
<
<







110681
110682
110683
110684
110685
110686
110687
110688
110689



110690
110691
110692
110693
110694
110695
110696
    }
    case TK_REGISTER: {
      return pExpr->iTable;
    }
#ifndef SQLITE_OMIT_CAST
    case TK_CAST: {
      /* Expressions of the form:   CAST(pLeft AS token) */
      sqlite3ExprCode(pParse, pExpr->pLeft, target);
      assert( inReg==target );



      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      sqlite3VdbeAddOp2(v, OP_Cast, target,
                        sqlite3AffinityType(pExpr->u.zToken, 0));
      return inReg;
    }
#endif /* SQLITE_OMIT_CAST */
    case TK_IS:
110444
110445
110446
110447
110448
110449
110450
110451
110452
110453
110454
110455
110456
110457
110458
110459
110460
110461
110462
110463
110464
      if( !ExprHasProperty(pExpr, EP_Collate) ){
        /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
        ** "SOFT-COLLATE" that is added to constraints that are pushed down
        ** from outer queries into sub-queries by the push-down optimization.
        ** Clear subtypes as subtypes may not cross a subquery boundary.
        */
        assert( pExpr->pLeft );
        inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
        if( inReg!=target ){
          sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
          inReg = target;
        }
        sqlite3VdbeAddOp1(v, OP_ClrSubtype, inReg);
        return inReg;
      }else{
        pExpr = pExpr->pLeft;
        goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
      }
    }
    case TK_SPAN:
    case TK_UPLUS: {







|
<
<
<
<
|
|







111021
111022
111023
111024
111025
111026
111027
111028




111029
111030
111031
111032
111033
111034
111035
111036
111037
      if( !ExprHasProperty(pExpr, EP_Collate) ){
        /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
        ** "SOFT-COLLATE" that is added to constraints that are pushed down
        ** from outer queries into sub-queries by the push-down optimization.
        ** Clear subtypes as subtypes may not cross a subquery boundary.
        */
        assert( pExpr->pLeft );
        sqlite3ExprCode(pParse, pExpr->pLeft, target);




        sqlite3VdbeAddOp1(v, OP_ClrSubtype, target);
        return target;
      }else{
        pExpr = pExpr->pLeft;
        goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
      }
    }
    case TK_SPAN:
    case TK_UPLUS: {
110560
110561
110562
110563
110564
110565
110566
110567

110568
110569
110570
110571
110572
110573
110574
110575
110576
110577
110578
110579
      ** NULL.  So we have to ensure that the result register is not a value
      ** that is suppose to be a constant.  Two defenses are needed:
      **   (1)  Temporarily disable factoring of constant expressions
      **   (2)  Make sure the computed value really is stored in register
      **        "target" and not someplace else.
      */
      pParse->okConstFactor = 0;   /* note (1) above */
      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);

      pParse->okConstFactor = okConstFactor;
      if( inReg!=target ){         /* note (2) above */
        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
        inReg = target;
      }
      sqlite3VdbeJumpHere(v, addrINR);
      break;
    }

    /*
    ** Form A:
    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END







|
>

<
<
<
<







111133
111134
111135
111136
111137
111138
111139
111140
111141
111142




111143
111144
111145
111146
111147
111148
111149
      ** NULL.  So we have to ensure that the result register is not a value
      ** that is suppose to be a constant.  Two defenses are needed:
      **   (1)  Temporarily disable factoring of constant expressions
      **   (2)  Make sure the computed value really is stored in register
      **        "target" and not someplace else.
      */
      pParse->okConstFactor = 0;   /* note (1) above */
      sqlite3ExprCode(pParse, pExpr->pLeft, target);
      assert( target==inReg );
      pParse->okConstFactor = okConstFactor;




      sqlite3VdbeJumpHere(v, addrINR);
      break;
    }

    /*
    ** Form A:
    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
110803
110804
110805
110806
110807
110808
110809
110810


110811
110812
110813
110814
110815
110816
110817
  assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
  assert( target>0 && target<=pParse->nMem );
  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  if( pParse->pVdbe==0 ) return;
  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  if( inReg!=target ){
    u8 op;
    if( ALWAYS(pExpr) && ExprHasProperty(pExpr,EP_Subquery) ){


      op = OP_Copy;
    }else{
      op = OP_SCopy;
    }
    sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
  }
}







|
>
>







111373
111374
111375
111376
111377
111378
111379
111380
111381
111382
111383
111384
111385
111386
111387
111388
111389
  assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
  assert( target>0 && target<=pParse->nMem );
  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  if( pParse->pVdbe==0 ) return;
  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  if( inReg!=target ){
    u8 op;
    if( ALWAYS(pExpr)
     && (ExprHasProperty(pExpr,EP_Subquery) || pExpr->op==TK_REGISTER)
    ){
      op = OP_Copy;
    }else{
      op = OP_SCopy;
    }
    sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
  }
}
111988
111989
111990
111991
111992
111993
111994

111995
111996
111997

111998
111999
112000
112001
112002
112003
112004
112005
112006
112007

112008
112009
112010
112011
112012
112013
112014
  if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
   && pExpr->pAggInfo!=0
  ){
    AggInfo *pAggInfo = pExpr->pAggInfo;
    int iAgg = pExpr->iAgg;
    Parse *pParse = pWalker->pParse;
    sqlite3 *db = pParse->db;

    if( pExpr->op!=TK_AGG_FUNCTION ){
      assert( iAgg>=0 && iAgg<pAggInfo->nColumn );
      if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){

        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr ){
          pAggInfo->aCol[iAgg].pCExpr = pExpr;
          sqlite3ExprDeferredDelete(pParse, pExpr);
        }
      }
    }else{
      assert( pExpr->op==TK_AGG_FUNCTION );
      assert( iAgg>=0 && iAgg<pAggInfo->nFunc );
      if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){

        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr ){
          pAggInfo->aFunc[iAgg].pFExpr = pExpr;
          sqlite3ExprDeferredDelete(pParse, pExpr);
        }
      }
    }







>

|
|
>








|
|
>







112560
112561
112562
112563
112564
112565
112566
112567
112568
112569
112570
112571
112572
112573
112574
112575
112576
112577
112578
112579
112580
112581
112582
112583
112584
112585
112586
112587
112588
112589
  if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
   && pExpr->pAggInfo!=0
  ){
    AggInfo *pAggInfo = pExpr->pAggInfo;
    int iAgg = pExpr->iAgg;
    Parse *pParse = pWalker->pParse;
    sqlite3 *db = pParse->db;
    assert( iAgg>=0 );
    if( pExpr->op!=TK_AGG_FUNCTION ){
      if( iAgg<pAggInfo->nColumn
       && pAggInfo->aCol[iAgg].pCExpr==pExpr
      ){
        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr ){
          pAggInfo->aCol[iAgg].pCExpr = pExpr;
          sqlite3ExprDeferredDelete(pParse, pExpr);
        }
      }
    }else{
      assert( pExpr->op==TK_AGG_FUNCTION );
      if( ALWAYS(iAgg<pAggInfo->nFunc)
       && pAggInfo->aFunc[iAgg].pFExpr==pExpr
      ){
        pExpr = sqlite3ExprDup(db, pExpr, 0);
        if( pExpr ){
          pAggInfo->aFunc[iAgg].pFExpr = pExpr;
          sqlite3ExprDeferredDelete(pParse, pExpr);
        }
      }
    }
112150
112151
112152
112153
112154
112155
112156




112157

112158
112159
112160
112161
112162
112163
112164
112165
112166
112167



112168
112169
112170
112171
112172
112173
112174
      for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
        int iDataCur = pIEpr->iDataCur;
        if( iDataCur<0 ) continue;
        if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
      }
      if( pIEpr==0 ) break;
      if( NEVER(!ExprUseYTab(pExpr)) ) break;




      if( pExpr->pAggInfo!=0 ) break; /* Already resolved by outer context */


      /* If we reach this point, it means that expression pExpr can be
      ** translated into a reference to an index column as described by
      ** pIEpr.
      */
      memset(&tmp, 0, sizeof(tmp));
      tmp.op = TK_AGG_COLUMN;
      tmp.iTable = pIEpr->iIdxCur;
      tmp.iColumn = pIEpr->iIdxCol;
      findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);



      pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
      pExpr->pAggInfo = pAggInfo;
      pExpr->iAgg = tmp.iAgg;
      return WRC_Prune;
    }
    case TK_IF_NULL_ROW:
    case TK_AGG_COLUMN:







>
>
>
>
|
>










>
>
>







112725
112726
112727
112728
112729
112730
112731
112732
112733
112734
112735
112736
112737
112738
112739
112740
112741
112742
112743
112744
112745
112746
112747
112748
112749
112750
112751
112752
112753
112754
112755
112756
112757
      for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
        int iDataCur = pIEpr->iDataCur;
        if( iDataCur<0 ) continue;
        if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
      }
      if( pIEpr==0 ) break;
      if( NEVER(!ExprUseYTab(pExpr)) ) break;
      for(i=0; i<pSrcList->nSrc; i++){
         if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
      }
      if( i>=pSrcList->nSrc ) break;
      if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
      if( pParse->nErr ){ return WRC_Abort; }

      /* If we reach this point, it means that expression pExpr can be
      ** translated into a reference to an index column as described by
      ** pIEpr.
      */
      memset(&tmp, 0, sizeof(tmp));
      tmp.op = TK_AGG_COLUMN;
      tmp.iTable = pIEpr->iIdxCur;
      tmp.iColumn = pIEpr->iIdxCol;
      findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);
      if( pParse->nErr ){ return WRC_Abort; }
      assert( pAggInfo->aCol!=0 );
      assert( tmp.iAgg<pAggInfo->nColumn );
      pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
      pExpr->pAggInfo = pAggInfo;
      pExpr->iAgg = tmp.iAgg;
      return WRC_Prune;
    }
    case TK_IF_NULL_ROW:
    case TK_AGG_COLUMN:
112184
112185
112186
112187
112188
112189
112190
112191
112192
112193
112194
112195
112196
112197
112198
          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
          if( pExpr->iTable==pItem->iCursor ){
            findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
            break;
          } /* endif pExpr->iTable==pItem->iCursor */
        } /* end loop over pSrcList */
      }
      return WRC_Prune;
    }
    case TK_AGG_FUNCTION: {
      if( (pNC->ncFlags & NC_InAggFunc)==0
       && pWalker->walkerDepth==pExpr->op2
      ){
        /* Check to see if pExpr is a duplicate of another aggregate
        ** function that is already in the pAggInfo structure







|







112767
112768
112769
112770
112771
112772
112773
112774
112775
112776
112777
112778
112779
112780
112781
          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
          if( pExpr->iTable==pItem->iCursor ){
            findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
            break;
          } /* endif pExpr->iTable==pItem->iCursor */
        } /* end loop over pSrcList */
      }
      return WRC_Continue;
    }
    case TK_AGG_FUNCTION: {
      if( (pNC->ncFlags & NC_InAggFunc)==0
       && pWalker->walkerDepth==pExpr->op2
      ){
        /* Check to see if pExpr is a duplicate of another aggregate
        ** function that is already in the pAggInfo structure
112337
112338
112339
112340
112341
112342
112343































112344
112345
112346
112347
112348
112349
112350
112351
112352
112353
112354
112355
112356
112357
112358
112359
112360
112361








112362
112363
112364
112365
112366
112367
112368
** invokes the sub/co-routine.
*/
SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  pParse->nTempReg = 0;
  pParse->nRangeReg = 0;
}
































/*
** Validate that no temporary register falls within the range of
** iFirst..iLast, inclusive.  This routine is only call from within assert()
** statements.
*/
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  int i;
  if( pParse->nRangeReg>0
   && pParse->iRangeReg+pParse->nRangeReg > iFirst
   && pParse->iRangeReg <= iLast
  ){
     return 0;
  }
  for(i=0; i<pParse->nTempReg; i++){
    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
      return 0;
    }








  }
  return 1;
}
#endif /* SQLITE_DEBUG */

/************** End of expr.c ************************************************/
/************** Begin file alter.c *******************************************/







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


















>
>
>
>
>
>
>
>







112920
112921
112922
112923
112924
112925
112926
112927
112928
112929
112930
112931
112932
112933
112934
112935
112936
112937
112938
112939
112940
112941
112942
112943
112944
112945
112946
112947
112948
112949
112950
112951
112952
112953
112954
112955
112956
112957
112958
112959
112960
112961
112962
112963
112964
112965
112966
112967
112968
112969
112970
112971
112972
112973
112974
112975
112976
112977
112978
112979
112980
112981
112982
112983
112984
112985
112986
112987
112988
112989
112990
** invokes the sub/co-routine.
*/
SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  pParse->nTempReg = 0;
  pParse->nRangeReg = 0;
}

/*
** Make sure sufficient registers have been allocated so that
** iReg is a valid register number.
*/
SQLITE_PRIVATE void sqlite3TouchRegister(Parse *pParse, int iReg){
  if( pParse->nMem<iReg ) pParse->nMem = iReg;
}

#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
/*
** Return the latest reusable register in the set of all registers.
** The value returned is no less than iMin.  If any register iMin or
** greater is in permanent use, then return one more than that last
** permanent register.
*/
SQLITE_PRIVATE int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){
  const ExprList *pList = pParse->pConstExpr;
  if( pList ){
    int i;
    for(i=0; i<pList->nExpr; i++){
      if( pList->a[i].u.iConstExprReg>=iMin ){
        iMin = pList->a[i].u.iConstExprReg + 1;
      }
    }
  }
  pParse->nTempReg = 0;
  pParse->nRangeReg = 0;
  return iMin;
}
#endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */

/*
** Validate that no temporary register falls within the range of
** iFirst..iLast, inclusive.  This routine is only call from within assert()
** statements.
*/
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  int i;
  if( pParse->nRangeReg>0
   && pParse->iRangeReg+pParse->nRangeReg > iFirst
   && pParse->iRangeReg <= iLast
  ){
     return 0;
  }
  for(i=0; i<pParse->nTempReg; i++){
    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
      return 0;
    }
  }
  if( pParse->pConstExpr ){
    ExprList *pList = pParse->pConstExpr;
    for(i=0; i<pList->nExpr; i++){
      int iReg = pList->a[i].u.iConstExprReg;
      if( iReg==0 ) continue;
      if( iReg>=iFirst && iReg<=iLast ) return 0;
    }
  }
  return 1;
}
#endif /* SQLITE_DEBUG */

/************** End of expr.c ************************************************/
/************** Begin file alter.c *******************************************/
113642
113643
113644
113645
113646
113647
113648













113649
113650
113651
113652
113653
113654
113655
  }else{
    rc = SQLITE_NOMEM;
  }

  sqlite3_free(zQuot);
  return rc;
}














/*
** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
** it was read from the schema of database zDb. Return SQLITE_OK if
** successful. Otherwise, return an SQLite error code and leave an error
** message in the Parse object.
*/







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







114264
114265
114266
114267
114268
114269
114270
114271
114272
114273
114274
114275
114276
114277
114278
114279
114280
114281
114282
114283
114284
114285
114286
114287
114288
114289
114290
  }else{
    rc = SQLITE_NOMEM;
  }

  sqlite3_free(zQuot);
  return rc;
}

/*
** Set all pEList->a[].fg.eEName fields in the expression-list to val.
*/
static void renameSetENames(ExprList *pEList, int val){
  if( pEList ){
    int i;
    for(i=0; i<pEList->nExpr; i++){
      assert( val==ENAME_NAME || pEList->a[i].fg.eEName==ENAME_NAME );
      pEList->a[i].fg.eEName = val;
    }
  }
}

/*
** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
** it was read from the schema of database zDb. Return SQLITE_OK if
** successful. Otherwise, return an SQLite error code and leave an error
** message in the Parse object.
*/
113690
113691
113692
113693
113694
113695
113696









113697

113698
113699
113700
113701
113702
113703
113704
            pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
        );
        if( pSel==0 ){
          pStep->pExprList = 0;
          pSrc = 0;
          rc = SQLITE_NOMEM;
        }else{









          sqlite3SelectPrep(pParse, pSel, 0);

          rc = pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
          assert( pStep->pExprList==0 || pStep->pExprList==pSel->pEList );
          assert( pSrc==pSel->pSrc );
          if( pStep->pExprList ) pSel->pEList = 0;
          pSel->pSrc = 0;
          sqlite3SelectDelete(db, pSel);
        }







>
>
>
>
>
>
>
>
>

>







114325
114326
114327
114328
114329
114330
114331
114332
114333
114334
114335
114336
114337
114338
114339
114340
114341
114342
114343
114344
114345
114346
114347
114348
114349
            pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
        );
        if( pSel==0 ){
          pStep->pExprList = 0;
          pSrc = 0;
          rc = SQLITE_NOMEM;
        }else{
          /* pStep->pExprList contains an expression-list used for an UPDATE
          ** statement. So the a[].zEName values are the RHS of the
          ** "<col> = <expr>" clauses of the UPDATE statement. So, before
          ** running SelectPrep(), change all the eEName values in
          ** pStep->pExprList to ENAME_SPAN (from their current value of
          ** ENAME_NAME). This is to prevent any ids in ON() clauses that are
          ** part of pSrc from being incorrectly resolved against the
          ** a[].zEName values as if they were column aliases.  */
          renameSetENames(pStep->pExprList, ENAME_SPAN);
          sqlite3SelectPrep(pParse, pSel, 0);
          renameSetENames(pStep->pExprList, ENAME_NAME);
          rc = pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
          assert( pStep->pExprList==0 || pStep->pExprList==pSel->pEList );
          assert( pSrc==pSel->pSrc );
          if( pStep->pExprList ) pSel->pEList = 0;
          pSel->pSrc = 0;
          sqlite3SelectDelete(db, pSel);
        }
115639
115640
115641
115642
115643
115644
115645



115646
115647
115648
115649
115650

115651
115652
115653
115654
115655
115656
115657
  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
  int regTemp = iMem++;        /* Temporary use register */
  int regTemp2 = iMem++;       /* Second temporary use register */
  int regTabname = iMem++;     /* Register containing table name */
  int regIdxname = iMem++;     /* Register containing index name */
  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
  int regPrev = iMem;          /* MUST BE LAST (see below) */



#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  Table *pStat1 = 0;
#endif

  pParse->nMem = MAX(pParse->nMem, iMem);

  v = sqlite3GetVdbe(pParse);
  if( v==0 || NEVER(pTab==0) ){
    return;
  }
  if( !IsOrdinaryTable(pTab) ){
    /* Do not gather statistics on views or virtual tables */
    return;







>
>
>




|
>







116284
116285
116286
116287
116288
116289
116290
116291
116292
116293
116294
116295
116296
116297
116298
116299
116300
116301
116302
116303
116304
116305
116306
  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
  int regTemp = iMem++;        /* Temporary use register */
  int regTemp2 = iMem++;       /* Second temporary use register */
  int regTabname = iMem++;     /* Register containing table name */
  int regIdxname = iMem++;     /* Register containing index name */
  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
  int regPrev = iMem;          /* MUST BE LAST (see below) */
#ifdef SQLITE_ENABLE_STAT4
  int doOnce = 1;              /* Flag for a one-time computation */
#endif
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  Table *pStat1 = 0;
#endif

  sqlite3TouchRegister(pParse, iMem);
  assert( sqlite3NoTempsInRange(pParse, regNewRowid, iMem) );
  v = sqlite3GetVdbe(pParse);
  if( v==0 || NEVER(pTab==0) ){
    return;
  }
  if( !IsOrdinaryTable(pTab) ){
    /* Do not gather statistics on views or virtual tables */
    return;
115749
115750
115751
115752
115753
115754
115755
115756
115757
115758
115759
115760
115761
115762
115763
    **  end_of_scan:
    */

    /* Make sure there are enough memory cells allocated to accommodate
    ** the regPrev array and a trailing rowid (the rowid slot is required
    ** when building a record to insert into the sample column of
    ** the sqlite_stat4 table.  */
    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);

    /* Open a read-only cursor on the index being analyzed. */
    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
    VdbeComment((v, "%s", pIdx->zName));








|







116398
116399
116400
116401
116402
116403
116404
116405
116406
116407
116408
116409
116410
116411
116412
    **  end_of_scan:
    */

    /* Make sure there are enough memory cells allocated to accommodate
    ** the regPrev array and a trailing rowid (the rowid slot is required
    ** when building a record to insert into the sample column of
    ** the sqlite_stat4 table.  */
    sqlite3TouchRegister(pParse, regPrev+nColTest);

    /* Open a read-only cursor on the index being analyzed. */
    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
    VdbeComment((v, "%s", pIdx->zName));

115921
115922
115923
115924
115925
115926
115927



115928

























115929
115930
115931
115932
115933
115934
115935
      int regSample = regStat1+3;
      int regCol = regStat1+4;
      int regSampleRowid = regCol + nCol;
      int addrNext;
      int addrIsNull;
      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;




      pParse->nMem = MAX(pParse->nMem, regCol+nCol);


























      addrNext = sqlite3VdbeCurrentAddr(v);
      callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
      VdbeCoverage(v);
      callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
      callStatGet(pParse, regStat, STAT_GET_NLT, regLt);







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







116570
116571
116572
116573
116574
116575
116576
116577
116578
116579
116580
116581
116582
116583
116584
116585
116586
116587
116588
116589
116590
116591
116592
116593
116594
116595
116596
116597
116598
116599
116600
116601
116602
116603
116604
116605
116606
116607
116608
116609
116610
116611
116612
      int regSample = regStat1+3;
      int regCol = regStat1+4;
      int regSampleRowid = regCol + nCol;
      int addrNext;
      int addrIsNull;
      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;

      if( doOnce ){
        int mxCol = nCol;
        Index *pX;

        /* Compute the maximum number of columns in any index */
        for(pX=pTab->pIndex; pX; pX=pX->pNext){
          int nColX;                     /* Number of columns in pX */
          if( !HasRowid(pTab) && IsPrimaryKeyIndex(pX) ){
            nColX = pX->nKeyCol;
          }else{
            nColX = pX->nColumn;
          }
          if( nColX>mxCol ) mxCol = nColX;
        }

        /* Allocate space to compute results for the largest index */
        sqlite3TouchRegister(pParse, regCol+mxCol);
        doOnce = 0;
#ifdef SQLITE_DEBUG
        /* Verify that the call to sqlite3ClearTempRegCache() below
        ** really is needed.
        ** https://sqlite.org/forum/forumpost/83cb4a95a0 (2023-03-25)
        */
        testcase( !sqlite3NoTempsInRange(pParse, regEq, regCol+mxCol) );
#endif
        sqlite3ClearTempRegCache(pParse);  /* tag-20230325-1 */
        assert( sqlite3NoTempsInRange(pParse, regEq, regCol+mxCol) );
      }
      assert( sqlite3NoTempsInRange(pParse, regEq, regCol+nCol) );

      addrNext = sqlite3VdbeCurrentAddr(v);
      callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
      VdbeCoverage(v);
      callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
      callStatGet(pParse, regStat, STAT_GET_NLT, regLt);
116002
116003
116004
116005
116006
116007
116008





116009
116010
116011
116012
116013
116014
116015
  openStatTable(pParse, iDb, iStatCur, 0, 0);
  iMem = pParse->nMem+1;
  iTab = pParse->nTab;
  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
    Table *pTab = (Table*)sqliteHashData(k);
    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);





  }
  loadAnalysis(pParse, iDb);
}

/*
** Generate code that will do an analysis of a single table in
** a database.  If pOnlyIdx is not NULL then it is a single index







>
>
>
>
>







116679
116680
116681
116682
116683
116684
116685
116686
116687
116688
116689
116690
116691
116692
116693
116694
116695
116696
116697
  openStatTable(pParse, iDb, iStatCur, 0, 0);
  iMem = pParse->nMem+1;
  iTab = pParse->nTab;
  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
    Table *pTab = (Table*)sqliteHashData(k);
    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
#ifdef SQLITE_ENABLE_STAT4
    iMem = sqlite3FirstAvailableRegister(pParse, iMem);
#else
    assert( iMem==sqlite3FirstAvailableRegister(pParse,iMem) );
#endif
  }
  loadAnalysis(pParse, iDb);
}

/*
** Generate code that will do an analysis of a single table in
** a database.  If pOnlyIdx is not NULL then it is a single index
116389
116390
116391
116392
116393
116394
116395




116396
116397
116398
116399
116400
116401
116402

116403
116404
116405
116406
116407
116408
116409

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




    assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
    if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
      nIdxCol = pIdx->nKeyCol;
    }else{
      nIdxCol = pIdx->nColumn;
    }
    pIdx->nSampleCol = nIdxCol;

    nByte = sizeof(IndexSample) * nSample;
    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */

    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
    if( pIdx->aSample==0 ){
      sqlite3_finalize(pStmt);







>
>
>
>







>







117071
117072
117073
117074
117075
117076
117077
117078
117079
117080
117081
117082
117083
117084
117085
117086
117087
117088
117089
117090
117091
117092
117093
117094
117095
117096

    zIndex = (char *)sqlite3_column_text(pStmt, 0);
    if( zIndex==0 ) continue;
    nSample = sqlite3_column_int(pStmt, 1);
    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
    assert( pIdx==0 || pIdx->nSample==0 );
    if( pIdx==0 ) continue;
    if( pIdx->aSample!=0 ){
      /* The same index appears in sqlite_stat4 under multiple names */
      continue;
    }
    assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
    if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
      nIdxCol = pIdx->nKeyCol;
    }else{
      nIdxCol = pIdx->nColumn;
    }
    pIdx->nSampleCol = nIdxCol;
    pIdx->mxSample = nSample;
    nByte = sizeof(IndexSample) * nSample;
    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */

    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
    if( pIdx->aSample==0 ){
      sqlite3_finalize(pStmt);
116435
116436
116437
116438
116439
116440
116441





116442
116443
116444
116445
116446
116447
116448
    Index *pIdx;                  /* Pointer to the index object */
    int nCol = 1;                 /* Number of columns in index */

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





    /* This next condition is true if data has already been loaded from
    ** the sqlite_stat4 table. */
    nCol = pIdx->nSampleCol;
    if( pIdx!=pPrevIdx ){
      initAvgEq(pPrevIdx);
      pPrevIdx = pIdx;
    }







>
>
>
>
>







117122
117123
117124
117125
117126
117127
117128
117129
117130
117131
117132
117133
117134
117135
117136
117137
117138
117139
117140
    Index *pIdx;                  /* Pointer to the index object */
    int nCol = 1;                 /* Number of columns in index */

    zIndex = (char *)sqlite3_column_text(pStmt, 0);
    if( zIndex==0 ) continue;
    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
    if( pIdx==0 ) continue;
    if( pIdx->nSample>=pIdx->mxSample ){
      /* Too many slots used because the same index appears in
      ** sqlite_stat4 using multiple names */
      continue;
    }
    /* This next condition is true if data has already been loaded from
    ** the sqlite_stat4 table. */
    nCol = pIdx->nSampleCol;
    if( pIdx!=pPrevIdx ){
      initAvgEq(pPrevIdx);
      pPrevIdx = pIdx;
    }
116478
116479
116480
116481
116482
116483
116484

116485
116486
116487
116488
116489
116490
116491
116492
116493
116494
116495
116496
** the Index.aSample[] arrays of all indices.
*/
static int loadStat4(sqlite3 *db, const char *zDb){
  int rc = SQLITE_OK;             /* Result codes from subroutines */
  const Table *pStat4;

  assert( db->lookaside.bDisable );

  if( (pStat4 = sqlite3FindTable(db, "sqlite_stat4", zDb))!=0
   && IsOrdinaryTable(pStat4)
  ){
    rc = loadStatTbl(db,
      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
      zDb
    );
  }
  return rc;
}
#endif /* SQLITE_ENABLE_STAT4 */







>
|



|







117170
117171
117172
117173
117174
117175
117176
117177
117178
117179
117180
117181
117182
117183
117184
117185
117186
117187
117188
117189
** the Index.aSample[] arrays of all indices.
*/
static int loadStat4(sqlite3 *db, const char *zDb){
  int rc = SQLITE_OK;             /* Result codes from subroutines */
  const Table *pStat4;

  assert( db->lookaside.bDisable );
  if( OptimizationEnabled(db, SQLITE_Stat4)
   && (pStat4 = sqlite3FindTable(db, "sqlite_stat4", zDb))!=0
   && IsOrdinaryTable(pStat4)
  ){
    rc = loadStatTbl(db,
      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx COLLATE nocase",
      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
      zDb
    );
  }
  return rc;
}
#endif /* SQLITE_ENABLE_STAT4 */
118326
118327
118328
118329
118330
118331
118332
118333
118334
118335
118336
118337
118338
118339
118340
    }
    sqlite3FreeIndex(db, pIndex);
  }

  if( IsOrdinaryTable(pTable) ){
    sqlite3FkDelete(db, pTable);
  }
#ifndef SQLITE_OMIT_VIRTUAL_TABLE
  else if( IsVirtual(pTable) ){
    sqlite3VtabClear(db, pTable);
  }
#endif
  else{
    assert( IsView(pTable) );
    sqlite3SelectDelete(db, pTable->u.view.pSelect);







|







119019
119020
119021
119022
119023
119024
119025
119026
119027
119028
119029
119030
119031
119032
119033
    }
    sqlite3FreeIndex(db, pIndex);
  }

  if( IsOrdinaryTable(pTable) ){
    sqlite3FkDelete(db, pTable);
  }
#ifndef SQLITE_OMIT_VIRTUALTABLE
  else if( IsVirtual(pTable) ){
    sqlite3VtabClear(db, pTable);
  }
#endif
  else{
    assert( IsView(pTable) );
    sqlite3SelectDelete(db, pTable->u.view.pSelect);
118929
118930
118931
118932
118933
118934
118935
118936
118937
118938
118939
118940
118941
118942
118943
SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){
  Returning *pRet;
  Hash *pHash;
  sqlite3 *db = pParse->db;
  if( pParse->pNewTrigger ){
    sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
  }else{
    assert( pParse->bReturning==0 );
  }
  pParse->bReturning = 1;
  pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
  if( pRet==0 ){
    sqlite3ExprListDelete(db, pList);
    return;
  }







|







119622
119623
119624
119625
119626
119627
119628
119629
119630
119631
119632
119633
119634
119635
119636
SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){
  Returning *pRet;
  Hash *pHash;
  sqlite3 *db = pParse->db;
  if( pParse->pNewTrigger ){
    sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
  }else{
    assert( pParse->bReturning==0 || pParse->ifNotExists );
  }
  pParse->bReturning = 1;
  pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
  if( pRet==0 ){
    sqlite3ExprListDelete(db, pList);
    return;
  }
118955
118956
118957
118958
118959
118960
118961
118962

118963
118964
118965
118966
118967
118968
118969
  pRet->retTrig.pSchema = db->aDb[1].pSchema;
  pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
  pRet->retTrig.step_list = &pRet->retTStep;
  pRet->retTStep.op = TK_RETURNING;
  pRet->retTStep.pTrig = &pRet->retTrig;
  pRet->retTStep.pExprList = pList;
  pHash = &(db->aDb[1].pSchema->trigHash);
  assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0 || pParse->nErr );

  if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig)
          ==&pRet->retTrig ){
    sqlite3OomFault(db);
  }
}

/*







|
>







119648
119649
119650
119651
119652
119653
119654
119655
119656
119657
119658
119659
119660
119661
119662
119663
  pRet->retTrig.pSchema = db->aDb[1].pSchema;
  pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
  pRet->retTrig.step_list = &pRet->retTStep;
  pRet->retTStep.op = TK_RETURNING;
  pRet->retTStep.pTrig = &pRet->retTrig;
  pRet->retTStep.pExprList = pList;
  pHash = &(db->aDb[1].pSchema->trigHash);
  assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0
          || pParse->nErr  || pParse->ifNotExists );
  if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig)
          ==&pRet->retTrig ){
    sqlite3OomFault(db);
  }
}

/*
123357
123358
123359
123360
123361
123362
123363

123364
123365
123366
123367
123368
123369
123370
SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){
  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  db->enc = enc;
  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  ** strings is BINARY.
  */
  db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);

}

/*
** This function is responsible for invoking the collation factory callback
** or substituting a collation sequence of a different encoding when the
** requested collation sequence is not available in the desired encoding.
**







>







124051
124052
124053
124054
124055
124056
124057
124058
124059
124060
124061
124062
124063
124064
124065
SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){
  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  db->enc = enc;
  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  ** strings is BINARY.
  */
  db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);
  sqlite3ExpirePreparedStatements(db, 1);
}

/*
** This function is responsible for invoking the collation factory callback
** or substituting a collation sequence of a different encoding when the
** requested collation sequence is not available in the desired encoding.
**
123828
123829
123830
123831
123832
123833
123834
123835
123836
123837
123838
123839
123840
123841


123842
123843
123844
123845
123846
123847
123848
/*
** Check to make sure the given table is writable.
**
** If pTab is not writable  ->  generate an error message and return 1.
** If pTab is writable but other errors have occurred -> return 1.
** If pTab is writable and no prior errors -> return 0;
*/
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  if( tabIsReadOnly(pParse, pTab) ){
    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
    return 1;
  }
#ifndef SQLITE_OMIT_VIEW
  if( !viewOk && IsView(pTab) ){


    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
    return 1;
  }
#endif
  return 0;
}








|





|
>
>







124523
124524
124525
124526
124527
124528
124529
124530
124531
124532
124533
124534
124535
124536
124537
124538
124539
124540
124541
124542
124543
124544
124545
/*
** Check to make sure the given table is writable.
**
** If pTab is not writable  ->  generate an error message and return 1.
** If pTab is writable but other errors have occurred -> return 1.
** If pTab is writable and no prior errors -> return 0;
*/
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, Trigger *pTrigger){
  if( tabIsReadOnly(pParse, pTab) ){
    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
    return 1;
  }
#ifndef SQLITE_OMIT_VIEW
  if( IsView(pTab)
   && (pTrigger==0 || (pTrigger->bReturning && pTrigger->pNext==0))
  ){
    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
    return 1;
  }
#endif
  return 0;
}

124088
124089
124090
124091
124092
124093
124094
124095
124096
124097
124098
124099
124100
124101
124102

  /* If pTab is really a view, make sure it has been initialized.
  */
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto delete_from_cleanup;
  }

  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
    goto delete_from_cleanup;
  }
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  assert( iDb<db->nDb );
  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
                            db->aDb[iDb].zDbSName);
  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );







|







124785
124786
124787
124788
124789
124790
124791
124792
124793
124794
124795
124796
124797
124798
124799

  /* If pTab is really a view, make sure it has been initialized.
  */
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto delete_from_cleanup;
  }

  if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
    goto delete_from_cleanup;
  }
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  assert( iDb<db->nDb );
  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
                            db->aDb[iDb].zDbSName);
  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
124197
124198
124199
124200
124201
124202
124203
124204
124205
124206
124207
124208
124209
124210
124211
        sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
      }
    }
  }else
#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  {
    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
    if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
    if( HasRowid(pTab) ){
      /* For a rowid table, initialize the RowSet to an empty set */
      pPk = 0;
      nPk = 1;
      iRowSet = ++pParse->nMem;
      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);







|







124894
124895
124896
124897
124898
124899
124900
124901
124902
124903
124904
124905
124906
124907
124908
        sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
      }
    }
  }else
#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  {
    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
    if( sNC.ncFlags & NC_Subquery ) bComplex = 1;
    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
    if( HasRowid(pTab) ){
      /* For a rowid table, initialize the RowSet to an empty set */
      pPk = 0;
      nPk = 1;
      iRowSet = ++pParse->nMem;
      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
126251
126252
126253
126254
126255
126256
126257
126258
126259
126260
126261
126262
126263
126264
126265
}


#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
/*
** The "unknown" function is automatically substituted in place of
** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
** When the "sqlite3" command-line shell is built using this functionality,
** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
** involving application-defined functions to be examined in a generic
** sqlite3 shell.
*/
static void unknownFunc(
  sqlite3_context *context,







|







126948
126949
126950
126951
126952
126953
126954
126955
126956
126957
126958
126959
126960
126961
126962
}


#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
/*
** The "unknown" function is automatically substituted in place of
** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
** when the SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION compile-time option is used.
** When the "sqlite3" command-line shell is built using this functionality,
** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
** involving application-defined functions to be examined in a generic
** sqlite3 shell.
*/
static void unknownFunc(
  sqlite3_context *context,
128554
128555
128556
128557
128558
128559
128560
128561
128562
128563
128564
128565
128566
128567
128568
128569
128570
128571
128572
128573






128574
128575
128576
128577
128578
128579
128580
128581
128582
128583
    sqlite3DbFree(db, aiCol);

    zFrom = pFKey->pFrom->zName;
    nFrom = sqlite3Strlen30(zFrom);

    if( action==OE_Restrict ){
      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
      Token tFrom;
      Token tDb;
      Expr *pRaise;

      tFrom.z = zFrom;
      tFrom.n = nFrom;
      tDb.z = db->aDb[iDb].zDbSName;
      tDb.n = sqlite3Strlen30(tDb.z);

      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
      if( pRaise ){
        pRaise->affExpr = OE_Abort;
      }






      pSelect = sqlite3SelectNew(pParse,
          sqlite3ExprListAppend(pParse, 0, pRaise),
          sqlite3SrcListAppend(pParse, 0, &tDb, &tFrom),
          pWhere,
          0, 0, 0, 0, 0
      );
      pWhere = 0;
    }

    /* Disable lookaside memory allocation */







|
<


<
<
<
<
<




>
>
>
>
>
>


|







129251
129252
129253
129254
129255
129256
129257
129258

129259
129260





129261
129262
129263
129264
129265
129266
129267
129268
129269
129270
129271
129272
129273
129274
129275
129276
129277
129278
129279
129280
    sqlite3DbFree(db, aiCol);

    zFrom = pFKey->pFrom->zName;
    nFrom = sqlite3Strlen30(zFrom);

    if( action==OE_Restrict ){
      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
      SrcList *pSrc;

      Expr *pRaise;






      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
      if( pRaise ){
        pRaise->affExpr = OE_Abort;
      }
      pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
      if( pSrc ){
        assert( pSrc->nSrc==1 );
        pSrc->a[0].zName = sqlite3DbStrDup(db, zFrom);
        pSrc->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
      }
      pSelect = sqlite3SelectNew(pParse,
          sqlite3ExprListAppend(pParse, 0, pRaise),
          pSrc,
          pWhere,
          0, 0, 0, 0, 0
      );
      pWhere = 0;
    }

    /* Disable lookaside memory allocation */
128785
128786
128787
128788
128789
128790
128791
128792
128793
128794
128795
128796
128797
128798
128799
128800
128801
128802
128803
128804
128805
128806
128807
128808
128809
128810
128811
128812
128813
128814
128815
128816
128817
128818
128819
128820
128821
128822
128823
128824
128825
128826

128827
128828

128829
128830

128831
128832
128833
128834
128835
128836
128837
** An extra 'D' is appended to the end of the string to cover the
** rowid that appears as the last column in every index.
**
** Memory for the buffer containing the column index affinity string
** is managed along with the rest of the Index structure. It will be
** released when sqlite3DeleteIndex() is called.
*/
SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  if( !pIdx->zColAff ){
    /* The first time a column affinity string for a particular index is
    ** required, it is allocated and populated here. It is then stored as
    ** a member of the Index structure for subsequent use.
    **
    ** The column affinity string will eventually be deleted by
    ** sqliteDeleteIndex() when the Index structure itself is cleaned
    ** up.
    */
    int n;
    Table *pTab = pIdx->pTable;
    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
    if( !pIdx->zColAff ){
      sqlite3OomFault(db);
      return 0;
    }
    for(n=0; n<pIdx->nColumn; n++){
      i16 x = pIdx->aiColumn[n];
      char aff;
      if( x>=0 ){
        aff = pTab->aCol[x].affinity;
      }else if( x==XN_ROWID ){
        aff = SQLITE_AFF_INTEGER;
      }else{
        assert( x==XN_EXPR );
        assert( pIdx->bHasExpr );
        assert( pIdx->aColExpr!=0 );
        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
      }
      if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
      if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
      pIdx->zColAff[n] = aff;
    }
    pIdx->zColAff[n] = 0;

  }


  return pIdx->zColAff;
}


/*
** Compute an affinity string for a table.   Space is obtained
** from sqlite3DbMalloc().  The caller is responsible for freeing
** the space when done.
*/
SQLITE_PRIVATE char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){







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


>







129482
129483
129484
129485
129486
129487
129488
129489

129490
129491
129492
129493
129494
129495
129496
129497
129498
129499
129500
129501
129502
129503
129504
129505
129506
129507
129508
129509
129510
129511
129512
129513
129514
129515
129516
129517
129518
129519
129520
129521
129522
129523
129524
129525
129526
129527
129528
129529
129530
129531
129532
129533
129534
129535
129536
** An extra 'D' is appended to the end of the string to cover the
** rowid that appears as the last column in every index.
**
** Memory for the buffer containing the column index affinity string
** is managed along with the rest of the Index structure. It will be
** released when sqlite3DeleteIndex() is called.
*/
static SQLITE_NOINLINE const char *computeIndexAffStr(sqlite3 *db, Index *pIdx){

  /* The first time a column affinity string for a particular index is
  ** required, it is allocated and populated here. It is then stored as
  ** a member of the Index structure for subsequent use.
  **
  ** The column affinity string will eventually be deleted by
  ** sqliteDeleteIndex() when the Index structure itself is cleaned
  ** up.
  */
  int n;
  Table *pTab = pIdx->pTable;
  pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  if( !pIdx->zColAff ){
    sqlite3OomFault(db);
    return 0;
  }
  for(n=0; n<pIdx->nColumn; n++){
    i16 x = pIdx->aiColumn[n];
    char aff;
    if( x>=0 ){
      aff = pTab->aCol[x].affinity;
    }else if( x==XN_ROWID ){
      aff = SQLITE_AFF_INTEGER;
    }else{
      assert( x==XN_EXPR );
      assert( pIdx->bHasExpr );
      assert( pIdx->aColExpr!=0 );
      aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
    }
    if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
    if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
    pIdx->zColAff[n] = aff;
  }
  pIdx->zColAff[n] = 0;
  return pIdx->zColAff;
}
SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
  return pIdx->zColAff;
}


/*
** Compute an affinity string for a table.   Space is obtained
** from sqlite3DbMalloc().  The caller is responsible for freeing
** the space when done.
*/
SQLITE_PRIVATE char *sqlite3TableAffinityStr(sqlite3 *db, const Table *pTab){
129509
129510
129511
129512
129513
129514
129515
129516
129517
129518
129519
129520
129521
129522
129523
  */
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto insert_cleanup;
  }

  /* Cannot insert into a read-only table.
  */
  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
    goto insert_cleanup;
  }

  /* Allocate a VDBE
  */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ) goto insert_cleanup;







|







130208
130209
130210
130211
130212
130213
130214
130215
130216
130217
130218
130219
130220
130221
130222
  */
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto insert_cleanup;
  }

  /* Cannot insert into a read-only table.
  */
  if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
    goto insert_cleanup;
  }

  /* Allocate a VDBE
  */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ) goto insert_cleanup;
129956
129957
129958
129959
129960
129961
129962
129963
129964
129965
129966
129967
129968
129969
129970
      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
      sqlite3VdbeJumpHere(v, addr1);
      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
    }

    /* Copy the new data already generated. */
    assert( pTab->nNVCol>0 );
    sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);

#ifndef SQLITE_OMIT_GENERATED_COLUMNS
    /* Compute the new value for generated columns after all other
    ** columns have already been computed.  This must be done after
    ** computing the ROWID in case one of the generated columns
    ** refers to the ROWID. */







|







130655
130656
130657
130658
130659
130660
130661
130662
130663
130664
130665
130666
130667
130668
130669
      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
      sqlite3VdbeJumpHere(v, addr1);
      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
    }

    /* Copy the new data already generated. */
    assert( pTab->nNVCol>0 || pParse->nErr>0 );
    sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);

#ifndef SQLITE_OMIT_GENERATED_COLUMNS
    /* Compute the new value for generated columns after all other
    ** columns have already been computed.  This must be done after
    ** computing the ROWID in case one of the generated columns
    ** refers to the ROWID. */
133319
133320
133321
133322
133323
133324
133325
133326




133327
133328
133329
133330
133331
133332
133333

133334

133335
133336
133337
133338
133339
133340
133341
  }

  zEntry = zProc ? zProc : "sqlite3_extension_init";

  /* tag-20210611-1.  Some dlopen() implementations will segfault if given
  ** an oversize filename.  Most filesystems have a pathname limit of 4K,
  ** so limit the extension filename length to about twice that.
  ** https://sqlite.org/forum/forumpost/08a0d6d9bf */




  if( nMsg>SQLITE_MAX_PATHLEN ) goto extension_not_found;

  handle = sqlite3OsDlOpen(pVfs, zFile);
#if SQLITE_OS_UNIX || SQLITE_OS_WIN
  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;

    handle = sqlite3OsDlOpen(pVfs, zAltFile);

    sqlite3_free(zAltFile);
  }
#endif
  if( handle==0 ) goto extension_not_found;
  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);

  /* If no entry point was specified and the default legacy







|
>
>
>
>







>
|
>







134018
134019
134020
134021
134022
134023
134024
134025
134026
134027
134028
134029
134030
134031
134032
134033
134034
134035
134036
134037
134038
134039
134040
134041
134042
134043
134044
134045
134046
  }

  zEntry = zProc ? zProc : "sqlite3_extension_init";

  /* tag-20210611-1.  Some dlopen() implementations will segfault if given
  ** an oversize filename.  Most filesystems have a pathname limit of 4K,
  ** so limit the extension filename length to about twice that.
  ** https://sqlite.org/forum/forumpost/08a0d6d9bf
  **
  ** Later (2023-03-25): Save an extra 6 bytes for the filename suffix.
  ** See https://sqlite.org/forum/forumpost/24083b579d.
  */
  if( nMsg>SQLITE_MAX_PATHLEN ) goto extension_not_found;

  handle = sqlite3OsDlOpen(pVfs, zFile);
#if SQLITE_OS_UNIX || SQLITE_OS_WIN
  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
    if( nMsg+strlen(azEndings[ii])+1<=SQLITE_MAX_PATHLEN ){
      handle = sqlite3OsDlOpen(pVfs, zAltFile);
    }
    sqlite3_free(zAltFile);
  }
#endif
  if( handle==0 ) goto extension_not_found;
  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);

  /* If no entry point was specified and the default legacy
135822
135823
135824
135825
135826
135827
135828
135829
135830
135831
135832
135833
135834
135835
135836
        k = sqliteHashNext(k);
      }
      if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
      zDb = db->aDb[iDb].zDbSName;
      sqlite3CodeVerifySchema(pParse, iDb);
      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
      sqlite3VdbeLoadString(v, regResult, pTab->zName);
      assert( IsOrdinaryTable(pTab) );
      for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
        if( pParent==0 ) continue;
        pIdx = 0;







|







136527
136528
136529
136530
136531
136532
136533
136534
136535
136536
136537
136538
136539
136540
136541
        k = sqliteHashNext(k);
      }
      if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
      zDb = db->aDb[iDb].zDbSName;
      sqlite3CodeVerifySchema(pParse, iDb);
      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
      sqlite3TouchRegister(pParse, pTab->nCol+regRow);
      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
      sqlite3VdbeLoadString(v, regResult, pTab->zName);
      assert( IsOrdinaryTable(pTab) );
      for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
        if( pParent==0 ) continue;
        pIdx = 0;
135863
135864
135865
135866
135867
135868
135869
135870
135871
135872
135873
135874
135875
135876
135877
        }
        addrOk = sqlite3VdbeMakeLabel(pParse);

        /* Generate code to read the child key values into registers
        ** regRow..regRow+n. If any of the child key values are NULL, this
        ** row cannot cause an FK violation. Jump directly to addrOk in
        ** this case. */
        if( regRow+pFK->nCol>pParse->nMem ) pParse->nMem = regRow+pFK->nCol;
        for(j=0; j<pFK->nCol; j++){
          int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
          sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
          sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
        }

        /* Generate code to query the parent index for a matching parent







|







136568
136569
136570
136571
136572
136573
136574
136575
136576
136577
136578
136579
136580
136581
136582
        }
        addrOk = sqlite3VdbeMakeLabel(pParse);

        /* Generate code to read the child key values into registers
        ** regRow..regRow+n. If any of the child key values are NULL, this
        ** row cannot cause an FK violation. Jump directly to addrOk in
        ** this case. */
        sqlite3TouchRegister(pParse, regRow + pFK->nCol);
        for(j=0; j<pFK->nCol; j++){
          int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
          sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
          sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
        }

        /* Generate code to query the parent index for a matching parent
135992
135993
135994
135995
135996
135997
135998

135999
136000
136001
136002
136003
136004
136005
      int cnt = 0;     /* Number of entries in aRoot[] */
      int mxIdx = 0;   /* Maximum number of indexes for any table */

      if( OMIT_TEMPDB && i==1 ) continue;
      if( iDb>=0 && i!=iDb ) continue;

      sqlite3CodeVerifySchema(pParse, i);


      /* Do an integrity check of the B-Tree
      **
      ** Begin by finding the root pages numbers
      ** for all tables and indices in the database.
      */
      assert( sqlite3SchemaMutexHeld(db, i, 0) );







>







136697
136698
136699
136700
136701
136702
136703
136704
136705
136706
136707
136708
136709
136710
136711
      int cnt = 0;     /* Number of entries in aRoot[] */
      int mxIdx = 0;   /* Maximum number of indexes for any table */

      if( OMIT_TEMPDB && i==1 ) continue;
      if( iDb>=0 && i!=iDb ) continue;

      sqlite3CodeVerifySchema(pParse, i);
      pParse->okConstFactor = 0;  /* tag-20230327-1 */

      /* Do an integrity check of the B-Tree
      **
      ** Begin by finding the root pages numbers
      ** for all tables and indices in the database.
      */
      assert( sqlite3SchemaMutexHeld(db, i, 0) );
136027
136028
136029
136030
136031
136032
136033
136034
136035
136036
136037
136038
136039
136040
136041
        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
          aRoot[++cnt] = pIdx->tnum;
        }
      }
      aRoot[0] = cnt;

      /* Make sure sufficient number of registers have been allocated */
      pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
      sqlite3ClearTempRegCache(pParse);

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







|







136733
136734
136735
136736
136737
136738
136739
136740
136741
136742
136743
136744
136745
136746
136747
        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
          aRoot[++cnt] = pIdx->tnum;
        }
      }
      aRoot[0] = cnt;

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

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

136184


136185









136186

136187
136188
136189
136190
136191
136192

136193
136194
136195
136196
136197
136198
136199
            }
          }

          labelError = sqlite3VdbeMakeLabel(pParse);
          labelOk = sqlite3VdbeMakeLabel(pParse);
          if( pCol->notNull ){
            /* (1) NOT NULL columns may not contain a NULL */

            int jmp2 = sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);


            sqlite3VdbeChangeP5(v, 0x0f);









            VdbeCoverage(v);

            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
                                pCol->zCnName);
            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
            if( doTypeCheck ){
              sqlite3VdbeGoto(v, labelError);
              sqlite3VdbeJumpHere(v, jmp2);

            }else{
              /* VDBE byte code will fall thru */
            }
          }
          if( bStrict && doTypeCheck ){
            /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
            static unsigned char aStdTypeMask[] = {







>

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






>







136883
136884
136885
136886
136887
136888
136889
136890
136891
136892
136893
136894
136895
136896
136897
136898
136899
136900
136901
136902
136903
136904
136905
136906
136907
136908
136909
136910
136911
136912
136913
136914
136915
136916
136917
136918
136919
            }
          }

          labelError = sqlite3VdbeMakeLabel(pParse);
          labelOk = sqlite3VdbeMakeLabel(pParse);
          if( pCol->notNull ){
            /* (1) NOT NULL columns may not contain a NULL */
            int jmp3;
            int jmp2 = sqlite3VdbeAddOp4Int(v, OP_IsType, p1, labelOk, p3, p4);
            VdbeCoverage(v);
            if( p1<0 ){
              sqlite3VdbeChangeP5(v, 0x0f); /* INT, REAL, TEXT, or BLOB */
              jmp3 = jmp2;
            }else{
              sqlite3VdbeChangeP5(v, 0x0d); /* INT, TEXT, or BLOB */
              /* OP_IsType does not detect NaN values in the database file
              ** which should be treated as a NULL.  So if the header type
              ** is REAL, we have to load the actual data using OP_Column
              ** to reliably determine if the value is a NULL. */
              sqlite3VdbeAddOp3(v, OP_Column, p1, p3, 3);
              jmp3 = sqlite3VdbeAddOp2(v, OP_NotNull, 3, labelOk);
              VdbeCoverage(v);
            }
            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
                                pCol->zCnName);
            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
            if( doTypeCheck ){
              sqlite3VdbeGoto(v, labelError);
              sqlite3VdbeJumpHere(v, jmp2);
              sqlite3VdbeJumpHere(v, jmp3);
            }else{
              /* VDBE byte code will fall thru */
            }
          }
          if( bStrict && doTypeCheck ){
            /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
            static unsigned char aStdTypeMask[] = {
136293
136294
136295
136296
136297
136298
136299
136300
136301
136302
136303
136304
136305
136306
136307
            ** that extracts the rowid off the end of the index record.
            ** But it only works correctly if index record does not have
            ** any extra bytes at the end.  Verify that this is the case. */
            if( HasRowid(pTab) ){
              int jmp7;
              sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur+j, 3);
              jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
              VdbeCoverage(v);
              sqlite3VdbeLoadString(v, 3,
                 "rowid not at end-of-record for row ");
              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
              sqlite3VdbeLoadString(v, 4, " of index ");
              sqlite3VdbeGoto(v, jmp5-1);
              sqlite3VdbeJumpHere(v, jmp7);
            }







|







137013
137014
137015
137016
137017
137018
137019
137020
137021
137022
137023
137024
137025
137026
137027
            ** that extracts the rowid off the end of the index record.
            ** But it only works correctly if index record does not have
            ** any extra bytes at the end.  Verify that this is the case. */
            if( HasRowid(pTab) ){
              int jmp7;
              sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur+j, 3);
              jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
              VdbeCoverageNeverNull(v);
              sqlite3VdbeLoadString(v, 3,
                 "rowid not at end-of-record for row ");
              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
              sqlite3VdbeLoadString(v, 4, " of index ");
              sqlite3VdbeGoto(v, jmp5-1);
              sqlite3VdbeJumpHere(v, jmp7);
            }
137499
137500
137501
137502
137503
137504
137505
137506


137507
137508
137509
137510
137511
137512
137513
#ifndef SQLITE_OMIT_UTF16
      /* If opening the main database, set ENC(db). */
      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
      if( encoding==0 ) encoding = SQLITE_UTF8;
#else
      encoding = SQLITE_UTF8;
#endif
      if( db->nVdbeActive>0 && encoding!=ENC(db) ){


        rc = SQLITE_LOCKED;
        goto initone_error_out;
      }else{
        sqlite3SetTextEncoding(db, encoding);
      }
    }else{
      /* If opening an attached database, the encoding much match ENC(db) */







|
>
>







138219
138220
138221
138222
138223
138224
138225
138226
138227
138228
138229
138230
138231
138232
138233
138234
138235
#ifndef SQLITE_OMIT_UTF16
      /* If opening the main database, set ENC(db). */
      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
      if( encoding==0 ) encoding = SQLITE_UTF8;
#else
      encoding = SQLITE_UTF8;
#endif
      if( db->nVdbeActive>0 && encoding!=ENC(db)
       && (db->mDbFlags & DBFLAG_Vacuum)==0
      ){
        rc = SQLITE_LOCKED;
        goto initone_error_out;
      }else{
        sqlite3SetTextEncoding(db, encoding);
      }
    }else{
      /* If opening an attached database, the encoding much match ENC(db) */
137893
137894
137895
137896
137897
137898
137899

137900



137901
137902
137903
137904
137905
137906
137907
  memset(PARSE_HDR(&sParse), 0, PARSE_HDR_SZ);
  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  sParse.pOuterParse = db->pParse;
  db->pParse = &sParse;
  sParse.db = db;
  sParse.pReprepare = pReprepare;
  assert( ppStmt && *ppStmt==0 );

  if( db->mallocFailed ) sqlite3ErrorMsg(&sParse, "out of memory");



  assert( sqlite3_mutex_held(db->mutex) );

  /* For a long-term use prepared statement avoid the use of
  ** lookaside memory.
  */
  if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
    sParse.disableLookaside++;







>
|
>
>
>







138615
138616
138617
138618
138619
138620
138621
138622
138623
138624
138625
138626
138627
138628
138629
138630
138631
138632
138633
  memset(PARSE_HDR(&sParse), 0, PARSE_HDR_SZ);
  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  sParse.pOuterParse = db->pParse;
  db->pParse = &sParse;
  sParse.db = db;
  sParse.pReprepare = pReprepare;
  assert( ppStmt && *ppStmt==0 );
  if( db->mallocFailed ){
    sqlite3ErrorMsg(&sParse, "out of memory");
    db->errCode = rc = SQLITE_NOMEM;
    goto end_prepare;
  }
  assert( sqlite3_mutex_held(db->mutex) );

  /* For a long-term use prepared statement avoid the use of
  ** lookaside memory.
  */
  if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
    sParse.disableLookaside++;
138982
138983
138984
138985
138986
138987
138988
138989
138990
138991
138992
138993
138994
138995
138996
  /* Three cases:
  **   (1) The data to be sorted has already been packed into a Record
  **       by a prior OP_MakeRecord.  In this case nData==1 and regData
  **       will be completely unrelated to regOrigData.
  **   (2) All output columns are included in the sort record.  In that
  **       case regData==regOrigData.
  **   (3) Some output columns are omitted from the sort record due to
  **       the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
  **       SQLITE_ECEL_OMITREF optimization, or due to the
  **       SortCtx.pDeferredRowLoad optimiation.  In any of these cases
  **       regOrigData is 0 to prevent this routine from trying to copy
  **       values that might not yet exist.
  */
  assert( nData==1 || regData==regOrigData || regOrigData==0 );








|







139708
139709
139710
139711
139712
139713
139714
139715
139716
139717
139718
139719
139720
139721
139722
  /* Three cases:
  **   (1) The data to be sorted has already been packed into a Record
  **       by a prior OP_MakeRecord.  In this case nData==1 and regData
  **       will be completely unrelated to regOrigData.
  **   (2) All output columns are included in the sort record.  In that
  **       case regData==regOrigData.
  **   (3) Some output columns are omitted from the sort record due to
  **       the SQLITE_ENABLE_SORTER_REFERENCES optimization, or due to the
  **       SQLITE_ECEL_OMITREF optimization, or due to the
  **       SortCtx.pDeferredRowLoad optimiation.  In any of these cases
  **       regOrigData is 0 to prevent this routine from trying to copy
  **       values that might not yet exist.
  */
  assert( nData==1 || regData==regOrigData || regOrigData==0 );

140583
140584
140585
140586
140587
140588
140589
140590
140591
140592
140593
140594
140595
140596
140597
  struct ExprList_item *a;
  NameContext sNC;

  assert( pSelect!=0 );
  assert( (pSelect->selFlags & SF_Resolved)!=0 );
  assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
  assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
  if( db->mallocFailed ) return;
  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  a = pSelect->pEList->a;
  memset(&sNC, 0, sizeof(sNC));
  sNC.pSrcList = pSelect->pSrc;
  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
    const char *zType;
    i64 n;







|







141309
141310
141311
141312
141313
141314
141315
141316
141317
141318
141319
141320
141321
141322
141323
  struct ExprList_item *a;
  NameContext sNC;

  assert( pSelect!=0 );
  assert( (pSelect->selFlags & SF_Resolved)!=0 );
  assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
  assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
  if( db->mallocFailed || IN_RENAME_OBJECT ) return;
  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  a = pSelect->pEList->a;
  memset(&sNC, 0, sizeof(sNC));
  sNC.pSrcList = pSelect->pSrc;
  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
    const char *zType;
    i64 n;
140628
140629
140630
140631
140632
140633
140634
140635
140636
140637
140638
140639
140640

140641
140642
140643
140644
140645
140646
140647
140648
140649
140650
140651
140652
140653
        zType = 0;
        for(j=1; j<SQLITE_N_STDTYPE; j++){
          if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
            zType = sqlite3StdType[j];
            break;
          }
        }
       }
     }
     if( zType ){
       i64 m = sqlite3Strlen30(zType);
       n = sqlite3Strlen30(pCol->zCnName);
       pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);

       if( pCol->zCnName ){
         memcpy(&pCol->zCnName[n+1], zType, m+1);
         pCol->colFlags |= COLFLAG_HASTYPE;
       }else{
         testcase( pCol->colFlags & COLFLAG_HASTYPE );
        pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
      }
    }
    pColl = sqlite3ExprCollSeq(pParse, p);
    if( pColl ){
      assert( pTab->pIndex==0 );
      sqlite3ColumnSetColl(db, pCol, pColl->zName);
    }







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







141354
141355
141356
141357
141358
141359
141360
141361
141362
141363
141364
141365
141366
141367
141368
141369
141370



141371
141372
141373
141374
141375
141376
141377
        zType = 0;
        for(j=1; j<SQLITE_N_STDTYPE; j++){
          if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
            zType = sqlite3StdType[j];
            break;
          }
        }
      }
    }
    if( zType ){
      i64 m = sqlite3Strlen30(zType);
      n = sqlite3Strlen30(pCol->zCnName);
      pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);
      pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
      if( pCol->zCnName ){
        memcpy(&pCol->zCnName[n+1], zType, m+1);
        pCol->colFlags |= COLFLAG_HASTYPE;



      }
    }
    pColl = sqlite3ExprCollSeq(pParse, p);
    if( pColl ){
      assert( pTab->pIndex==0 );
      sqlite3ColumnSetColl(db, pCol, pColl->zName);
    }
142127
142128
142129
142130
142131
142132
142133
142134


142135
142136
142137
142138
142139
142140
142141
      Expr ifNullRow;
      assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
      assert( pExpr->pRight==0 );
      if( sqlite3ExprIsVector(pCopy) ){
        sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
      }else{
        sqlite3 *db = pSubst->pParse->db;
        if( pSubst->isOuterJoin ){


          memset(&ifNullRow, 0, sizeof(ifNullRow));
          ifNullRow.op = TK_IF_NULL_ROW;
          ifNullRow.pLeft = pCopy;
          ifNullRow.iTable = pSubst->iNewTable;
          ifNullRow.iColumn = -99;
          ifNullRow.flags = EP_IfNullRow;
          pCopy = &ifNullRow;







|
>
>







142851
142852
142853
142854
142855
142856
142857
142858
142859
142860
142861
142862
142863
142864
142865
142866
142867
      Expr ifNullRow;
      assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
      assert( pExpr->pRight==0 );
      if( sqlite3ExprIsVector(pCopy) ){
        sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
      }else{
        sqlite3 *db = pSubst->pParse->db;
        if( pSubst->isOuterJoin
         && (pCopy->op!=TK_COLUMN || pCopy->iTable!=pSubst->iNewTable)
        ){
          memset(&ifNullRow, 0, sizeof(ifNullRow));
          ifNullRow.op = TK_IF_NULL_ROW;
          ifNullRow.pLeft = pCopy;
          ifNullRow.iTable = pSubst->iNewTable;
          ifNullRow.iColumn = -99;
          ifNullRow.flags = EP_IfNullRow;
          pCopy = &ifNullRow;
142504
142505
142506
142507
142508
142509
142510
142511
142512
142513
142514
142515
142516
142517
142518
142519
**              (17d2) DISTINCT
**        (17e) the subquery may not contain window functions, and
**        (17f) the subquery must not be the RHS of a LEFT JOIN.
**        (17g) either the subquery is the first element of the outer
**              query or there are no RIGHT or FULL JOINs in any arm
**              of the subquery.  (This is a duplicate of condition (27b).)
**        (17h) The corresponding result set expressions in all arms of the
**              compound must have the same affinity. (See restriction (9)
**              on the push-down optimization.)
**
**        The parent and sub-query may contain WHERE clauses. Subject to
**        rules (11), (13) and (14), they may also contain ORDER BY,
**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
**        operator other than UNION ALL because all the other compound
**        operators have an implied DISTINCT which is disallowed by
**        restriction (4).







|
<







143230
143231
143232
143233
143234
143235
143236
143237

143238
143239
143240
143241
143242
143243
143244
**              (17d2) DISTINCT
**        (17e) the subquery may not contain window functions, and
**        (17f) the subquery must not be the RHS of a LEFT JOIN.
**        (17g) either the subquery is the first element of the outer
**              query or there are no RIGHT or FULL JOINs in any arm
**              of the subquery.  (This is a duplicate of condition (27b).)
**        (17h) The corresponding result set expressions in all arms of the
**              compound must have the same affinity.

**
**        The parent and sub-query may contain WHERE clauses. Subject to
**        rules (11), (13) and (14), they may also contain ORDER BY,
**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
**        operator other than UNION ALL because all the other compound
**        operators have an implied DISTINCT which is disallowed by
**        restriction (4).
143373
143374
143375
143376
143377
143378
143379





143380

143381
143382
143383








143384
143385
143386
143387
143388
143389
143390
143391

143392
143393
143394

143395

143396
143397


143398


143399
143400
143401
143402
143403
143404
143405
143406
143407
143408
143409
143410
143411
143412
143413
143414
143415
143416
143417
143418
143419
143420
143421
143422
143423
**       be materialized.  (This restriction is implemented in the calling
**       routine.)
**
**   (8) If the subquery is a compound that uses UNION, INTERSECT,
**       or EXCEPT, then all of the result set columns for all arms of
**       the compound must use the BINARY collating sequence.
**





**   (9) If the subquery is a compound, then all arms of the compound must

**       have the same affinity.  (This is the same as restriction (17h)
**       for query flattening.)
**








**
** Return 0 if no changes are made and non-zero if one or more WHERE clause
** terms are duplicated into the subquery.
*/
static int pushDownWhereTerms(
  Parse *pParse,        /* Parse context (for malloc() and error reporting) */
  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
  Expr *pWhere,         /* The WHERE clause of the outer query */

  SrcItem *pSrc         /* The subquery term of the outer FROM clause */
){
  Expr *pNew;

  int nChng = 0;

  if( pWhere==0 ) return 0;
  if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ) return 0;


  if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ) return 0;



  if( pSubq->pPrior ){
    Select *pSel;
    int notUnionAll = 0;
    for(pSel=pSubq; pSel; pSel=pSel->pPrior){
      u8 op = pSel->op;
      assert( op==TK_ALL || op==TK_SELECT
           || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
      if( op!=TK_ALL && op!=TK_SELECT ){
        notUnionAll = 1;
      }
#ifndef SQLITE_OMIT_WINDOWFUNC
      if( pSel->pWin ) return 0;    /* restriction (6b) */
#endif
    }
    if( compoundHasDifferentAffinities(pSubq) ){
      return 0;  /* restriction (9) */
    }
    if( notUnionAll ){
      /* If any of the compound arms are connected using UNION, INTERSECT,
      ** or EXCEPT, then we must ensure that none of the columns use a
      ** non-BINARY collating sequence. */
      for(pSel=pSubq; pSel; pSel=pSel->pPrior){
        int ii;
        const ExprList *pList = pSel->pEList;







>
>
>
>
>
|
>
|
|

>
>
>
>
>
>
>
>








>
|


>

>

|
>
>
|
>
>















<
<
<







144098
144099
144100
144101
144102
144103
144104
144105
144106
144107
144108
144109
144110
144111
144112
144113
144114
144115
144116
144117
144118
144119
144120
144121
144122
144123
144124
144125
144126
144127
144128
144129
144130
144131
144132
144133
144134
144135
144136
144137
144138
144139
144140
144141
144142
144143
144144
144145
144146
144147
144148
144149
144150
144151
144152
144153
144154
144155
144156
144157
144158
144159



144160
144161
144162
144163
144164
144165
144166
**       be materialized.  (This restriction is implemented in the calling
**       routine.)
**
**   (8) If the subquery is a compound that uses UNION, INTERSECT,
**       or EXCEPT, then all of the result set columns for all arms of
**       the compound must use the BINARY collating sequence.
**
**   (9) All three of the following are true:
**
**       (9a) The WHERE clause expression originates in the ON or USING clause
**            of a join (either an INNER or an OUTER join), and
**
**       (9b) The subquery is to the right of the ON/USING clause
**
**       (9c) There is a RIGHT JOIN (or FULL JOIN) in between the ON/USING
**            clause and the subquery.
**
**       Without this restriction, the push-down optimization might move
**       the ON/USING filter expression from the left side of a RIGHT JOIN
**       over to the right side, which leads to incorrect answers.  See
**       also restriction (6) in sqlite3ExprIsSingleTableConstraint().
**
**  (10) The inner query is not the right-hand table of a RIGHT JOIN.
**
**  (11) The subquery is not a VALUES clause
**
** Return 0 if no changes are made and non-zero if one or more WHERE clause
** terms are duplicated into the subquery.
*/
static int pushDownWhereTerms(
  Parse *pParse,        /* Parse context (for malloc() and error reporting) */
  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
  Expr *pWhere,         /* The WHERE clause of the outer query */
  SrcList *pSrcList,    /* The complete from clause of the outer query */
  int iSrc              /* Which FROM clause term to try to push into  */
){
  Expr *pNew;
  SrcItem *pSrc;        /* The subquery FROM term into which WHERE is pushed */
  int nChng = 0;
  pSrc = &pSrcList->a[iSrc];
  if( pWhere==0 ) return 0;
  if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ){
    return 0;           /* restrictions (2) and (11) */
  }
  if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ){
    return 0;           /* restrictions (10) */
  }

  if( pSubq->pPrior ){
    Select *pSel;
    int notUnionAll = 0;
    for(pSel=pSubq; pSel; pSel=pSel->pPrior){
      u8 op = pSel->op;
      assert( op==TK_ALL || op==TK_SELECT
           || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
      if( op!=TK_ALL && op!=TK_SELECT ){
        notUnionAll = 1;
      }
#ifndef SQLITE_OMIT_WINDOWFUNC
      if( pSel->pWin ) return 0;    /* restriction (6b) */
#endif
    }



    if( notUnionAll ){
      /* If any of the compound arms are connected using UNION, INTERSECT,
      ** or EXCEPT, then we must ensure that none of the columns use a
      ** non-BINARY collating sequence. */
      for(pSel=pSubq; pSel; pSel=pSel->pPrior){
        int ii;
        const ExprList *pList = pSel->pEList;
143449
143450
143451
143452
143453
143454
143455
143456
143457
143458
143459
143460

















143461
143462
143463
143464
143465
143466
143467
143468
143469
143470
143471
143472
143473
143474
143475
143476
143477
143478
143479
143480
143481
  }
#endif

  if( pSubq->pLimit!=0 ){
    return 0; /* restriction (3) */
  }
  while( pWhere->op==TK_AND ){
    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrc);
    pWhere = pWhere->pLeft;
  }

#if 0  /* Legacy code. Checks now done by sqlite3ExprIsTableConstraint() */

















  if( isLeftJoin
   && (ExprHasProperty(pWhere,EP_OuterON)==0
         || pWhere->w.iJoin!=iCursor)
  ){
    return 0; /* restriction (4) */
  }
  if( ExprHasProperty(pWhere,EP_OuterON)
   && pWhere->w.iJoin!=iCursor
  ){
    return 0; /* restriction (5) */
  }
#endif

  if( sqlite3ExprIsTableConstraint(pWhere, pSrc) ){
    nChng++;
    pSubq->selFlags |= SF_PushDown;
    while( pSubq ){
      SubstContext x;
      pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
      unsetJoinExpr(pNew, -1, 1);
      x.pParse = pParse;







|



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













|







144192
144193
144194
144195
144196
144197
144198
144199
144200
144201
144202
144203
144204
144205
144206
144207
144208
144209
144210
144211
144212
144213
144214
144215
144216
144217
144218
144219
144220
144221
144222
144223
144224
144225
144226
144227
144228
144229
144230
144231
144232
144233
144234
144235
144236
144237
144238
144239
144240
144241
  }
#endif

  if( pSubq->pLimit!=0 ){
    return 0; /* restriction (3) */
  }
  while( pWhere->op==TK_AND ){
    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrcList, iSrc);
    pWhere = pWhere->pLeft;
  }

#if 0 /* These checks now done by sqlite3ExprIsSingleTableConstraint() */
  if( ExprHasProperty(pWhere, EP_OuterON|EP_InnerON) /* (9a) */
   && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0     /* Fast pre-test of (9c) */
  ){
    int jj;
    for(jj=0; jj<iSrc; jj++){
      if( pWhere->w.iJoin==pSrcList->a[jj].iCursor ){
        /* If we reach this point, both (9a) and (9b) are satisfied.
        ** The following loop checks (9c):
        */
        for(jj++; jj<iSrc; jj++){
          if( (pSrcList->a[jj].fg.jointype & JT_RIGHT)!=0 ){
            return 0;  /* restriction (9) */
          }
        }
      }
    }
  }
  if( isLeftJoin
   && (ExprHasProperty(pWhere,EP_OuterON)==0
         || pWhere->w.iJoin!=iCursor)
  ){
    return 0; /* restriction (4) */
  }
  if( ExprHasProperty(pWhere,EP_OuterON)
   && pWhere->w.iJoin!=iCursor
  ){
    return 0; /* restriction (5) */
  }
#endif

  if( sqlite3ExprIsSingleTableConstraint(pWhere, pSrcList, iSrc) ){
    nChng++;
    pSubq->selFlags |= SF_PushDown;
    while( pSubq ){
      SubstContext x;
      pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
      unsetJoinExpr(pNew, -1, 1);
      x.pParse = pParse;
143500
143501
143502
143503
143504
143505
143506








































































143507
143508
143509
143510
143511
143512
143513
      }
      pSubq = pSubq->pPrior;
    }
  }
  return nChng;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */









































































/*
** The pFunc is the only aggregate function in the query.  Check to see
** if the query is a candidate for the min/max optimization.
**
** If the query is a candidate for the min/max optimization, then set
** *ppMinMax to be an ORDER BY clause to be used for the optimization







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







144260
144261
144262
144263
144264
144265
144266
144267
144268
144269
144270
144271
144272
144273
144274
144275
144276
144277
144278
144279
144280
144281
144282
144283
144284
144285
144286
144287
144288
144289
144290
144291
144292
144293
144294
144295
144296
144297
144298
144299
144300
144301
144302
144303
144304
144305
144306
144307
144308
144309
144310
144311
144312
144313
144314
144315
144316
144317
144318
144319
144320
144321
144322
144323
144324
144325
144326
144327
144328
144329
144330
144331
144332
144333
144334
144335
144336
144337
144338
144339
144340
144341
144342
144343
144344
144345
      }
      pSubq = pSubq->pPrior;
    }
  }
  return nChng;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */

/*
** Check to see if a subquery contains result-set columns that are
** never used.  If it does, change the value of those result-set columns
** to NULL so that they do not cause unnecessary work to compute.
**
** Return the number of column that were changed to NULL.
*/
static int disableUnusedSubqueryResultColumns(SrcItem *pItem){
  int nCol;
  Select *pSub;      /* The subquery to be simplified */
  Select *pX;        /* For looping over compound elements of pSub */
  Table *pTab;       /* The table that describes the subquery */
  int j;             /* Column number */
  int nChng = 0;     /* Number of columns converted to NULL */
  Bitmask colUsed;   /* Columns that may not be NULLed out */

  assert( pItem!=0 );
  if( pItem->fg.isCorrelated || pItem->fg.isCte ){
    return 0;
  }
  assert( pItem->pTab!=0 );
  pTab = pItem->pTab;
  assert( pItem->pSelect!=0 );
  pSub = pItem->pSelect;
  assert( pSub->pEList->nExpr==pTab->nCol );
  if( (pSub->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
    testcase( pSub->selFlags & SF_Distinct );
    testcase( pSub->selFlags & SF_Aggregate );
    return 0;
  }
  for(pX=pSub; pX; pX=pX->pPrior){
    if( pX->pPrior && pX->op!=TK_ALL ){
      /* This optimization does not work for compound subqueries that
      ** use UNION, INTERSECT, or EXCEPT.  Only UNION ALL is allowed. */
      return 0;
    }
#ifndef SQLITE_OMIT_WINDOWFUNC
    if( pX->pWin ){
      /* This optimization does not work for subqueries that use window
      ** functions. */
      return 0;
    }
#endif
  }
  colUsed = pItem->colUsed;
  if( pSub->pOrderBy ){
    ExprList *pList = pSub->pOrderBy;
    for(j=0; j<pList->nExpr; j++){
      u16 iCol = pList->a[j].u.x.iOrderByCol;
      if( iCol>0 ){
        iCol--;
        colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
      }
    }
  }
  nCol = pTab->nCol;
  for(j=0; j<nCol; j++){
    Bitmask m = j<BMS-1 ? MASKBIT(j) : TOPBIT;
    if( (m & colUsed)!=0 ) continue;
    for(pX=pSub; pX; pX=pX->pPrior) {
      Expr *pY = pX->pEList->a[j].pExpr;
      if( pY->op==TK_NULL ) continue;
      pY->op = TK_NULL;
      ExprClearProperty(pY, EP_Skip|EP_Unlikely);
      pX->selFlags |= SF_PushDown;
      nChng++;
    }
  }
  return nChng;
}


/*
** The pFunc is the only aggregate function in the query.  Check to see
** if the query is a candidate for the min/max optimization.
**
** If the query is a candidate for the min/max optimization, then set
** *ppMinMax to be an ORDER BY clause to be used for the optimization
144647
144648
144649
144650
144651
144652
144653
144654
144655
144656

144657
144658

144659

144660
144661
144662
144663
144664
144665
144666
  NameContext *pNC        /* Name context used to resolve agg-func args */
){
  assert( pAggInfo->iFirstReg==0 );
  assert( pSelect!=0 );
  assert( pSelect->pGroupBy!=0 );
  pAggInfo->nColumn = pAggInfo->nAccumulator;
  if( ALWAYS(pAggInfo->nSortingColumn>0) ){
    if( pAggInfo->nColumn==0 ){
      pAggInfo->nSortingColumn = pSelect->pGroupBy->nExpr;
    }else{

      pAggInfo->nSortingColumn =
        pAggInfo->aCol[pAggInfo->nColumn-1].iSorterColumn+1;

    }

  }
  analyzeAggFuncArgs(pAggInfo, pNC);
#if TREETRACE_ENABLED
  if( sqlite3TreeTrace & 0x20 ){
    IndexedExpr *pIEpr;
    TREETRACE(0x20, pParse, pSelect,
        ("AggInfo (possibly) adjusted for Indexed Exprs\n"));







<
|
<
>
|
|
>

>







145479
145480
145481
145482
145483
145484
145485

145486

145487
145488
145489
145490
145491
145492
145493
145494
145495
145496
145497
145498
145499
  NameContext *pNC        /* Name context used to resolve agg-func args */
){
  assert( pAggInfo->iFirstReg==0 );
  assert( pSelect!=0 );
  assert( pSelect->pGroupBy!=0 );
  pAggInfo->nColumn = pAggInfo->nAccumulator;
  if( ALWAYS(pAggInfo->nSortingColumn>0) ){

    int mx = pSelect->pGroupBy->nExpr - 1;

    int j, k;
    for(j=0; j<pAggInfo->nColumn; j++){
      k = pAggInfo->aCol[j].iSorterColumn;
      if( k>mx ) mx = k;
    }
    pAggInfo->nSortingColumn = mx+1;
  }
  analyzeAggFuncArgs(pAggInfo, pNC);
#if TREETRACE_ENABLED
  if( sqlite3TreeTrace & 0x20 ){
    IndexedExpr *pIEpr;
    TREETRACE(0x20, pParse, pSelect,
        ("AggInfo (possibly) adjusted for Indexed Exprs\n"));
144686
144687
144688
144689
144690
144691
144692

144693
144694
144695
144696
144697

144698
144699
144700
144701
144702
144703
144704
  struct AggInfo_col *pCol;
  UNUSED_PARAMETER(pWalker);
  if( pExpr->pAggInfo==0 ) return WRC_Continue;
  if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
  if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
  if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
  pAggInfo = pExpr->pAggInfo;

  assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
  pCol = &pAggInfo->aCol[pExpr->iAgg];
  pExpr->op = TK_AGG_COLUMN;
  pExpr->iTable = pCol->iTable;
  pExpr->iColumn = pCol->iColumn;

  return WRC_Prune;
}

/*
** Convert every pAggInfo->aFunc[].pExpr such that any node within
** those expressions that has pAppInfo set is changed into a TK_AGG_COLUMN
** opcode.







>
|




>







145519
145520
145521
145522
145523
145524
145525
145526
145527
145528
145529
145530
145531
145532
145533
145534
145535
145536
145537
145538
145539
  struct AggInfo_col *pCol;
  UNUSED_PARAMETER(pWalker);
  if( pExpr->pAggInfo==0 ) return WRC_Continue;
  if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
  if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
  if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
  pAggInfo = pExpr->pAggInfo;
  if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ) return WRC_Continue;
  assert( pExpr->iAgg>=0 );
  pCol = &pAggInfo->aCol[pExpr->iAgg];
  pExpr->op = TK_AGG_COLUMN;
  pExpr->iTable = pCol->iTable;
  pExpr->iColumn = pCol->iColumn;
  ExprClearProperty(pExpr, EP_Skip|EP_Collate);
  return WRC_Prune;
}

/*
** Convert every pAggInfo->aFunc[].pExpr such that any node within
** those expressions that has pAppInfo set is changed into a TK_AGG_COLUMN
** opcode.
145044
145045
145046
145047
145048
145049
145050
145051
145052
145053
145054
145055
145056
145057
145058
*/
static void agginfoFree(sqlite3 *db, AggInfo *p){
  sqlite3DbFree(db, p->aCol);
  sqlite3DbFree(db, p->aFunc);
  sqlite3DbFreeNN(db, p);
}

#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
/*
** Attempt to transform a query of the form
**
**    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
**
** Into this:
**







<







145879
145880
145881
145882
145883
145884
145885

145886
145887
145888
145889
145890
145891
145892
*/
static void agginfoFree(sqlite3 *db, AggInfo *p){
  sqlite3DbFree(db, p->aCol);
  sqlite3DbFree(db, p->aFunc);
  sqlite3DbFreeNN(db, p);
}


/*
** Attempt to transform a query of the form
**
**    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
**
** Into this:
**
145072
145073
145074
145075
145076
145077
145078

145079
145080
145081
145082
145083
145084
145085
145086
145087
145088
145089
145090
145091
145092
145093
145094
145095
145096
145097

145098
145099
145100
145101
145102
145103
145104
145105
  Select *pSub, *pPrior;
  Expr *pExpr;
  Expr *pCount;
  sqlite3 *db;
  if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
  if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
  if( p->pWhere ) return 0;

  if( p->pGroupBy ) return 0;
  if( p->pOrderBy ) return 0;
  pExpr = p->pEList->a[0].pExpr;
  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
  assert( ExprUseUToken(pExpr) );
  if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
  assert( ExprUseXList(pExpr) );
  if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
  if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
  if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
  pSub = p->pSrc->a[0].pSelect;
  if( pSub==0 ) return 0;                           /* The FROM is a subquery */
  if( pSub->pPrior==0 ) return 0;                   /* Must be a compound */
  if( pSub->selFlags & SF_CopyCte ) return 0;       /* Not a CTE */
  do{
    if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
    if( pSub->pWhere ) return 0;                      /* No WHERE clause */
    if( pSub->pLimit ) return 0;                      /* No LIMIT clause */
    if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */

    pSub = pSub->pPrior;                              /* Repeat over compound */
  }while( pSub );

  /* If we reach this point then it is OK to perform the transformation */

  db = pParse->db;
  pCount = pExpr;
  pExpr = 0;







>



















>
|







145906
145907
145908
145909
145910
145911
145912
145913
145914
145915
145916
145917
145918
145919
145920
145921
145922
145923
145924
145925
145926
145927
145928
145929
145930
145931
145932
145933
145934
145935
145936
145937
145938
145939
145940
145941
  Select *pSub, *pPrior;
  Expr *pExpr;
  Expr *pCount;
  sqlite3 *db;
  if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
  if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
  if( p->pWhere ) return 0;
  if( p->pHaving ) return 0;
  if( p->pGroupBy ) return 0;
  if( p->pOrderBy ) return 0;
  pExpr = p->pEList->a[0].pExpr;
  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
  assert( ExprUseUToken(pExpr) );
  if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
  assert( ExprUseXList(pExpr) );
  if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
  if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
  if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
  pSub = p->pSrc->a[0].pSelect;
  if( pSub==0 ) return 0;                           /* The FROM is a subquery */
  if( pSub->pPrior==0 ) return 0;                   /* Must be a compound */
  if( pSub->selFlags & SF_CopyCte ) return 0;       /* Not a CTE */
  do{
    if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
    if( pSub->pWhere ) return 0;                      /* No WHERE clause */
    if( pSub->pLimit ) return 0;                      /* No LIMIT clause */
    if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
    assert( pSub->pHaving==0 );  /* Due to the previous */
   pSub = pSub->pPrior;                              /* Repeat over compound */
  }while( pSub );

  /* If we reach this point then it is OK to perform the transformation */

  db = pParse->db;
  pCount = pExpr;
  pExpr = 0;
145134
145135
145136
145137
145138
145139
145140
145141
145142
145143
145144
145145
145146
145147
145148
  if( sqlite3TreeTrace & 0x200 ){
    TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
    sqlite3TreeViewSelect(0, p, 0);
  }
#endif
  return 1;
}
#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */

/*
** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
** as pSrcItem but has the same alias as p0, then return true.
** Otherwise return false.
*/
static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){







<







145970
145971
145972
145973
145974
145975
145976

145977
145978
145979
145980
145981
145982
145983
  if( sqlite3TreeTrace & 0x200 ){
    TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
    sqlite3TreeViewSelect(0, p, 0);
  }
#endif
  return 1;
}


/*
** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
** as pSrcItem but has the same alias as p0, then return true.
** Otherwise return false.
*/
static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){
145390
145391
145392
145393
145394
145395
145396
145397
145398
145399
145400
145401
145402
145403
145404
                ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
      pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
      assert( pItem->iCursor>=0 );
      unsetJoinExpr(p->pWhere, pItem->iCursor,
                    pTabList->a[0].fg.jointype & JT_LTORJ);
    }

    /* No futher action if this term of the FROM clause is no a subquery */
    if( pSub==0 ) continue;

    /* Catch mismatch in the declared columns of a view and the number of
    ** columns in the SELECT on the RHS */
    if( pTab->nCol!=pSub->pEList->nExpr ){
      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);







|







146225
146226
146227
146228
146229
146230
146231
146232
146233
146234
146235
146236
146237
146238
146239
                ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
      pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
      assert( pItem->iCursor>=0 );
      unsetJoinExpr(p->pWhere, pItem->iCursor,
                    pTabList->a[0].fg.jointype & JT_LTORJ);
    }

    /* No futher action if this term of the FROM clause is not a subquery */
    if( pSub==0 ) continue;

    /* Catch mismatch in the declared columns of a view and the number of
    ** columns in the SELECT on the RHS */
    if( pTab->nCol!=pSub->pEList->nExpr ){
      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
145523
145524
145525
145526
145527
145528
145529
145530
145531
145532
145533
145534
145535
145536
145537
145538
145539
145540
145541
145542
145543
145544
      sqlite3TreeViewSelect(0, p, 0);
    }
#endif
  }else{
    TREETRACE(0x2000,pParse,p,("Constant propagation not helpful\n"));
  }

#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
   && countOfViewOptimization(pParse, p)
  ){
    if( db->mallocFailed ) goto select_end;
    pTabList = p->pSrc;
  }
#endif

  /* For each term in the FROM clause, do two things:
  ** (1) Authorized unreferenced tables
  ** (2) Generate code for all sub-queries
  */
  for(i=0; i<pTabList->nSrc; i++){
    SrcItem *pItem = &pTabList->a[i];







<






<







146358
146359
146360
146361
146362
146363
146364

146365
146366
146367
146368
146369
146370

146371
146372
146373
146374
146375
146376
146377
      sqlite3TreeViewSelect(0, p, 0);
    }
#endif
  }else{
    TREETRACE(0x2000,pParse,p,("Constant propagation not helpful\n"));
  }


  if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
   && countOfViewOptimization(pParse, p)
  ){
    if( db->mallocFailed ) goto select_end;
    pTabList = p->pSrc;
  }


  /* For each term in the FROM clause, do two things:
  ** (1) Authorized unreferenced tables
  ** (2) Generate code for all sub-queries
  */
  for(i=0; i<pTabList->nSrc; i++){
    SrcItem *pItem = &pTabList->a[i];
145589
145590
145591
145592
145593
145594
145595
145596
145597
145598
145599
145600
145601
145602
145603
145604
145605
145606
145607
145608
















145609
145610
145611
145612
145613
145614
145615

    /* Make copies of constant WHERE-clause terms in the outer query down
    ** inside the subquery.  This can help the subquery to run more efficiently.
    */
    if( OptimizationEnabled(db, SQLITE_PushDown)
     && (pItem->fg.isCte==0
         || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
     && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem)
    ){
#if TREETRACE_ENABLED
      if( sqlite3TreeTrace & 0x4000 ){
        TREETRACE(0x4000,pParse,p,
            ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
        sqlite3TreeViewSelect(0, p, 0);
      }
#endif
      assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
    }else{
      TREETRACE(0x4000,pParse,p,("Push-down not possible\n"));
    }

















    zSavedAuthContext = pParse->zAuthContext;
    pParse->zAuthContext = pItem->zName;

    /* Generate code to implement the subquery
    */
    if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){







|












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







146422
146423
146424
146425
146426
146427
146428
146429
146430
146431
146432
146433
146434
146435
146436
146437
146438
146439
146440
146441
146442
146443
146444
146445
146446
146447
146448
146449
146450
146451
146452
146453
146454
146455
146456
146457
146458
146459
146460
146461
146462
146463
146464

    /* Make copies of constant WHERE-clause terms in the outer query down
    ** inside the subquery.  This can help the subquery to run more efficiently.
    */
    if( OptimizationEnabled(db, SQLITE_PushDown)
     && (pItem->fg.isCte==0
         || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
     && pushDownWhereTerms(pParse, pSub, p->pWhere, pTabList, i)
    ){
#if TREETRACE_ENABLED
      if( sqlite3TreeTrace & 0x4000 ){
        TREETRACE(0x4000,pParse,p,
            ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
        sqlite3TreeViewSelect(0, p, 0);
      }
#endif
      assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
    }else{
      TREETRACE(0x4000,pParse,p,("Push-down not possible\n"));
    }

    /* Convert unused result columns of the subquery into simple NULL
    ** expressions, to avoid unneeded searching and computation.
    */
    if( OptimizationEnabled(db, SQLITE_NullUnusedCols)
     && disableUnusedSubqueryResultColumns(pItem)
    ){
#if TREETRACE_ENABLED
      if( sqlite3TreeTrace & 0x4000 ){
        TREETRACE(0x4000,pParse,p,
            ("Change unused result columns to NULL for subquery %d:\n",
             pSub->selId));
        sqlite3TreeViewSelect(0, p, 0);
      }
#endif
    }

    zSavedAuthContext = pParse->zAuthContext;
    pParse->zAuthContext = pItem->zName;

    /* Generate code to implement the subquery
    */
    if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){
146889
146890
146891
146892
146893
146894
146895

146896
146897
146898
146899
146900
146901
146902
  if( !IN_RENAME_OBJECT ){
    if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
      if( !noErr ){
        sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
      }else{
        assert( !db->init.busy );
        sqlite3CodeVerifySchema(pParse, iDb);

      }
      goto trigger_cleanup;
    }
  }

  /* Do not create a trigger on a system table */
  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){







>







147738
147739
147740
147741
147742
147743
147744
147745
147746
147747
147748
147749
147750
147751
147752
  if( !IN_RENAME_OBJECT ){
    if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
      if( !noErr ){
        sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
      }else{
        assert( !db->init.busy );
        sqlite3CodeVerifySchema(pParse, iDb);
        VVA_ONLY( pParse->ifNotExists = 1; )
      }
      goto trigger_cleanup;
    }
  }

  /* Do not create a trigger on a system table */
  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
148139
148140
148141
148142
148143
148144
148145



148146
148147
148148
148149
148150
148151
148152
  int orconf           /* Default ON CONFLICT policy for trigger steps */
){
  const int op = pChanges ? TK_UPDATE : TK_DELETE;
  u32 mask = 0;
  Trigger *p;

  assert( isNew==1 || isNew==0 );



  for(p=pTrigger; p; p=p->pNext){
    if( p->op==op
     && (tr_tm&p->tr_tm)
     && checkColumnOverlap(p->pColumns,pChanges)
    ){
      if( p->bReturning ){
        mask = 0xffffffff;







>
>
>







148989
148990
148991
148992
148993
148994
148995
148996
148997
148998
148999
149000
149001
149002
149003
149004
149005
  int orconf           /* Default ON CONFLICT policy for trigger steps */
){
  const int op = pChanges ? TK_UPDATE : TK_DELETE;
  u32 mask = 0;
  Trigger *p;

  assert( isNew==1 || isNew==0 );
  if( IsView(pTab) ){
    return 0xffffffff;
  }
  for(p=pTrigger; p; p=p->pNext){
    if( p->op==op
     && (tr_tm&p->tr_tm)
     && checkColumnOverlap(p->pColumns,pChanges)
    ){
      if( p->bReturning ){
        mask = 0xffffffff;
148573
148574
148575
148576
148577
148578
148579
148580
148581
148582
148583
148584
148585
148586
148587
    pLimit = 0;
  }
#endif

  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto update_cleanup;
  }
  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
    goto update_cleanup;
  }

  /* Allocate a cursors for the main database table and for all indices.
  ** The index cursors might not be used, but if they are used they
  ** need to occur right after the database cursor.  So go ahead and
  ** allocate enough space, just in case.







|







149426
149427
149428
149429
149430
149431
149432
149433
149434
149435
149436
149437
149438
149439
149440
    pLimit = 0;
  }
#endif

  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto update_cleanup;
  }
  if( sqlite3IsReadOnly(pParse, pTab, pTrigger) ){
    goto update_cleanup;
  }

  /* Allocate a cursors for the main database table and for all indices.
  ** The index cursors might not be used, but if they are used they
  ** need to occur right after the database cursor.  So go ahead and
  ** allocate enough space, just in case.
148892
148893
148894
148895
148896
148897
148898



148899

148900
148901
148902


148903
148904






148905
148906
148907
148908
148909
148910
148911
      eOnePass = ONEPASS_SINGLE;
      sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
      bFinishSeek = 0;
    }else{
      /* Begin the database scan.
      **
      ** Do not consider a single-pass strategy for a multi-row update if



      ** there are any triggers or foreign keys to process, or rows may

      ** be deleted as a result of REPLACE conflict handling. Any of these
      ** things might disturb a cursor being used to scan through the table
      ** or index, causing a single-pass approach to malfunction.  */


      flags = WHERE_ONEPASS_DESIRED;
      if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){






        flags |= WHERE_ONEPASS_MULTIROW;
      }
      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,0,0,flags,iIdxCur);
      if( pWInfo==0 ) goto update_cleanup;

      /* A one-pass strategy that might update more than one row may not
      ** be used if any column of the index used for the scan is being







>
>
>
|
>
|
<
<
>
>

|
>
>
>
>
>
>







149745
149746
149747
149748
149749
149750
149751
149752
149753
149754
149755
149756
149757


149758
149759
149760
149761
149762
149763
149764
149765
149766
149767
149768
149769
149770
149771
149772
149773
149774
      eOnePass = ONEPASS_SINGLE;
      sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
      bFinishSeek = 0;
    }else{
      /* Begin the database scan.
      **
      ** Do not consider a single-pass strategy for a multi-row update if
      ** there is anything that might disrupt the cursor being used to do
      ** the UPDATE:
      **   (1) This is a nested UPDATE
      **   (2) There are triggers
      **   (3) There are FOREIGN KEY constraints
      **   (4) There are REPLACE conflict handlers


      **   (5) There are subqueries in the WHERE clause
      */
      flags = WHERE_ONEPASS_DESIRED;
      if( !pParse->nested
       && !pTrigger
       && !hasFK
       && !chngKey
       && !bReplace
       && (sNC.ncFlags & NC_Subquery)==0
      ){
        flags |= WHERE_ONEPASS_MULTIROW;
      }
      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,0,0,flags,iIdxCur);
      if( pWInfo==0 ) goto update_cleanup;

      /* A one-pass strategy that might update more than one row may not
      ** be used if any column of the index used for the scan is being
150862
150863
150864
150865
150866
150867
150868

150869

150870
150871
150872
150873
150874
150875
150876
  assert( &db->pVtabCtx );
  assert( xConstruct );
  sCtx.pTab = pTab;
  sCtx.pVTable = pVTable;
  sCtx.pPrior = db->pVtabCtx;
  sCtx.bDeclared = 0;
  db->pVtabCtx = &sCtx;

  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);

  db->pVtabCtx = sCtx.pPrior;
  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  assert( sCtx.pTab==pTab );

  if( SQLITE_OK!=rc ){
    if( zErr==0 ){
      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);







>

>







151725
151726
151727
151728
151729
151730
151731
151732
151733
151734
151735
151736
151737
151738
151739
151740
151741
  assert( &db->pVtabCtx );
  assert( xConstruct );
  sCtx.pTab = pTab;
  sCtx.pVTable = pVTable;
  sCtx.pPrior = db->pVtabCtx;
  sCtx.bDeclared = 0;
  db->pVtabCtx = &sCtx;
  pTab->nTabRef++;
  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  sqlite3DeleteTable(db, pTab);
  db->pVtabCtx = sCtx.pPrior;
  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  assert( sCtx.pTab==pTab );

  if( SQLITE_OK!=rc ){
    if( zErr==0 ){
      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
151352
151353
151354
151355
151356
151357
151358


151359

151360
151361
151362
151363
151364
151365
151366
            xMethod = pMod->xRollbackTo;
            break;
          default:
            xMethod = pMod->xRelease;
            break;
        }
        if( xMethod && pVTab->iSavepoint>iSavepoint ){


          rc = xMethod(pVTab->pVtab, iSavepoint);

        }
        sqlite3VtabUnlock(pVTab);
      }
    }
  }
  return rc;
}







>
>

>







152217
152218
152219
152220
152221
152222
152223
152224
152225
152226
152227
152228
152229
152230
152231
152232
152233
152234
            xMethod = pMod->xRollbackTo;
            break;
          default:
            xMethod = pMod->xRelease;
            break;
        }
        if( xMethod && pVTab->iSavepoint>iSavepoint ){
          u64 savedFlags = (db->flags & SQLITE_Defensive);
          db->flags &= ~(u64)SQLITE_Defensive;
          rc = xMethod(pVTab->pVtab, iSavepoint);
          db->flags |= savedFlags;
        }
        sqlite3VtabUnlock(pVTab);
      }
    }
  }
  return rc;
}
151580
151581
151582
151583
151584
151585
151586




151587
151588
151589
151590
151591
151592
151593
      case SQLITE_VTAB_INNOCUOUS: {
        p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
        break;
      }
      case SQLITE_VTAB_DIRECTONLY: {
        p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
        break;




      }
      default: {
        rc = SQLITE_MISUSE_BKPT;
        break;
      }
    }
    va_end(ap);







>
>
>
>







152448
152449
152450
152451
152452
152453
152454
152455
152456
152457
152458
152459
152460
152461
152462
152463
152464
152465
      case SQLITE_VTAB_INNOCUOUS: {
        p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
        break;
      }
      case SQLITE_VTAB_DIRECTONLY: {
        p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
        break;
      }
      case SQLITE_VTAB_USES_ALL_SCHEMAS: {
        p->pVTable->bAllSchemas = 1;
        break;
      }
      default: {
        rc = SQLITE_MISUSE_BKPT;
        break;
      }
    }
    va_end(ap);
152354
152355
152356
152357
152358
152359
152360
152361
152362
152363
152364
152365
152366
152367
152368
152369
152370
152371
152372
152373
152374
152375
152376
152377
152378
152379
152380
152381
152382
152383
    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  }
  sqlite3_str_append(pStr, ")", 1);
}

/*
** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
** is added to the output to describe the table scan strategy in pLevel.
**
** If an OP_Explain opcode is added to the VM, its address is returned.
** Otherwise, if no OP_Explain is coded, zero is returned.
*/
SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  Parse *pParse,                  /* Parse context */
  SrcList *pTabList,              /* Table list this loop refers to */
  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
){
  int ret = 0;
#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  if( sqlite3ParseToplevel(pParse)->explain==2 )
#endif
  {
    SrcItem *pItem = &pTabList->a[pLevel->iFrom];
    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
    sqlite3 *db = pParse->db;     /* Database handle */
    int isSearch;                 /* True for a SEARCH. False for SCAN. */
    WhereLoop *pLoop;             /* The controlling WhereLoop object */







|
|
|











|
|







153226
153227
153228
153229
153230
153231
153232
153233
153234
153235
153236
153237
153238
153239
153240
153241
153242
153243
153244
153245
153246
153247
153248
153249
153250
153251
153252
153253
153254
153255
    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  }
  sqlite3_str_append(pStr, ")", 1);
}

/*
** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
** command, or if stmt_scanstatus_v2() stats are enabled, or if SQLITE_DEBUG
** was defined at compile-time. If it is not a no-op, a single OP_Explain
** opcode is added to the output to describe the table scan strategy in pLevel.
**
** If an OP_Explain opcode is added to the VM, its address is returned.
** Otherwise, if no OP_Explain is coded, zero is returned.
*/
SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  Parse *pParse,                  /* Parse context */
  SrcList *pTabList,              /* Table list this loop refers to */
  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
){
  int ret = 0;
#if !defined(SQLITE_DEBUG)
  if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
#endif
  {
    SrcItem *pItem = &pTabList->a[pLevel->iFrom];
    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
    sqlite3 *db = pParse->db;     /* Database handle */
    int isSearch;                 /* True for a SEARCH. False for SCAN. */
    WhereLoop *pLoop;             /* The controlling WhereLoop object */
152535
152536
152537
152538
152539
152540
152541

152542
152543
152544
152545
152546
152547
152548
152549
152550
152551
152552
152553
152554
152555
152556
152557
152558
152559
152560
152561
152562

152563
152564
152565
152566
152567
152568
152569
*/
SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
  int addrExplain                 /* Address of OP_Explain (or 0) */
){

  const char *zObj = 0;
  WhereLoop *pLoop = pLvl->pWLoop;
  int wsFlags = pLoop->wsFlags;
  int viaCoroutine = 0;

  if( (wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
    zObj = pLoop->u.btree.pIndex->zName;
  }else{
    zObj = pSrclist->a[pLvl->iFrom].zName;
    viaCoroutine = pSrclist->a[pLvl->iFrom].fg.viaCoroutine;
  }
  sqlite3VdbeScanStatus(
      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  );

  if( viaCoroutine==0 ){
    if( (wsFlags & (WHERE_MULTI_OR|WHERE_AUTO_INDEX))==0 ){
      sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iTabCur);
    }
    if( wsFlags & WHERE_INDEXED ){
      sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iIdxCur);

    }
  }
}
#endif


/*







>
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
>







153407
153408
153409
153410
153411
153412
153413
153414
153415
153416
153417
153418
153419
153420
153421
153422
153423
153424
153425
153426
153427
153428
153429
153430
153431
153432
153433
153434
153435
153436
153437
153438
153439
153440
153441
153442
153443
*/
SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
  int addrExplain                 /* Address of OP_Explain (or 0) */
){
  if( IS_STMT_SCANSTATUS( sqlite3VdbeDb(v) ) ){
    const char *zObj = 0;
    WhereLoop *pLoop = pLvl->pWLoop;
    int wsFlags = pLoop->wsFlags;
    int viaCoroutine = 0;

    if( (wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
      zObj = pLoop->u.btree.pIndex->zName;
    }else{
      zObj = pSrclist->a[pLvl->iFrom].zName;
      viaCoroutine = pSrclist->a[pLvl->iFrom].fg.viaCoroutine;
    }
    sqlite3VdbeScanStatus(
        v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
    );

    if( viaCoroutine==0 ){
      if( (wsFlags & (WHERE_MULTI_OR|WHERE_AUTO_INDEX))==0 ){
        sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iTabCur);
      }
      if( wsFlags & WHERE_INDEXED ){
        sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iIdxCur);
      }
    }
  }
}
#endif


/*
153252
153253
153254
153255
153256
153257
153258

153259
153260
153261
153262
153263
153264
153265
153266
153267
153268
153269
153270
153271
153272
153273
153274
153275
153276


153277
153278
153279
153280
153281
153282
153283
153284
153285
153286
** Also, if the node is a TK_COLUMN that does access the table idenified
** by pCCurHint.iTabCur, and an index is being used (which we will
** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
** an access of the index rather than the original table.
*/
static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  int rc = WRC_Continue;

  struct CCurHint *pHint = pWalker->u.pCCurHint;
  if( pExpr->op==TK_COLUMN ){
    if( pExpr->iTable!=pHint->iTabCur ){
      int reg = ++pWalker->pParse->nMem;   /* Register for column value */
      sqlite3ExprCode(pWalker->pParse, pExpr, reg);
      pExpr->op = TK_REGISTER;
      pExpr->iTable = reg;
    }else if( pHint->pIdx!=0 ){
      pExpr->iTable = pHint->iIdxCur;
      pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
      assert( pExpr->iColumn>=0 );
    }
  }else if( pExpr->op==TK_AGG_FUNCTION ){
    /* An aggregate function in the WHERE clause of a query means this must
    ** be a correlated sub-query, and expression pExpr is an aggregate from
    ** the parent context. Do not walk the function arguments in this case.
    **
    ** todo: It should be possible to replace this node with a TK_REGISTER


    ** expression, as the result of the expression must be stored in a
    ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
    rc = WRC_Prune;
  }
  return rc;
}

/*
** Insert an OP_CursorHint instruction if it is appropriate to do so.
*/







>



|
|







|
|
|
|
<
|
>
>
|
<
|







154126
154127
154128
154129
154130
154131
154132
154133
154134
154135
154136
154137
154138
154139
154140
154141
154142
154143
154144
154145
154146
154147
154148
154149

154150
154151
154152
154153

154154
154155
154156
154157
154158
154159
154160
154161
** Also, if the node is a TK_COLUMN that does access the table idenified
** by pCCurHint.iTabCur, and an index is being used (which we will
** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
** an access of the index rather than the original table.
*/
static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  int rc = WRC_Continue;
  int reg;
  struct CCurHint *pHint = pWalker->u.pCCurHint;
  if( pExpr->op==TK_COLUMN ){
    if( pExpr->iTable!=pHint->iTabCur ){
      reg = ++pWalker->pParse->nMem;   /* Register for column value */
      reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);
      pExpr->op = TK_REGISTER;
      pExpr->iTable = reg;
    }else if( pHint->pIdx!=0 ){
      pExpr->iTable = pHint->iIdxCur;
      pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
      assert( pExpr->iColumn>=0 );
    }
  }else if( pExpr->pAggInfo ){
    rc = WRC_Prune;
    reg = ++pWalker->pParse->nMem;   /* Register for column value */
    reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);

    pExpr->op = TK_REGISTER;
    pExpr->iTable = reg;
  }else if( pExpr->op==TK_TRUEFALSE ){
    /* Do not walk disabled expressions.  tag-20230504-1 */

    return WRC_Prune;
  }
  return rc;
}

/*
** Insert an OP_CursorHint instruction if it is appropriate to do so.
*/
153374
153375
153376
153377
153378
153379
153380
153381
153382
153383
153384
153385
153386
153387
153388
    }

    /* If we survive all prior tests, that means this term is worth hinting */
    pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  }
  if( pExpr!=0 ){
    sWalker.xExprCallback = codeCursorHintFixExpr;
    sqlite3WalkExpr(&sWalker, pExpr);
    sqlite3VdbeAddOp4(v, OP_CursorHint,
                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
                      (const char*)pExpr, P4_EXPR);
  }
}
#else
# define codeCursorHint(A,B,C,D)  /* No-op */







|







154249
154250
154251
154252
154253
154254
154255
154256
154257
154258
154259
154260
154261
154262
154263
    }

    /* If we survive all prior tests, that means this term is worth hinting */
    pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  }
  if( pExpr!=0 ){
    sWalker.xExprCallback = codeCursorHintFixExpr;
    if( pParse->nErr==0 ) sqlite3WalkExpr(&sWalker, pExpr);
    sqlite3VdbeAddOp4(v, OP_CursorHint,
                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
                      (const char*)pExpr, P4_EXPR);
  }
}
#else
# define codeCursorHint(A,B,C,D)  /* No-op */
154168
154169
154170
154171
154172
154173
154174
154175
154176
154177
154178
154179
154180
154181
154182
        ** should we try before giving up and going with a seek.  The cost
        ** of a seek is proportional to the logarithm of the of the number
        ** of entries in the tree, so basing the number of steps to try
        ** on the estimated number of rows in the btree seems like a good
        ** guess. */
        addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan,
                                         (pIdx->aiRowLogEst[0]+9)/10);
        if( pRangeStart ){
          sqlite3VdbeChangeP5(v, 1);
          sqlite3VdbeChangeP2(v, addrSeekScan, sqlite3VdbeCurrentAddr(v)+1);
          addrSeekScan = 0;
        }
        VdbeCoverage(v);
      }
      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);







|







155043
155044
155045
155046
155047
155048
155049
155050
155051
155052
155053
155054
155055
155056
155057
        ** should we try before giving up and going with a seek.  The cost
        ** of a seek is proportional to the logarithm of the of the number
        ** of entries in the tree, so basing the number of steps to try
        ** on the estimated number of rows in the btree seems like a good
        ** guess. */
        addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan,
                                         (pIdx->aiRowLogEst[0]+9)/10);
        if( pRangeStart || pRangeEnd ){
          sqlite3VdbeChangeP5(v, 1);
          sqlite3VdbeChangeP2(v, addrSeekScan, sqlite3VdbeCurrentAddr(v)+1);
          addrSeekScan = 0;
        }
        VdbeCoverage(v);
      }
      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
154209
154210
154211
154212
154213
154214
154215
154216
154217
154218
154219
154220
154221
154222
154223
154224
154225
154226
154227
154228
154229
154230
154231
154232
    /* Load the value for the inequality constraint at the end of the
    ** range (if any).
    */
    nConstraint = nEq;
    assert( pLevel->p2==0 );
    if( pRangeEnd ){
      Expr *pRight = pRangeEnd->pExpr->pRight;
      if( addrSeekScan ){
        /* For a seek-scan that has a range on the lowest term of the index,
        ** we have to make the top of the loop be code that sets the end
        ** condition of the range.  Otherwise, the OP_SeekScan might jump
        ** over that initialization, leaving the range-end value set to the
        ** range-start value, resulting in a wrong answer.
        ** See ticket 5981a8c041a3c2f3 (2021-11-02).
        */
        pLevel->p2 = sqlite3VdbeCurrentAddr(v);
      }
      codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
       && sqlite3ExprCanBeNull(pRight)
      ){
        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
        VdbeCoverage(v);







|
<
<
<
<
<
<
<
<
<







155084
155085
155086
155087
155088
155089
155090
155091









155092
155093
155094
155095
155096
155097
155098
    /* Load the value for the inequality constraint at the end of the
    ** range (if any).
    */
    nConstraint = nEq;
    assert( pLevel->p2==0 );
    if( pRangeEnd ){
      Expr *pRight = pRangeEnd->pExpr->pRight;
      assert( addrSeekScan==0 );









      codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
       && sqlite3ExprCanBeNull(pRight)
      ){
        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
        VdbeCoverage(v);
154252
154253
154254
154255
154256
154257
154258
154259
154260
154261
154262
154263
154264
154265
154266
      }
      nConstraint++;
    }
    if( zStartAff ) sqlite3DbNNFreeNN(db, zStartAff);
    if( zEndAff ) sqlite3DbNNFreeNN(db, zEndAff);

    /* Top of the loop body */
    if( pLevel->p2==0 ) pLevel->p2 = sqlite3VdbeCurrentAddr(v);

    /* Check if the index cursor is past the end of the range. */
    if( nConstraint ){
      if( regBignull ){
        /* Except, skip the end-of-range check while doing the NULL-scan */
        sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);
        VdbeComment((v, "If NULL-scan 2nd pass"));







|







155118
155119
155120
155121
155122
155123
155124
155125
155126
155127
155128
155129
155130
155131
155132
      }
      nConstraint++;
    }
    if( zStartAff ) sqlite3DbNNFreeNN(db, zStartAff);
    if( zEndAff ) sqlite3DbNNFreeNN(db, zEndAff);

    /* Top of the loop body */
    pLevel->p2 = sqlite3VdbeCurrentAddr(v);

    /* Check if the index cursor is past the end of the range. */
    if( nConstraint ){
      if( regBignull ){
        /* Except, skip the end-of-range check while doing the NULL-scan */
        sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);
        VdbeComment((v, "If NULL-scan 2nd pass"));
156249
156250
156251
156252
156253
156254
156255
156256
156257
156258
156259
156260
156261
156262
156263
      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
    }else
    if( op==TK_ISNULL
     && !ExprHasProperty(pExpr,EP_OuterON)
     && 0==sqlite3ExprCanBeNull(pLeft)
    ){
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      pExpr->op = TK_TRUEFALSE;
      pExpr->u.zToken = "false";
      ExprSetProperty(pExpr, EP_IsFalse);
      pTerm->prereqAll = 0;
      pTerm->eOperator = 0;
    }
  }








|







157115
157116
157117
157118
157119
157120
157121
157122
157123
157124
157125
157126
157127
157128
157129
      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
    }else
    if( op==TK_ISNULL
     && !ExprHasProperty(pExpr,EP_OuterON)
     && 0==sqlite3ExprCanBeNull(pLeft)
    ){
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
      pExpr->op = TK_TRUEFALSE;  /* See tag-20230504-1 */
      pExpr->u.zToken = "false";
      ExprSetProperty(pExpr, EP_IsFalse);
      pTerm->prereqAll = 0;
      pTerm->eOperator = 0;
    }
  }

156894
156895
156896
156897
156898
156899
156900
156901


156902
156903

156904
156905
156906
156907
156908
156909
156910
    pColRef->iColumn = k++;
    assert( ExprUseYTab(pColRef) );
    pColRef->y.pTab = pTab;
    pItem->colUsed |= sqlite3ExprColUsed(pColRef);
    pRhs = sqlite3PExpr(pParse, TK_UPLUS,
        sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
    if( pItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){


      joinType = EP_OuterON;
    }else{

      joinType = EP_InnerON;
    }
    sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  }
}








|
>
>


>







157760
157761
157762
157763
157764
157765
157766
157767
157768
157769
157770
157771
157772
157773
157774
157775
157776
157777
157778
157779
    pColRef->iColumn = k++;
    assert( ExprUseYTab(pColRef) );
    pColRef->y.pTab = pTab;
    pItem->colUsed |= sqlite3ExprColUsed(pColRef);
    pRhs = sqlite3PExpr(pParse, TK_UPLUS,
        sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
    if( pItem->fg.jointype & (JT_LEFT|JT_RIGHT) ){
      testcase( pItem->fg.jointype & JT_LEFT );  /* testtag-20230227a */
      testcase( pItem->fg.jointype & JT_RIGHT ); /* testtag-20230227b */
      joinType = EP_OuterON;
    }else{
      testcase( pItem->fg.jointype & JT_LTORJ ); /* testtag-20230227c */
      joinType = EP_InnerON;
    }
    sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  }
}

157739
157740
157741
157742
157743
157744
157745
157746
157747
157748
157749
157750
157751
157752
157753
*/
static void explainAutomaticIndex(
  Parse *pParse,
  Index *pIdx,                    /* Automatic index to explain */
  int bPartial,                   /* True if pIdx is a partial index */
  int *pAddrExplain               /* OUT: Address of OP_Explain */
){
  if( pParse->explain!=2 ){
    Table *pTab = pIdx->pTable;
    const char *zSep = "";
    char *zText = 0;
    int ii = 0;
    sqlite3_str *pStr = sqlite3_str_new(pParse->db);
    sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName);
    assert( pIdx->nColumn>1 );







|







158608
158609
158610
158611
158612
158613
158614
158615
158616
158617
158618
158619
158620
158621
158622
*/
static void explainAutomaticIndex(
  Parse *pParse,
  Index *pIdx,                    /* Automatic index to explain */
  int bPartial,                   /* True if pIdx is a partial index */
  int *pAddrExplain               /* OUT: Address of OP_Explain */
){
  if( IS_STMT_SCANSTATUS(pParse->db) && pParse->explain!=2 ){
    Table *pTab = pIdx->pTable;
    const char *zSep = "";
    char *zText = 0;
    int ii = 0;
    sqlite3_str *pStr = sqlite3_str_new(pParse->db);
    sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName);
    assert( pIdx->nColumn>1 );
157778
157779
157780
157781
157782
157783
157784
157785
157786
157787
157788
157789
157790
157791
157792
157793
157794
157795
157796
157797
157798
157799
157800
157801
157802
157803
157804
157805
157806
157807

157808
157809

157810
157811
157812
157813
157814
157815
157816
157817
157818
157819
157820
157821
157822
157823
157824
157825


157826
157827
157828
157829
157830
157831
157832
157833
157834
157835
157836
157837
157838
157839
157840
157841
157842
157843
/*
** Generate code to construct the Index object for an automatic index
** and to set up the WhereLevel object pLevel so that the code generator
** makes use of the automatic index.
*/
static SQLITE_NOINLINE void constructAutomaticIndex(
  Parse *pParse,              /* The parsing context */
  const WhereClause *pWC,     /* The WHERE clause */
  const SrcItem *pSrc,        /* The FROM clause term to get the next index */
  const Bitmask notReady,     /* Mask of cursors that are not available */
  WhereLevel *pLevel          /* Write new index here */
){
  int nKeyCol;                /* Number of columns in the constructed index */
  WhereTerm *pTerm;           /* A single term of the WHERE clause */
  WhereTerm *pWCEnd;          /* End of pWC->a[] */
  Index *pIdx;                /* Object describing the transient index */
  Vdbe *v;                    /* Prepared statement under construction */
  int addrInit;               /* Address of the initialization bypass jump */
  Table *pTable;              /* The table being indexed */
  int addrTop;                /* Top of the index fill loop */
  int regRecord;              /* Register holding an index record */
  int n;                      /* Column counter */
  int i;                      /* Loop counter */
  int mxBitCol;               /* Maximum column in pSrc->colUsed */
  CollSeq *pColl;             /* Collating sequence to on a column */
  WhereLoop *pLoop;           /* The Loop object */
  char *zNotUsed;             /* Extra space on the end of pIdx */
  Bitmask idxCols;            /* Bitmap of columns used for indexing */
  Bitmask extraCols;          /* Bitmap of additional columns */
  u8 sentWarning = 0;         /* True if a warnning has been issued */

  Expr *pPartial = 0;         /* Partial Index Expression */
  int iContinue = 0;          /* Jump here to skip excluded rows */

  SrcItem *pTabItem;          /* FROM clause term being indexed */
  int addrCounter = 0;        /* Address where integer counter is initialized */
  int regBase;                /* Array of registers where record is assembled */
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  int addrExp = 0;            /* Address of OP_Explain */
#endif

  /* Generate code to skip over the creation and initialization of the
  ** transient index on 2nd and subsequent iterations of the loop. */
  v = pParse->pVdbe;
  assert( v!=0 );
  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);

  /* Count the number of columns that will be added to the index
  ** and used to match WHERE clause constraints */
  nKeyCol = 0;


  pTable = pSrc->pTab;
  pWCEnd = &pWC->a[pWC->nTerm];
  pLoop = pLevel->pWLoop;
  idxCols = 0;
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
    Expr *pExpr = pTerm->pExpr;
    /* Make the automatic index a partial index if there are terms in the
    ** WHERE clause (or the ON clause of a LEFT join) that constrain which
    ** rows of the target table (pSrc) that can be used. */
    if( (pTerm->wtFlags & TERM_VIRTUAL)==0
     && sqlite3ExprIsTableConstraint(pExpr, pSrc)
    ){
      pPartial = sqlite3ExprAnd(pParse, pPartial,
                                sqlite3ExprDup(pParse->db, pExpr, 0));
    }
    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
      int iCol;
      Bitmask cMask;







|
<




















|
>


>
|















>
>










|







158647
158648
158649
158650
158651
158652
158653
158654

158655
158656
158657
158658
158659
158660
158661
158662
158663
158664
158665
158666
158667
158668
158669
158670
158671
158672
158673
158674
158675
158676
158677
158678
158679
158680
158681
158682
158683
158684
158685
158686
158687
158688
158689
158690
158691
158692
158693
158694
158695
158696
158697
158698
158699
158700
158701
158702
158703
158704
158705
158706
158707
158708
158709
158710
158711
158712
158713
158714
158715
/*
** Generate code to construct the Index object for an automatic index
** and to set up the WhereLevel object pLevel so that the code generator
** makes use of the automatic index.
*/
static SQLITE_NOINLINE void constructAutomaticIndex(
  Parse *pParse,              /* The parsing context */
  WhereClause *pWC,           /* The WHERE clause */

  const Bitmask notReady,     /* Mask of cursors that are not available */
  WhereLevel *pLevel          /* Write new index here */
){
  int nKeyCol;                /* Number of columns in the constructed index */
  WhereTerm *pTerm;           /* A single term of the WHERE clause */
  WhereTerm *pWCEnd;          /* End of pWC->a[] */
  Index *pIdx;                /* Object describing the transient index */
  Vdbe *v;                    /* Prepared statement under construction */
  int addrInit;               /* Address of the initialization bypass jump */
  Table *pTable;              /* The table being indexed */
  int addrTop;                /* Top of the index fill loop */
  int regRecord;              /* Register holding an index record */
  int n;                      /* Column counter */
  int i;                      /* Loop counter */
  int mxBitCol;               /* Maximum column in pSrc->colUsed */
  CollSeq *pColl;             /* Collating sequence to on a column */
  WhereLoop *pLoop;           /* The Loop object */
  char *zNotUsed;             /* Extra space on the end of pIdx */
  Bitmask idxCols;            /* Bitmap of columns used for indexing */
  Bitmask extraCols;          /* Bitmap of additional columns */
  u8 sentWarning = 0;         /* True if a warning has been issued */
  u8 useBloomFilter = 0;      /* True to also add a Bloom filter */
  Expr *pPartial = 0;         /* Partial Index Expression */
  int iContinue = 0;          /* Jump here to skip excluded rows */
  SrcList *pTabList;          /* The complete FROM clause */
  SrcItem *pSrc;              /* The FROM clause term to get the next index */
  int addrCounter = 0;        /* Address where integer counter is initialized */
  int regBase;                /* Array of registers where record is assembled */
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  int addrExp = 0;            /* Address of OP_Explain */
#endif

  /* Generate code to skip over the creation and initialization of the
  ** transient index on 2nd and subsequent iterations of the loop. */
  v = pParse->pVdbe;
  assert( v!=0 );
  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);

  /* Count the number of columns that will be added to the index
  ** and used to match WHERE clause constraints */
  nKeyCol = 0;
  pTabList = pWC->pWInfo->pTabList;
  pSrc = &pTabList->a[pLevel->iFrom];
  pTable = pSrc->pTab;
  pWCEnd = &pWC->a[pWC->nTerm];
  pLoop = pLevel->pWLoop;
  idxCols = 0;
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
    Expr *pExpr = pTerm->pExpr;
    /* Make the automatic index a partial index if there are terms in the
    ** WHERE clause (or the ON clause of a LEFT join) that constrain which
    ** rows of the target table (pSrc) that can be used. */
    if( (pTerm->wtFlags & TERM_VIRTUAL)==0
     && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, pLevel->iFrom)
    ){
      pPartial = sqlite3ExprAnd(pParse, pPartial,
                                sqlite3ExprDup(pParse->db, pExpr, 0));
    }
    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
      int iCol;
      Bitmask cMask;
157870
157871
157872
157873
157874
157875
157876



157877

157878
157879
157880
157881
157882
157883
157884
  ** covering index.  A "covering index" is an index that contains all
  ** columns that are needed by the query.  With a covering index, the
  ** original table never needs to be accessed.  Automatic indices must
  ** be a covering index because the index will not be updated if the
  ** original table changes and the index and table cannot both be used
  ** if they go out of sync.
  */



  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));

  mxBitCol = MIN(BMS-1,pTable->nCol);
  testcase( pTable->nCol==BMS-1 );
  testcase( pTable->nCol==BMS-2 );
  for(i=0; i<mxBitCol; i++){
    if( extraCols & MASKBIT(i) ) nKeyCol++;
  }
  if( pSrc->colUsed & MASKBIT(BMS-1) ){







>
>
>
|
>







158742
158743
158744
158745
158746
158747
158748
158749
158750
158751
158752
158753
158754
158755
158756
158757
158758
158759
158760
  ** covering index.  A "covering index" is an index that contains all
  ** columns that are needed by the query.  With a covering index, the
  ** original table never needs to be accessed.  Automatic indices must
  ** be a covering index because the index will not be updated if the
  ** original table changes and the index and table cannot both be used
  ** if they go out of sync.
  */
  if( IsView(pTable) ){
    extraCols = ALLBITS;
  }else{
    extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  }
  mxBitCol = MIN(BMS-1,pTable->nCol);
  testcase( pTable->nCol==BMS-1 );
  testcase( pTable->nCol==BMS-2 );
  for(i=0; i<mxBitCol; i++){
    if( extraCols & MASKBIT(i) ) nKeyCol++;
  }
  if( pSrc->colUsed & MASKBIT(BMS-1) ){
157906
157907
157908
157909
157910
157911
157912










157913
157914
157915
157916
157917
157918
157919
        Expr *pX = pTerm->pExpr;
        idxCols |= cMask;
        pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
        pColl = sqlite3ExprCompareCollSeq(pParse, pX);
        assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
        n++;










      }
    }
  }
  assert( (u32)n==pLoop->u.btree.nEq );

  /* Add additional columns needed to make the automatic index into
  ** a covering index */







>
>
>
>
>
>
>
>
>
>







158782
158783
158784
158785
158786
158787
158788
158789
158790
158791
158792
158793
158794
158795
158796
158797
158798
158799
158800
158801
158802
158803
158804
158805
        Expr *pX = pTerm->pExpr;
        idxCols |= cMask;
        pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
        pColl = sqlite3ExprCompareCollSeq(pParse, pX);
        assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
        n++;
        if( ALWAYS(pX->pLeft!=0)
         && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT
        ){
          /* TUNING: only use a Bloom filter on an automatic index
          ** if one or more key columns has the ability to hold numeric
          ** values, since strings all have the same hash in the Bloom
          ** filter implementation and hence a Bloom filter on a text column
          ** is not usually helpful. */
          useBloomFilter = 1;
        }
      }
    }
  }
  assert( (u32)n==pLoop->u.btree.nEq );

  /* Add additional columns needed to make the automatic index into
  ** a covering index */
157938
157939
157940
157941
157942
157943
157944
157945

157946
157947
157948
157949
157950
157951
157952
157953
157954
157955
157956
157957
157958
157959
157960
157961
157962
157963
157964
157965
157966
157967
157968
157969
157970
157971
157972
157973
157974
157975
157976
157977
157978
157979
157980
157981
157982
157983
157984
157985
157986
157987
157988
157989
157990
157991
157992
157993
  /* Create the automatic index */
  explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp);
  assert( pLevel->iIdxCur>=0 );
  pLevel->iIdxCur = pParse->nTab++;
  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  VdbeComment((v, "for %s", pTable->zName));
  if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ){

    pLevel->regFilter = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
  }

  /* Fill the automatic index with content */
  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  if( pTabItem->fg.viaCoroutine ){
    int regYield = pTabItem->regReturn;
    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
    VdbeCoverage(v);
    VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  }else{
    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  }
  if( pPartial ){
    iContinue = sqlite3VdbeMakeLabel(pParse);
    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
    pLoop->wsFlags |= WHERE_PARTIALIDX;
  }
  regRecord = sqlite3GetTempReg(pParse);
  regBase = sqlite3GenerateIndexKey(
      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  );
  if( pLevel->regFilter ){
    sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
                         regBase, pLoop->u.btree.nEq);
  }
  sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  if( pTabItem->fg.viaCoroutine ){
    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
    testcase( pParse->db->mallocFailed );
    assert( pLevel->iIdxCur>0 );
    translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
                          pTabItem->regResult, pLevel->iIdxCur);
    sqlite3VdbeGoto(v, addrTop);
    pTabItem->fg.viaCoroutine = 0;
  }else{
    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
    sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  }
  sqlite3VdbeJumpHere(v, addrTop);
  sqlite3ReleaseTempReg(pParse, regRecord);








|
>





|
|
|

|


|




















|




|

|







158824
158825
158826
158827
158828
158829
158830
158831
158832
158833
158834
158835
158836
158837
158838
158839
158840
158841
158842
158843
158844
158845
158846
158847
158848
158849
158850
158851
158852
158853
158854
158855
158856
158857
158858
158859
158860
158861
158862
158863
158864
158865
158866
158867
158868
158869
158870
158871
158872
158873
158874
158875
158876
158877
158878
158879
158880
  /* Create the automatic index */
  explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp);
  assert( pLevel->iIdxCur>=0 );
  pLevel->iIdxCur = pParse->nTab++;
  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  VdbeComment((v, "for %s", pTable->zName));
  if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) && useBloomFilter ){
    sqlite3WhereExplainBloomFilter(pParse, pWC->pWInfo, pLevel);
    pLevel->regFilter = ++pParse->nMem;
    sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
  }

  /* Fill the automatic index with content */
  assert( pSrc == &pWC->pWInfo->pTabList->a[pLevel->iFrom] );
  if( pSrc->fg.viaCoroutine ){
    int regYield = pSrc->regReturn;
    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSrc->addrFillSub);
    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
    VdbeCoverage(v);
    VdbeComment((v, "next row of %s", pSrc->pTab->zName));
  }else{
    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  }
  if( pPartial ){
    iContinue = sqlite3VdbeMakeLabel(pParse);
    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
    pLoop->wsFlags |= WHERE_PARTIALIDX;
  }
  regRecord = sqlite3GetTempReg(pParse);
  regBase = sqlite3GenerateIndexKey(
      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  );
  if( pLevel->regFilter ){
    sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
                         regBase, pLoop->u.btree.nEq);
  }
  sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  if( pSrc->fg.viaCoroutine ){
    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
    testcase( pParse->db->mallocFailed );
    assert( pLevel->iIdxCur>0 );
    translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
                          pSrc->regResult, pLevel->iIdxCur);
    sqlite3VdbeGoto(v, addrTop);
    pSrc->fg.viaCoroutine = 0;
  }else{
    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
    sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  }
  sqlite3VdbeJumpHere(v, addrTop);
  sqlite3ReleaseTempReg(pParse, regRecord);

158031
158032
158033
158034
158035
158036
158037




158038
158039
158040
158041
158042
158043
158044

158045
158046
158047

158048
158049
158050
158051
158052
158053
158054
158055
158056
158057
158058
158059
158060
158061


158062
158063
158064
158065
158066
158067
158068
158069
158070
158071
158072
158073
158074
158075
158076
158077
158078
158079
158080
158081
158082
158083
158084
158085
158086
158087
158088
158089
158090
158091
158092
158093
158094
158095
158096
158097
158098
158099
158100
158101
158102
158103
  int addrCont;                        /* Jump here to skip a row */
  const WhereTerm *pTerm;              /* For looping over WHERE clause terms */
  const WhereTerm *pWCEnd;             /* Last WHERE clause term */
  Parse *pParse = pWInfo->pParse;      /* Parsing context */
  Vdbe *v = pParse->pVdbe;             /* VDBE under construction */
  WhereLoop *pLoop = pLevel->pWLoop;   /* The loop being coded */
  int iCur;                            /* Cursor for table getting the filter */





  assert( pLoop!=0 );
  assert( v!=0 );
  assert( pLoop->wsFlags & WHERE_BLOOMFILTER );

  addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  do{

    const SrcItem *pItem;
    const Table *pTab;
    u64 sz;

    sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
    addrCont = sqlite3VdbeMakeLabel(pParse);
    iCur = pLevel->iTabCur;
    pLevel->regFilter = ++pParse->nMem;

    /* The Bloom filter is a Blob held in a register.  Initialize it
    ** to zero-filled blob of at least 80K bits, but maybe more if the
    ** estimated size of the table is larger.  We could actually
    ** measure the size of the table at run-time using OP_Count with
    ** P3==1 and use that value to initialize the blob.  But that makes
    ** testing complicated.  By basing the blob size on the value in the
    ** sqlite_stat1 table, testing is much easier.
    */
    pItem = &pWInfo->pTabList->a[pLevel->iFrom];


    assert( pItem!=0 );
    pTab = pItem->pTab;
    assert( pTab!=0 );
    sz = sqlite3LogEstToInt(pTab->nRowLogEst);
    if( sz<10000 ){
      sz = 10000;
    }else if( sz>10000000 ){
      sz = 10000000;
    }
    sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);

    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
    pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
    for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
      Expr *pExpr = pTerm->pExpr;
      if( (pTerm->wtFlags & TERM_VIRTUAL)==0
       && sqlite3ExprIsTableConstraint(pExpr, pItem)
      ){
        sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
      }
    }
    if( pLoop->wsFlags & WHERE_IPK ){
      int r1 = sqlite3GetTempReg(pParse);
      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
      sqlite3ReleaseTempReg(pParse, r1);
    }else{
      Index *pIdx = pLoop->u.btree.pIndex;
      int n = pLoop->u.btree.nEq;
      int r1 = sqlite3GetTempRange(pParse, n);
      int jj;
      for(jj=0; jj<n; jj++){
        int iCol = pIdx->aiColumn[jj];
        assert( pIdx->pTable==pItem->pTab );
        sqlite3ExprCodeGetColumnOfTable(v, pIdx->pTable, iCur, iCol,r1+jj);
      }
      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
      sqlite3ReleaseTempRange(pParse, r1, n);
    }
    sqlite3VdbeResolveLabel(v, addrCont);
    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
    VdbeCoverage(v);







>
>
>
>







>



>













|
>
>
















|















<

|







158918
158919
158920
158921
158922
158923
158924
158925
158926
158927
158928
158929
158930
158931
158932
158933
158934
158935
158936
158937
158938
158939
158940
158941
158942
158943
158944
158945
158946
158947
158948
158949
158950
158951
158952
158953
158954
158955
158956
158957
158958
158959
158960
158961
158962
158963
158964
158965
158966
158967
158968
158969
158970
158971
158972
158973
158974
158975
158976
158977
158978
158979
158980
158981
158982
158983
158984
158985
158986
158987
158988

158989
158990
158991
158992
158993
158994
158995
158996
158997
  int addrCont;                        /* Jump here to skip a row */
  const WhereTerm *pTerm;              /* For looping over WHERE clause terms */
  const WhereTerm *pWCEnd;             /* Last WHERE clause term */
  Parse *pParse = pWInfo->pParse;      /* Parsing context */
  Vdbe *v = pParse->pVdbe;             /* VDBE under construction */
  WhereLoop *pLoop = pLevel->pWLoop;   /* The loop being coded */
  int iCur;                            /* Cursor for table getting the filter */
  IndexedExpr *saved_pIdxEpr;          /* saved copy of Parse.pIdxEpr */

  saved_pIdxEpr = pParse->pIdxEpr;
  pParse->pIdxEpr = 0;

  assert( pLoop!=0 );
  assert( v!=0 );
  assert( pLoop->wsFlags & WHERE_BLOOMFILTER );

  addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  do{
    const SrcList *pTabList;
    const SrcItem *pItem;
    const Table *pTab;
    u64 sz;
    int iSrc;
    sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
    addrCont = sqlite3VdbeMakeLabel(pParse);
    iCur = pLevel->iTabCur;
    pLevel->regFilter = ++pParse->nMem;

    /* The Bloom filter is a Blob held in a register.  Initialize it
    ** to zero-filled blob of at least 80K bits, but maybe more if the
    ** estimated size of the table is larger.  We could actually
    ** measure the size of the table at run-time using OP_Count with
    ** P3==1 and use that value to initialize the blob.  But that makes
    ** testing complicated.  By basing the blob size on the value in the
    ** sqlite_stat1 table, testing is much easier.
    */
    pTabList = pWInfo->pTabList;
    iSrc = pLevel->iFrom;
    pItem = &pTabList->a[iSrc];
    assert( pItem!=0 );
    pTab = pItem->pTab;
    assert( pTab!=0 );
    sz = sqlite3LogEstToInt(pTab->nRowLogEst);
    if( sz<10000 ){
      sz = 10000;
    }else if( sz>10000000 ){
      sz = 10000000;
    }
    sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);

    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
    pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
    for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
      Expr *pExpr = pTerm->pExpr;
      if( (pTerm->wtFlags & TERM_VIRTUAL)==0
       && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, iSrc)
      ){
        sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
      }
    }
    if( pLoop->wsFlags & WHERE_IPK ){
      int r1 = sqlite3GetTempReg(pParse);
      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
      sqlite3ReleaseTempReg(pParse, r1);
    }else{
      Index *pIdx = pLoop->u.btree.pIndex;
      int n = pLoop->u.btree.nEq;
      int r1 = sqlite3GetTempRange(pParse, n);
      int jj;
      for(jj=0; jj<n; jj++){

        assert( pIdx->pTable==pItem->pTab );
        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
      }
      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
      sqlite3ReleaseTempRange(pParse, r1, n);
    }
    sqlite3VdbeResolveLabel(v, addrCont);
    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
    VdbeCoverage(v);
158120
158121
158122
158123
158124
158125
158126

158127
158128
158129
158130
158131
158132
158133
        ** not able to do early evaluation of bloom filters that make use of
        ** the IN operator */
        break;
      }
    }
  }while( iLevel < pWInfo->nLevel );
  sqlite3VdbeJumpHere(v, addrOnce);

}


#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Allocate and populate an sqlite3_index_info structure. It is the
** responsibility of the caller to eventually release the structure







>







159014
159015
159016
159017
159018
159019
159020
159021
159022
159023
159024
159025
159026
159027
159028
        ** not able to do early evaluation of bloom filters that make use of
        ** the IN operator */
        break;
      }
    }
  }while( iLevel < pWInfo->nLevel );
  sqlite3VdbeJumpHere(v, addrOnce);
  pParse->pIdxEpr = saved_pIdxEpr;
}


#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Allocate and populate an sqlite3_index_info structure. It is the
** responsibility of the caller to eventually release the structure
158375
158376
158377
158378
158379
158380
158381



158382
158383
158384
158385
158386
158387
158388
      sqlite3OomFault(pParse->db);
    }else if( !pVtab->zErrMsg ){
      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
    }else{
      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
    }
  }



  sqlite3_free(pVtab->zErrMsg);
  pVtab->zErrMsg = 0;
  return rc;
}
#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */

#ifdef SQLITE_ENABLE_STAT4







>
>
>







159270
159271
159272
159273
159274
159275
159276
159277
159278
159279
159280
159281
159282
159283
159284
159285
159286
      sqlite3OomFault(pParse->db);
    }else if( !pVtab->zErrMsg ){
      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
    }else{
      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
    }
  }
  if( pTab->u.vtab.p->bAllSchemas ){
    sqlite3VtabUsesAllSchemas(pParse);
  }
  sqlite3_free(pVtab->zErrMsg);
  pVtab->zErrMsg = 0;
  return rc;
}
#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */

#ifdef SQLITE_ENABLE_STAT4
158418
158419
158420
158421
158422
158423
158424

158425
158426
158427
158428
158429
158430
158431

#ifndef SQLITE_DEBUG
  UNUSED_PARAMETER( pParse );
#endif
  assert( pRec!=0 );
  assert( pIdx->nSample>0 );
  assert( pRec->nField>0 );


  /* Do a binary search to find the first sample greater than or equal
  ** to pRec. If pRec contains a single field, the set of samples to search
  ** is simply the aSample[] array. If the samples in aSample[] contain more
  ** than one fields, all fields following the first are ignored.
  **
  ** If pRec contains N fields, where N is more than one, then as well as the







>







159316
159317
159318
159319
159320
159321
159322
159323
159324
159325
159326
159327
159328
159329
159330

#ifndef SQLITE_DEBUG
  UNUSED_PARAMETER( pParse );
#endif
  assert( pRec!=0 );
  assert( pIdx->nSample>0 );
  assert( pRec->nField>0 );


  /* Do a binary search to find the first sample greater than or equal
  ** to pRec. If pRec contains a single field, the set of samples to search
  ** is simply the aSample[] array. If the samples in aSample[] contain more
  ** than one fields, all fields following the first are ignored.
  **
  ** If pRec contains N fields, where N is more than one, then as well as the
158463
158464
158465
158466
158467
158468
158469





158470
158471
158472
158473
158474
158475
158476
158477
  ** equal to the previous sample in the array. For example, in the above,
  ** sample 2 is the first sample of a block of N samples, so at first it
  ** appears that it should be 1 field in size. However, that would make it
  ** smaller than sample 1, so the binary search would not work. As a result,
  ** it is extended to two fields. The duplicates that this creates do not
  ** cause any problems.
  */





  nField = MIN(pRec->nField, pIdx->nSample);
  iCol = 0;
  iSample = pIdx->nSample * nField;
  do{
    int iSamp;                    /* Index in aSample[] of test sample */
    int n;                        /* Number of fields in test sample */

    iTest = (iMin+iSample)/2;







>
>
>
>
>
|







159362
159363
159364
159365
159366
159367
159368
159369
159370
159371
159372
159373
159374
159375
159376
159377
159378
159379
159380
159381
  ** equal to the previous sample in the array. For example, in the above,
  ** sample 2 is the first sample of a block of N samples, so at first it
  ** appears that it should be 1 field in size. However, that would make it
  ** smaller than sample 1, so the binary search would not work. As a result,
  ** it is extended to two fields. The duplicates that this creates do not
  ** cause any problems.
  */
  if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
    nField = pIdx->nKeyCol;
  }else{
    nField = pIdx->nColumn;
  }
  nField = MIN(pRec->nField, nField);
  iCol = 0;
  iSample = pIdx->nSample * nField;
  do{
    int iSamp;                    /* Index in aSample[] of test sample */
    int n;                        /* Number of fields in test sample */

    iTest = (iMin+iSample)/2;
158899
158900
158901
158902
158903
158904
158905
158906
158907
158908
158909
158910
158911
158912
158913
    }
  }
#else
  UNUSED_PARAMETER(pParse);
  UNUSED_PARAMETER(pBuilder);
  assert( pLower || pUpper );
#endif
  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  nNew = whereRangeAdjust(pLower, nOut);
  nNew = whereRangeAdjust(pUpper, nNew);

  /* TUNING: If there is both an upper and lower limit and neither limit
  ** has an application-defined likelihood(), assume the range is
  ** reduced by an additional 75%. This means that, by default, an open-ended
  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the







|







159803
159804
159805
159806
159807
159808
159809
159810
159811
159812
159813
159814
159815
159816
159817
    }
  }
#else
  UNUSED_PARAMETER(pParse);
  UNUSED_PARAMETER(pBuilder);
  assert( pLower || pUpper );
#endif
  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 || pParse->nErr>0 );
  nNew = whereRangeAdjust(pLower, nOut);
  nNew = whereRangeAdjust(pUpper, nNew);

  /* TUNING: If there is both an upper and lower limit and neither limit
  ** has an application-defined likelihood(), assume the range is
  ** reduced by an additional 75%. This means that, by default, an open-ended
  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
161000
161001
161002
161003
161004
161005
161006
161007
161008
161009
161010
161011
161012
161013
161014
161015
161016
161017
161018
161019
161020
161021
161022
161023
161024
161025
161026
161027
161028
161029
161030
161031
161032
161033
161034
161035
161036
161037
161038
161039
*/
SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
  return pHidden->eDistinct;
}

#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
    && !defined(SQLITE_OMIT_VIRTUALTABLE)
/*
** Cause the prepared statement that is associated with a call to
** xBestIndex to potentially use all schemas.  If the statement being
** prepared is read-only, then just start read transactions on all
** schemas.  But if this is a write operation, start writes on all
** schemas.
**
** This is used by the (built-in) sqlite_dbpage virtual table.
*/
SQLITE_PRIVATE void sqlite3VtabUsesAllSchemas(sqlite3_index_info *pIdxInfo){
  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  Parse *pParse = pHidden->pParse;
  int nDb = pParse->db->nDb;
  int i;
  for(i=0; i<nDb; i++){
    sqlite3CodeVerifySchema(pParse, i);
  }
  if( DbMaskNonZero(pParse->writeMask) ){
    for(i=0; i<nDb; i++){
      sqlite3BeginWriteOperation(pParse, 0, i);
    }
  }
}
#endif

/*
** Add all WhereLoop objects for a table of the join identified by
** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
**
** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause







<
<









|
<
<











<







161904
161905
161906
161907
161908
161909
161910


161911
161912
161913
161914
161915
161916
161917
161918
161919
161920


161921
161922
161923
161924
161925
161926
161927
161928
161929
161930
161931

161932
161933
161934
161935
161936
161937
161938
*/
SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
  return pHidden->eDistinct;
}



/*
** Cause the prepared statement that is associated with a call to
** xBestIndex to potentially use all schemas.  If the statement being
** prepared is read-only, then just start read transactions on all
** schemas.  But if this is a write operation, start writes on all
** schemas.
**
** This is used by the (built-in) sqlite_dbpage virtual table.
*/
SQLITE_PRIVATE void sqlite3VtabUsesAllSchemas(Parse *pParse){


  int nDb = pParse->db->nDb;
  int i;
  for(i=0; i<nDb; i++){
    sqlite3CodeVerifySchema(pParse, i);
  }
  if( DbMaskNonZero(pParse->writeMask) ){
    for(i=0; i<nDb; i++){
      sqlite3BeginWriteOperation(pParse, 0, i);
    }
  }
}


/*
** Add all WhereLoop objects for a table of the join identified by
** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
**
** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
162191
162192
162193
162194
162195
162196
162197




162198
162199
162200
162201
162202
162203
162204
  pWInfo->bOrderedInnerLoop = 0;
  if( pWInfo->pOrderBy ){
    pWInfo->nOBSat = pFrom->isOrdered;
    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
      }




    }else{
      pWInfo->revMask = pFrom->revLoop;
      if( pWInfo->nOBSat<=0 ){
        pWInfo->nOBSat = 0;
        if( nLoop>0 ){
          u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
          if( (wsFlags & WHERE_ONEROW)==0







>
>
>
>







163090
163091
163092
163093
163094
163095
163096
163097
163098
163099
163100
163101
163102
163103
163104
163105
163106
163107
  pWInfo->bOrderedInnerLoop = 0;
  if( pWInfo->pOrderBy ){
    pWInfo->nOBSat = pFrom->isOrdered;
    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
      }
      if( pWInfo->pSelect->pOrderBy
       && pWInfo->nOBSat > pWInfo->pSelect->pOrderBy->nExpr ){
        pWInfo->nOBSat = pWInfo->pSelect->pOrderBy->nExpr;
      }
    }else{
      pWInfo->revMask = pFrom->revLoop;
      if( pWInfo->nOBSat<=0 ){
        pWInfo->nOBSat = 0;
        if( nLoop>0 ){
          u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
          if( (wsFlags & WHERE_ONEROW)==0
162402
162403
162404
162405
162406
162407
162408







162409
162410
162411
162412
162413
162414
162415
**   1) The query must not be an aggregate.
**   2) The table must be the RHS of a LEFT JOIN.
**   3) Either the query must be DISTINCT, or else the ON or USING clause
**      must contain a constraint that limits the scan of the table to
**      at most a single row.
**   4) The table must not be referenced by any part of the query apart
**      from its own USING or ON clause.







**
** For example, given:
**
**     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
**     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
**     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
**







>
>
>
>
>
>
>







163305
163306
163307
163308
163309
163310
163311
163312
163313
163314
163315
163316
163317
163318
163319
163320
163321
163322
163323
163324
163325
**   1) The query must not be an aggregate.
**   2) The table must be the RHS of a LEFT JOIN.
**   3) Either the query must be DISTINCT, or else the ON or USING clause
**      must contain a constraint that limits the scan of the table to
**      at most a single row.
**   4) The table must not be referenced by any part of the query apart
**      from its own USING or ON clause.
**   5) The table must not have an inner-join ON or USING clause if there is
**      a RIGHT JOIN anywhere in the query.  Otherwise the ON/USING clause
**      might move from the right side to the left side of the RIGHT JOIN.
**      Note: Due to (2), this condition can only arise if the table is
**      the right-most table of a subquery that was flattened into the
**      main query and that subquery was the right-hand operand of an
**      inner join that held an ON or USING clause.
**
** For example, given:
**
**     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
**     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
**     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
**
162427
162428
162429
162430
162431
162432
162433

162434
162435
162436
162437
162438
162439
162440
162441
162442
162443
162444
162445
162446
162447

162448
162449
162450
162451
162452
162453
162454
*/
static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
  WhereInfo *pWInfo,
  Bitmask notReady
){
  int i;
  Bitmask tabUsed;


  /* Preconditions checked by the caller */
  assert( pWInfo->nLevel>=2 );
  assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );

  /* These two preconditions checked by the caller combine to guarantee
  ** condition (1) of the header comment */
  assert( pWInfo->pResultSet!=0 );
  assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );

  tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
  if( pWInfo->pOrderBy ){
    tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
  }

  for(i=pWInfo->nLevel-1; i>=1; i--){
    WhereTerm *pTerm, *pEnd;
    SrcItem *pItem;
    WhereLoop *pLoop;
    pLoop = pWInfo->a[i].pWLoop;
    pItem = &pWInfo->pTabList->a[pLoop->iTab];
    if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;







>














>







163337
163338
163339
163340
163341
163342
163343
163344
163345
163346
163347
163348
163349
163350
163351
163352
163353
163354
163355
163356
163357
163358
163359
163360
163361
163362
163363
163364
163365
163366
*/
static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
  WhereInfo *pWInfo,
  Bitmask notReady
){
  int i;
  Bitmask tabUsed;
  int hasRightJoin;

  /* Preconditions checked by the caller */
  assert( pWInfo->nLevel>=2 );
  assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );

  /* These two preconditions checked by the caller combine to guarantee
  ** condition (1) of the header comment */
  assert( pWInfo->pResultSet!=0 );
  assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );

  tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
  if( pWInfo->pOrderBy ){
    tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
  }
  hasRightJoin = (pWInfo->pTabList->a[0].fg.jointype & JT_LTORJ)!=0;
  for(i=pWInfo->nLevel-1; i>=1; i--){
    WhereTerm *pTerm, *pEnd;
    SrcItem *pItem;
    WhereLoop *pLoop;
    pLoop = pWInfo->a[i].pWLoop;
    pItem = &pWInfo->pTabList->a[pLoop->iTab];
    if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
162463
162464
162465
162466
162467
162468
162469






162470
162471
162472
162473
162474
162475
162476
      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
        if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
         || pTerm->pExpr->w.iJoin!=pItem->iCursor
        ){
          break;
        }
      }






    }
    if( pTerm<pEnd ) continue;
    WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop->cId));
    notReady &= ~pLoop->maskSelf;
    for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
        pTerm->wtFlags |= TERM_CODED;







>
>
>
>
>
>







163375
163376
163377
163378
163379
163380
163381
163382
163383
163384
163385
163386
163387
163388
163389
163390
163391
163392
163393
163394
      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
        if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
         || pTerm->pExpr->w.iJoin!=pItem->iCursor
        ){
          break;
        }
      }
      if( hasRightJoin
       && ExprHasProperty(pTerm->pExpr, EP_InnerON)
       && pTerm->pExpr->w.iJoin==pItem->iCursor
      ){
        break;  /* restriction (5) */
      }
    }
    if( pTerm<pEnd ) continue;
    WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop->cId));
    notReady &= ~pLoop->maskSelf;
    for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
        pTerm->wtFlags |= TERM_CODED;
162862
162863
162864
162865
162866
162867
162868


162869
162870

162871
162872





162873
162874

162875
162876
162877
162878






162879
162880
162881

162882




162883



162884
162885
162886
162887
162888
162889
162890
162891
  /* Analyze all of the subexpressions. */
  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  if( pSelect && pSelect->pLimit ){
    sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
  }
  if( pParse->nErr ) goto whereBeginError;



  /* Special case: WHERE terms that do not refer to any tables in the join
  ** (constant expressions). Evaluate each such term, and jump over all the

  ** generated code if the result is not true.
  **





  ** Do not do this if the expression contains non-deterministic functions
  ** that are not within a sub-select. This is not strictly required, but

  ** preserves SQLite's legacy behaviour in the following two cases:
  **
  **   FROM ... WHERE random()>0;           -- eval random() once per row
  **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall






  */
  for(ii=0; ii<sWLB.pWC->nBase; ii++){
    WhereTerm *pT = &sWLB.pWC->a[ii];

    if( pT->wtFlags & TERM_VIRTUAL ) continue;




    if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){



      sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
      pT->wtFlags |= TERM_CODED;
    }
  }

  if( wctrlFlags & WHERE_WANT_DISTINCT ){
    if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
      /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via







>
>
|
|
>
|

>
>
>
>
>
|
|
>
|

|
|
>
>
>
>
>
>


|
>

>
>
>
>
|
>
>
>
|







163780
163781
163782
163783
163784
163785
163786
163787
163788
163789
163790
163791
163792
163793
163794
163795
163796
163797
163798
163799
163800
163801
163802
163803
163804
163805
163806
163807
163808
163809
163810
163811
163812
163813
163814
163815
163816
163817
163818
163819
163820
163821
163822
163823
163824
163825
163826
163827
163828
163829
163830
163831
163832
  /* Analyze all of the subexpressions. */
  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  if( pSelect && pSelect->pLimit ){
    sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
  }
  if( pParse->nErr ) goto whereBeginError;

  /* The False-WHERE-Term-Bypass optimization:
  **
  ** If there are WHERE terms that are false, then no rows will be output,
  ** so skip over all of the code generated here.
  **
  ** Conditions:
  **
  **   (1)  The WHERE term must not refer to any tables in the join.
  **   (2)  The term must not come from an ON clause on the
  **        right-hand side of a LEFT or FULL JOIN.
  **   (3)  The term must not come from an ON clause, or there must be
  **        no RIGHT or FULL OUTER joins in pTabList.
  **   (4)  If the expression contains non-deterministic functions
  **        that are not within a sub-select. This is not required
  **        for correctness but rather to preserves SQLite's legacy
  **        behaviour in the following two cases:
  **
  **          WHERE random()>0;           -- eval random() once per row
  **          WHERE (SELECT random())>0;  -- eval random() just once overall
  **
  ** Note that the Where term need not be a constant in order for this
  ** optimization to apply, though it does need to be constant relative to
  ** the current subquery (condition 1).  The term might include variables
  ** from outer queries so that the value of the term changes from one
  ** invocation of the current subquery to the next.
  */
  for(ii=0; ii<sWLB.pWC->nBase; ii++){
    WhereTerm *pT = &sWLB.pWC->a[ii];  /* A term of the WHERE clause */
    Expr *pX;                          /* The expression of pT */
    if( pT->wtFlags & TERM_VIRTUAL ) continue;
    pX = pT->pExpr;
    assert( pX!=0 );
    assert( pT->prereqAll!=0 || !ExprHasProperty(pX, EP_OuterON) );
    if( pT->prereqAll==0                           /* Conditions (1) and (2) */
     && (nTabList==0 || exprIsDeterministic(pX))   /* Condition (4) */
     && !(ExprHasProperty(pX, EP_InnerON)          /* Condition (3) */
          && (pTabList->a[0].fg.jointype & JT_LTORJ)!=0 )
    ){
      sqlite3ExprIfFalse(pParse, pX, pWInfo->iBreak, SQLITE_JUMPIFNULL);
      pT->wtFlags |= TERM_CODED;
    }
  }

  if( wctrlFlags & WHERE_WANT_DISTINCT ){
    if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
      /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
163120
163121
163122
163123
163124
163125
163126
163127
163128
163129
163130
163131
163132
163133
163134
        Bitmask b = pTabItem->colUsed;
        int n = 0;
        for(; b; b=b>>1, n++){}
        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
        assert( n<=pTab->nCol );
      }
#ifdef SQLITE_ENABLE_CURSOR_HINTS
      if( pLoop->u.btree.pIndex!=0 ){
        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
      }else
#endif
      {
        sqlite3VdbeChangeP5(v, bFordelete);
      }
#ifdef SQLITE_ENABLE_COLUMN_USED_MASK







|







164061
164062
164063
164064
164065
164066
164067
164068
164069
164070
164071
164072
164073
164074
164075
        Bitmask b = pTabItem->colUsed;
        int n = 0;
        for(; b; b=b>>1, n++){}
        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
        assert( n<=pTab->nCol );
      }
#ifdef SQLITE_ENABLE_CURSOR_HINTS
      if( pLoop->u.btree.pIndex!=0 && (pTab->tabFlags & TF_WithoutRowid)==0 ){
        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
      }else
#endif
      {
        sqlite3VdbeChangeP5(v, bFordelete);
      }
#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
163257
163258
163259
163260
163261
163262
163263

163264
163265
163266
163267
163268
163269
163270
163271
163272
163273
163274
163275
        sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
      }else{
        int iOnce = sqlite3VdbeAddOp0(v, OP_Once);  VdbeCoverage(v);
        sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
        sqlite3VdbeJumpHere(v, iOnce);
      }
    }

    if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
      if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
        constructAutomaticIndex(pParse, &pWInfo->sWC,
                  &pTabList->a[pLevel->iFrom], notReady, pLevel);
#endif
      }else{
        sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
      }
      if( db->mallocFailed ) goto whereBeginError;
    }
    addrExplain = sqlite3WhereExplainOneScan(







>



|
<







164198
164199
164200
164201
164202
164203
164204
164205
164206
164207
164208
164209

164210
164211
164212
164213
164214
164215
164216
        sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
      }else{
        int iOnce = sqlite3VdbeAddOp0(v, OP_Once);  VdbeCoverage(v);
        sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
        sqlite3VdbeJumpHere(v, iOnce);
      }
    }
    assert( pTabList == pWInfo->pTabList );
    if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
      if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
        constructAutomaticIndex(pParse, &pWInfo->sWC, notReady, pLevel);

#endif
      }else{
        sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
      }
      if( db->mallocFailed ) goto whereBeginError;
    }
    addrExplain = sqlite3WhereExplainOneScan(
163578
163579
163580
163581
163582
163583
163584
163585

163586
163587
163588
163589
163590
163591
163592
          }
          p = p->pIENext;
        }
      }
      k = pLevel->addrBody + 1;
#ifdef SQLITE_DEBUG
      if( db->flags & SQLITE_VdbeAddopTrace ){
        printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);

      }
      /* Proof that the "+1" on the k value above is safe */
      pOp = sqlite3VdbeGetOp(v, k - 1);
      assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
      assert( pOp->opcode!=OP_Rowid  || pOp->p1!=pLevel->iTabCur );
      assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
#endif







|
>







164519
164520
164521
164522
164523
164524
164525
164526
164527
164528
164529
164530
164531
164532
164533
164534
          }
          p = p->pIENext;
        }
      }
      k = pLevel->addrBody + 1;
#ifdef SQLITE_DEBUG
      if( db->flags & SQLITE_VdbeAddopTrace ){
        printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n",
                pLevel->iTabCur, pLevel->iIdxCur, k, last-1);
      }
      /* Proof that the "+1" on the k value above is safe */
      pOp = sqlite3VdbeGetOp(v, k - 1);
      assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
      assert( pOp->opcode!=OP_Rowid  || pOp->p1!=pLevel->iTabCur );
      assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
#endif
164453
164454
164455
164456
164457
164458
164459

164460
164461
164462
164463
164464
164465
164466
            assert( pWin->pOwner==pExpr );
            return WRC_Prune;
          }
        }
      }
      /* no break */ deliberate_fall_through


    case TK_AGG_FUNCTION:
    case TK_COLUMN: {
      int iCol = -1;
      if( pParse->db->mallocFailed ) return WRC_Abort;
      if( p->pSub ){
        int i;
        for(i=0; i<p->pSub->nExpr; i++){







>







165395
165396
165397
165398
165399
165400
165401
165402
165403
165404
165405
165406
165407
165408
165409
            assert( pWin->pOwner==pExpr );
            return WRC_Prune;
          }
        }
      }
      /* no break */ deliberate_fall_through

    case TK_IF_NULL_ROW:
    case TK_AGG_FUNCTION:
    case TK_COLUMN: {
      int iCol = -1;
      if( pParse->db->mallocFailed ) return WRC_Abort;
      if( p->pSub ){
        int i;
        for(i=0; i<p->pSub->nExpr; i++){
167281
167282
167283
167284
167285
167286
167287
167288
167289
167290
167291
167292
167293
167294
167295
167296
167297
167298
167299
167300
167301
167302
167303
167304
167305
167306
#define sqlite3ParserARG_STORE
#define sqlite3ParserCTX_SDECL Parse *pParse;
#define sqlite3ParserCTX_PDECL ,Parse *pParse
#define sqlite3ParserCTX_PARAM ,pParse
#define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
#define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
#define YYFALLBACK 1
#define YYNSTATE             576
#define YYNRULE              405
#define YYNRULE_WITH_ACTION  342
#define YYNTOKEN             185
#define YY_MAX_SHIFT         575
#define YY_MIN_SHIFTREDUCE   835
#define YY_MAX_SHIFTREDUCE   1239
#define YY_ERROR_ACTION      1240
#define YY_ACCEPT_ACTION     1241
#define YY_NO_ACTION         1242
#define YY_MIN_REDUCE        1243
#define YY_MAX_REDUCE        1647
/************* End control #defines *******************************************/
#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))

/* Define the yytestcase() macro to be a no-op if is not already defined
** otherwise.
**
** Applications can choose to define yytestcase() in the %include section







|
|
|

|
|
|
|
|
|
|
|







168224
168225
168226
168227
168228
168229
168230
168231
168232
168233
168234
168235
168236
168237
168238
168239
168240
168241
168242
168243
168244
168245
168246
168247
168248
168249
#define sqlite3ParserARG_STORE
#define sqlite3ParserCTX_SDECL Parse *pParse;
#define sqlite3ParserCTX_PDECL ,Parse *pParse
#define sqlite3ParserCTX_PARAM ,pParse
#define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
#define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
#define YYFALLBACK 1
#define YYNSTATE             575
#define YYNRULE              403
#define YYNRULE_WITH_ACTION  340
#define YYNTOKEN             185
#define YY_MAX_SHIFT         574
#define YY_MIN_SHIFTREDUCE   833
#define YY_MAX_SHIFTREDUCE   1235
#define YY_ERROR_ACTION      1236
#define YY_ACCEPT_ACTION     1237
#define YY_NO_ACTION         1238
#define YY_MIN_REDUCE        1239
#define YY_MAX_REDUCE        1641
/************* End control #defines *******************************************/
#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))

/* Define the yytestcase() macro to be a no-op if is not already defined
** otherwise.
**
** Applications can choose to define yytestcase() in the %include section
167359
167360
167361
167362
167363
167364
167365
167366
167367
167368
167369
167370
167371
167372
167373
167374
167375
167376
167377
167378
167379
167380
167381
167382
167383
167384
167385
167386
167387
167388
167389
167390
167391
167392
167393
167394
167395
167396
167397
167398
167399
167400
167401
167402
167403
167404
167405
167406
167407
167408
167409
167410
167411
167412
167413
167414
167415
167416
167417
167418
167419
167420
167421
167422
167423
167424
167425
167426
167427
167428
167429
167430
167431
167432
167433
167434
167435
167436
167437
167438
167439
167440
167441
167442
167443
167444
167445
167446
167447
167448
167449
167450
167451
167452
167453
167454
167455
167456
167457
167458
167459
167460
167461
167462
167463
167464
167465
167466
167467
167468
167469
167470
167471
167472
167473
167474
167475
167476
167477
167478
167479
167480
167481
167482
167483
167484
167485
167486
167487
167488
167489
167490
167491
167492
167493
167494
167495
167496
167497
167498
167499
167500
167501
167502
167503
167504
167505
167506
167507
167508
167509
167510
167511
167512
167513
167514
167515
167516
167517
167518
167519
167520
167521
167522
167523
167524
167525
167526
167527
167528
167529
167530
167531
167532
167533
167534
167535
167536
167537
167538
167539
167540
167541
167542
167543
167544
167545
167546
167547
167548
167549
167550
167551
167552
167553
167554
167555
167556
167557
167558
167559
167560
167561
167562
167563
167564
167565
167566
167567
167568
167569
167570
167571
167572
167573
167574
167575
167576
167577
167578
167579
167580
167581
167582
167583
167584
**  yy_shift_ofst[]    For each state, the offset into yy_action for
**                     shifting terminals.
**  yy_reduce_ofst[]   For each state, the offset into yy_action for
**                     shifting non-terminals after a reduce.
**  yy_default[]       Default action for each state.
**
*********** Begin parsing tables **********************************************/
#define YY_ACTTAB_COUNT (2098)
static const YYACTIONTYPE yy_action[] = {
 /*     0 */   568,  208,  568,  118,  115,  229,  568,  118,  115,  229,
 /*    10 */   568, 1314,  377, 1293,  408,  562,  562,  562,  568,  409,
 /*    20 */   378, 1314, 1276,   41,   41,   41,   41,  208, 1526,   71,
 /*    30 */    71,  971,  419,   41,   41,  491,  303,  279,  303,  972,
 /*    40 */   397,   71,   71,  125,  126,   80, 1217, 1217, 1050, 1053,
 /*    50 */  1040, 1040,  123,  123,  124,  124,  124,  124,  476,  409,
 /*    60 */  1241,    1,    1,  575,    2, 1245,  550,  118,  115,  229,
 /*    70 */   317,  480,  146,  480,  524,  118,  115,  229,  529, 1327,
 /*    80 */   417,  523,  142,  125,  126,   80, 1217, 1217, 1050, 1053,
 /*    90 */  1040, 1040,  123,  123,  124,  124,  124,  124,  118,  115,
 /*   100 */   229,  327,  122,  122,  122,  122,  121,  121,  120,  120,
 /*   110 */   120,  119,  116,  444,  284,  284,  284,  284,  442,  442,
 /*   120 */   442, 1567,  376, 1569, 1192,  375, 1163,  565, 1163,  565,
 /*   130 */   409, 1567,  537,  259,  226,  444,  101,  145,  449,  316,
 /*   140 */   559,  240,  122,  122,  122,  122,  121,  121,  120,  120,
 /*   150 */   120,  119,  116,  444,  125,  126,   80, 1217, 1217, 1050,
 /*   160 */  1053, 1040, 1040,  123,  123,  124,  124,  124,  124,  142,
 /*   170 */   294, 1192,  339,  448,  120,  120,  120,  119,  116,  444,
 /*   180 */   127, 1192, 1193, 1194,  148,  441,  440,  568,  119,  116,
 /*   190 */   444,  124,  124,  124,  124,  117,  122,  122,  122,  122,
 /*   200 */   121,  121,  120,  120,  120,  119,  116,  444,  454,  113,
 /*   210 */    13,   13,  546,  122,  122,  122,  122,  121,  121,  120,
 /*   220 */   120,  120,  119,  116,  444,  422,  316,  559, 1192, 1193,
 /*   230 */  1194,  149, 1224,  409, 1224,  124,  124,  124,  124,  122,
 /*   240 */   122,  122,  122,  121,  121,  120,  120,  120,  119,  116,
 /*   250 */   444,  465,  342, 1037, 1037, 1051, 1054,  125,  126,   80,
 /*   260 */  1217, 1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,
 /*   270 */   124,  124, 1279,  522,  222, 1192,  568,  409,  224,  514,
 /*   280 */   175,   82,   83,  122,  122,  122,  122,  121,  121,  120,
 /*   290 */   120,  120,  119,  116,  444, 1007,   16,   16, 1192,  133,
 /*   300 */   133,  125,  126,   80, 1217, 1217, 1050, 1053, 1040, 1040,
 /*   310 */   123,  123,  124,  124,  124,  124,  122,  122,  122,  122,
 /*   320 */   121,  121,  120,  120,  120,  119,  116,  444, 1041,  546,
 /*   330 */  1192,  373, 1192, 1193, 1194,  252, 1434,  399,  504,  501,
 /*   340 */   500,  111,  560,  566,    4,  926,  926,  433,  499,  340,
 /*   350 */   460,  328,  360,  394, 1237, 1192, 1193, 1194,  563,  568,
 /*   360 */   122,  122,  122,  122,  121,  121,  120,  120,  120,  119,
 /*   370 */   116,  444,  284,  284,  369, 1580, 1607,  441,  440,  154,
 /*   380 */   409,  445,   71,   71, 1286,  565, 1221, 1192, 1193, 1194,
 /*   390 */    85, 1223,  271,  557,  543,  515, 1561,  568,   98, 1222,
 /*   400 */     6, 1278,  472,  142,  125,  126,   80, 1217, 1217, 1050,
 /*   410 */  1053, 1040, 1040,  123,  123,  124,  124,  124,  124,  550,
 /*   420 */    13,   13, 1027,  507, 1224, 1192, 1224,  549,  109,  109,
 /*   430 */   222,  568, 1238,  175,  568,  427,  110,  197,  445,  570,
 /*   440 */   569,  430, 1552, 1017,  325,  551, 1192,  270,  287,  368,
 /*   450 */   510,  363,  509,  257,   71,   71,  543,   71,   71,  359,
 /*   460 */   316,  559, 1613,  122,  122,  122,  122,  121,  121,  120,
 /*   470 */   120,  120,  119,  116,  444, 1017, 1017, 1019, 1020,   27,
 /*   480 */   284,  284, 1192, 1193, 1194, 1158,  568, 1612,  409,  901,
 /*   490 */   190,  550,  356,  565,  550,  937,  533,  517, 1158,  516,
 /*   500 */   413, 1158,  552, 1192, 1193, 1194,  568,  544, 1554,   51,
 /*   510 */    51,  214,  125,  126,   80, 1217, 1217, 1050, 1053, 1040,
 /*   520 */  1040,  123,  123,  124,  124,  124,  124, 1192,  474,  135,
 /*   530 */   135,  409,  284,  284, 1490,  505,  121,  121,  120,  120,
 /*   540 */   120,  119,  116,  444, 1007,  565,  518,  217,  541, 1561,
 /*   550 */   316,  559,  142,    6,  532,  125,  126,   80, 1217, 1217,
 /*   560 */  1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,  124,
 /*   570 */  1555,  122,  122,  122,  122,  121,  121,  120,  120,  120,
 /*   580 */   119,  116,  444,  485, 1192, 1193, 1194,  482,  281, 1267,
 /*   590 */   957,  252, 1192,  373,  504,  501,  500, 1192,  340,  571,
 /*   600 */  1192,  571,  409,  292,  499,  957,  876,  191,  480,  316,
 /*   610 */   559,  384,  290,  380,  122,  122,  122,  122,  121,  121,
 /*   620 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1217,
 /*   630 */  1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,
 /*   640 */   124,  409,  394, 1136, 1192,  869,  100,  284,  284, 1192,
 /*   650 */  1193, 1194,  373, 1093, 1192, 1193, 1194, 1192, 1193, 1194,
 /*   660 */   565,  455,   32,  373,  233,  125,  126,   80, 1217, 1217,
 /*   670 */  1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,  124,
 /*   680 */  1433,  959,  568,  228,  958,  122,  122,  122,  122,  121,
 /*   690 */   121,  120,  120,  120,  119,  116,  444, 1158,  228, 1192,
 /*   700 */   157, 1192, 1193, 1194, 1553,   13,   13,  301,  957, 1232,
 /*   710 */  1158,  153,  409, 1158,  373, 1583, 1176,    5,  369, 1580,
 /*   720 */   429, 1238,    3,  957,  122,  122,  122,  122,  121,  121,
 /*   730 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1217,
 /*   740 */  1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,
 /*   750 */   124,  409,  208,  567, 1192, 1028, 1192, 1193, 1194, 1192,
 /*   760 */   388,  852,  155, 1552,  286,  402, 1098, 1098,  488,  568,
 /*   770 */   465,  342, 1319, 1319, 1552,  125,  126,   80, 1217, 1217,
 /*   780 */  1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,  124,
 /*   790 */   129,  568,   13,   13,  374,  122,  122,  122,  122,  121,
 /*   800 */   121,  120,  120,  120,  119,  116,  444,  302,  568,  453,
 /*   810 */   528, 1192, 1193, 1194,   13,   13, 1192, 1193, 1194, 1297,
 /*   820 */   463, 1267,  409, 1317, 1317, 1552, 1012,  453,  452,  200,
 /*   830 */   299,   71,   71, 1265,  122,  122,  122,  122,  121,  121,
 /*   840 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1217,
 /*   850 */  1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,
 /*   860 */   124,  409,  227, 1073, 1158,  284,  284,  419,  312,  278,
 /*   870 */   278,  285,  285, 1419,  406,  405,  382, 1158,  565,  568,
 /*   880 */  1158, 1196,  565, 1600,  565,  125,  126,   80, 1217, 1217,
 /*   890 */  1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,  124,
 /*   900 */   453, 1482,   13,   13, 1536,  122,  122,  122,  122,  121,
 /*   910 */   121,  120,  120,  120,  119,  116,  444,  201,  568,  354,
 /*   920 */  1586,  575,    2, 1245,  840,  841,  842, 1562,  317, 1212,
 /*   930 */   146,    6,  409,  255,  254,  253,  206, 1327,    9, 1196,
 /*   940 */   262,   71,   71,  424,  122,  122,  122,  122,  121,  121,
 /*   950 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1217,
 /*   960 */  1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,
 /*   970 */   124,  568,  284,  284,  568, 1213,  409,  574,  313, 1245,
 /*   980 */   349, 1296,  352,  419,  317,  565,  146,  491,  525, 1643,
 /*   990 */   395,  371,  491, 1327,   70,   70, 1295,   71,   71,  240,
 /*  1000 */  1325,  104,   80, 1217, 1217, 1050, 1053, 1040, 1040,  123,
 /*  1010 */   123,  124,  124,  124,  124,  122,  122,  122,  122,  121,
 /*  1020 */   121,  120,  120,  120,  119,  116,  444, 1114,  284,  284,
 /*  1030 */   428,  448, 1525, 1213,  439,  284,  284, 1489, 1352,  311,
 /*  1040 */   474,  565, 1115,  971,  491,  491,  217, 1263,  565, 1538,
 /*  1050 */   568,  972,  207,  568, 1027,  240,  383, 1116,  519,  122,
 /*  1060 */   122,  122,  122,  121,  121,  120,  120,  120,  119,  116,
 /*  1070 */   444, 1018,  107,   71,   71, 1017,   13,   13,  912,  568,
 /*  1080 */  1495,  568,  284,  284,   97,  526,  491,  448,  913, 1326,
 /*  1090 */  1322,  545,  409,  284,  284,  565,  151,  209, 1495, 1497,
 /*  1100 */   262,  450,   55,   55,   56,   56,  565, 1017, 1017, 1019,
 /*  1110 */   443,  332,  409,  527,   12,  295,  125,  126,   80, 1217,
 /*  1120 */  1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,
 /*  1130 */   124,  347,  409,  864, 1534, 1213,  125,  126,   80, 1217,
 /*  1140 */  1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,
 /*  1150 */   124, 1137, 1641,  474, 1641,  371,  125,  114,   80, 1217,
 /*  1160 */  1217, 1050, 1053, 1040, 1040,  123,  123,  124,  124,  124,
 /*  1170 */   124, 1495,  329,  474,  331,  122,  122,  122,  122,  121,
 /*  1180 */   121,  120,  120,  120,  119,  116,  444,  203, 1419,  568,
 /*  1190 */  1294,  864,  464, 1213,  436,  122,  122,  122,  122,  121,
 /*  1200 */   121,  120,  120,  120,  119,  116,  444,  553, 1137, 1642,
 /*  1210 */   539, 1642,   15,   15,  892,  122,  122,  122,  122,  121,
 /*  1220 */   121,  120,  120,  120,  119,  116,  444,  568,  298,  538,
 /*  1230 */  1135, 1419, 1559, 1560, 1331,  409,    6,    6, 1169, 1268,
 /*  1240 */   415,  320,  284,  284, 1419,  508,  565,  525,  300,  457,
 /*  1250 */    43,   43,  568,  893,   12,  565,  330,  478,  425,  407,
 /*  1260 */   126,   80, 1217, 1217, 1050, 1053, 1040, 1040,  123,  123,
 /*  1270 */   124,  124,  124,  124,  568,   57,   57,  288, 1192, 1419,
 /*  1280 */   496,  458,  392,  392,  391,  273,  389, 1135, 1558,  849,
 /*  1290 */  1169,  407,    6,  568,  321, 1158,  470,   44,   44, 1557,
 /*  1300 */  1114,  426,  234,    6,  323,  256,  540,  256, 1158,  431,
 /*  1310 */   568, 1158,  322,   17,  487, 1115,   58,   58,  122,  122,
 /*  1320 */   122,  122,  121,  121,  120,  120,  120,  119,  116,  444,
 /*  1330 */  1116,  216,  481,   59,   59, 1192, 1193, 1194,  111,  560,
 /*  1340 */   324,    4,  236,  456,  526,  568,  237,  456,  568,  437,
 /*  1350 */   168,  556,  420,  141,  479,  563,  568,  293,  568, 1095,
 /*  1360 */   568,  293,  568, 1095,  531,  568,  872,    8,   60,   60,
 /*  1370 */   235,   61,   61,  568,  414,  568,  414,  568,  445,   62,
 /*  1380 */    62,   45,   45,   46,   46,   47,   47,  199,   49,   49,
 /*  1390 */   557,  568,  359,  568,  100,  486,   50,   50,   63,   63,
 /*  1400 */    64,   64,  561,  415,  535,  410,  568, 1027,  568,  534,
 /*  1410 */   316,  559,  316,  559,   65,   65,   14,   14,  568, 1027,
 /*  1420 */   568,  512,  932,  872, 1018,  109,  109,  931, 1017,   66,
 /*  1430 */    66,  131,  131,  110,  451,  445,  570,  569,  416,  177,
 /*  1440 */  1017,  132,  132,   67,   67,  568,  467,  568,  932,  471,
 /*  1450 */  1364,  283,  226,  931,  315, 1363,  407,  568,  459,  407,
 /*  1460 */  1017, 1017, 1019,  239,  407,   86,  213, 1350,   52,   52,
 /*  1470 */    68,   68, 1017, 1017, 1019, 1020,   27, 1585, 1180,  447,
 /*  1480 */    69,   69,  288,   97,  108, 1541,  106,  392,  392,  391,
 /*  1490 */   273,  389,  568,  879,  849,  883,  568,  111,  560,  466,
 /*  1500 */     4,  568,  152,   30,   38,  568, 1132,  234,  396,  323,
 /*  1510 */   111,  560,  527,    4,  563,   53,   53,  322,  568,  163,
 /*  1520 */   163,  568,  337,  468,  164,  164,  333,  563,   76,   76,
 /*  1530 */   568,  289, 1514,  568,   31, 1513,  568,  445,  338,  483,
 /*  1540 */   100,   54,   54,  344,   72,   72,  296,  236, 1080,  557,
 /*  1550 */   445,  879, 1360,  134,  134,  168,   73,   73,  141,  161,
 /*  1560 */   161, 1574,  557,  535,  568,  319,  568,  348,  536, 1009,
 /*  1570 */   473,  261,  261,  891,  890,  235,  535,  568, 1027,  568,
 /*  1580 */   475,  534,  261,  367,  109,  109,  521,  136,  136,  130,
 /*  1590 */   130, 1027,  110,  366,  445,  570,  569,  109,  109, 1017,
 /*  1600 */   162,  162,  156,  156,  568,  110, 1080,  445,  570,  569,
 /*  1610 */   410,  351, 1017,  568,  353,  316,  559,  568,  343,  568,
 /*  1620 */   100,  497,  357,  258,  100,  898,  899,  140,  140,  355,
 /*  1630 */  1310, 1017, 1017, 1019, 1020,   27,  139,  139,  362,  451,
 /*  1640 */   137,  137,  138,  138, 1017, 1017, 1019, 1020,   27, 1180,
 /*  1650 */   447,  568,  372,  288,  111,  560, 1021,    4,  392,  392,
 /*  1660 */   391,  273,  389,  568, 1141,  849,  568, 1076,  568,  258,
 /*  1670 */   492,  563,  568,  211,   75,   75,  555,  962,  234,  261,
 /*  1680 */   323,  111,  560,  929,    4,  113,   77,   77,  322,   74,
 /*  1690 */    74,   42,   42, 1373,  445,   48,   48, 1418,  563,  974,
 /*  1700 */   975, 1092, 1091, 1092, 1091,  862,  557,  150,  930, 1346,
 /*  1710 */   113, 1358,  554, 1424, 1021, 1275, 1266, 1254,  236, 1253,
 /*  1720 */  1255,  445, 1593, 1343,  308,  276,  168,  309,   11,  141,
 /*  1730 */   393,  310,  232,  557, 1405, 1027,  335,  291, 1400,  219,
 /*  1740 */   336,  109,  109,  936,  297, 1410,  235,  341,  477,  110,
 /*  1750 */   502,  445,  570,  569, 1393, 1409, 1017,  400, 1293,  365,
 /*  1760 */   223, 1486, 1027, 1485, 1355, 1356, 1354, 1353,  109,  109,
 /*  1770 */   204, 1596, 1232,  558,  265,  218,  110,  205,  445,  570,
 /*  1780 */   569,  410,  387, 1017, 1533,  179,  316,  559, 1017, 1017,
 /*  1790 */  1019, 1020,   27,  230, 1531, 1229,   79,  560,   85,    4,
 /*  1800 */   418,  215,  548,   81,   84,  188, 1406,  173,  181,  461,
 /*  1810 */   451,   35,  462,  563,  183, 1017, 1017, 1019, 1020,   27,
 /*  1820 */   184, 1491,  185,  186,  495,  242,   98,  398, 1412,   36,
 /*  1830 */  1411,  484,   91,  469,  401, 1414,  445,  192, 1480,  246,
 /*  1840 */  1502,  490,  346,  277,  248,  196,  493,  511,  557,  350,
 /*  1850 */  1256,  249,  250,  403, 1313, 1312,  111,  560,  432,    4,
 /*  1860 */  1311, 1304,   93, 1611,  883, 1610,  224,  404,  434,  520,
 /*  1870 */   263,  435, 1579,  563, 1283, 1282,  364, 1027,  306, 1281,
 /*  1880 */   264, 1609, 1565,  109,  109,  370, 1303,  307, 1564,  438,
 /*  1890 */   128,  110, 1378,  445,  570,  569,  445,  546, 1017,   10,
 /*  1900 */  1466,  105,  381, 1377,   34,  572,   99, 1336,  557,  314,
 /*  1910 */  1186,  530,  272,  274,  379,  210, 1335,  547,  385,  386,
 /*  1920 */   275,  573, 1251, 1246,  411,  412, 1518,  165,  178, 1519,
 /*  1930 */  1017, 1017, 1019, 1020,   27, 1517, 1516, 1027,   78,  147,
 /*  1940 */   166,  220,  221,  109,  109,  836,  304,  167,  446,  212,
 /*  1950 */   318,  110,  231,  445,  570,  569,  144, 1090, 1017, 1088,
 /*  1960 */   326,  180,  169, 1212,  182,  334,  238,  915,  241, 1104,
 /*  1970 */   187,  170,  171,  421,   87,   88,  423,  189,   89,   90,
 /*  1980 */   172, 1107,  243, 1103,  244,  158,   18,  245,  345,  247,
 /*  1990 */  1017, 1017, 1019, 1020,   27,  261, 1096,  193, 1226,  489,
 /*  2000 */   194,   37,  366,  851,  494,  251,  195,  506,   92,   19,
 /*  2010 */   498,  358,   20,  503,  881,  361,   94,  894,  305,  159,
 /*  2020 */   513,   39,   95, 1174,  160, 1056,  966, 1143,   96,  174,
 /*  2030 */  1142,  225,  280,  282,  198,  960,  113, 1164, 1160,  260,
 /*  2040 */    21,   22,   23, 1162, 1168, 1167, 1148,   24,   33,   25,
 /*  2050 */   202,  542,   26,  100, 1071,  102, 1057,  103,    7, 1055,
 /*  2060 */  1059, 1113, 1060, 1112,  266,  267,   28,   40,  390, 1022,
 /*  2070 */   863,  112,   29,  564, 1182, 1181,  268,  176,  143,  925,
 /*  2080 */  1242, 1242, 1242, 1242, 1242, 1242, 1242, 1242, 1242, 1242,
 /*  2090 */  1242, 1242, 1242, 1242,  269, 1602, 1242, 1601,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */   193,  193,  193,  274,  275,  276,  193,  274,  275,  276,
 /*    10 */   193,  223,  219,  225,  206,  210,  211,  212,  193,   19,
 /*    20 */   219,  233,  216,  216,  217,  216,  217,  193,  295,  216,
 /*    30 */   217,   31,  193,  216,  217,  193,  228,  213,  230,   39,
 /*    40 */   206,  216,  217,   43,   44,   45,   46,   47,   48,   49,







|


|
|
|
|
|
|
|
|
|


|
|

|
|
|
|



|
|

|
|
|

|
|

|
|
|
|

|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|
|
|
|
|
|
|
|
|

|
|

|
|
|
|
|
|

|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|

|
|



|
|
|
|
|
|
|
|
|
|
|


|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|







168302
168303
168304
168305
168306
168307
168308
168309
168310
168311
168312
168313
168314
168315
168316
168317
168318
168319
168320
168321
168322
168323
168324
168325
168326
168327
168328
168329
168330
168331
168332
168333
168334
168335
168336
168337
168338
168339
168340
168341
168342
168343
168344
168345
168346
168347
168348
168349
168350
168351
168352
168353
168354
168355
168356
168357
168358
168359
168360
168361
168362
168363
168364
168365
168366
168367
168368
168369
168370
168371
168372
168373
168374
168375
168376
168377
168378
168379
168380
168381
168382
168383
168384
168385
168386
168387
168388
168389
168390
168391
168392
168393
168394
168395
168396
168397
168398
168399
168400
168401
168402
168403
168404
168405
168406
168407
168408
168409
168410
168411
168412
168413
168414
168415
168416
168417
168418
168419
168420
168421
168422
168423
168424
168425
168426
168427
168428
168429
168430
168431
168432
168433
168434
168435
168436
168437
168438
168439
168440
168441
168442
168443
168444
168445
168446
168447
168448
168449
168450
168451
168452
168453
168454
168455
168456
168457
168458
168459
168460
168461
168462
168463
168464
168465
168466
168467
168468
168469
168470
168471
168472
168473
168474
168475
168476
168477
168478
168479
168480
168481
168482
168483
168484
168485
168486
168487
168488
168489
168490
168491
168492
168493
168494
168495
168496
168497
168498
168499
168500
168501
168502
168503
168504
168505
168506
168507
168508
168509
168510
168511
168512
168513
168514
168515
168516
168517
168518
168519
168520
168521
168522
168523
168524
168525
168526
168527
**  yy_shift_ofst[]    For each state, the offset into yy_action for
**                     shifting terminals.
**  yy_reduce_ofst[]   For each state, the offset into yy_action for
**                     shifting non-terminals after a reduce.
**  yy_default[]       Default action for each state.
**
*********** Begin parsing tables **********************************************/
#define YY_ACTTAB_COUNT (2096)
static const YYACTIONTYPE yy_action[] = {
 /*     0 */   568,  208,  568,  118,  115,  229,  568,  118,  115,  229,
 /*    10 */   568, 1310,  377, 1289,  408,  562,  562,  562,  568,  409,
 /*    20 */   378, 1310, 1272,   41,   41,   41,   41,  208, 1520,   71,
 /*    30 */    71,  969,  419,   41,   41,  491,  303,  279,  303,  970,
 /*    40 */   397,   71,   71,  125,  126,   80, 1212, 1212, 1047, 1050,
 /*    50 */  1037, 1037,  123,  123,  124,  124,  124,  124,  476,  409,
 /*    60 */  1237,    1,    1,  574,    2, 1241,  550,  118,  115,  229,
 /*    70 */   317,  480,  146,  480,  524,  118,  115,  229,  529, 1323,
 /*    80 */   417,  523,  142,  125,  126,   80, 1212, 1212, 1047, 1050,
 /*    90 */  1037, 1037,  123,  123,  124,  124,  124,  124,  118,  115,
 /*   100 */   229,  327,  122,  122,  122,  122,  121,  121,  120,  120,
 /*   110 */   120,  119,  116,  444,  284,  284,  284,  284,  442,  442,
 /*   120 */   442, 1561,  376, 1563, 1188,  375, 1159,  565, 1159,  565,
 /*   130 */   409, 1561,  537,  259,  226,  444,  101,  145,  449,  316,
 /*   140 */   559,  240,  122,  122,  122,  122,  121,  121,  120,  120,
 /*   150 */   120,  119,  116,  444,  125,  126,   80, 1212, 1212, 1047,
 /*   160 */  1050, 1037, 1037,  123,  123,  124,  124,  124,  124,  142,
 /*   170 */   294, 1188,  339,  448,  120,  120,  120,  119,  116,  444,
 /*   180 */   127, 1188, 1189, 1188,  148,  441,  440,  568,  119,  116,
 /*   190 */   444,  124,  124,  124,  124,  117,  122,  122,  122,  122,
 /*   200 */   121,  121,  120,  120,  120,  119,  116,  444,  454,  113,
 /*   210 */    13,   13,  546,  122,  122,  122,  122,  121,  121,  120,
 /*   220 */   120,  120,  119,  116,  444,  422,  316,  559, 1188, 1189,
 /*   230 */  1188,  149, 1220,  409, 1220,  124,  124,  124,  124,  122,
 /*   240 */   122,  122,  122,  121,  121,  120,  120,  120,  119,  116,
 /*   250 */   444,  465,  342, 1034, 1034, 1048, 1051,  125,  126,   80,
 /*   260 */  1212, 1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,
 /*   270 */   124,  124, 1275,  522,  222, 1188,  568,  409,  224,  514,
 /*   280 */   175,   82,   83,  122,  122,  122,  122,  121,  121,  120,
 /*   290 */   120,  120,  119,  116,  444, 1005,   16,   16, 1188,  133,
 /*   300 */   133,  125,  126,   80, 1212, 1212, 1047, 1050, 1037, 1037,
 /*   310 */   123,  123,  124,  124,  124,  124,  122,  122,  122,  122,
 /*   320 */   121,  121,  120,  120,  120,  119,  116,  444, 1038,  546,
 /*   330 */  1188,  373, 1188, 1189, 1188,  252, 1429,  399,  504,  501,
 /*   340 */   500,  111,  560,  566,    4,  924,  924,  433,  499,  340,
 /*   350 */   460,  328,  360,  394, 1233, 1188, 1189, 1188,  563,  568,
 /*   360 */   122,  122,  122,  122,  121,  121,  120,  120,  120,  119,
 /*   370 */   116,  444,  284,  284,  369, 1574, 1600,  441,  440,  154,
 /*   380 */   409,  445,   71,   71, 1282,  565, 1217, 1188, 1189, 1188,
 /*   390 */    85, 1219,  271,  557,  543,  515, 1555,  568,   98, 1218,
 /*   400 */     6, 1274,  472,  142,  125,  126,   80, 1212, 1212, 1047,
 /*   410 */  1050, 1037, 1037,  123,  123,  124,  124,  124,  124,  550,
 /*   420 */    13,   13, 1024,  507, 1220, 1188, 1220,  549,  109,  109,
 /*   430 */   222,  568, 1234,  175,  568,  427,  110,  197,  445,  569,
 /*   440 */   445,  430, 1546, 1014,  325,  551, 1188,  270,  287,  368,
 /*   450 */   510,  363,  509,  257,   71,   71,  543,   71,   71,  359,
 /*   460 */   316,  559, 1606,  122,  122,  122,  122,  121,  121,  120,
 /*   470 */   120,  120,  119,  116,  444, 1014, 1014, 1016, 1017,   27,
 /*   480 */   284,  284, 1188, 1189, 1188, 1154,  568, 1605,  409,  899,
 /*   490 */   190,  550,  356,  565,  550,  935,  533,  517, 1154,  516,
 /*   500 */   413, 1154,  552, 1188, 1189, 1188,  568,  544, 1548,   51,
 /*   510 */    51,  214,  125,  126,   80, 1212, 1212, 1047, 1050, 1037,
 /*   520 */  1037,  123,  123,  124,  124,  124,  124, 1188,  474,  135,
 /*   530 */   135,  409,  284,  284, 1484,  505,  121,  121,  120,  120,
 /*   540 */   120,  119,  116,  444, 1005,  565,  518,  217,  541, 1555,
 /*   550 */   316,  559,  142,    6,  532,  125,  126,   80, 1212, 1212,
 /*   560 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
 /*   570 */  1549,  122,  122,  122,  122,  121,  121,  120,  120,  120,
 /*   580 */   119,  116,  444,  485, 1188, 1189, 1188,  482,  281, 1263,
 /*   590 */   955,  252, 1188,  373,  504,  501,  500, 1188,  340,  570,
 /*   600 */  1188,  570,  409,  292,  499,  955,  874,  191,  480,  316,
 /*   610 */   559,  384,  290,  380,  122,  122,  122,  122,  121,  121,
 /*   620 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1212,
 /*   630 */  1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
 /*   640 */   124,  409,  394, 1132, 1188,  867,  100,  284,  284, 1188,
 /*   650 */  1189, 1188,  373, 1089, 1188, 1189, 1188, 1188, 1189, 1188,
 /*   660 */   565,  455,   32,  373,  233,  125,  126,   80, 1212, 1212,
 /*   670 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
 /*   680 */  1428,  957,  568,  228,  956,  122,  122,  122,  122,  121,
 /*   690 */   121,  120,  120,  120,  119,  116,  444, 1154,  228, 1188,
 /*   700 */   157, 1188, 1189, 1188, 1547,   13,   13,  301,  955, 1228,
 /*   710 */  1154,  153,  409, 1154,  373, 1577, 1172,    5,  369, 1574,
 /*   720 */   429, 1234,    3,  955,  122,  122,  122,  122,  121,  121,
 /*   730 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1212,
 /*   740 */  1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
 /*   750 */   124,  409,  208,  567, 1188, 1025, 1188, 1189, 1188, 1188,
 /*   760 */   388,  850,  155, 1546,  286,  402, 1094, 1094,  488,  568,
 /*   770 */   465,  342, 1315, 1315, 1546,  125,  126,   80, 1212, 1212,
 /*   780 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
 /*   790 */   129,  568,   13,   13,  374,  122,  122,  122,  122,  121,
 /*   800 */   121,  120,  120,  120,  119,  116,  444,  302,  568,  453,
 /*   810 */   528, 1188, 1189, 1188,   13,   13, 1188, 1189, 1188, 1293,
 /*   820 */   463, 1263,  409, 1313, 1313, 1546, 1010,  453,  452,  200,
 /*   830 */   299,   71,   71, 1261,  122,  122,  122,  122,  121,  121,
 /*   840 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1212,
 /*   850 */  1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
 /*   860 */   124,  409,  227, 1069, 1154,  284,  284,  419,  312,  278,
 /*   870 */   278,  285,  285, 1415,  406,  405,  382, 1154,  565,  568,
 /*   880 */  1154, 1191,  565, 1594,  565,  125,  126,   80, 1212, 1212,
 /*   890 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
 /*   900 */   453, 1476,   13,   13, 1530,  122,  122,  122,  122,  121,
 /*   910 */   121,  120,  120,  120,  119,  116,  444,  201,  568,  354,
 /*   920 */  1580,  574,    2, 1241,  838,  839,  840, 1556,  317, 1207,
 /*   930 */   146,    6,  409,  255,  254,  253,  206, 1323,    9, 1191,
 /*   940 */   262,   71,   71,  424,  122,  122,  122,  122,  121,  121,
 /*   950 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1212,
 /*   960 */  1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
 /*   970 */   124,  568,  284,  284,  568, 1208,  409,  573,  313, 1241,
 /*   980 */   349, 1292,  352,  419,  317,  565,  146,  491,  525, 1637,
 /*   990 */   395,  371,  491, 1323,   70,   70, 1291,   71,   71,  240,
 /*  1000 */  1321,  104,   80, 1212, 1212, 1047, 1050, 1037, 1037,  123,
 /*  1010 */   123,  124,  124,  124,  124,  122,  122,  122,  122,  121,
 /*  1020 */   121,  120,  120,  120,  119,  116,  444, 1110,  284,  284,
 /*  1030 */   428,  448, 1519, 1208,  439,  284,  284, 1483, 1348,  311,
 /*  1040 */   474,  565, 1111,  969,  491,  491,  217, 1259,  565, 1532,
 /*  1050 */   568,  970,  207,  568, 1024,  240,  383, 1112,  519,  122,
 /*  1060 */   122,  122,  122,  121,  121,  120,  120,  120,  119,  116,
 /*  1070 */   444, 1015,  107,   71,   71, 1014,   13,   13,  910,  568,
 /*  1080 */  1489,  568,  284,  284,   97,  526,  491,  448,  911, 1322,
 /*  1090 */  1318,  545,  409,  284,  284,  565,  151,  209, 1489, 1491,
 /*  1100 */   262,  450,   55,   55,   56,   56,  565, 1014, 1014, 1016,
 /*  1110 */   443,  332,  409,  527,   12,  295,  125,  126,   80, 1212,
 /*  1120 */  1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
 /*  1130 */   124,  347,  409,  862, 1528, 1208,  125,  126,   80, 1212,
 /*  1140 */  1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
 /*  1150 */   124, 1133, 1635,  474, 1635,  371,  125,  114,   80, 1212,
 /*  1160 */  1212, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
 /*  1170 */   124, 1489,  329,  474,  331,  122,  122,  122,  122,  121,
 /*  1180 */   121,  120,  120,  120,  119,  116,  444,  203, 1415,  568,
 /*  1190 */  1290,  862,  464, 1208,  436,  122,  122,  122,  122,  121,
 /*  1200 */   121,  120,  120,  120,  119,  116,  444,  553, 1133, 1636,
 /*  1210 */   539, 1636,   15,   15,  890,  122,  122,  122,  122,  121,
 /*  1220 */   121,  120,  120,  120,  119,  116,  444,  568,  298,  538,
 /*  1230 */  1131, 1415, 1553, 1554, 1327,  409,    6,    6, 1165, 1264,
 /*  1240 */   415,  320,  284,  284, 1415,  508,  565,  525,  300,  457,
 /*  1250 */    43,   43,  568,  891,   12,  565,  330,  478,  425,  407,
 /*  1260 */   126,   80, 1212, 1212, 1047, 1050, 1037, 1037,  123,  123,
 /*  1270 */   124,  124,  124,  124,  568,   57,   57,  288, 1188, 1415,
 /*  1280 */   496,  458,  392,  392,  391,  273,  389, 1131, 1552,  847,
 /*  1290 */  1165,  407,    6,  568,  321, 1154,  470,   44,   44, 1551,
 /*  1300 */  1110,  426,  234,    6,  323,  256,  540,  256, 1154,  431,
 /*  1310 */   568, 1154,  322,   17,  487, 1111,   58,   58,  122,  122,
 /*  1320 */   122,  122,  121,  121,  120,  120,  120,  119,  116,  444,
 /*  1330 */  1112,  216,  481,   59,   59, 1188, 1189, 1188,  111,  560,
 /*  1340 */   324,    4,  236,  456,  526,  568,  237,  456,  568,  437,
 /*  1350 */   168,  556,  420,  141,  479,  563,  568,  293,  568, 1091,
 /*  1360 */   568,  293,  568, 1091,  531,  568,  870,    8,   60,   60,
 /*  1370 */   235,   61,   61,  568,  414,  568,  414,  568,  445,   62,
 /*  1380 */    62,   45,   45,   46,   46,   47,   47,  199,   49,   49,
 /*  1390 */   557,  568,  359,  568,  100,  486,   50,   50,   63,   63,
 /*  1400 */    64,   64,  561,  415,  535,  410,  568, 1024,  568,  534,
 /*  1410 */   316,  559,  316,  559,   65,   65,   14,   14,  568, 1024,
 /*  1420 */   568,  512,  930,  870, 1015,  109,  109,  929, 1014,   66,
 /*  1430 */    66,  131,  131,  110,  451,  445,  569,  445,  416,  177,
 /*  1440 */  1014,  132,  132,   67,   67,  568,  467,  568,  930,  471,
 /*  1450 */  1360,  283,  226,  929,  315, 1359,  407,  568,  459,  407,
 /*  1460 */  1014, 1014, 1016,  239,  407,   86,  213, 1346,   52,   52,
 /*  1470 */    68,   68, 1014, 1014, 1016, 1017,   27, 1579, 1176,  447,
 /*  1480 */    69,   69,  288,   97,  108, 1535,  106,  392,  392,  391,
 /*  1490 */   273,  389,  568,  877,  847,  881,  568,  111,  560,  466,
 /*  1500 */     4,  568,  152,   30,   38,  568, 1128,  234,  396,  323,
 /*  1510 */   111,  560,  527,    4,  563,   53,   53,  322,  568,  163,
 /*  1520 */   163,  568,  337,  468,  164,  164,  333,  563,   76,   76,
 /*  1530 */   568,  289, 1508,  568,   31, 1507,  568,  445,  338,  483,
 /*  1540 */   100,   54,   54,  344,   72,   72,  296,  236, 1076,  557,
 /*  1550 */   445,  877, 1356,  134,  134,  168,   73,   73,  141,  161,
 /*  1560 */   161, 1568,  557,  535,  568,  319,  568,  348,  536, 1007,
 /*  1570 */   473,  261,  261,  889,  888,  235,  535,  568, 1024,  568,
 /*  1580 */   475,  534,  261,  367,  109,  109,  521,  136,  136,  130,
 /*  1590 */   130, 1024,  110,  366,  445,  569,  445,  109,  109, 1014,
 /*  1600 */   162,  162,  156,  156,  568,  110, 1076,  445,  569,  445,
 /*  1610 */   410,  351, 1014,  568,  353,  316,  559,  568,  343,  568,
 /*  1620 */   100,  497,  357,  258,  100,  896,  897,  140,  140,  355,
 /*  1630 */  1306, 1014, 1014, 1016, 1017,   27,  139,  139,  362,  451,
 /*  1640 */   137,  137,  138,  138, 1014, 1014, 1016, 1017,   27, 1176,
 /*  1650 */   447,  568,  372,  288,  111,  560, 1018,    4,  392,  392,
 /*  1660 */   391,  273,  389,  568, 1137,  847,  568, 1072,  568,  258,
 /*  1670 */   492,  563,  568,  211,   75,   75,  555,  960,  234,  261,
 /*  1680 */   323,  111,  560,  927,    4,  113,   77,   77,  322,   74,
 /*  1690 */    74,   42,   42, 1369,  445,   48,   48, 1414,  563,  972,
 /*  1700 */   973, 1088, 1087, 1088, 1087,  860,  557,  150,  928, 1342,
 /*  1710 */   113, 1354,  554, 1419, 1018, 1271, 1262, 1250,  236, 1249,
 /*  1720 */  1251,  445, 1587, 1339,  308,  276,  168,  309,   11,  141,
 /*  1730 */   393,  310,  232,  557, 1401, 1024,  335,  291, 1396,  219,
 /*  1740 */   336,  109,  109,  934,  297, 1406,  235,  341,  477,  110,
 /*  1750 */   502,  445,  569,  445, 1389, 1405, 1014,  400, 1289,  365,
 /*  1760 */   223, 1480, 1024, 1479, 1351, 1352, 1350, 1349,  109,  109,
 /*  1770 */   204, 1590, 1228,  558,  265,  218,  110,  205,  445,  569,
 /*  1780 */   445,  410,  387, 1014, 1527,  179,  316,  559, 1014, 1014,
 /*  1790 */  1016, 1017,   27,  230, 1525, 1225,   79,  560,   85,    4,
 /*  1800 */   418,  215,  548,   81,   84,  188, 1402,  173,  181,  461,
 /*  1810 */   451,   35,  462,  563,  183, 1014, 1014, 1016, 1017,   27,
 /*  1820 */   184, 1485,  185,  186,  495,  242,   98,  398, 1408,   36,
 /*  1830 */  1407,  484,   91,  469,  401, 1410,  445,  192, 1474,  246,
 /*  1840 */  1496,  490,  346,  277,  248,  196,  493,  511,  557,  350,
 /*  1850 */  1252,  249,  250,  403, 1309, 1308,  111,  560,  432,    4,
 /*  1860 */  1307, 1300,   93, 1604,  881, 1603,  224,  404,  434,  520,
 /*  1870 */   263,  435, 1573,  563, 1279, 1278,  364, 1024,  306, 1277,
 /*  1880 */   264, 1602, 1559,  109,  109,  370, 1299,  307, 1558,  438,
 /*  1890 */   128,  110, 1374,  445,  569,  445,  445,  546, 1014,   10,
 /*  1900 */  1461,  105,  381, 1373,   34,  571,   99, 1332,  557,  314,
 /*  1910 */  1182,  530,  272,  274,  379,  210, 1331,  547,  385,  386,
 /*  1920 */   275,  572, 1247, 1242,  411,  412, 1512,  165,  178, 1513,
 /*  1930 */  1014, 1014, 1016, 1017,   27, 1511, 1510, 1024,   78,  147,
 /*  1940 */   166,  220,  221,  109,  109,  834,  304,  167,  446,  212,
 /*  1950 */   318,  110,  231,  445,  569,  445,  144, 1086, 1014, 1084,
 /*  1960 */   326,  180,  169, 1207,  182,  334,  238,  913,  241, 1100,
 /*  1970 */   187,  170,  171,  421,   87,   88,  423,  189,   89,   90,
 /*  1980 */   172, 1103,  243, 1099,  244,  158,   18,  245,  345,  247,
 /*  1990 */  1014, 1014, 1016, 1017,   27,  261, 1092,  193, 1222,  489,
 /*  2000 */   194,   37,  366,  849,  494,  251,  195,  506,   92,   19,
 /*  2010 */   498,  358,   20,  503,  879,  361,   94,  892,  305,  159,
 /*  2020 */   513,   39,   95, 1170,  160, 1053,  964, 1139,   96,  174,
 /*  2030 */  1138,  225,  280,  282,  198,  958,  113, 1160, 1156,  260,
 /*  2040 */    21,   22,   23, 1158, 1164, 1163, 1144,   24,   33,   25,
 /*  2050 */   202,  542,   26,  100, 1067,  102, 1054,  103,    7, 1052,
 /*  2060 */  1056, 1109, 1057, 1108,  266,  267,   28,   40,  390, 1019,
 /*  2070 */   861,  112,   29,  564, 1178, 1177,  268,  176,  143,  923,
 /*  2080 */  1238, 1238, 1238, 1238, 1238, 1238, 1238, 1238, 1238, 1238,
 /*  2090 */  1238, 1238, 1238, 1238,  269, 1595,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */   193,  193,  193,  274,  275,  276,  193,  274,  275,  276,
 /*    10 */   193,  223,  219,  225,  206,  210,  211,  212,  193,   19,
 /*    20 */   219,  233,  216,  216,  217,  216,  217,  193,  295,  216,
 /*    30 */   217,   31,  193,  216,  217,  193,  228,  213,  230,   39,
 /*    40 */   206,  216,  217,   43,   44,   45,   46,   47,   48,   49,
167782
167783
167784
167785
167786
167787
167788
167789
167790
167791
167792
167793
167794
167795
167796
167797
167798
167799
167800
167801
167802
167803
167804
167805
167806
167807
167808
167809
167810
167811
167812
167813
167814
167815
167816
167817
167818
167819
167820
167821
167822
167823
167824
167825
167826
167827
167828
167829
167830
167831
167832
167833
167834
167835
167836
167837
167838
167839
167840
167841
167842
167843
167844
167845
167846
167847
167848
167849
167850
167851
167852
167853
167854
167855
167856
167857
167858
167859
167860
167861
167862
167863
167864
167865
167866
167867
167868
167869
167870
167871
167872
167873
167874
167875
167876
167877
167878
 /*  2020 */    22,   22,  149,   23,   23,   23,  116,   23,   25,   37,
 /*  2030 */    97,  141,   23,   23,   22,  143,   25,   75,   88,   34,
 /*  2040 */    34,   34,   34,   86,   75,   93,   23,   34,   22,   34,
 /*  2050 */    25,   24,   34,   25,   23,  142,   23,  142,   44,   23,
 /*  2060 */    23,   23,   11,   23,   25,   22,   22,   22,   15,   23,
 /*  2070 */    23,   22,   22,   25,    1,    1,  141,   25,   23,  135,
 /*  2080 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2090 */   319,  319,  319,  319,  141,  141,  319,  141,  319,  319,
 /*  2100 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2110 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2120 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2130 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2140 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2150 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2160 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2170 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2180 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2190 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2200 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2210 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2220 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2230 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2240 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2250 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2260 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2270 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2280 */   319,  319,  319,
};
#define YY_SHIFT_COUNT    (575)
#define YY_SHIFT_MIN      (0)
#define YY_SHIFT_MAX      (2074)
static const unsigned short int yy_shift_ofst[] = {
 /*     0 */  1648, 1477, 1272,  322,  322,    1, 1319, 1478, 1491, 1837,
 /*    10 */  1837, 1837,  471,    0,    0,  214, 1093, 1837, 1837, 1837,
 /*    20 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*    30 */   271,  271, 1219, 1219,  216,   88,    1,    1,    1,    1,
 /*    40 */     1,   40,  111,  258,  361,  469,  512,  583,  622,  693,
 /*    50 */   732,  803,  842,  913, 1073, 1093, 1093, 1093, 1093, 1093,
 /*    60 */  1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093,
 /*    70 */  1093, 1093, 1093, 1113, 1093, 1216,  957,  957, 1635, 1662,
 /*    80 */  1777, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*    90 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   100 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   110 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   120 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   130 */   137,  181,  181,  181,  181,  181,  181,  181,   94,  430,
 /*   140 */    66,   65,  112,  366,  533,  533,  740, 1261,  533,  533,
 /*   150 */    79,   79,  533,  412,  412,  412,   77,  412,  123,  113,
 /*   160 */   113,   22,   22, 2098, 2098,  328,  328,  328,  239,  468,
 /*   170 */   468,  468,  468, 1015, 1015,  409,  366, 1129, 1186,  533,
 /*   180 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  533,
 /*   190 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  969,
 /*   200 */   621,  621,  533,  642,  788,  788, 1228, 1228,  822,  822,
 /*   210 */    67, 1274, 2098, 2098, 2098, 2098, 2098, 2098, 2098, 1307,
 /*   220 */   954,  954,  585,  472,  640,  387,  695,  538,  541,  700,
 /*   230 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  533,
 /*   240 */   222,  533,  533,  533,  533,  533,  533,  533,  533,  533,
 /*   250 */   533,  533,  533, 1179, 1179, 1179,  533,  533,  533,  565,
 /*   260 */   533,  533,  533,  916, 1144,  533,  533, 1288,  533,  533,
 /*   270 */   533,  533,  533,  533,  533,  533,  639, 1330,  209, 1076,
 /*   280 */  1076, 1076, 1076,  580,  209,  209, 1313,  768,  917,  649,
 /*   290 */  1181, 1316,  405, 1316, 1238,  249, 1181, 1181,  249, 1181,
 /*   300 */   405, 1238, 1369,  464, 1259, 1012, 1012, 1012, 1368, 1368,
 /*   310 */  1368, 1368,  184,  184, 1326,  904, 1287, 1480, 1712, 1712,
 /*   320 */  1633, 1633, 1757, 1757, 1633, 1647, 1651, 1783, 1764, 1791,
 /*   330 */  1791, 1791, 1791, 1633, 1806, 1677, 1651, 1651, 1677, 1783,
 /*   340 */  1764, 1677, 1764, 1677, 1633, 1806, 1674, 1779, 1633, 1806,
 /*   350 */  1823, 1633, 1806, 1633, 1806, 1823, 1732, 1732, 1732, 1794,
 /*   360 */  1840, 1840, 1823, 1732, 1738, 1732, 1794, 1732, 1732, 1701,
 /*   370 */  1844, 1758, 1758, 1823, 1633, 1789, 1789, 1807, 1807, 1742,
 /*   380 */  1752, 1877, 1633, 1743, 1742, 1759, 1765, 1677, 1879, 1897,
 /*   390 */  1897, 1914, 1914, 1914, 2098, 2098, 2098, 2098, 2098, 2098,
 /*   400 */  2098, 2098, 2098, 2098, 2098, 2098, 2098, 2098, 2098,  207,
 /*   410 */  1095,  331,  620,  903,  806, 1074, 1483, 1432, 1481, 1322,
 /*   420 */  1370, 1394, 1515, 1291, 1546, 1547, 1557, 1595, 1598, 1599,
 /*   430 */  1434, 1453, 1618, 1462, 1567, 1489, 1644, 1654, 1616, 1660,
 /*   440 */  1548, 1549, 1682, 1685, 1597,  742, 1941, 1945, 1927, 1787,
 /*   450 */  1937, 1940, 1934, 1936, 1821, 1810, 1832, 1938, 1938, 1942,
 /*   460 */  1822, 1947, 1824, 1949, 1968, 1828, 1841, 1938, 1842, 1912,
 /*   470 */  1939, 1938, 1826, 1921, 1922, 1925, 1926, 1850, 1865, 1948,
 /*   480 */  1843, 1982, 1980, 1964, 1872, 1827, 1928, 1970, 1929, 1923,
 /*   490 */  1958, 1848, 1885, 1977, 1983, 1985, 1871, 1880, 1984, 1943,
 /*   500 */  1986, 1987, 1988, 1990, 1946, 1955, 1991, 1911, 1989, 1994,
 /*   510 */  1951, 1992, 1996, 1873, 1998, 2000, 2001, 2002, 2003, 2004,
 /*   520 */  1999, 1933, 1890, 2009, 2010, 1910, 2005, 2012, 1892, 2011,
 /*   530 */  2006, 2007, 2008, 2013, 1950, 1962, 1957, 2014, 1969, 1952,
 /*   540 */  2015, 2023, 2026, 2027, 2025, 2028, 2018, 1913, 1915, 2031,
 /*   550 */  2011, 2033, 2036, 2037, 2038, 2039, 2040, 2043, 2051, 2044,
 /*   560 */  2045, 2046, 2047, 2049, 2050, 2048, 1944, 1935, 1953, 1954,
 /*   570 */  1956, 2052, 2055, 2053, 2073, 2074,
};
#define YY_REDUCE_COUNT (408)
#define YY_REDUCE_MIN   (-271)
#define YY_REDUCE_MAX   (1740)
static const short yy_reduce_ofst[] = {
 /*     0 */  -125,  733,  789,  241,  293, -123, -193, -191, -183, -187,
 /*    10 */   166,  238,  133, -207, -199, -267, -176,   -6,  204,  489,







|


















|

|



















|




|

















|
|
















|







168725
168726
168727
168728
168729
168730
168731
168732
168733
168734
168735
168736
168737
168738
168739
168740
168741
168742
168743
168744
168745
168746
168747
168748
168749
168750
168751
168752
168753
168754
168755
168756
168757
168758
168759
168760
168761
168762
168763
168764
168765
168766
168767
168768
168769
168770
168771
168772
168773
168774
168775
168776
168777
168778
168779
168780
168781
168782
168783
168784
168785
168786
168787
168788
168789
168790
168791
168792
168793
168794
168795
168796
168797
168798
168799
168800
168801
168802
168803
168804
168805
168806
168807
168808
168809
168810
168811
168812
168813
168814
168815
168816
168817
168818
168819
168820
168821
 /*  2020 */    22,   22,  149,   23,   23,   23,  116,   23,   25,   37,
 /*  2030 */    97,  141,   23,   23,   22,  143,   25,   75,   88,   34,
 /*  2040 */    34,   34,   34,   86,   75,   93,   23,   34,   22,   34,
 /*  2050 */    25,   24,   34,   25,   23,  142,   23,  142,   44,   23,
 /*  2060 */    23,   23,   11,   23,   25,   22,   22,   22,   15,   23,
 /*  2070 */    23,   22,   22,   25,    1,    1,  141,   25,   23,  135,
 /*  2080 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2090 */   319,  319,  319,  319,  141,  141,  319,  319,  319,  319,
 /*  2100 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2110 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2120 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2130 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2140 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2150 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2160 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2170 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2180 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2190 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2200 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2210 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2220 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2230 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2240 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2250 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2260 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2270 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2280 */   319,
};
#define YY_SHIFT_COUNT    (574)
#define YY_SHIFT_MIN      (0)
#define YY_SHIFT_MAX      (2074)
static const unsigned short int yy_shift_ofst[] = {
 /*     0 */  1648, 1477, 1272,  322,  322,    1, 1319, 1478, 1491, 1837,
 /*    10 */  1837, 1837,  471,    0,    0,  214, 1093, 1837, 1837, 1837,
 /*    20 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*    30 */   271,  271, 1219, 1219,  216,   88,    1,    1,    1,    1,
 /*    40 */     1,   40,  111,  258,  361,  469,  512,  583,  622,  693,
 /*    50 */   732,  803,  842,  913, 1073, 1093, 1093, 1093, 1093, 1093,
 /*    60 */  1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093,
 /*    70 */  1093, 1093, 1093, 1113, 1093, 1216,  957,  957, 1635, 1662,
 /*    80 */  1777, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*    90 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   100 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   110 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   120 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   130 */   137,  181,  181,  181,  181,  181,  181,  181,   94,  430,
 /*   140 */    66,   65,  112,  366,  533,  533,  740, 1261,  533,  533,
 /*   150 */    79,   79,  533,  412,  412,  412,   77,  412,  123,  113,
 /*   160 */   113,   22,   22, 2096, 2096,  328,  328,  328,  239,  468,
 /*   170 */   468,  468,  468, 1015, 1015,  409,  366, 1129, 1186,  533,
 /*   180 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  533,
 /*   190 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  969,
 /*   200 */   621,  621,  533,  642,  788,  788, 1228, 1228,  822,  822,
 /*   210 */    67, 1274, 2096, 2096, 2096, 2096, 2096, 2096, 2096, 1307,
 /*   220 */   954,  954,  585,  472,  640,  387,  695,  538,  541,  700,
 /*   230 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  533,
 /*   240 */   222,  533,  533,  533,  533,  533,  533,  533,  533,  533,
 /*   250 */   533,  533,  533, 1179, 1179, 1179,  533,  533,  533,  565,
 /*   260 */   533,  533,  533,  916, 1144,  533,  533, 1288,  533,  533,
 /*   270 */   533,  533,  533,  533,  533,  533,  639, 1330,  209, 1076,
 /*   280 */  1076, 1076, 1076,  580,  209,  209, 1313,  768,  917,  649,
 /*   290 */  1181, 1316,  405, 1316, 1238,  249, 1181, 1181,  249, 1181,
 /*   300 */   405, 1238, 1369,  464, 1259, 1012, 1012, 1012, 1368, 1368,
 /*   310 */  1368, 1368,  184,  184, 1326,  904, 1287, 1480, 1712, 1712,
 /*   320 */  1633, 1633, 1757, 1757, 1633, 1647, 1651, 1783, 1764, 1791,
 /*   330 */  1791, 1791, 1791, 1633, 1806, 1677, 1651, 1651, 1677, 1783,
 /*   340 */  1764, 1677, 1764, 1677, 1633, 1806, 1674, 1779, 1633, 1806,
 /*   350 */  1823, 1633, 1806, 1633, 1806, 1823, 1732, 1732, 1732, 1794,
 /*   360 */  1840, 1840, 1823, 1732, 1738, 1732, 1794, 1732, 1732, 1701,
 /*   370 */  1844, 1758, 1758, 1823, 1633, 1789, 1789, 1807, 1807, 1742,
 /*   380 */  1752, 1877, 1633, 1743, 1742, 1759, 1765, 1677, 1879, 1897,
 /*   390 */  1897, 1914, 1914, 1914, 2096, 2096, 2096, 2096, 2096, 2096,
 /*   400 */  2096, 2096, 2096, 2096, 2096, 2096, 2096, 2096, 2096,  207,
 /*   410 */  1095,  331,  620,  903,  806, 1074, 1483, 1432, 1481, 1322,
 /*   420 */  1370, 1394, 1515, 1291, 1546, 1547, 1557, 1595, 1598, 1599,
 /*   430 */  1434, 1453, 1618, 1462, 1567, 1489, 1644, 1654, 1616, 1660,
 /*   440 */  1548, 1549, 1682, 1685, 1597,  742, 1941, 1945, 1927, 1787,
 /*   450 */  1937, 1940, 1934, 1936, 1821, 1810, 1832, 1938, 1938, 1942,
 /*   460 */  1822, 1947, 1824, 1949, 1968, 1828, 1841, 1938, 1842, 1912,
 /*   470 */  1939, 1938, 1826, 1921, 1922, 1925, 1926, 1850, 1865, 1948,
 /*   480 */  1843, 1982, 1980, 1964, 1872, 1827, 1928, 1970, 1929, 1923,
 /*   490 */  1958, 1848, 1885, 1977, 1983, 1985, 1871, 1880, 1984, 1943,
 /*   500 */  1986, 1987, 1988, 1990, 1946, 1955, 1991, 1911, 1989, 1994,
 /*   510 */  1951, 1992, 1996, 1873, 1998, 2000, 2001, 2002, 2003, 2004,
 /*   520 */  1999, 1933, 1890, 2009, 2010, 1910, 2005, 2012, 1892, 2011,
 /*   530 */  2006, 2007, 2008, 2013, 1950, 1962, 1957, 2014, 1969, 1952,
 /*   540 */  2015, 2023, 2026, 2027, 2025, 2028, 2018, 1913, 1915, 2031,
 /*   550 */  2011, 2033, 2036, 2037, 2038, 2039, 2040, 2043, 2051, 2044,
 /*   560 */  2045, 2046, 2047, 2049, 2050, 2048, 1944, 1935, 1953, 1954,
 /*   570 */  2052, 2055, 2053, 2073, 2074,
};
#define YY_REDUCE_COUNT (408)
#define YY_REDUCE_MIN   (-271)
#define YY_REDUCE_MAX   (1740)
static const short yy_reduce_ofst[] = {
 /*     0 */  -125,  733,  789,  241,  293, -123, -193, -191, -183, -187,
 /*    10 */   166,  238,  133, -207, -199, -267, -176,   -6,  204,  489,
167913
167914
167915
167916
167917
167918
167919
167920
167921
167922
167923
167924
167925
167926
167927
167928
167929
167930
167931
167932
167933
167934
167935
167936
167937
167938
167939
167940
167941
167942
167943
167944
167945
167946
167947
167948
167949
167950
167951
167952
167953
167954
167955
167956
167957
167958
167959
167960
167961
167962
167963
167964
167965
167966
167967
167968
167969
167970
167971
167972
167973
167974
167975
167976
167977
167978
167979
167980
167981
167982
167983
167984
 /*   360 */  1639, 1641, 1646, 1656, 1655, 1658, 1659, 1661, 1663, 1560,
 /*   370 */  1564, 1596, 1605, 1664, 1670, 1565, 1571, 1627, 1638, 1657,
 /*   380 */  1665, 1623, 1702, 1630, 1666, 1667, 1671, 1673, 1703, 1718,
 /*   390 */  1719, 1729, 1730, 1731, 1621, 1622, 1628, 1720, 1713, 1716,
 /*   400 */  1722, 1723, 1733, 1717, 1724, 1727, 1728, 1725, 1740,
};
static const YYACTIONTYPE yy_default[] = {
 /*     0 */  1647, 1647, 1647, 1475, 1240, 1351, 1240, 1240, 1240, 1475,
 /*    10 */  1475, 1475, 1240, 1381, 1381, 1528, 1273, 1240, 1240, 1240,
 /*    20 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1474, 1240, 1240,
 /*    30 */  1240, 1240, 1563, 1563, 1240, 1240, 1240, 1240, 1240, 1240,
 /*    40 */  1240, 1240, 1390, 1240, 1397, 1240, 1240, 1240, 1240, 1240,
 /*    50 */  1476, 1477, 1240, 1240, 1240, 1527, 1529, 1492, 1404, 1403,
 /*    60 */  1402, 1401, 1510, 1369, 1395, 1388, 1392, 1470, 1471, 1469,
 /*    70 */  1473, 1477, 1476, 1240, 1391, 1438, 1454, 1437, 1240, 1240,
 /*    80 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*    90 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   100 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   110 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   120 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   130 */  1446, 1453, 1452, 1451, 1460, 1450, 1447, 1440, 1439, 1441,
 /*   140 */  1442, 1240, 1240, 1264, 1240, 1240, 1261, 1315, 1240, 1240,
 /*   150 */  1240, 1240, 1240, 1547, 1546, 1240, 1443, 1240, 1273, 1432,
 /*   160 */  1431, 1457, 1444, 1456, 1455, 1535, 1599, 1598, 1493, 1240,
 /*   170 */  1240, 1240, 1240, 1240, 1240, 1563, 1240, 1240, 1240, 1240,
 /*   180 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   190 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1371,
 /*   200 */  1563, 1563, 1240, 1273, 1563, 1563, 1372, 1372, 1269, 1269,
 /*   210 */  1375, 1240, 1542, 1342, 1342, 1342, 1342, 1351, 1342, 1240,
 /*   220 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   230 */  1240, 1240, 1240, 1240, 1532, 1530, 1240, 1240, 1240, 1240,
 /*   240 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   250 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   260 */  1240, 1240, 1240, 1347, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   270 */  1240, 1240, 1240, 1240, 1240, 1592, 1240, 1505, 1329, 1347,
 /*   280 */  1347, 1347, 1347, 1349, 1330, 1328, 1341, 1274, 1247, 1639,
 /*   290 */  1407, 1396, 1348, 1396, 1636, 1394, 1407, 1407, 1394, 1407,
 /*   300 */  1348, 1636, 1290, 1615, 1285, 1381, 1381, 1381, 1371, 1371,
 /*   310 */  1371, 1371, 1375, 1375, 1472, 1348, 1341, 1240, 1639, 1639,
 /*   320 */  1357, 1357, 1638, 1638, 1357, 1493, 1623, 1416, 1318, 1324,
 /*   330 */  1324, 1324, 1324, 1357, 1258, 1394, 1623, 1623, 1394, 1416,
 /*   340 */  1318, 1394, 1318, 1394, 1357, 1258, 1509, 1633, 1357, 1258,
 /*   350 */  1483, 1357, 1258, 1357, 1258, 1483, 1316, 1316, 1316, 1305,
 /*   360 */  1240, 1240, 1483, 1316, 1290, 1316, 1305, 1316, 1316, 1581,
 /*   370 */  1240, 1487, 1487, 1483, 1357, 1573, 1573, 1384, 1384, 1389,
 /*   380 */  1375, 1478, 1357, 1240, 1389, 1387, 1385, 1394, 1308, 1595,
 /*   390 */  1595, 1591, 1591, 1591, 1644, 1644, 1542, 1608, 1273, 1273,
 /*   400 */  1273, 1273, 1608, 1292, 1292, 1274, 1274, 1273, 1608, 1240,
 /*   410 */  1240, 1240, 1240, 1240, 1240, 1603, 1240, 1537, 1494, 1361,
 /*   420 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   430 */  1240, 1240, 1240, 1240, 1548, 1240, 1240, 1240, 1240, 1240,
 /*   440 */  1240, 1240, 1240, 1240, 1240, 1421, 1240, 1243, 1539, 1240,
 /*   450 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1398, 1399, 1362,
 /*   460 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1413, 1240, 1240,
 /*   470 */  1240, 1408, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   480 */  1635, 1240, 1240, 1240, 1240, 1240, 1240, 1508, 1507, 1240,
 /*   490 */  1240, 1359, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   500 */  1240, 1240, 1240, 1240, 1240, 1288, 1240, 1240, 1240, 1240,
 /*   510 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   520 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1386,
 /*   530 */  1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   540 */  1240, 1240, 1240, 1240, 1578, 1376, 1240, 1240, 1240, 1240,
 /*   550 */  1626, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240, 1240,
 /*   560 */  1240, 1240, 1240, 1240, 1240, 1619, 1332, 1423, 1240, 1422,
 /*   570 */  1426, 1262, 1240, 1252, 1240, 1240,
};
/********** End of lemon-generated parsing tables *****************************/

/* The next table maps tokens (terminal symbols) into fallback tokens.
** If a construct like the following:
**
**      %fallback ID X Y Z.







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







168856
168857
168858
168859
168860
168861
168862
168863
168864
168865
168866
168867
168868
168869
168870
168871
168872
168873
168874
168875
168876
168877
168878
168879
168880
168881
168882
168883
168884
168885
168886
168887
168888
168889
168890
168891
168892
168893
168894
168895
168896
168897
168898
168899
168900
168901
168902
168903
168904
168905
168906
168907
168908
168909
168910
168911
168912
168913
168914
168915
168916
168917
168918
168919
168920
168921
168922
168923
168924
168925
168926
168927
 /*   360 */  1639, 1641, 1646, 1656, 1655, 1658, 1659, 1661, 1663, 1560,
 /*   370 */  1564, 1596, 1605, 1664, 1670, 1565, 1571, 1627, 1638, 1657,
 /*   380 */  1665, 1623, 1702, 1630, 1666, 1667, 1671, 1673, 1703, 1718,
 /*   390 */  1719, 1729, 1730, 1731, 1621, 1622, 1628, 1720, 1713, 1716,
 /*   400 */  1722, 1723, 1733, 1717, 1724, 1727, 1728, 1725, 1740,
};
static const YYACTIONTYPE yy_default[] = {
 /*     0 */  1641, 1641, 1641, 1469, 1236, 1347, 1236, 1236, 1236, 1469,
 /*    10 */  1469, 1469, 1236, 1377, 1377, 1522, 1269, 1236, 1236, 1236,
 /*    20 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1468, 1236, 1236,
 /*    30 */  1236, 1236, 1557, 1557, 1236, 1236, 1236, 1236, 1236, 1236,
 /*    40 */  1236, 1236, 1386, 1236, 1393, 1236, 1236, 1236, 1236, 1236,
 /*    50 */  1470, 1471, 1236, 1236, 1236, 1521, 1523, 1486, 1400, 1399,
 /*    60 */  1398, 1397, 1504, 1365, 1391, 1384, 1388, 1465, 1466, 1464,
 /*    70 */  1619, 1471, 1470, 1236, 1387, 1433, 1449, 1432, 1236, 1236,
 /*    80 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*    90 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   100 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   110 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   120 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   130 */  1441, 1448, 1447, 1446, 1455, 1445, 1442, 1435, 1434, 1436,
 /*   140 */  1437, 1236, 1236, 1260, 1236, 1236, 1257, 1311, 1236, 1236,
 /*   150 */  1236, 1236, 1236, 1541, 1540, 1236, 1438, 1236, 1269, 1427,
 /*   160 */  1426, 1452, 1439, 1451, 1450, 1529, 1593, 1592, 1487, 1236,
 /*   170 */  1236, 1236, 1236, 1236, 1236, 1557, 1236, 1236, 1236, 1236,
 /*   180 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   190 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1367,
 /*   200 */  1557, 1557, 1236, 1269, 1557, 1557, 1368, 1368, 1265, 1265,
 /*   210 */  1371, 1236, 1536, 1338, 1338, 1338, 1338, 1347, 1338, 1236,
 /*   220 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   230 */  1236, 1236, 1236, 1236, 1526, 1524, 1236, 1236, 1236, 1236,
 /*   240 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   250 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   260 */  1236, 1236, 1236, 1343, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   270 */  1236, 1236, 1236, 1236, 1236, 1586, 1236, 1499, 1325, 1343,
 /*   280 */  1343, 1343, 1343, 1345, 1326, 1324, 1337, 1270, 1243, 1633,
 /*   290 */  1403, 1392, 1344, 1392, 1630, 1390, 1403, 1403, 1390, 1403,
 /*   300 */  1344, 1630, 1286, 1608, 1281, 1377, 1377, 1377, 1367, 1367,
 /*   310 */  1367, 1367, 1371, 1371, 1467, 1344, 1337, 1236, 1633, 1633,
 /*   320 */  1353, 1353, 1632, 1632, 1353, 1487, 1616, 1412, 1314, 1320,
 /*   330 */  1320, 1320, 1320, 1353, 1254, 1390, 1616, 1616, 1390, 1412,
 /*   340 */  1314, 1390, 1314, 1390, 1353, 1254, 1503, 1627, 1353, 1254,
 /*   350 */  1477, 1353, 1254, 1353, 1254, 1477, 1312, 1312, 1312, 1301,
 /*   360 */  1236, 1236, 1477, 1312, 1286, 1312, 1301, 1312, 1312, 1575,
 /*   370 */  1236, 1481, 1481, 1477, 1353, 1567, 1567, 1380, 1380, 1385,
 /*   380 */  1371, 1472, 1353, 1236, 1385, 1383, 1381, 1390, 1304, 1589,
 /*   390 */  1589, 1585, 1585, 1585, 1638, 1638, 1536, 1601, 1269, 1269,
 /*   400 */  1269, 1269, 1601, 1288, 1288, 1270, 1270, 1269, 1601, 1236,
 /*   410 */  1236, 1236, 1236, 1236, 1236, 1596, 1236, 1531, 1488, 1357,
 /*   420 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   430 */  1236, 1236, 1236, 1236, 1542, 1236, 1236, 1236, 1236, 1236,
 /*   440 */  1236, 1236, 1236, 1236, 1236, 1417, 1236, 1239, 1533, 1236,
 /*   450 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1394, 1395, 1358,
 /*   460 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1409, 1236, 1236,
 /*   470 */  1236, 1404, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   480 */  1629, 1236, 1236, 1236, 1236, 1236, 1236, 1502, 1501, 1236,
 /*   490 */  1236, 1355, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   500 */  1236, 1236, 1236, 1236, 1236, 1284, 1236, 1236, 1236, 1236,
 /*   510 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   520 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1382,
 /*   530 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   540 */  1236, 1236, 1236, 1236, 1572, 1372, 1236, 1236, 1236, 1236,
 /*   550 */  1620, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
 /*   560 */  1236, 1236, 1236, 1236, 1236, 1612, 1328, 1418, 1236, 1421,
 /*   570 */  1258, 1236, 1248, 1236, 1236,
};
/********** End of lemon-generated parsing tables *****************************/

/* The next table maps tokens (terminal symbols) into fallback tokens.
** If a construct like the following:
**
**      %fallback ID X Y Z.
168767
168768
168769
168770
168771
168772
168773
168774
168775
168776
168777
168778
168779
168780
168781
168782
168783

168784
168785
168786
168787
168788
168789

168790
168791
168792
168793
168794
168795
168796
168797
168798

168799
168800
168801
168802
168803
168804
168805
168806
168807
168808
168809
168810
168811
168812
168813
168814
168815
168816
168817
168818
168819
168820
168821
168822
168823
168824
168825
168826
168827
168828
168829
168830
168831
168832
168833
168834
168835
168836
168837
168838
168839
168840
168841
168842
168843
168844
168845
168846
168847
168848
168849
168850
168851
168852
168853
168854
168855
168856
168857


168858
168859
168860
168861
168862
168863
168864
168865
168866
168867
168868
168869
168870
168871
168872
168873
168874
168875
168876
168877
168878
168879
168880
168881
168882


168883
168884
168885
168886
168887
168888
168889
168890
168891
168892
168893
168894
168895
168896
168897
168898
168899
168900
168901
168902
168903
168904
168905
168906
168907
168908
168909
168910
168911
168912
168913
168914
168915
168916
168917
168918
168919
168920
168921
168922
168923
168924
168925
168926
168927
168928
168929
168930
168931
168932
168933
168934
168935
168936
168937
168938
168939
168940
168941
168942
168943


168944
168945
168946
168947
168948
168949
168950
168951
168952
168953
168954
168955
168956
168957
168958
168959
168960
168961
168962
168963
168964
168965
168966
168967
168968
168969
168970
168971
168972
168973
168974
168975
168976
168977
168978

168979
168980
168981
168982
168983
168984
168985
168986
168987
168988
168989
168990
168991
168992
168993
168994
168995
168996
168997
168998
168999
169000
169001
169002
169003
169004
169005
169006
169007
 /* 171 */ "insert_cmd ::= INSERT orconf",
 /* 172 */ "insert_cmd ::= REPLACE",
 /* 173 */ "idlist_opt ::=",
 /* 174 */ "idlist_opt ::= LP idlist RP",
 /* 175 */ "idlist ::= idlist COMMA nm",
 /* 176 */ "idlist ::= nm",
 /* 177 */ "expr ::= LP expr RP",
 /* 178 */ "expr ::= ID|INDEXED",
 /* 179 */ "expr ::= JOIN_KW",
 /* 180 */ "expr ::= nm DOT nm",
 /* 181 */ "expr ::= nm DOT nm DOT nm",
 /* 182 */ "term ::= NULL|FLOAT|BLOB",
 /* 183 */ "term ::= STRING",
 /* 184 */ "term ::= INTEGER",
 /* 185 */ "expr ::= VARIABLE",
 /* 186 */ "expr ::= expr COLLATE ID|STRING",
 /* 187 */ "expr ::= CAST LP expr AS typetoken RP",

 /* 188 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
 /* 189 */ "expr ::= ID|INDEXED LP STAR RP",
 /* 190 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over",
 /* 191 */ "expr ::= ID|INDEXED LP STAR RP filter_over",
 /* 192 */ "term ::= CTIME_KW",
 /* 193 */ "expr ::= LP nexprlist COMMA expr RP",

 /* 194 */ "expr ::= expr AND expr",
 /* 195 */ "expr ::= expr OR expr",
 /* 196 */ "expr ::= expr LT|GT|GE|LE expr",
 /* 197 */ "expr ::= expr EQ|NE expr",
 /* 198 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
 /* 199 */ "expr ::= expr PLUS|MINUS expr",
 /* 200 */ "expr ::= expr STAR|SLASH|REM expr",
 /* 201 */ "expr ::= expr CONCAT expr",
 /* 202 */ "likeop ::= NOT LIKE_KW|MATCH",

 /* 203 */ "expr ::= expr likeop expr",
 /* 204 */ "expr ::= expr likeop expr ESCAPE expr",
 /* 205 */ "expr ::= expr ISNULL|NOTNULL",
 /* 206 */ "expr ::= expr NOT NULL",
 /* 207 */ "expr ::= expr IS expr",
 /* 208 */ "expr ::= expr IS NOT expr",
 /* 209 */ "expr ::= expr IS NOT DISTINCT FROM expr",
 /* 210 */ "expr ::= expr IS DISTINCT FROM expr",
 /* 211 */ "expr ::= NOT expr",
 /* 212 */ "expr ::= BITNOT expr",
 /* 213 */ "expr ::= PLUS|MINUS expr",
 /* 214 */ "expr ::= expr PTR expr",
 /* 215 */ "between_op ::= BETWEEN",
 /* 216 */ "between_op ::= NOT BETWEEN",
 /* 217 */ "expr ::= expr between_op expr AND expr",
 /* 218 */ "in_op ::= IN",
 /* 219 */ "in_op ::= NOT IN",
 /* 220 */ "expr ::= expr in_op LP exprlist RP",
 /* 221 */ "expr ::= LP select RP",
 /* 222 */ "expr ::= expr in_op LP select RP",
 /* 223 */ "expr ::= expr in_op nm dbnm paren_exprlist",
 /* 224 */ "expr ::= EXISTS LP select RP",
 /* 225 */ "expr ::= CASE case_operand case_exprlist case_else END",
 /* 226 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
 /* 227 */ "case_exprlist ::= WHEN expr THEN expr",
 /* 228 */ "case_else ::= ELSE expr",
 /* 229 */ "case_else ::=",
 /* 230 */ "case_operand ::= expr",
 /* 231 */ "case_operand ::=",
 /* 232 */ "exprlist ::=",
 /* 233 */ "nexprlist ::= nexprlist COMMA expr",
 /* 234 */ "nexprlist ::= expr",
 /* 235 */ "paren_exprlist ::=",
 /* 236 */ "paren_exprlist ::= LP exprlist RP",
 /* 237 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
 /* 238 */ "uniqueflag ::= UNIQUE",
 /* 239 */ "uniqueflag ::=",
 /* 240 */ "eidlist_opt ::=",
 /* 241 */ "eidlist_opt ::= LP eidlist RP",
 /* 242 */ "eidlist ::= eidlist COMMA nm collate sortorder",
 /* 243 */ "eidlist ::= nm collate sortorder",
 /* 244 */ "collate ::=",
 /* 245 */ "collate ::= COLLATE ID|STRING",
 /* 246 */ "cmd ::= DROP INDEX ifexists fullname",
 /* 247 */ "cmd ::= VACUUM vinto",
 /* 248 */ "cmd ::= VACUUM nm vinto",
 /* 249 */ "vinto ::= INTO expr",
 /* 250 */ "vinto ::=",
 /* 251 */ "cmd ::= PRAGMA nm dbnm",
 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
 /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
 /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
 /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
 /* 256 */ "plus_num ::= PLUS INTEGER|FLOAT",
 /* 257 */ "minus_num ::= MINUS INTEGER|FLOAT",
 /* 258 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
 /* 259 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
 /* 260 */ "trigger_time ::= BEFORE|AFTER",
 /* 261 */ "trigger_time ::= INSTEAD OF",


 /* 262 */ "trigger_time ::=",
 /* 263 */ "trigger_event ::= DELETE|INSERT",
 /* 264 */ "trigger_event ::= UPDATE",
 /* 265 */ "trigger_event ::= UPDATE OF idlist",
 /* 266 */ "when_clause ::=",
 /* 267 */ "when_clause ::= WHEN expr",
 /* 268 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
 /* 269 */ "trigger_cmd_list ::= trigger_cmd SEMI",
 /* 270 */ "trnm ::= nm DOT nm",
 /* 271 */ "tridxby ::= INDEXED BY nm",
 /* 272 */ "tridxby ::= NOT INDEXED",
 /* 273 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
 /* 274 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
 /* 275 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
 /* 276 */ "trigger_cmd ::= scanpt select scanpt",
 /* 277 */ "expr ::= RAISE LP IGNORE RP",
 /* 278 */ "expr ::= RAISE LP raisetype COMMA nm RP",
 /* 279 */ "raisetype ::= ROLLBACK",
 /* 280 */ "raisetype ::= ABORT",
 /* 281 */ "raisetype ::= FAIL",
 /* 282 */ "cmd ::= DROP TRIGGER ifexists fullname",
 /* 283 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
 /* 284 */ "cmd ::= DETACH database_kw_opt expr",
 /* 285 */ "key_opt ::=",
 /* 286 */ "key_opt ::= KEY expr",


 /* 287 */ "cmd ::= REINDEX",
 /* 288 */ "cmd ::= REINDEX nm dbnm",
 /* 289 */ "cmd ::= ANALYZE",
 /* 290 */ "cmd ::= ANALYZE nm dbnm",
 /* 291 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
 /* 292 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
 /* 293 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm",
 /* 294 */ "add_column_fullname ::= fullname",
 /* 295 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
 /* 296 */ "cmd ::= create_vtab",
 /* 297 */ "cmd ::= create_vtab LP vtabarglist RP",
 /* 298 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
 /* 299 */ "vtabarg ::=",
 /* 300 */ "vtabargtoken ::= ANY",
 /* 301 */ "vtabargtoken ::= lp anylist RP",
 /* 302 */ "lp ::= LP",
 /* 303 */ "with ::= WITH wqlist",
 /* 304 */ "with ::= WITH RECURSIVE wqlist",
 /* 305 */ "wqas ::= AS",
 /* 306 */ "wqas ::= AS MATERIALIZED",
 /* 307 */ "wqas ::= AS NOT MATERIALIZED",
 /* 308 */ "wqitem ::= nm eidlist_opt wqas LP select RP",
 /* 309 */ "wqlist ::= wqitem",
 /* 310 */ "wqlist ::= wqlist COMMA wqitem",
 /* 311 */ "windowdefn_list ::= windowdefn",
 /* 312 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
 /* 313 */ "windowdefn ::= nm AS LP window RP",
 /* 314 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
 /* 315 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
 /* 316 */ "window ::= ORDER BY sortlist frame_opt",
 /* 317 */ "window ::= nm ORDER BY sortlist frame_opt",
 /* 318 */ "window ::= frame_opt",
 /* 319 */ "window ::= nm frame_opt",
 /* 320 */ "frame_opt ::=",
 /* 321 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
 /* 322 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
 /* 323 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
 /* 324 */ "frame_bound_s ::= frame_bound",
 /* 325 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
 /* 326 */ "frame_bound_e ::= frame_bound",
 /* 327 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
 /* 328 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
 /* 329 */ "frame_bound ::= CURRENT ROW",
 /* 330 */ "frame_exclude_opt ::=",
 /* 331 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
 /* 332 */ "frame_exclude ::= NO OTHERS",
 /* 333 */ "frame_exclude ::= CURRENT ROW",
 /* 334 */ "frame_exclude ::= GROUP|TIES",
 /* 335 */ "window_clause ::= WINDOW windowdefn_list",
 /* 336 */ "filter_over ::= filter_clause over_clause",
 /* 337 */ "filter_over ::= over_clause",
 /* 338 */ "filter_over ::= filter_clause",
 /* 339 */ "over_clause ::= OVER LP window RP",
 /* 340 */ "over_clause ::= OVER nm",
 /* 341 */ "filter_clause ::= FILTER LP WHERE expr RP",
 /* 342 */ "input ::= cmdlist",
 /* 343 */ "cmdlist ::= cmdlist ecmd",
 /* 344 */ "cmdlist ::= ecmd",
 /* 345 */ "ecmd ::= SEMI",
 /* 346 */ "ecmd ::= cmdx SEMI",
 /* 347 */ "ecmd ::= explain cmdx SEMI",


 /* 348 */ "trans_opt ::=",
 /* 349 */ "trans_opt ::= TRANSACTION",
 /* 350 */ "trans_opt ::= TRANSACTION nm",
 /* 351 */ "savepoint_opt ::= SAVEPOINT",
 /* 352 */ "savepoint_opt ::=",
 /* 353 */ "cmd ::= create_table create_table_args",
 /* 354 */ "table_option_set ::= table_option",
 /* 355 */ "columnlist ::= columnlist COMMA columnname carglist",
 /* 356 */ "columnlist ::= columnname carglist",
 /* 357 */ "nm ::= ID|INDEXED",
 /* 358 */ "nm ::= STRING",
 /* 359 */ "nm ::= JOIN_KW",
 /* 360 */ "typetoken ::= typename",
 /* 361 */ "typename ::= ID|STRING",
 /* 362 */ "signed ::= plus_num",
 /* 363 */ "signed ::= minus_num",
 /* 364 */ "carglist ::= carglist ccons",
 /* 365 */ "carglist ::=",
 /* 366 */ "ccons ::= NULL onconf",
 /* 367 */ "ccons ::= GENERATED ALWAYS AS generated",
 /* 368 */ "ccons ::= AS generated",
 /* 369 */ "conslist_opt ::= COMMA conslist",
 /* 370 */ "conslist ::= conslist tconscomma tcons",
 /* 371 */ "conslist ::= tcons",
 /* 372 */ "tconscomma ::=",
 /* 373 */ "defer_subclause_opt ::= defer_subclause",
 /* 374 */ "resolvetype ::= raisetype",
 /* 375 */ "selectnowith ::= oneselect",
 /* 376 */ "oneselect ::= values",
 /* 377 */ "sclp ::= selcollist COMMA",
 /* 378 */ "as ::= ID|STRING",
 /* 379 */ "indexed_opt ::= indexed_by",
 /* 380 */ "returning ::=",
 /* 381 */ "expr ::= term",
 /* 382 */ "likeop ::= LIKE_KW|MATCH",

 /* 383 */ "exprlist ::= nexprlist",
 /* 384 */ "nmnum ::= plus_num",
 /* 385 */ "nmnum ::= nm",
 /* 386 */ "nmnum ::= ON",
 /* 387 */ "nmnum ::= DELETE",
 /* 388 */ "nmnum ::= DEFAULT",
 /* 389 */ "plus_num ::= INTEGER|FLOAT",
 /* 390 */ "foreach_clause ::=",
 /* 391 */ "foreach_clause ::= FOR EACH ROW",
 /* 392 */ "trnm ::= nm",
 /* 393 */ "tridxby ::=",
 /* 394 */ "database_kw_opt ::= DATABASE",
 /* 395 */ "database_kw_opt ::=",
 /* 396 */ "kwcolumn_opt ::=",
 /* 397 */ "kwcolumn_opt ::= COLUMNKW",
 /* 398 */ "vtabarglist ::= vtabarg",
 /* 399 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
 /* 400 */ "vtabarg ::= vtabarg vtabargtoken",
 /* 401 */ "anylist ::=",
 /* 402 */ "anylist ::= anylist LP anylist RP",
 /* 403 */ "anylist ::= anylist ANY",
 /* 404 */ "with ::=",
};
#endif /* NDEBUG */


#if YYSTACKDEPTH<=0
/*
** Try to increase the size of the parser stack.  Return the number







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







169710
169711
169712
169713
169714
169715
169716
169717
169718
169719
169720
169721
169722

169723
169724
169725
169726
169727
169728
169729

169730
169731
169732
169733
169734
169735
169736
169737
169738
169739

169740
169741
169742
169743
169744
169745
169746
169747
169748
169749
169750
169751
169752

169753
169754
169755
169756
169757
169758
169759
169760
169761
169762
169763
169764
169765
169766
169767

169768
169769
169770
169771
169772
169773
169774
169775
169776
169777
169778
169779
169780
169781
169782
169783
169784
169785
169786
169787
169788
169789
169790
169791
169792
169793
169794
169795
169796
169797
169798
169799
169800
169801
169802


169803
169804
169805
169806
169807
169808
169809
169810
169811
169812
169813
169814
169815
169816
169817
169818
169819
169820
169821
169822
169823
169824
169825
169826
169827
169828
169829
169830


169831
169832
169833
169834
169835
169836
169837
169838
169839
169840
169841
169842
169843
169844
169845
169846
169847
169848
169849
169850
169851
169852
169853
169854
169855
169856
169857
169858
169859
169860
169861
169862
169863
169864
169865
169866
169867
169868
169869
169870
169871
169872
169873
169874
169875
169876
169877
169878
169879
169880
169881
169882
169883
169884
169885
169886
169887


169888
169889
169890
169891
169892
169893
169894
169895

169896
169897
169898
169899
169900
169901
169902
169903
169904
169905
169906
169907
169908
169909
169910
169911
169912
169913
169914
169915
169916
169917
169918
169919
169920
169921
169922
169923
169924
169925
169926
169927
169928
169929
169930
169931
169932
169933
169934
169935
169936
169937
169938
169939
169940
169941
169942
169943
169944
169945
169946
169947
169948
 /* 171 */ "insert_cmd ::= INSERT orconf",
 /* 172 */ "insert_cmd ::= REPLACE",
 /* 173 */ "idlist_opt ::=",
 /* 174 */ "idlist_opt ::= LP idlist RP",
 /* 175 */ "idlist ::= idlist COMMA nm",
 /* 176 */ "idlist ::= nm",
 /* 177 */ "expr ::= LP expr RP",
 /* 178 */ "expr ::= ID|INDEXED|JOIN_KW",
 /* 179 */ "expr ::= nm DOT nm",
 /* 180 */ "expr ::= nm DOT nm DOT nm",
 /* 181 */ "term ::= NULL|FLOAT|BLOB",
 /* 182 */ "term ::= STRING",
 /* 183 */ "term ::= INTEGER",

 /* 184 */ "expr ::= VARIABLE",
 /* 185 */ "expr ::= expr COLLATE ID|STRING",
 /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
 /* 187 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP",
 /* 188 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP",
 /* 189 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over",
 /* 190 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over",

 /* 191 */ "term ::= CTIME_KW",
 /* 192 */ "expr ::= LP nexprlist COMMA expr RP",
 /* 193 */ "expr ::= expr AND expr",
 /* 194 */ "expr ::= expr OR expr",
 /* 195 */ "expr ::= expr LT|GT|GE|LE expr",
 /* 196 */ "expr ::= expr EQ|NE expr",
 /* 197 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
 /* 198 */ "expr ::= expr PLUS|MINUS expr",
 /* 199 */ "expr ::= expr STAR|SLASH|REM expr",
 /* 200 */ "expr ::= expr CONCAT expr",

 /* 201 */ "likeop ::= NOT LIKE_KW|MATCH",
 /* 202 */ "expr ::= expr likeop expr",
 /* 203 */ "expr ::= expr likeop expr ESCAPE expr",
 /* 204 */ "expr ::= expr ISNULL|NOTNULL",
 /* 205 */ "expr ::= expr NOT NULL",
 /* 206 */ "expr ::= expr IS expr",
 /* 207 */ "expr ::= expr IS NOT expr",
 /* 208 */ "expr ::= expr IS NOT DISTINCT FROM expr",
 /* 209 */ "expr ::= expr IS DISTINCT FROM expr",
 /* 210 */ "expr ::= NOT expr",
 /* 211 */ "expr ::= BITNOT expr",
 /* 212 */ "expr ::= PLUS|MINUS expr",
 /* 213 */ "expr ::= expr PTR expr",

 /* 214 */ "between_op ::= BETWEEN",
 /* 215 */ "between_op ::= NOT BETWEEN",
 /* 216 */ "expr ::= expr between_op expr AND expr",
 /* 217 */ "in_op ::= IN",
 /* 218 */ "in_op ::= NOT IN",
 /* 219 */ "expr ::= expr in_op LP exprlist RP",
 /* 220 */ "expr ::= LP select RP",
 /* 221 */ "expr ::= expr in_op LP select RP",
 /* 222 */ "expr ::= expr in_op nm dbnm paren_exprlist",
 /* 223 */ "expr ::= EXISTS LP select RP",
 /* 224 */ "expr ::= CASE case_operand case_exprlist case_else END",
 /* 225 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
 /* 226 */ "case_exprlist ::= WHEN expr THEN expr",
 /* 227 */ "case_else ::= ELSE expr",
 /* 228 */ "case_else ::=",

 /* 229 */ "case_operand ::=",
 /* 230 */ "exprlist ::=",
 /* 231 */ "nexprlist ::= nexprlist COMMA expr",
 /* 232 */ "nexprlist ::= expr",
 /* 233 */ "paren_exprlist ::=",
 /* 234 */ "paren_exprlist ::= LP exprlist RP",
 /* 235 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
 /* 236 */ "uniqueflag ::= UNIQUE",
 /* 237 */ "uniqueflag ::=",
 /* 238 */ "eidlist_opt ::=",
 /* 239 */ "eidlist_opt ::= LP eidlist RP",
 /* 240 */ "eidlist ::= eidlist COMMA nm collate sortorder",
 /* 241 */ "eidlist ::= nm collate sortorder",
 /* 242 */ "collate ::=",
 /* 243 */ "collate ::= COLLATE ID|STRING",
 /* 244 */ "cmd ::= DROP INDEX ifexists fullname",
 /* 245 */ "cmd ::= VACUUM vinto",
 /* 246 */ "cmd ::= VACUUM nm vinto",
 /* 247 */ "vinto ::= INTO expr",
 /* 248 */ "vinto ::=",
 /* 249 */ "cmd ::= PRAGMA nm dbnm",
 /* 250 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
 /* 251 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
 /* 253 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
 /* 254 */ "plus_num ::= PLUS INTEGER|FLOAT",
 /* 255 */ "minus_num ::= MINUS INTEGER|FLOAT",
 /* 256 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
 /* 257 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
 /* 258 */ "trigger_time ::= BEFORE|AFTER",
 /* 259 */ "trigger_time ::= INSTEAD OF",
 /* 260 */ "trigger_time ::=",
 /* 261 */ "trigger_event ::= DELETE|INSERT",
 /* 262 */ "trigger_event ::= UPDATE",
 /* 263 */ "trigger_event ::= UPDATE OF idlist",


 /* 264 */ "when_clause ::=",
 /* 265 */ "when_clause ::= WHEN expr",
 /* 266 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
 /* 267 */ "trigger_cmd_list ::= trigger_cmd SEMI",
 /* 268 */ "trnm ::= nm DOT nm",
 /* 269 */ "tridxby ::= INDEXED BY nm",
 /* 270 */ "tridxby ::= NOT INDEXED",
 /* 271 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
 /* 272 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
 /* 273 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
 /* 274 */ "trigger_cmd ::= scanpt select scanpt",
 /* 275 */ "expr ::= RAISE LP IGNORE RP",
 /* 276 */ "expr ::= RAISE LP raisetype COMMA nm RP",
 /* 277 */ "raisetype ::= ROLLBACK",
 /* 278 */ "raisetype ::= ABORT",
 /* 279 */ "raisetype ::= FAIL",
 /* 280 */ "cmd ::= DROP TRIGGER ifexists fullname",
 /* 281 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
 /* 282 */ "cmd ::= DETACH database_kw_opt expr",
 /* 283 */ "key_opt ::=",
 /* 284 */ "key_opt ::= KEY expr",
 /* 285 */ "cmd ::= REINDEX",
 /* 286 */ "cmd ::= REINDEX nm dbnm",
 /* 287 */ "cmd ::= ANALYZE",
 /* 288 */ "cmd ::= ANALYZE nm dbnm",
 /* 289 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
 /* 290 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
 /* 291 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm",


 /* 292 */ "add_column_fullname ::= fullname",
 /* 293 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
 /* 294 */ "cmd ::= create_vtab",
 /* 295 */ "cmd ::= create_vtab LP vtabarglist RP",
 /* 296 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
 /* 297 */ "vtabarg ::=",
 /* 298 */ "vtabargtoken ::= ANY",
 /* 299 */ "vtabargtoken ::= lp anylist RP",
 /* 300 */ "lp ::= LP",
 /* 301 */ "with ::= WITH wqlist",
 /* 302 */ "with ::= WITH RECURSIVE wqlist",
 /* 303 */ "wqas ::= AS",
 /* 304 */ "wqas ::= AS MATERIALIZED",
 /* 305 */ "wqas ::= AS NOT MATERIALIZED",
 /* 306 */ "wqitem ::= nm eidlist_opt wqas LP select RP",
 /* 307 */ "wqlist ::= wqitem",
 /* 308 */ "wqlist ::= wqlist COMMA wqitem",
 /* 309 */ "windowdefn_list ::= windowdefn",
 /* 310 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
 /* 311 */ "windowdefn ::= nm AS LP window RP",
 /* 312 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
 /* 313 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
 /* 314 */ "window ::= ORDER BY sortlist frame_opt",
 /* 315 */ "window ::= nm ORDER BY sortlist frame_opt",
 /* 316 */ "window ::= frame_opt",
 /* 317 */ "window ::= nm frame_opt",
 /* 318 */ "frame_opt ::=",
 /* 319 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
 /* 320 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
 /* 321 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
 /* 322 */ "frame_bound_s ::= frame_bound",
 /* 323 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
 /* 324 */ "frame_bound_e ::= frame_bound",
 /* 325 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
 /* 326 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
 /* 327 */ "frame_bound ::= CURRENT ROW",
 /* 328 */ "frame_exclude_opt ::=",
 /* 329 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
 /* 330 */ "frame_exclude ::= NO OTHERS",
 /* 331 */ "frame_exclude ::= CURRENT ROW",
 /* 332 */ "frame_exclude ::= GROUP|TIES",
 /* 333 */ "window_clause ::= WINDOW windowdefn_list",
 /* 334 */ "filter_over ::= filter_clause over_clause",
 /* 335 */ "filter_over ::= over_clause",
 /* 336 */ "filter_over ::= filter_clause",
 /* 337 */ "over_clause ::= OVER LP window RP",
 /* 338 */ "over_clause ::= OVER nm",
 /* 339 */ "filter_clause ::= FILTER LP WHERE expr RP",
 /* 340 */ "input ::= cmdlist",
 /* 341 */ "cmdlist ::= cmdlist ecmd",
 /* 342 */ "cmdlist ::= ecmd",
 /* 343 */ "ecmd ::= SEMI",
 /* 344 */ "ecmd ::= cmdx SEMI",
 /* 345 */ "ecmd ::= explain cmdx SEMI",
 /* 346 */ "trans_opt ::=",
 /* 347 */ "trans_opt ::= TRANSACTION",
 /* 348 */ "trans_opt ::= TRANSACTION nm",


 /* 349 */ "savepoint_opt ::= SAVEPOINT",
 /* 350 */ "savepoint_opt ::=",
 /* 351 */ "cmd ::= create_table create_table_args",
 /* 352 */ "table_option_set ::= table_option",
 /* 353 */ "columnlist ::= columnlist COMMA columnname carglist",
 /* 354 */ "columnlist ::= columnname carglist",
 /* 355 */ "nm ::= ID|INDEXED|JOIN_KW",
 /* 356 */ "nm ::= STRING",

 /* 357 */ "typetoken ::= typename",
 /* 358 */ "typename ::= ID|STRING",
 /* 359 */ "signed ::= plus_num",
 /* 360 */ "signed ::= minus_num",
 /* 361 */ "carglist ::= carglist ccons",
 /* 362 */ "carglist ::=",
 /* 363 */ "ccons ::= NULL onconf",
 /* 364 */ "ccons ::= GENERATED ALWAYS AS generated",
 /* 365 */ "ccons ::= AS generated",
 /* 366 */ "conslist_opt ::= COMMA conslist",
 /* 367 */ "conslist ::= conslist tconscomma tcons",
 /* 368 */ "conslist ::= tcons",
 /* 369 */ "tconscomma ::=",
 /* 370 */ "defer_subclause_opt ::= defer_subclause",
 /* 371 */ "resolvetype ::= raisetype",
 /* 372 */ "selectnowith ::= oneselect",
 /* 373 */ "oneselect ::= values",
 /* 374 */ "sclp ::= selcollist COMMA",
 /* 375 */ "as ::= ID|STRING",
 /* 376 */ "indexed_opt ::= indexed_by",
 /* 377 */ "returning ::=",
 /* 378 */ "expr ::= term",
 /* 379 */ "likeop ::= LIKE_KW|MATCH",
 /* 380 */ "case_operand ::= expr",
 /* 381 */ "exprlist ::= nexprlist",
 /* 382 */ "nmnum ::= plus_num",
 /* 383 */ "nmnum ::= nm",
 /* 384 */ "nmnum ::= ON",
 /* 385 */ "nmnum ::= DELETE",
 /* 386 */ "nmnum ::= DEFAULT",
 /* 387 */ "plus_num ::= INTEGER|FLOAT",
 /* 388 */ "foreach_clause ::=",
 /* 389 */ "foreach_clause ::= FOR EACH ROW",
 /* 390 */ "trnm ::= nm",
 /* 391 */ "tridxby ::=",
 /* 392 */ "database_kw_opt ::= DATABASE",
 /* 393 */ "database_kw_opt ::=",
 /* 394 */ "kwcolumn_opt ::=",
 /* 395 */ "kwcolumn_opt ::= COLUMNKW",
 /* 396 */ "vtabarglist ::= vtabarg",
 /* 397 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
 /* 398 */ "vtabarg ::= vtabarg vtabargtoken",
 /* 399 */ "anylist ::=",
 /* 400 */ "anylist ::= anylist LP anylist RP",
 /* 401 */ "anylist ::= anylist ANY",
 /* 402 */ "with ::=",
};
#endif /* NDEBUG */


#if YYSTACKDEPTH<=0
/*
** Try to increase the size of the parser stack.  Return the number
169678
169679
169680
169681
169682
169683
169684
169685
169686
169687
169688
169689
169690
169691
169692
169693
169694

169695
169696
169697
169698
169699

169700
169701
169702
169703
169704
169705
169706
169707
169708
169709

169710
169711
169712
169713
169714
169715
169716
169717
169718
169719
169720
169721
169722
169723
169724
169725
169726
169727
169728
169729
169730
169731
169732
169733
169734
169735
169736
169737
169738
169739
169740
169741
169742
169743
169744
169745
169746
169747
169748
169749
169750
169751
169752
169753
169754
169755
169756
169757
169758
169759
169760
169761
169762
169763
169764
169765
169766
169767
169768
169769
169770
169771
169772
169773
169774
169775
169776
169777
169778
169779
169780
169781
169782
169783
169784
169785
169786
169787
169788
169789
169790
169791
169792
169793


169794
169795
169796
169797
169798
169799
169800
169801
169802
169803
169804
169805
169806
169807
169808
169809
169810
169811
169812
169813
169814
169815
169816
169817
169818
169819
169820
169821
169822
169823
169824
169825
169826
169827
169828
169829
169830
169831
169832
169833
169834
169835
169836
169837
169838
169839
169840
169841
169842
169843
169844
169845
169846
169847
169848
169849
169850
169851
169852
169853
169854


169855
169856
169857
169858
169859
169860
169861
169862
169863
169864
169865
169866
169867
169868
169869
169870
169871
169872
169873
169874
169875
169876
169877
169878
169879
169880
169881
169882
169883
169884
169885
169886
169887
169888
169889

169890
169891
169892
169893
169894
169895
169896
169897
169898
169899
169900
169901
169902
169903
169904
169905
169906
169907
169908
169909
169910
169911
169912
169913
169914
169915
169916
169917
169918
   269,  /* (171) insert_cmd ::= INSERT orconf */
   269,  /* (172) insert_cmd ::= REPLACE */
   270,  /* (173) idlist_opt ::= */
   270,  /* (174) idlist_opt ::= LP idlist RP */
   263,  /* (175) idlist ::= idlist COMMA nm */
   263,  /* (176) idlist ::= nm */
   217,  /* (177) expr ::= LP expr RP */
   217,  /* (178) expr ::= ID|INDEXED */
   217,  /* (179) expr ::= JOIN_KW */
   217,  /* (180) expr ::= nm DOT nm */
   217,  /* (181) expr ::= nm DOT nm DOT nm */
   216,  /* (182) term ::= NULL|FLOAT|BLOB */
   216,  /* (183) term ::= STRING */
   216,  /* (184) term ::= INTEGER */
   217,  /* (185) expr ::= VARIABLE */
   217,  /* (186) expr ::= expr COLLATE ID|STRING */
   217,  /* (187) expr ::= CAST LP expr AS typetoken RP */

   217,  /* (188) expr ::= ID|INDEXED LP distinct exprlist RP */
   217,  /* (189) expr ::= ID|INDEXED LP STAR RP */
   217,  /* (190) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
   217,  /* (191) expr ::= ID|INDEXED LP STAR RP filter_over */
   216,  /* (192) term ::= CTIME_KW */

   217,  /* (193) expr ::= LP nexprlist COMMA expr RP */
   217,  /* (194) expr ::= expr AND expr */
   217,  /* (195) expr ::= expr OR expr */
   217,  /* (196) expr ::= expr LT|GT|GE|LE expr */
   217,  /* (197) expr ::= expr EQ|NE expr */
   217,  /* (198) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
   217,  /* (199) expr ::= expr PLUS|MINUS expr */
   217,  /* (200) expr ::= expr STAR|SLASH|REM expr */
   217,  /* (201) expr ::= expr CONCAT expr */
   274,  /* (202) likeop ::= NOT LIKE_KW|MATCH */

   217,  /* (203) expr ::= expr likeop expr */
   217,  /* (204) expr ::= expr likeop expr ESCAPE expr */
   217,  /* (205) expr ::= expr ISNULL|NOTNULL */
   217,  /* (206) expr ::= expr NOT NULL */
   217,  /* (207) expr ::= expr IS expr */
   217,  /* (208) expr ::= expr IS NOT expr */
   217,  /* (209) expr ::= expr IS NOT DISTINCT FROM expr */
   217,  /* (210) expr ::= expr IS DISTINCT FROM expr */
   217,  /* (211) expr ::= NOT expr */
   217,  /* (212) expr ::= BITNOT expr */
   217,  /* (213) expr ::= PLUS|MINUS expr */
   217,  /* (214) expr ::= expr PTR expr */
   275,  /* (215) between_op ::= BETWEEN */
   275,  /* (216) between_op ::= NOT BETWEEN */
   217,  /* (217) expr ::= expr between_op expr AND expr */
   276,  /* (218) in_op ::= IN */
   276,  /* (219) in_op ::= NOT IN */
   217,  /* (220) expr ::= expr in_op LP exprlist RP */
   217,  /* (221) expr ::= LP select RP */
   217,  /* (222) expr ::= expr in_op LP select RP */
   217,  /* (223) expr ::= expr in_op nm dbnm paren_exprlist */
   217,  /* (224) expr ::= EXISTS LP select RP */
   217,  /* (225) expr ::= CASE case_operand case_exprlist case_else END */
   279,  /* (226) case_exprlist ::= case_exprlist WHEN expr THEN expr */
   279,  /* (227) case_exprlist ::= WHEN expr THEN expr */
   280,  /* (228) case_else ::= ELSE expr */
   280,  /* (229) case_else ::= */
   278,  /* (230) case_operand ::= expr */
   278,  /* (231) case_operand ::= */
   261,  /* (232) exprlist ::= */
   253,  /* (233) nexprlist ::= nexprlist COMMA expr */
   253,  /* (234) nexprlist ::= expr */
   277,  /* (235) paren_exprlist ::= */
   277,  /* (236) paren_exprlist ::= LP exprlist RP */
   190,  /* (237) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
   281,  /* (238) uniqueflag ::= UNIQUE */
   281,  /* (239) uniqueflag ::= */
   221,  /* (240) eidlist_opt ::= */
   221,  /* (241) eidlist_opt ::= LP eidlist RP */
   232,  /* (242) eidlist ::= eidlist COMMA nm collate sortorder */
   232,  /* (243) eidlist ::= nm collate sortorder */
   282,  /* (244) collate ::= */
   282,  /* (245) collate ::= COLLATE ID|STRING */
   190,  /* (246) cmd ::= DROP INDEX ifexists fullname */
   190,  /* (247) cmd ::= VACUUM vinto */
   190,  /* (248) cmd ::= VACUUM nm vinto */
   283,  /* (249) vinto ::= INTO expr */
   283,  /* (250) vinto ::= */
   190,  /* (251) cmd ::= PRAGMA nm dbnm */
   190,  /* (252) cmd ::= PRAGMA nm dbnm EQ nmnum */
   190,  /* (253) cmd ::= PRAGMA nm dbnm LP nmnum RP */
   190,  /* (254) cmd ::= PRAGMA nm dbnm EQ minus_num */
   190,  /* (255) cmd ::= PRAGMA nm dbnm LP minus_num RP */
   211,  /* (256) plus_num ::= PLUS INTEGER|FLOAT */
   212,  /* (257) minus_num ::= MINUS INTEGER|FLOAT */
   190,  /* (258) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   285,  /* (259) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   287,  /* (260) trigger_time ::= BEFORE|AFTER */
   287,  /* (261) trigger_time ::= INSTEAD OF */
   287,  /* (262) trigger_time ::= */
   288,  /* (263) trigger_event ::= DELETE|INSERT */
   288,  /* (264) trigger_event ::= UPDATE */
   288,  /* (265) trigger_event ::= UPDATE OF idlist */
   290,  /* (266) when_clause ::= */
   290,  /* (267) when_clause ::= WHEN expr */
   286,  /* (268) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   286,  /* (269) trigger_cmd_list ::= trigger_cmd SEMI */
   292,  /* (270) trnm ::= nm DOT nm */
   293,  /* (271) tridxby ::= INDEXED BY nm */
   293,  /* (272) tridxby ::= NOT INDEXED */
   291,  /* (273) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
   291,  /* (274) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
   291,  /* (275) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
   291,  /* (276) trigger_cmd ::= scanpt select scanpt */
   217,  /* (277) expr ::= RAISE LP IGNORE RP */
   217,  /* (278) expr ::= RAISE LP raisetype COMMA nm RP */
   236,  /* (279) raisetype ::= ROLLBACK */
   236,  /* (280) raisetype ::= ABORT */
   236,  /* (281) raisetype ::= FAIL */
   190,  /* (282) cmd ::= DROP TRIGGER ifexists fullname */
   190,  /* (283) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   190,  /* (284) cmd ::= DETACH database_kw_opt expr */
   295,  /* (285) key_opt ::= */
   295,  /* (286) key_opt ::= KEY expr */


   190,  /* (287) cmd ::= REINDEX */
   190,  /* (288) cmd ::= REINDEX nm dbnm */
   190,  /* (289) cmd ::= ANALYZE */
   190,  /* (290) cmd ::= ANALYZE nm dbnm */
   190,  /* (291) cmd ::= ALTER TABLE fullname RENAME TO nm */
   190,  /* (292) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
   190,  /* (293) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
   296,  /* (294) add_column_fullname ::= fullname */
   190,  /* (295) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
   190,  /* (296) cmd ::= create_vtab */
   190,  /* (297) cmd ::= create_vtab LP vtabarglist RP */
   298,  /* (298) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   300,  /* (299) vtabarg ::= */
   301,  /* (300) vtabargtoken ::= ANY */
   301,  /* (301) vtabargtoken ::= lp anylist RP */
   302,  /* (302) lp ::= LP */
   266,  /* (303) with ::= WITH wqlist */
   266,  /* (304) with ::= WITH RECURSIVE wqlist */
   305,  /* (305) wqas ::= AS */
   305,  /* (306) wqas ::= AS MATERIALIZED */
   305,  /* (307) wqas ::= AS NOT MATERIALIZED */
   304,  /* (308) wqitem ::= nm eidlist_opt wqas LP select RP */
   241,  /* (309) wqlist ::= wqitem */
   241,  /* (310) wqlist ::= wqlist COMMA wqitem */
   306,  /* (311) windowdefn_list ::= windowdefn */
   306,  /* (312) windowdefn_list ::= windowdefn_list COMMA windowdefn */
   307,  /* (313) windowdefn ::= nm AS LP window RP */
   308,  /* (314) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
   308,  /* (315) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
   308,  /* (316) window ::= ORDER BY sortlist frame_opt */
   308,  /* (317) window ::= nm ORDER BY sortlist frame_opt */
   308,  /* (318) window ::= frame_opt */
   308,  /* (319) window ::= nm frame_opt */
   309,  /* (320) frame_opt ::= */
   309,  /* (321) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
   309,  /* (322) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
   313,  /* (323) range_or_rows ::= RANGE|ROWS|GROUPS */
   315,  /* (324) frame_bound_s ::= frame_bound */
   315,  /* (325) frame_bound_s ::= UNBOUNDED PRECEDING */
   316,  /* (326) frame_bound_e ::= frame_bound */
   316,  /* (327) frame_bound_e ::= UNBOUNDED FOLLOWING */
   314,  /* (328) frame_bound ::= expr PRECEDING|FOLLOWING */
   314,  /* (329) frame_bound ::= CURRENT ROW */
   317,  /* (330) frame_exclude_opt ::= */
   317,  /* (331) frame_exclude_opt ::= EXCLUDE frame_exclude */
   318,  /* (332) frame_exclude ::= NO OTHERS */
   318,  /* (333) frame_exclude ::= CURRENT ROW */
   318,  /* (334) frame_exclude ::= GROUP|TIES */
   251,  /* (335) window_clause ::= WINDOW windowdefn_list */
   273,  /* (336) filter_over ::= filter_clause over_clause */
   273,  /* (337) filter_over ::= over_clause */
   273,  /* (338) filter_over ::= filter_clause */
   312,  /* (339) over_clause ::= OVER LP window RP */
   312,  /* (340) over_clause ::= OVER nm */
   311,  /* (341) filter_clause ::= FILTER LP WHERE expr RP */
   185,  /* (342) input ::= cmdlist */
   186,  /* (343) cmdlist ::= cmdlist ecmd */
   186,  /* (344) cmdlist ::= ecmd */
   187,  /* (345) ecmd ::= SEMI */
   187,  /* (346) ecmd ::= cmdx SEMI */
   187,  /* (347) ecmd ::= explain cmdx SEMI */


   192,  /* (348) trans_opt ::= */
   192,  /* (349) trans_opt ::= TRANSACTION */
   192,  /* (350) trans_opt ::= TRANSACTION nm */
   194,  /* (351) savepoint_opt ::= SAVEPOINT */
   194,  /* (352) savepoint_opt ::= */
   190,  /* (353) cmd ::= create_table create_table_args */
   203,  /* (354) table_option_set ::= table_option */
   201,  /* (355) columnlist ::= columnlist COMMA columnname carglist */
   201,  /* (356) columnlist ::= columnname carglist */
   193,  /* (357) nm ::= ID|INDEXED */
   193,  /* (358) nm ::= STRING */
   193,  /* (359) nm ::= JOIN_KW */
   208,  /* (360) typetoken ::= typename */
   209,  /* (361) typename ::= ID|STRING */
   210,  /* (362) signed ::= plus_num */
   210,  /* (363) signed ::= minus_num */
   207,  /* (364) carglist ::= carglist ccons */
   207,  /* (365) carglist ::= */
   215,  /* (366) ccons ::= NULL onconf */
   215,  /* (367) ccons ::= GENERATED ALWAYS AS generated */
   215,  /* (368) ccons ::= AS generated */
   202,  /* (369) conslist_opt ::= COMMA conslist */
   228,  /* (370) conslist ::= conslist tconscomma tcons */
   228,  /* (371) conslist ::= tcons */
   229,  /* (372) tconscomma ::= */
   233,  /* (373) defer_subclause_opt ::= defer_subclause */
   235,  /* (374) resolvetype ::= raisetype */
   239,  /* (375) selectnowith ::= oneselect */
   240,  /* (376) oneselect ::= values */
   254,  /* (377) sclp ::= selcollist COMMA */
   255,  /* (378) as ::= ID|STRING */
   264,  /* (379) indexed_opt ::= indexed_by */
   272,  /* (380) returning ::= */
   217,  /* (381) expr ::= term */
   274,  /* (382) likeop ::= LIKE_KW|MATCH */

   261,  /* (383) exprlist ::= nexprlist */
   284,  /* (384) nmnum ::= plus_num */
   284,  /* (385) nmnum ::= nm */
   284,  /* (386) nmnum ::= ON */
   284,  /* (387) nmnum ::= DELETE */
   284,  /* (388) nmnum ::= DEFAULT */
   211,  /* (389) plus_num ::= INTEGER|FLOAT */
   289,  /* (390) foreach_clause ::= */
   289,  /* (391) foreach_clause ::= FOR EACH ROW */
   292,  /* (392) trnm ::= nm */
   293,  /* (393) tridxby ::= */
   294,  /* (394) database_kw_opt ::= DATABASE */
   294,  /* (395) database_kw_opt ::= */
   297,  /* (396) kwcolumn_opt ::= */
   297,  /* (397) kwcolumn_opt ::= COLUMNKW */
   299,  /* (398) vtabarglist ::= vtabarg */
   299,  /* (399) vtabarglist ::= vtabarglist COMMA vtabarg */
   300,  /* (400) vtabarg ::= vtabarg vtabargtoken */
   303,  /* (401) anylist ::= */
   303,  /* (402) anylist ::= anylist LP anylist RP */
   303,  /* (403) anylist ::= anylist ANY */
   266,  /* (404) with ::= */
};

/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
** of symbols on the right-hand side of that rule. */
static const signed char yyRuleInfoNRhs[] = {
   -1,  /* (0) explain ::= EXPLAIN */
   -3,  /* (1) explain ::= EXPLAIN QUERY PLAN */







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







170619
170620
170621
170622
170623
170624
170625
170626
170627
170628
170629
170630
170631

170632
170633
170634
170635
170636
170637
170638

170639
170640
170641
170642
170643
170644
170645
170646
170647
170648

170649
170650
170651
170652
170653
170654
170655
170656
170657
170658
170659
170660
170661

170662
170663
170664
170665
170666
170667
170668
170669
170670
170671
170672
170673
170674
170675
170676

170677
170678
170679
170680
170681
170682
170683
170684
170685
170686
170687
170688
170689
170690
170691
170692
170693
170694
170695
170696
170697
170698
170699
170700
170701
170702
170703
170704
170705
170706
170707
170708
170709
170710
170711
170712
170713
170714
170715
170716
170717
170718
170719
170720
170721
170722
170723
170724
170725
170726
170727
170728
170729
170730
170731
170732
170733
170734
170735
170736
170737
170738
170739


170740
170741
170742
170743
170744
170745
170746
170747
170748
170749
170750
170751
170752
170753
170754
170755
170756
170757
170758
170759
170760
170761
170762
170763
170764
170765
170766
170767
170768
170769
170770
170771
170772
170773
170774
170775
170776
170777
170778
170779
170780
170781
170782
170783
170784
170785
170786
170787
170788
170789
170790
170791
170792
170793
170794
170795
170796


170797
170798
170799
170800
170801
170802
170803
170804

170805
170806
170807
170808
170809
170810
170811
170812
170813
170814
170815
170816
170817
170818
170819
170820
170821
170822
170823
170824
170825
170826
170827
170828
170829
170830
170831
170832
170833
170834
170835
170836
170837
170838
170839
170840
170841
170842
170843
170844
170845
170846
170847
170848
170849
170850
170851
170852
170853
170854
170855
170856
170857
   269,  /* (171) insert_cmd ::= INSERT orconf */
   269,  /* (172) insert_cmd ::= REPLACE */
   270,  /* (173) idlist_opt ::= */
   270,  /* (174) idlist_opt ::= LP idlist RP */
   263,  /* (175) idlist ::= idlist COMMA nm */
   263,  /* (176) idlist ::= nm */
   217,  /* (177) expr ::= LP expr RP */
   217,  /* (178) expr ::= ID|INDEXED|JOIN_KW */
   217,  /* (179) expr ::= nm DOT nm */
   217,  /* (180) expr ::= nm DOT nm DOT nm */
   216,  /* (181) term ::= NULL|FLOAT|BLOB */
   216,  /* (182) term ::= STRING */
   216,  /* (183) term ::= INTEGER */

   217,  /* (184) expr ::= VARIABLE */
   217,  /* (185) expr ::= expr COLLATE ID|STRING */
   217,  /* (186) expr ::= CAST LP expr AS typetoken RP */
   217,  /* (187) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
   217,  /* (188) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
   217,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
   217,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */

   216,  /* (191) term ::= CTIME_KW */
   217,  /* (192) expr ::= LP nexprlist COMMA expr RP */
   217,  /* (193) expr ::= expr AND expr */
   217,  /* (194) expr ::= expr OR expr */
   217,  /* (195) expr ::= expr LT|GT|GE|LE expr */
   217,  /* (196) expr ::= expr EQ|NE expr */
   217,  /* (197) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
   217,  /* (198) expr ::= expr PLUS|MINUS expr */
   217,  /* (199) expr ::= expr STAR|SLASH|REM expr */
   217,  /* (200) expr ::= expr CONCAT expr */

   274,  /* (201) likeop ::= NOT LIKE_KW|MATCH */
   217,  /* (202) expr ::= expr likeop expr */
   217,  /* (203) expr ::= expr likeop expr ESCAPE expr */
   217,  /* (204) expr ::= expr ISNULL|NOTNULL */
   217,  /* (205) expr ::= expr NOT NULL */
   217,  /* (206) expr ::= expr IS expr */
   217,  /* (207) expr ::= expr IS NOT expr */
   217,  /* (208) expr ::= expr IS NOT DISTINCT FROM expr */
   217,  /* (209) expr ::= expr IS DISTINCT FROM expr */
   217,  /* (210) expr ::= NOT expr */
   217,  /* (211) expr ::= BITNOT expr */
   217,  /* (212) expr ::= PLUS|MINUS expr */
   217,  /* (213) expr ::= expr PTR expr */

   275,  /* (214) between_op ::= BETWEEN */
   275,  /* (215) between_op ::= NOT BETWEEN */
   217,  /* (216) expr ::= expr between_op expr AND expr */
   276,  /* (217) in_op ::= IN */
   276,  /* (218) in_op ::= NOT IN */
   217,  /* (219) expr ::= expr in_op LP exprlist RP */
   217,  /* (220) expr ::= LP select RP */
   217,  /* (221) expr ::= expr in_op LP select RP */
   217,  /* (222) expr ::= expr in_op nm dbnm paren_exprlist */
   217,  /* (223) expr ::= EXISTS LP select RP */
   217,  /* (224) expr ::= CASE case_operand case_exprlist case_else END */
   279,  /* (225) case_exprlist ::= case_exprlist WHEN expr THEN expr */
   279,  /* (226) case_exprlist ::= WHEN expr THEN expr */
   280,  /* (227) case_else ::= ELSE expr */
   280,  /* (228) case_else ::= */

   278,  /* (229) case_operand ::= */
   261,  /* (230) exprlist ::= */
   253,  /* (231) nexprlist ::= nexprlist COMMA expr */
   253,  /* (232) nexprlist ::= expr */
   277,  /* (233) paren_exprlist ::= */
   277,  /* (234) paren_exprlist ::= LP exprlist RP */
   190,  /* (235) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
   281,  /* (236) uniqueflag ::= UNIQUE */
   281,  /* (237) uniqueflag ::= */
   221,  /* (238) eidlist_opt ::= */
   221,  /* (239) eidlist_opt ::= LP eidlist RP */
   232,  /* (240) eidlist ::= eidlist COMMA nm collate sortorder */
   232,  /* (241) eidlist ::= nm collate sortorder */
   282,  /* (242) collate ::= */
   282,  /* (243) collate ::= COLLATE ID|STRING */
   190,  /* (244) cmd ::= DROP INDEX ifexists fullname */
   190,  /* (245) cmd ::= VACUUM vinto */
   190,  /* (246) cmd ::= VACUUM nm vinto */
   283,  /* (247) vinto ::= INTO expr */
   283,  /* (248) vinto ::= */
   190,  /* (249) cmd ::= PRAGMA nm dbnm */
   190,  /* (250) cmd ::= PRAGMA nm dbnm EQ nmnum */
   190,  /* (251) cmd ::= PRAGMA nm dbnm LP nmnum RP */
   190,  /* (252) cmd ::= PRAGMA nm dbnm EQ minus_num */
   190,  /* (253) cmd ::= PRAGMA nm dbnm LP minus_num RP */
   211,  /* (254) plus_num ::= PLUS INTEGER|FLOAT */
   212,  /* (255) minus_num ::= MINUS INTEGER|FLOAT */
   190,  /* (256) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   285,  /* (257) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   287,  /* (258) trigger_time ::= BEFORE|AFTER */
   287,  /* (259) trigger_time ::= INSTEAD OF */
   287,  /* (260) trigger_time ::= */
   288,  /* (261) trigger_event ::= DELETE|INSERT */
   288,  /* (262) trigger_event ::= UPDATE */
   288,  /* (263) trigger_event ::= UPDATE OF idlist */
   290,  /* (264) when_clause ::= */
   290,  /* (265) when_clause ::= WHEN expr */
   286,  /* (266) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   286,  /* (267) trigger_cmd_list ::= trigger_cmd SEMI */
   292,  /* (268) trnm ::= nm DOT nm */
   293,  /* (269) tridxby ::= INDEXED BY nm */
   293,  /* (270) tridxby ::= NOT INDEXED */
   291,  /* (271) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
   291,  /* (272) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
   291,  /* (273) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
   291,  /* (274) trigger_cmd ::= scanpt select scanpt */
   217,  /* (275) expr ::= RAISE LP IGNORE RP */
   217,  /* (276) expr ::= RAISE LP raisetype COMMA nm RP */
   236,  /* (277) raisetype ::= ROLLBACK */
   236,  /* (278) raisetype ::= ABORT */
   236,  /* (279) raisetype ::= FAIL */
   190,  /* (280) cmd ::= DROP TRIGGER ifexists fullname */
   190,  /* (281) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   190,  /* (282) cmd ::= DETACH database_kw_opt expr */
   295,  /* (283) key_opt ::= */
   295,  /* (284) key_opt ::= KEY expr */
   190,  /* (285) cmd ::= REINDEX */
   190,  /* (286) cmd ::= REINDEX nm dbnm */
   190,  /* (287) cmd ::= ANALYZE */
   190,  /* (288) cmd ::= ANALYZE nm dbnm */
   190,  /* (289) cmd ::= ALTER TABLE fullname RENAME TO nm */
   190,  /* (290) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
   190,  /* (291) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */


   296,  /* (292) add_column_fullname ::= fullname */
   190,  /* (293) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
   190,  /* (294) cmd ::= create_vtab */
   190,  /* (295) cmd ::= create_vtab LP vtabarglist RP */
   298,  /* (296) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   300,  /* (297) vtabarg ::= */
   301,  /* (298) vtabargtoken ::= ANY */
   301,  /* (299) vtabargtoken ::= lp anylist RP */
   302,  /* (300) lp ::= LP */
   266,  /* (301) with ::= WITH wqlist */
   266,  /* (302) with ::= WITH RECURSIVE wqlist */
   305,  /* (303) wqas ::= AS */
   305,  /* (304) wqas ::= AS MATERIALIZED */
   305,  /* (305) wqas ::= AS NOT MATERIALIZED */
   304,  /* (306) wqitem ::= nm eidlist_opt wqas LP select RP */
   241,  /* (307) wqlist ::= wqitem */
   241,  /* (308) wqlist ::= wqlist COMMA wqitem */
   306,  /* (309) windowdefn_list ::= windowdefn */
   306,  /* (310) windowdefn_list ::= windowdefn_list COMMA windowdefn */
   307,  /* (311) windowdefn ::= nm AS LP window RP */
   308,  /* (312) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
   308,  /* (313) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
   308,  /* (314) window ::= ORDER BY sortlist frame_opt */
   308,  /* (315) window ::= nm ORDER BY sortlist frame_opt */
   308,  /* (316) window ::= frame_opt */
   308,  /* (317) window ::= nm frame_opt */
   309,  /* (318) frame_opt ::= */
   309,  /* (319) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
   309,  /* (320) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
   313,  /* (321) range_or_rows ::= RANGE|ROWS|GROUPS */
   315,  /* (322) frame_bound_s ::= frame_bound */
   315,  /* (323) frame_bound_s ::= UNBOUNDED PRECEDING */
   316,  /* (324) frame_bound_e ::= frame_bound */
   316,  /* (325) frame_bound_e ::= UNBOUNDED FOLLOWING */
   314,  /* (326) frame_bound ::= expr PRECEDING|FOLLOWING */
   314,  /* (327) frame_bound ::= CURRENT ROW */
   317,  /* (328) frame_exclude_opt ::= */
   317,  /* (329) frame_exclude_opt ::= EXCLUDE frame_exclude */
   318,  /* (330) frame_exclude ::= NO OTHERS */
   318,  /* (331) frame_exclude ::= CURRENT ROW */
   318,  /* (332) frame_exclude ::= GROUP|TIES */
   251,  /* (333) window_clause ::= WINDOW windowdefn_list */
   273,  /* (334) filter_over ::= filter_clause over_clause */
   273,  /* (335) filter_over ::= over_clause */
   273,  /* (336) filter_over ::= filter_clause */
   312,  /* (337) over_clause ::= OVER LP window RP */
   312,  /* (338) over_clause ::= OVER nm */
   311,  /* (339) filter_clause ::= FILTER LP WHERE expr RP */
   185,  /* (340) input ::= cmdlist */
   186,  /* (341) cmdlist ::= cmdlist ecmd */
   186,  /* (342) cmdlist ::= ecmd */
   187,  /* (343) ecmd ::= SEMI */
   187,  /* (344) ecmd ::= cmdx SEMI */
   187,  /* (345) ecmd ::= explain cmdx SEMI */
   192,  /* (346) trans_opt ::= */
   192,  /* (347) trans_opt ::= TRANSACTION */
   192,  /* (348) trans_opt ::= TRANSACTION nm */


   194,  /* (349) savepoint_opt ::= SAVEPOINT */
   194,  /* (350) savepoint_opt ::= */
   190,  /* (351) cmd ::= create_table create_table_args */
   203,  /* (352) table_option_set ::= table_option */
   201,  /* (353) columnlist ::= columnlist COMMA columnname carglist */
   201,  /* (354) columnlist ::= columnname carglist */
   193,  /* (355) nm ::= ID|INDEXED|JOIN_KW */
   193,  /* (356) nm ::= STRING */

   208,  /* (357) typetoken ::= typename */
   209,  /* (358) typename ::= ID|STRING */
   210,  /* (359) signed ::= plus_num */
   210,  /* (360) signed ::= minus_num */
   207,  /* (361) carglist ::= carglist ccons */
   207,  /* (362) carglist ::= */
   215,  /* (363) ccons ::= NULL onconf */
   215,  /* (364) ccons ::= GENERATED ALWAYS AS generated */
   215,  /* (365) ccons ::= AS generated */
   202,  /* (366) conslist_opt ::= COMMA conslist */
   228,  /* (367) conslist ::= conslist tconscomma tcons */
   228,  /* (368) conslist ::= tcons */
   229,  /* (369) tconscomma ::= */
   233,  /* (370) defer_subclause_opt ::= defer_subclause */
   235,  /* (371) resolvetype ::= raisetype */
   239,  /* (372) selectnowith ::= oneselect */
   240,  /* (373) oneselect ::= values */
   254,  /* (374) sclp ::= selcollist COMMA */
   255,  /* (375) as ::= ID|STRING */
   264,  /* (376) indexed_opt ::= indexed_by */
   272,  /* (377) returning ::= */
   217,  /* (378) expr ::= term */
   274,  /* (379) likeop ::= LIKE_KW|MATCH */
   278,  /* (380) case_operand ::= expr */
   261,  /* (381) exprlist ::= nexprlist */
   284,  /* (382) nmnum ::= plus_num */
   284,  /* (383) nmnum ::= nm */
   284,  /* (384) nmnum ::= ON */
   284,  /* (385) nmnum ::= DELETE */
   284,  /* (386) nmnum ::= DEFAULT */
   211,  /* (387) plus_num ::= INTEGER|FLOAT */
   289,  /* (388) foreach_clause ::= */
   289,  /* (389) foreach_clause ::= FOR EACH ROW */
   292,  /* (390) trnm ::= nm */
   293,  /* (391) tridxby ::= */
   294,  /* (392) database_kw_opt ::= DATABASE */
   294,  /* (393) database_kw_opt ::= */
   297,  /* (394) kwcolumn_opt ::= */
   297,  /* (395) kwcolumn_opt ::= COLUMNKW */
   299,  /* (396) vtabarglist ::= vtabarg */
   299,  /* (397) vtabarglist ::= vtabarglist COMMA vtabarg */
   300,  /* (398) vtabarg ::= vtabarg vtabargtoken */
   303,  /* (399) anylist ::= */
   303,  /* (400) anylist ::= anylist LP anylist RP */
   303,  /* (401) anylist ::= anylist ANY */
   266,  /* (402) with ::= */
};

/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
** of symbols on the right-hand side of that rule. */
static const signed char yyRuleInfoNRhs[] = {
   -1,  /* (0) explain ::= EXPLAIN */
   -3,  /* (1) explain ::= EXPLAIN QUERY PLAN */
170088
170089
170090
170091
170092
170093
170094
170095
170096
170097
170098
170099
170100
170101
170102
170103
170104
170105
170106
170107
170108
170109
170110

170111
170112
170113
170114
170115
170116
170117
170118
170119
170120
170121
170122

170123
170124
170125
170126
170127
170128
170129
170130
170131
170132
170133
170134
170135
170136
170137
170138
170139
170140
170141
170142
170143
170144
170145
170146
170147
170148
170149
170150
170151
170152
170153
170154
170155
170156
170157
170158
170159
170160
170161
170162
170163
170164
170165
170166
170167
170168
170169
170170
170171
170172
170173
170174
170175
170176
170177
170178
170179
170180
170181
170182
170183
170184
170185
170186
170187
170188
170189
170190
170191
170192
170193
170194
170195
170196
170197
170198
170199
170200
170201
170202
170203
170204
170205
170206
170207


170208
170209
170210
170211
170212
170213
170214
170215
170216
170217
170218
170219
170220
170221
170222
170223
170224
170225
170226
170227
170228
170229
170230
170231
170232
170233
170234
170235
170236
170237
170238
170239
170240
170241
170242
170243
170244
170245
170246
170247
170248
170249
170250
170251
170252
170253
170254
170255
170256
170257
170258
170259
170260
170261
170262
170263
170264


170265
170266
170267
170268
170269
170270
170271
170272
170273
170274
170275
170276
170277
170278
170279
170280
170281
170282
170283
170284
170285
170286
170287
170288
170289
170290
170291
170292
170293
170294
170295
170296
170297
170298
170299

170300
170301
170302
170303
170304
170305
170306
170307
170308
170309
170310
170311
170312
170313
170314
170315
170316
170317
170318
170319
170320
170321
170322
170323
170324
170325
170326
170327
170328
   -2,  /* (171) insert_cmd ::= INSERT orconf */
   -1,  /* (172) insert_cmd ::= REPLACE */
    0,  /* (173) idlist_opt ::= */
   -3,  /* (174) idlist_opt ::= LP idlist RP */
   -3,  /* (175) idlist ::= idlist COMMA nm */
   -1,  /* (176) idlist ::= nm */
   -3,  /* (177) expr ::= LP expr RP */
   -1,  /* (178) expr ::= ID|INDEXED */
   -1,  /* (179) expr ::= JOIN_KW */
   -3,  /* (180) expr ::= nm DOT nm */
   -5,  /* (181) expr ::= nm DOT nm DOT nm */
   -1,  /* (182) term ::= NULL|FLOAT|BLOB */
   -1,  /* (183) term ::= STRING */
   -1,  /* (184) term ::= INTEGER */
   -1,  /* (185) expr ::= VARIABLE */
   -3,  /* (186) expr ::= expr COLLATE ID|STRING */
   -6,  /* (187) expr ::= CAST LP expr AS typetoken RP */
   -5,  /* (188) expr ::= ID|INDEXED LP distinct exprlist RP */
   -4,  /* (189) expr ::= ID|INDEXED LP STAR RP */
   -6,  /* (190) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
   -5,  /* (191) expr ::= ID|INDEXED LP STAR RP filter_over */
   -1,  /* (192) term ::= CTIME_KW */
   -5,  /* (193) expr ::= LP nexprlist COMMA expr RP */

   -3,  /* (194) expr ::= expr AND expr */
   -3,  /* (195) expr ::= expr OR expr */
   -3,  /* (196) expr ::= expr LT|GT|GE|LE expr */
   -3,  /* (197) expr ::= expr EQ|NE expr */
   -3,  /* (198) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
   -3,  /* (199) expr ::= expr PLUS|MINUS expr */
   -3,  /* (200) expr ::= expr STAR|SLASH|REM expr */
   -3,  /* (201) expr ::= expr CONCAT expr */
   -2,  /* (202) likeop ::= NOT LIKE_KW|MATCH */
   -3,  /* (203) expr ::= expr likeop expr */
   -5,  /* (204) expr ::= expr likeop expr ESCAPE expr */
   -2,  /* (205) expr ::= expr ISNULL|NOTNULL */

   -3,  /* (206) expr ::= expr NOT NULL */
   -3,  /* (207) expr ::= expr IS expr */
   -4,  /* (208) expr ::= expr IS NOT expr */
   -6,  /* (209) expr ::= expr IS NOT DISTINCT FROM expr */
   -5,  /* (210) expr ::= expr IS DISTINCT FROM expr */
   -2,  /* (211) expr ::= NOT expr */
   -2,  /* (212) expr ::= BITNOT expr */
   -2,  /* (213) expr ::= PLUS|MINUS expr */
   -3,  /* (214) expr ::= expr PTR expr */
   -1,  /* (215) between_op ::= BETWEEN */
   -2,  /* (216) between_op ::= NOT BETWEEN */
   -5,  /* (217) expr ::= expr between_op expr AND expr */
   -1,  /* (218) in_op ::= IN */
   -2,  /* (219) in_op ::= NOT IN */
   -5,  /* (220) expr ::= expr in_op LP exprlist RP */
   -3,  /* (221) expr ::= LP select RP */
   -5,  /* (222) expr ::= expr in_op LP select RP */
   -5,  /* (223) expr ::= expr in_op nm dbnm paren_exprlist */
   -4,  /* (224) expr ::= EXISTS LP select RP */
   -5,  /* (225) expr ::= CASE case_operand case_exprlist case_else END */
   -5,  /* (226) case_exprlist ::= case_exprlist WHEN expr THEN expr */
   -4,  /* (227) case_exprlist ::= WHEN expr THEN expr */
   -2,  /* (228) case_else ::= ELSE expr */
    0,  /* (229) case_else ::= */
   -1,  /* (230) case_operand ::= expr */
    0,  /* (231) case_operand ::= */
    0,  /* (232) exprlist ::= */
   -3,  /* (233) nexprlist ::= nexprlist COMMA expr */
   -1,  /* (234) nexprlist ::= expr */
    0,  /* (235) paren_exprlist ::= */
   -3,  /* (236) paren_exprlist ::= LP exprlist RP */
  -12,  /* (237) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
   -1,  /* (238) uniqueflag ::= UNIQUE */
    0,  /* (239) uniqueflag ::= */
    0,  /* (240) eidlist_opt ::= */
   -3,  /* (241) eidlist_opt ::= LP eidlist RP */
   -5,  /* (242) eidlist ::= eidlist COMMA nm collate sortorder */
   -3,  /* (243) eidlist ::= nm collate sortorder */
    0,  /* (244) collate ::= */
   -2,  /* (245) collate ::= COLLATE ID|STRING */
   -4,  /* (246) cmd ::= DROP INDEX ifexists fullname */
   -2,  /* (247) cmd ::= VACUUM vinto */
   -3,  /* (248) cmd ::= VACUUM nm vinto */
   -2,  /* (249) vinto ::= INTO expr */
    0,  /* (250) vinto ::= */
   -3,  /* (251) cmd ::= PRAGMA nm dbnm */
   -5,  /* (252) cmd ::= PRAGMA nm dbnm EQ nmnum */
   -6,  /* (253) cmd ::= PRAGMA nm dbnm LP nmnum RP */
   -5,  /* (254) cmd ::= PRAGMA nm dbnm EQ minus_num */
   -6,  /* (255) cmd ::= PRAGMA nm dbnm LP minus_num RP */
   -2,  /* (256) plus_num ::= PLUS INTEGER|FLOAT */
   -2,  /* (257) minus_num ::= MINUS INTEGER|FLOAT */
   -5,  /* (258) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  -11,  /* (259) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   -1,  /* (260) trigger_time ::= BEFORE|AFTER */
   -2,  /* (261) trigger_time ::= INSTEAD OF */
    0,  /* (262) trigger_time ::= */
   -1,  /* (263) trigger_event ::= DELETE|INSERT */
   -1,  /* (264) trigger_event ::= UPDATE */
   -3,  /* (265) trigger_event ::= UPDATE OF idlist */
    0,  /* (266) when_clause ::= */
   -2,  /* (267) when_clause ::= WHEN expr */
   -3,  /* (268) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   -2,  /* (269) trigger_cmd_list ::= trigger_cmd SEMI */
   -3,  /* (270) trnm ::= nm DOT nm */
   -3,  /* (271) tridxby ::= INDEXED BY nm */
   -2,  /* (272) tridxby ::= NOT INDEXED */
   -9,  /* (273) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
   -8,  /* (274) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
   -6,  /* (275) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
   -3,  /* (276) trigger_cmd ::= scanpt select scanpt */
   -4,  /* (277) expr ::= RAISE LP IGNORE RP */
   -6,  /* (278) expr ::= RAISE LP raisetype COMMA nm RP */
   -1,  /* (279) raisetype ::= ROLLBACK */
   -1,  /* (280) raisetype ::= ABORT */
   -1,  /* (281) raisetype ::= FAIL */
   -4,  /* (282) cmd ::= DROP TRIGGER ifexists fullname */
   -6,  /* (283) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   -3,  /* (284) cmd ::= DETACH database_kw_opt expr */
    0,  /* (285) key_opt ::= */
   -2,  /* (286) key_opt ::= KEY expr */
   -1,  /* (287) cmd ::= REINDEX */
   -3,  /* (288) cmd ::= REINDEX nm dbnm */
   -1,  /* (289) cmd ::= ANALYZE */
   -3,  /* (290) cmd ::= ANALYZE nm dbnm */


   -6,  /* (291) cmd ::= ALTER TABLE fullname RENAME TO nm */
   -7,  /* (292) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
   -6,  /* (293) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
   -1,  /* (294) add_column_fullname ::= fullname */
   -8,  /* (295) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
   -1,  /* (296) cmd ::= create_vtab */
   -4,  /* (297) cmd ::= create_vtab LP vtabarglist RP */
   -8,  /* (298) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
    0,  /* (299) vtabarg ::= */
   -1,  /* (300) vtabargtoken ::= ANY */
   -3,  /* (301) vtabargtoken ::= lp anylist RP */
   -1,  /* (302) lp ::= LP */
   -2,  /* (303) with ::= WITH wqlist */
   -3,  /* (304) with ::= WITH RECURSIVE wqlist */
   -1,  /* (305) wqas ::= AS */
   -2,  /* (306) wqas ::= AS MATERIALIZED */
   -3,  /* (307) wqas ::= AS NOT MATERIALIZED */
   -6,  /* (308) wqitem ::= nm eidlist_opt wqas LP select RP */
   -1,  /* (309) wqlist ::= wqitem */
   -3,  /* (310) wqlist ::= wqlist COMMA wqitem */
   -1,  /* (311) windowdefn_list ::= windowdefn */
   -3,  /* (312) windowdefn_list ::= windowdefn_list COMMA windowdefn */
   -5,  /* (313) windowdefn ::= nm AS LP window RP */
   -5,  /* (314) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
   -6,  /* (315) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
   -4,  /* (316) window ::= ORDER BY sortlist frame_opt */
   -5,  /* (317) window ::= nm ORDER BY sortlist frame_opt */
   -1,  /* (318) window ::= frame_opt */
   -2,  /* (319) window ::= nm frame_opt */
    0,  /* (320) frame_opt ::= */
   -3,  /* (321) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
   -6,  /* (322) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
   -1,  /* (323) range_or_rows ::= RANGE|ROWS|GROUPS */
   -1,  /* (324) frame_bound_s ::= frame_bound */
   -2,  /* (325) frame_bound_s ::= UNBOUNDED PRECEDING */
   -1,  /* (326) frame_bound_e ::= frame_bound */
   -2,  /* (327) frame_bound_e ::= UNBOUNDED FOLLOWING */
   -2,  /* (328) frame_bound ::= expr PRECEDING|FOLLOWING */
   -2,  /* (329) frame_bound ::= CURRENT ROW */
    0,  /* (330) frame_exclude_opt ::= */
   -2,  /* (331) frame_exclude_opt ::= EXCLUDE frame_exclude */
   -2,  /* (332) frame_exclude ::= NO OTHERS */
   -2,  /* (333) frame_exclude ::= CURRENT ROW */
   -1,  /* (334) frame_exclude ::= GROUP|TIES */
   -2,  /* (335) window_clause ::= WINDOW windowdefn_list */
   -2,  /* (336) filter_over ::= filter_clause over_clause */
   -1,  /* (337) filter_over ::= over_clause */
   -1,  /* (338) filter_over ::= filter_clause */
   -4,  /* (339) over_clause ::= OVER LP window RP */
   -2,  /* (340) over_clause ::= OVER nm */
   -5,  /* (341) filter_clause ::= FILTER LP WHERE expr RP */
   -1,  /* (342) input ::= cmdlist */
   -2,  /* (343) cmdlist ::= cmdlist ecmd */
   -1,  /* (344) cmdlist ::= ecmd */
   -1,  /* (345) ecmd ::= SEMI */
   -2,  /* (346) ecmd ::= cmdx SEMI */
   -3,  /* (347) ecmd ::= explain cmdx SEMI */


    0,  /* (348) trans_opt ::= */
   -1,  /* (349) trans_opt ::= TRANSACTION */
   -2,  /* (350) trans_opt ::= TRANSACTION nm */
   -1,  /* (351) savepoint_opt ::= SAVEPOINT */
    0,  /* (352) savepoint_opt ::= */
   -2,  /* (353) cmd ::= create_table create_table_args */
   -1,  /* (354) table_option_set ::= table_option */
   -4,  /* (355) columnlist ::= columnlist COMMA columnname carglist */
   -2,  /* (356) columnlist ::= columnname carglist */
   -1,  /* (357) nm ::= ID|INDEXED */
   -1,  /* (358) nm ::= STRING */
   -1,  /* (359) nm ::= JOIN_KW */
   -1,  /* (360) typetoken ::= typename */
   -1,  /* (361) typename ::= ID|STRING */
   -1,  /* (362) signed ::= plus_num */
   -1,  /* (363) signed ::= minus_num */
   -2,  /* (364) carglist ::= carglist ccons */
    0,  /* (365) carglist ::= */
   -2,  /* (366) ccons ::= NULL onconf */
   -4,  /* (367) ccons ::= GENERATED ALWAYS AS generated */
   -2,  /* (368) ccons ::= AS generated */
   -2,  /* (369) conslist_opt ::= COMMA conslist */
   -3,  /* (370) conslist ::= conslist tconscomma tcons */
   -1,  /* (371) conslist ::= tcons */
    0,  /* (372) tconscomma ::= */
   -1,  /* (373) defer_subclause_opt ::= defer_subclause */
   -1,  /* (374) resolvetype ::= raisetype */
   -1,  /* (375) selectnowith ::= oneselect */
   -1,  /* (376) oneselect ::= values */
   -2,  /* (377) sclp ::= selcollist COMMA */
   -1,  /* (378) as ::= ID|STRING */
   -1,  /* (379) indexed_opt ::= indexed_by */
    0,  /* (380) returning ::= */
   -1,  /* (381) expr ::= term */
   -1,  /* (382) likeop ::= LIKE_KW|MATCH */

   -1,  /* (383) exprlist ::= nexprlist */
   -1,  /* (384) nmnum ::= plus_num */
   -1,  /* (385) nmnum ::= nm */
   -1,  /* (386) nmnum ::= ON */
   -1,  /* (387) nmnum ::= DELETE */
   -1,  /* (388) nmnum ::= DEFAULT */
   -1,  /* (389) plus_num ::= INTEGER|FLOAT */
    0,  /* (390) foreach_clause ::= */
   -3,  /* (391) foreach_clause ::= FOR EACH ROW */
   -1,  /* (392) trnm ::= nm */
    0,  /* (393) tridxby ::= */
   -1,  /* (394) database_kw_opt ::= DATABASE */
    0,  /* (395) database_kw_opt ::= */
    0,  /* (396) kwcolumn_opt ::= */
   -1,  /* (397) kwcolumn_opt ::= COLUMNKW */
   -1,  /* (398) vtabarglist ::= vtabarg */
   -3,  /* (399) vtabarglist ::= vtabarglist COMMA vtabarg */
   -2,  /* (400) vtabarg ::= vtabarg vtabargtoken */
    0,  /* (401) anylist ::= */
   -4,  /* (402) anylist ::= anylist LP anylist RP */
   -2,  /* (403) anylist ::= anylist ANY */
    0,  /* (404) with ::= */
};

static void yy_accept(yyParser*);  /* Forward Declaration */

/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.







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







171027
171028
171029
171030
171031
171032
171033
171034
171035
171036
171037
171038
171039

171040
171041
171042
171043
171044
171045
171046
171047
171048
171049
171050
171051
171052
171053
171054
171055
171056

171057
171058
171059
171060
171061
171062
171063

171064
171065
171066
171067
171068
171069
171070
171071
171072
171073
171074
171075
171076
171077
171078
171079
171080
171081
171082
171083
171084

171085
171086
171087
171088
171089
171090
171091
171092
171093
171094
171095
171096
171097
171098
171099
171100
171101
171102
171103
171104
171105
171106
171107
171108
171109
171110
171111
171112
171113
171114
171115
171116
171117
171118
171119
171120
171121
171122
171123
171124
171125
171126
171127
171128
171129
171130
171131
171132
171133
171134
171135
171136
171137
171138
171139
171140
171141
171142
171143
171144
171145
171146
171147


171148
171149
171150
171151
171152
171153
171154
171155
171156
171157
171158
171159
171160
171161
171162
171163
171164
171165
171166
171167
171168
171169
171170
171171
171172
171173
171174
171175
171176
171177
171178
171179
171180
171181
171182
171183
171184
171185
171186
171187
171188
171189
171190
171191
171192
171193
171194
171195
171196
171197
171198
171199
171200
171201
171202
171203


171204
171205
171206
171207
171208
171209
171210
171211
171212

171213
171214
171215
171216
171217
171218
171219
171220
171221
171222
171223
171224
171225
171226
171227
171228
171229
171230
171231
171232
171233
171234
171235
171236
171237
171238
171239
171240
171241
171242
171243
171244
171245
171246
171247
171248
171249
171250
171251
171252
171253
171254
171255
171256
171257
171258
171259
171260
171261
171262
171263
171264
171265
   -2,  /* (171) insert_cmd ::= INSERT orconf */
   -1,  /* (172) insert_cmd ::= REPLACE */
    0,  /* (173) idlist_opt ::= */
   -3,  /* (174) idlist_opt ::= LP idlist RP */
   -3,  /* (175) idlist ::= idlist COMMA nm */
   -1,  /* (176) idlist ::= nm */
   -3,  /* (177) expr ::= LP expr RP */
   -1,  /* (178) expr ::= ID|INDEXED|JOIN_KW */
   -3,  /* (179) expr ::= nm DOT nm */
   -5,  /* (180) expr ::= nm DOT nm DOT nm */
   -1,  /* (181) term ::= NULL|FLOAT|BLOB */
   -1,  /* (182) term ::= STRING */
   -1,  /* (183) term ::= INTEGER */

   -1,  /* (184) expr ::= VARIABLE */
   -3,  /* (185) expr ::= expr COLLATE ID|STRING */
   -6,  /* (186) expr ::= CAST LP expr AS typetoken RP */
   -5,  /* (187) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
   -4,  /* (188) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
   -6,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
   -5,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
   -1,  /* (191) term ::= CTIME_KW */
   -5,  /* (192) expr ::= LP nexprlist COMMA expr RP */
   -3,  /* (193) expr ::= expr AND expr */
   -3,  /* (194) expr ::= expr OR expr */
   -3,  /* (195) expr ::= expr LT|GT|GE|LE expr */
   -3,  /* (196) expr ::= expr EQ|NE expr */
   -3,  /* (197) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
   -3,  /* (198) expr ::= expr PLUS|MINUS expr */
   -3,  /* (199) expr ::= expr STAR|SLASH|REM expr */
   -3,  /* (200) expr ::= expr CONCAT expr */

   -2,  /* (201) likeop ::= NOT LIKE_KW|MATCH */
   -3,  /* (202) expr ::= expr likeop expr */
   -5,  /* (203) expr ::= expr likeop expr ESCAPE expr */
   -2,  /* (204) expr ::= expr ISNULL|NOTNULL */
   -3,  /* (205) expr ::= expr NOT NULL */
   -3,  /* (206) expr ::= expr IS expr */
   -4,  /* (207) expr ::= expr IS NOT expr */

   -6,  /* (208) expr ::= expr IS NOT DISTINCT FROM expr */
   -5,  /* (209) expr ::= expr IS DISTINCT FROM expr */
   -2,  /* (210) expr ::= NOT expr */
   -2,  /* (211) expr ::= BITNOT expr */
   -2,  /* (212) expr ::= PLUS|MINUS expr */
   -3,  /* (213) expr ::= expr PTR expr */
   -1,  /* (214) between_op ::= BETWEEN */
   -2,  /* (215) between_op ::= NOT BETWEEN */
   -5,  /* (216) expr ::= expr between_op expr AND expr */
   -1,  /* (217) in_op ::= IN */
   -2,  /* (218) in_op ::= NOT IN */
   -5,  /* (219) expr ::= expr in_op LP exprlist RP */
   -3,  /* (220) expr ::= LP select RP */
   -5,  /* (221) expr ::= expr in_op LP select RP */
   -5,  /* (222) expr ::= expr in_op nm dbnm paren_exprlist */
   -4,  /* (223) expr ::= EXISTS LP select RP */
   -5,  /* (224) expr ::= CASE case_operand case_exprlist case_else END */
   -5,  /* (225) case_exprlist ::= case_exprlist WHEN expr THEN expr */
   -4,  /* (226) case_exprlist ::= WHEN expr THEN expr */
   -2,  /* (227) case_else ::= ELSE expr */
    0,  /* (228) case_else ::= */

    0,  /* (229) case_operand ::= */
    0,  /* (230) exprlist ::= */
   -3,  /* (231) nexprlist ::= nexprlist COMMA expr */
   -1,  /* (232) nexprlist ::= expr */
    0,  /* (233) paren_exprlist ::= */
   -3,  /* (234) paren_exprlist ::= LP exprlist RP */
  -12,  /* (235) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
   -1,  /* (236) uniqueflag ::= UNIQUE */
    0,  /* (237) uniqueflag ::= */
    0,  /* (238) eidlist_opt ::= */
   -3,  /* (239) eidlist_opt ::= LP eidlist RP */
   -5,  /* (240) eidlist ::= eidlist COMMA nm collate sortorder */
   -3,  /* (241) eidlist ::= nm collate sortorder */
    0,  /* (242) collate ::= */
   -2,  /* (243) collate ::= COLLATE ID|STRING */
   -4,  /* (244) cmd ::= DROP INDEX ifexists fullname */
   -2,  /* (245) cmd ::= VACUUM vinto */
   -3,  /* (246) cmd ::= VACUUM nm vinto */
   -2,  /* (247) vinto ::= INTO expr */
    0,  /* (248) vinto ::= */
   -3,  /* (249) cmd ::= PRAGMA nm dbnm */
   -5,  /* (250) cmd ::= PRAGMA nm dbnm EQ nmnum */
   -6,  /* (251) cmd ::= PRAGMA nm dbnm LP nmnum RP */
   -5,  /* (252) cmd ::= PRAGMA nm dbnm EQ minus_num */
   -6,  /* (253) cmd ::= PRAGMA nm dbnm LP minus_num RP */
   -2,  /* (254) plus_num ::= PLUS INTEGER|FLOAT */
   -2,  /* (255) minus_num ::= MINUS INTEGER|FLOAT */
   -5,  /* (256) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  -11,  /* (257) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   -1,  /* (258) trigger_time ::= BEFORE|AFTER */
   -2,  /* (259) trigger_time ::= INSTEAD OF */
    0,  /* (260) trigger_time ::= */
   -1,  /* (261) trigger_event ::= DELETE|INSERT */
   -1,  /* (262) trigger_event ::= UPDATE */
   -3,  /* (263) trigger_event ::= UPDATE OF idlist */
    0,  /* (264) when_clause ::= */
   -2,  /* (265) when_clause ::= WHEN expr */
   -3,  /* (266) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   -2,  /* (267) trigger_cmd_list ::= trigger_cmd SEMI */
   -3,  /* (268) trnm ::= nm DOT nm */
   -3,  /* (269) tridxby ::= INDEXED BY nm */
   -2,  /* (270) tridxby ::= NOT INDEXED */
   -9,  /* (271) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
   -8,  /* (272) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
   -6,  /* (273) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
   -3,  /* (274) trigger_cmd ::= scanpt select scanpt */
   -4,  /* (275) expr ::= RAISE LP IGNORE RP */
   -6,  /* (276) expr ::= RAISE LP raisetype COMMA nm RP */
   -1,  /* (277) raisetype ::= ROLLBACK */
   -1,  /* (278) raisetype ::= ABORT */
   -1,  /* (279) raisetype ::= FAIL */
   -4,  /* (280) cmd ::= DROP TRIGGER ifexists fullname */
   -6,  /* (281) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   -3,  /* (282) cmd ::= DETACH database_kw_opt expr */
    0,  /* (283) key_opt ::= */
   -2,  /* (284) key_opt ::= KEY expr */
   -1,  /* (285) cmd ::= REINDEX */
   -3,  /* (286) cmd ::= REINDEX nm dbnm */
   -1,  /* (287) cmd ::= ANALYZE */
   -3,  /* (288) cmd ::= ANALYZE nm dbnm */
   -6,  /* (289) cmd ::= ALTER TABLE fullname RENAME TO nm */
   -7,  /* (290) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
   -6,  /* (291) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */


   -1,  /* (292) add_column_fullname ::= fullname */
   -8,  /* (293) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
   -1,  /* (294) cmd ::= create_vtab */
   -4,  /* (295) cmd ::= create_vtab LP vtabarglist RP */
   -8,  /* (296) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
    0,  /* (297) vtabarg ::= */
   -1,  /* (298) vtabargtoken ::= ANY */
   -3,  /* (299) vtabargtoken ::= lp anylist RP */
   -1,  /* (300) lp ::= LP */
   -2,  /* (301) with ::= WITH wqlist */
   -3,  /* (302) with ::= WITH RECURSIVE wqlist */
   -1,  /* (303) wqas ::= AS */
   -2,  /* (304) wqas ::= AS MATERIALIZED */
   -3,  /* (305) wqas ::= AS NOT MATERIALIZED */
   -6,  /* (306) wqitem ::= nm eidlist_opt wqas LP select RP */
   -1,  /* (307) wqlist ::= wqitem */
   -3,  /* (308) wqlist ::= wqlist COMMA wqitem */
   -1,  /* (309) windowdefn_list ::= windowdefn */
   -3,  /* (310) windowdefn_list ::= windowdefn_list COMMA windowdefn */
   -5,  /* (311) windowdefn ::= nm AS LP window RP */
   -5,  /* (312) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
   -6,  /* (313) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
   -4,  /* (314) window ::= ORDER BY sortlist frame_opt */
   -5,  /* (315) window ::= nm ORDER BY sortlist frame_opt */
   -1,  /* (316) window ::= frame_opt */
   -2,  /* (317) window ::= nm frame_opt */
    0,  /* (318) frame_opt ::= */
   -3,  /* (319) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
   -6,  /* (320) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
   -1,  /* (321) range_or_rows ::= RANGE|ROWS|GROUPS */
   -1,  /* (322) frame_bound_s ::= frame_bound */
   -2,  /* (323) frame_bound_s ::= UNBOUNDED PRECEDING */
   -1,  /* (324) frame_bound_e ::= frame_bound */
   -2,  /* (325) frame_bound_e ::= UNBOUNDED FOLLOWING */
   -2,  /* (326) frame_bound ::= expr PRECEDING|FOLLOWING */
   -2,  /* (327) frame_bound ::= CURRENT ROW */
    0,  /* (328) frame_exclude_opt ::= */
   -2,  /* (329) frame_exclude_opt ::= EXCLUDE frame_exclude */
   -2,  /* (330) frame_exclude ::= NO OTHERS */
   -2,  /* (331) frame_exclude ::= CURRENT ROW */
   -1,  /* (332) frame_exclude ::= GROUP|TIES */
   -2,  /* (333) window_clause ::= WINDOW windowdefn_list */
   -2,  /* (334) filter_over ::= filter_clause over_clause */
   -1,  /* (335) filter_over ::= over_clause */
   -1,  /* (336) filter_over ::= filter_clause */
   -4,  /* (337) over_clause ::= OVER LP window RP */
   -2,  /* (338) over_clause ::= OVER nm */
   -5,  /* (339) filter_clause ::= FILTER LP WHERE expr RP */
   -1,  /* (340) input ::= cmdlist */
   -2,  /* (341) cmdlist ::= cmdlist ecmd */
   -1,  /* (342) cmdlist ::= ecmd */
   -1,  /* (343) ecmd ::= SEMI */
   -2,  /* (344) ecmd ::= cmdx SEMI */
   -3,  /* (345) ecmd ::= explain cmdx SEMI */
    0,  /* (346) trans_opt ::= */
   -1,  /* (347) trans_opt ::= TRANSACTION */


   -2,  /* (348) trans_opt ::= TRANSACTION nm */
   -1,  /* (349) savepoint_opt ::= SAVEPOINT */
    0,  /* (350) savepoint_opt ::= */
   -2,  /* (351) cmd ::= create_table create_table_args */
   -1,  /* (352) table_option_set ::= table_option */
   -4,  /* (353) columnlist ::= columnlist COMMA columnname carglist */
   -2,  /* (354) columnlist ::= columnname carglist */
   -1,  /* (355) nm ::= ID|INDEXED|JOIN_KW */
   -1,  /* (356) nm ::= STRING */

   -1,  /* (357) typetoken ::= typename */
   -1,  /* (358) typename ::= ID|STRING */
   -1,  /* (359) signed ::= plus_num */
   -1,  /* (360) signed ::= minus_num */
   -2,  /* (361) carglist ::= carglist ccons */
    0,  /* (362) carglist ::= */
   -2,  /* (363) ccons ::= NULL onconf */
   -4,  /* (364) ccons ::= GENERATED ALWAYS AS generated */
   -2,  /* (365) ccons ::= AS generated */
   -2,  /* (366) conslist_opt ::= COMMA conslist */
   -3,  /* (367) conslist ::= conslist tconscomma tcons */
   -1,  /* (368) conslist ::= tcons */
    0,  /* (369) tconscomma ::= */
   -1,  /* (370) defer_subclause_opt ::= defer_subclause */
   -1,  /* (371) resolvetype ::= raisetype */
   -1,  /* (372) selectnowith ::= oneselect */
   -1,  /* (373) oneselect ::= values */
   -2,  /* (374) sclp ::= selcollist COMMA */
   -1,  /* (375) as ::= ID|STRING */
   -1,  /* (376) indexed_opt ::= indexed_by */
    0,  /* (377) returning ::= */
   -1,  /* (378) expr ::= term */
   -1,  /* (379) likeop ::= LIKE_KW|MATCH */
   -1,  /* (380) case_operand ::= expr */
   -1,  /* (381) exprlist ::= nexprlist */
   -1,  /* (382) nmnum ::= plus_num */
   -1,  /* (383) nmnum ::= nm */
   -1,  /* (384) nmnum ::= ON */
   -1,  /* (385) nmnum ::= DELETE */
   -1,  /* (386) nmnum ::= DEFAULT */
   -1,  /* (387) plus_num ::= INTEGER|FLOAT */
    0,  /* (388) foreach_clause ::= */
   -3,  /* (389) foreach_clause ::= FOR EACH ROW */
   -1,  /* (390) trnm ::= nm */
    0,  /* (391) tridxby ::= */
   -1,  /* (392) database_kw_opt ::= DATABASE */
    0,  /* (393) database_kw_opt ::= */
    0,  /* (394) kwcolumn_opt ::= */
   -1,  /* (395) kwcolumn_opt ::= COLUMNKW */
   -1,  /* (396) vtabarglist ::= vtabarg */
   -3,  /* (397) vtabarglist ::= vtabarglist COMMA vtabarg */
   -2,  /* (398) vtabarg ::= vtabarg vtabargtoken */
    0,  /* (399) anylist ::= */
   -4,  /* (400) anylist ::= anylist LP anylist RP */
   -2,  /* (401) anylist ::= anylist ANY */
    0,  /* (402) with ::= */
};

static void yy_accept(yyParser*);  /* Forward Declaration */

/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.
170374
170375
170376
170377
170378
170379
170380
170381
170382
170383
170384
170385
170386
170387
170388
        break;
      case 4: /* transtype ::= */
{yymsp[1].minor.yy394 = TK_DEFERRED;}
        break;
      case 5: /* transtype ::= DEFERRED */
      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
      case 323: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==323);
{yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/}
        break;
      case 8: /* cmd ::= COMMIT|END trans_opt */
      case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
{sqlite3EndTransaction(pParse,yymsp[-1].major);}
        break;
      case 10: /* cmd ::= SAVEPOINT nm */







|







171311
171312
171313
171314
171315
171316
171317
171318
171319
171320
171321
171322
171323
171324
171325
        break;
      case 4: /* transtype ::= */
{yymsp[1].minor.yy394 = TK_DEFERRED;}
        break;
      case 5: /* transtype ::= DEFERRED */
      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
      case 321: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==321);
{yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/}
        break;
      case 8: /* cmd ::= COMMIT|END trans_opt */
      case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
{sqlite3EndTransaction(pParse,yymsp[-1].major);}
        break;
      case 10: /* cmd ::= SAVEPOINT nm */
170411
170412
170413
170414
170415
170416
170417
170418
170419
170420
170421
170422
170423
170424
170425
      case 15: /* ifnotexists ::= */
      case 18: /* temp ::= */ yytestcase(yyruleno==18);
      case 47: /* autoinc ::= */ yytestcase(yyruleno==47);
      case 62: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==62);
      case 72: /* defer_subclause_opt ::= */ yytestcase(yyruleno==72);
      case 81: /* ifexists ::= */ yytestcase(yyruleno==81);
      case 98: /* distinct ::= */ yytestcase(yyruleno==98);
      case 244: /* collate ::= */ yytestcase(yyruleno==244);
{yymsp[1].minor.yy394 = 0;}
        break;
      case 16: /* ifnotexists ::= IF NOT EXISTS */
{yymsp[-2].minor.yy394 = 1;}
        break;
      case 17: /* temp ::= TEMP */
{yymsp[0].minor.yy394 = pParse->db->init.busy==0;}







|







171348
171349
171350
171351
171352
171353
171354
171355
171356
171357
171358
171359
171360
171361
171362
      case 15: /* ifnotexists ::= */
      case 18: /* temp ::= */ yytestcase(yyruleno==18);
      case 47: /* autoinc ::= */ yytestcase(yyruleno==47);
      case 62: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==62);
      case 72: /* defer_subclause_opt ::= */ yytestcase(yyruleno==72);
      case 81: /* ifexists ::= */ yytestcase(yyruleno==81);
      case 98: /* distinct ::= */ yytestcase(yyruleno==98);
      case 242: /* collate ::= */ yytestcase(yyruleno==242);
{yymsp[1].minor.yy394 = 0;}
        break;
      case 16: /* ifnotexists ::= IF NOT EXISTS */
{yymsp[-2].minor.yy394 = 1;}
        break;
      case 17: /* temp ::= TEMP */
{yymsp[0].minor.yy394 = pParse->db->init.busy==0;}
170595
170596
170597
170598
170599
170600
170601
170602
170603
170604
170605
170606
170607
170608
170609
170610
170611
      case 61: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
      case 76: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==76);
      case 171: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==171);
{yymsp[-1].minor.yy394 = yymsp[0].minor.yy394;}
        break;
      case 63: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
      case 80: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==80);
      case 216: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==216);
      case 219: /* in_op ::= NOT IN */ yytestcase(yyruleno==219);
      case 245: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==245);
{yymsp[-1].minor.yy394 = 1;}
        break;
      case 64: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
{yymsp[-1].minor.yy394 = 0;}
        break;
      case 66: /* tconscomma ::= COMMA */
{pParse->constraintName.n = 0;}







|
|
|







171532
171533
171534
171535
171536
171537
171538
171539
171540
171541
171542
171543
171544
171545
171546
171547
171548
      case 61: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
      case 76: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==76);
      case 171: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==171);
{yymsp[-1].minor.yy394 = yymsp[0].minor.yy394;}
        break;
      case 63: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
      case 80: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==80);
      case 215: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==215);
      case 218: /* in_op ::= NOT IN */ yytestcase(yyruleno==218);
      case 243: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==243);
{yymsp[-1].minor.yy394 = 1;}
        break;
      case 64: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
{yymsp[-1].minor.yy394 = 0;}
        break;
      case 66: /* tconscomma ::= COMMA */
{pParse->constraintName.n = 0;}
170747
170748
170749
170750
170751
170752
170753
170754
170755
170756
170757
170758
170759
170760
170761
170762
170763
        break;
      case 97: /* distinct ::= ALL */
{yymsp[0].minor.yy394 = SF_All;}
        break;
      case 99: /* sclp ::= */
      case 132: /* orderby_opt ::= */ yytestcase(yyruleno==132);
      case 142: /* groupby_opt ::= */ yytestcase(yyruleno==142);
      case 232: /* exprlist ::= */ yytestcase(yyruleno==232);
      case 235: /* paren_exprlist ::= */ yytestcase(yyruleno==235);
      case 240: /* eidlist_opt ::= */ yytestcase(yyruleno==240);
{yymsp[1].minor.yy322 = 0;}
        break;
      case 100: /* selcollist ::= sclp scanpt expr scanpt as */
{
   yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[0].minor.yy0, 1);
   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy322,yymsp[-3].minor.yy522,yymsp[-1].minor.yy522);







|
|
|







171684
171685
171686
171687
171688
171689
171690
171691
171692
171693
171694
171695
171696
171697
171698
171699
171700
        break;
      case 97: /* distinct ::= ALL */
{yymsp[0].minor.yy394 = SF_All;}
        break;
      case 99: /* sclp ::= */
      case 132: /* orderby_opt ::= */ yytestcase(yyruleno==132);
      case 142: /* groupby_opt ::= */ yytestcase(yyruleno==142);
      case 230: /* exprlist ::= */ yytestcase(yyruleno==230);
      case 233: /* paren_exprlist ::= */ yytestcase(yyruleno==233);
      case 238: /* eidlist_opt ::= */ yytestcase(yyruleno==238);
{yymsp[1].minor.yy322 = 0;}
        break;
      case 100: /* selcollist ::= sclp scanpt expr scanpt as */
{
   yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[0].minor.yy0, 1);
   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy322,yymsp[-3].minor.yy522,yymsp[-1].minor.yy522);
170775
170776
170777
170778
170779
170780
170781
170782
170783
170784
170785
170786
170787
170788
170789
170790
  Expr *pLeft = tokenExpr(pParse, TK_ID, yymsp[-2].minor.yy0);
  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, pDot);
}
        break;
      case 103: /* as ::= AS nm */
      case 115: /* dbnm ::= DOT nm */ yytestcase(yyruleno==115);
      case 256: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==256);
      case 257: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==257);
{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
        break;
      case 105: /* from ::= */
      case 108: /* stl_prefix ::= */ yytestcase(yyruleno==108);
{yymsp[1].minor.yy131 = 0;}
        break;
      case 106: /* from ::= FROM seltablist */







|
|







171712
171713
171714
171715
171716
171717
171718
171719
171720
171721
171722
171723
171724
171725
171726
171727
  Expr *pLeft = tokenExpr(pParse, TK_ID, yymsp[-2].minor.yy0);
  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, pDot);
}
        break;
      case 103: /* as ::= AS nm */
      case 115: /* dbnm ::= DOT nm */ yytestcase(yyruleno==115);
      case 254: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==254);
      case 255: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==255);
{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
        break;
      case 105: /* from ::= */
      case 108: /* stl_prefix ::= */ yytestcase(yyruleno==108);
{yymsp[1].minor.yy131 = 0;}
        break;
      case 106: /* from ::= FROM seltablist */
170820
170821
170822
170823
170824
170825
170826
170827
170828
170829
170830
170831
170832
170833
170834
    yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,0,0,&yymsp[-1].minor.yy0,yymsp[-3].minor.yy47,&yymsp[0].minor.yy561);
  }
        break;
      case 113: /* seltablist ::= stl_prefix LP seltablist RP as on_using */
{
    if( yymsp[-5].minor.yy131==0 && yymsp[-1].minor.yy0.n==0 && yymsp[0].minor.yy561.pOn==0 && yymsp[0].minor.yy561.pUsing==0 ){
      yymsp[-5].minor.yy131 = yymsp[-3].minor.yy131;
    }else if( yymsp[-3].minor.yy131->nSrc==1 ){
      yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,0,0,&yymsp[-1].minor.yy0,0,&yymsp[0].minor.yy561);
      if( yymsp[-5].minor.yy131 ){
        SrcItem *pNew = &yymsp[-5].minor.yy131->a[yymsp[-5].minor.yy131->nSrc-1];
        SrcItem *pOld = yymsp[-3].minor.yy131->a;
        pNew->zName = pOld->zName;
        pNew->zDatabase = pOld->zDatabase;
        pNew->pSelect = pOld->pSelect;







|







171757
171758
171759
171760
171761
171762
171763
171764
171765
171766
171767
171768
171769
171770
171771
    yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,0,0,&yymsp[-1].minor.yy0,yymsp[-3].minor.yy47,&yymsp[0].minor.yy561);
  }
        break;
      case 113: /* seltablist ::= stl_prefix LP seltablist RP as on_using */
{
    if( yymsp[-5].minor.yy131==0 && yymsp[-1].minor.yy0.n==0 && yymsp[0].minor.yy561.pOn==0 && yymsp[0].minor.yy561.pUsing==0 ){
      yymsp[-5].minor.yy131 = yymsp[-3].minor.yy131;
    }else if( ALWAYS(yymsp[-3].minor.yy131!=0) && yymsp[-3].minor.yy131->nSrc==1 ){
      yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,0,0,&yymsp[-1].minor.yy0,0,&yymsp[0].minor.yy561);
      if( yymsp[-5].minor.yy131 ){
        SrcItem *pNew = &yymsp[-5].minor.yy131->a[yymsp[-5].minor.yy131->nSrc-1];
        SrcItem *pOld = yymsp[-3].minor.yy131->a;
        pNew->zName = pOld->zName;
        pNew->zDatabase = pOld->zDatabase;
        pNew->pSelect = pOld->pSelect;
170948
170949
170950
170951
170952
170953
170954
170955
170956
170957
170958
170959
170960
170961
170962
170963
170964
170965
170966
170967
170968
170969
170970
170971
      case 140: /* nulls ::= NULLS LAST */
{yymsp[-1].minor.yy394 = SQLITE_SO_DESC;}
        break;
      case 144: /* having_opt ::= */
      case 146: /* limit_opt ::= */ yytestcase(yyruleno==146);
      case 151: /* where_opt ::= */ yytestcase(yyruleno==151);
      case 153: /* where_opt_ret ::= */ yytestcase(yyruleno==153);
      case 229: /* case_else ::= */ yytestcase(yyruleno==229);
      case 231: /* case_operand ::= */ yytestcase(yyruleno==231);
      case 250: /* vinto ::= */ yytestcase(yyruleno==250);
{yymsp[1].minor.yy528 = 0;}
        break;
      case 145: /* having_opt ::= HAVING expr */
      case 152: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==152);
      case 154: /* where_opt_ret ::= WHERE expr */ yytestcase(yyruleno==154);
      case 228: /* case_else ::= ELSE expr */ yytestcase(yyruleno==228);
      case 249: /* vinto ::= INTO expr */ yytestcase(yyruleno==249);
{yymsp[-1].minor.yy528 = yymsp[0].minor.yy528;}
        break;
      case 147: /* limit_opt ::= LIMIT expr */
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy528,0);}
        break;
      case 148: /* limit_opt ::= LIMIT expr OFFSET expr */
{yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}







|
|
|





|
|







171885
171886
171887
171888
171889
171890
171891
171892
171893
171894
171895
171896
171897
171898
171899
171900
171901
171902
171903
171904
171905
171906
171907
171908
      case 140: /* nulls ::= NULLS LAST */
{yymsp[-1].minor.yy394 = SQLITE_SO_DESC;}
        break;
      case 144: /* having_opt ::= */
      case 146: /* limit_opt ::= */ yytestcase(yyruleno==146);
      case 151: /* where_opt ::= */ yytestcase(yyruleno==151);
      case 153: /* where_opt_ret ::= */ yytestcase(yyruleno==153);
      case 228: /* case_else ::= */ yytestcase(yyruleno==228);
      case 229: /* case_operand ::= */ yytestcase(yyruleno==229);
      case 248: /* vinto ::= */ yytestcase(yyruleno==248);
{yymsp[1].minor.yy528 = 0;}
        break;
      case 145: /* having_opt ::= HAVING expr */
      case 152: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==152);
      case 154: /* where_opt_ret ::= WHERE expr */ yytestcase(yyruleno==154);
      case 227: /* case_else ::= ELSE expr */ yytestcase(yyruleno==227);
      case 247: /* vinto ::= INTO expr */ yytestcase(yyruleno==247);
{yymsp[-1].minor.yy528 = yymsp[0].minor.yy528;}
        break;
      case 147: /* limit_opt ::= LIMIT expr */
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy528,0);}
        break;
      case 148: /* limit_opt ::= LIMIT expr OFFSET expr */
{yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
171069
171070
171071
171072
171073
171074
171075
171076
171077
171078
171079
171080
171081
171082
171083
171084
171085
171086
171087
171088
171089
171090
171091
171092
171093
171094
171095
171096
171097
171098
171099
171100
171101
171102
171103
171104
171105
171106
171107
171108
171109
171110
171111
171112
171113
171114
171115
171116
171117
171118
171119
        break;
      case 176: /* idlist ::= nm */
{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
        break;
      case 177: /* expr ::= LP expr RP */
{yymsp[-2].minor.yy528 = yymsp[-1].minor.yy528;}
        break;
      case 178: /* expr ::= ID|INDEXED */
      case 179: /* expr ::= JOIN_KW */ yytestcase(yyruleno==179);
{yymsp[0].minor.yy528=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
        break;
      case 180: /* expr ::= nm DOT nm */
{
  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
  yylhsminor.yy528 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
}
  yymsp[-2].minor.yy528 = yylhsminor.yy528;
        break;
      case 181: /* expr ::= nm DOT nm DOT nm */
{
  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-4].minor.yy0);
  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
  Expr *temp3 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  if( IN_RENAME_OBJECT ){
    sqlite3RenameTokenRemap(pParse, 0, temp1);
  }
  yylhsminor.yy528 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
      case 182: /* term ::= NULL|FLOAT|BLOB */
      case 183: /* term ::= STRING */ yytestcase(yyruleno==183);
{yymsp[0].minor.yy528=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
        break;
      case 184: /* term ::= INTEGER */
{
  yylhsminor.yy528 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  if( yylhsminor.yy528 ) yylhsminor.yy528->w.iOfst = (int)(yymsp[0].minor.yy0.z - pParse->zTail);
}
  yymsp[0].minor.yy528 = yylhsminor.yy528;
        break;
      case 185: /* expr ::= VARIABLE */
{
  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
    u32 n = yymsp[0].minor.yy0.n;
    yymsp[0].minor.yy528 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy528, n);
  }else{
    /* When doing a nested parse, one can include terms in an expression







|
<


|







|












|
|


|






|







172006
172007
172008
172009
172010
172011
172012
172013

172014
172015
172016
172017
172018
172019
172020
172021
172022
172023
172024
172025
172026
172027
172028
172029
172030
172031
172032
172033
172034
172035
172036
172037
172038
172039
172040
172041
172042
172043
172044
172045
172046
172047
172048
172049
172050
172051
172052
172053
172054
172055
        break;
      case 176: /* idlist ::= nm */
{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
        break;
      case 177: /* expr ::= LP expr RP */
{yymsp[-2].minor.yy528 = yymsp[-1].minor.yy528;}
        break;
      case 178: /* expr ::= ID|INDEXED|JOIN_KW */

{yymsp[0].minor.yy528=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
        break;
      case 179: /* expr ::= nm DOT nm */
{
  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
  yylhsminor.yy528 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
}
  yymsp[-2].minor.yy528 = yylhsminor.yy528;
        break;
      case 180: /* expr ::= nm DOT nm DOT nm */
{
  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-4].minor.yy0);
  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
  Expr *temp3 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  if( IN_RENAME_OBJECT ){
    sqlite3RenameTokenRemap(pParse, 0, temp1);
  }
  yylhsminor.yy528 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
      case 181: /* term ::= NULL|FLOAT|BLOB */
      case 182: /* term ::= STRING */ yytestcase(yyruleno==182);
{yymsp[0].minor.yy528=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
        break;
      case 183: /* term ::= INTEGER */
{
  yylhsminor.yy528 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  if( yylhsminor.yy528 ) yylhsminor.yy528->w.iOfst = (int)(yymsp[0].minor.yy0.z - pParse->zTail);
}
  yymsp[0].minor.yy528 = yylhsminor.yy528;
        break;
      case 184: /* expr ::= VARIABLE */
{
  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
    u32 n = yymsp[0].minor.yy0.n;
    yymsp[0].minor.yy528 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy528, n);
  }else{
    /* When doing a nested parse, one can include terms in an expression
171127
171128
171129
171130
171131
171132
171133
171134
171135
171136
171137
171138
171139
171140
171141
171142
171143
171144
171145
171146
171147
171148
171149
171150
171151
171152
171153
171154
171155
171156
171157
171158
171159
171160
171161
171162
171163
171164
171165
171166
171167
171168
171169
171170
171171
171172
171173
171174
171175
171176
171177
171178
171179
171180
171181
171182
171183
171184
171185
171186
171187
171188
171189
171190
171191
171192
171193
171194
171195
171196
171197
171198
171199
171200
171201
171202
171203
171204
171205
171206
171207
171208
171209
171210
171211
171212
171213
171214
171215
171216
171217
171218
171219
171220
171221
171222
171223
171224
171225
171226
171227
171228
171229
171230
171231
171232
171233
171234
171235
171236
171237
171238
171239
171240
171241
171242
171243
171244
171245
171246
171247
171248
171249
171250
171251
171252
171253
171254
171255
171256
171257
171258
171259
171260
171261
171262
171263
171264
171265
171266
171267
171268
171269
171270
171271
171272
171273
171274
171275
171276
171277
171278
171279
171280
171281
171282
171283
171284
171285
171286
171287
171288
171289
171290
171291
171292
171293
171294
171295
171296
171297
171298
171299
171300
171301
171302
171303
    }else{
      yymsp[0].minor.yy528 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
      if( yymsp[0].minor.yy528 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy528->iTable);
    }
  }
}
        break;
      case 186: /* expr ::= expr COLLATE ID|STRING */
{
  yymsp[-2].minor.yy528 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy528, &yymsp[0].minor.yy0, 1);
}
        break;
      case 187: /* expr ::= CAST LP expr AS typetoken RP */
{
  yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy528, yymsp[-3].minor.yy528, 0);
}
        break;
      case 188: /* expr ::= ID|INDEXED LP distinct exprlist RP */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy394);
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
      case 189: /* expr ::= ID|INDEXED LP STAR RP */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
}
  yymsp[-3].minor.yy528 = yylhsminor.yy528;
        break;
      case 190: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy322, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy394);
  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
}
  yymsp[-5].minor.yy528 = yylhsminor.yy528;
        break;
      case 191: /* expr ::= ID|INDEXED LP STAR RP filter_over */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
      case 192: /* term ::= CTIME_KW */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
}
  yymsp[0].minor.yy528 = yylhsminor.yy528;
        break;
      case 193: /* expr ::= LP nexprlist COMMA expr RP */
{
  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528);
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  if( yymsp[-4].minor.yy528 ){
    yymsp[-4].minor.yy528->x.pList = pList;
    if( ALWAYS(pList->nExpr) ){
      yymsp[-4].minor.yy528->flags |= pList->a[0].pExpr->flags & EP_Propagate;
    }
  }else{
    sqlite3ExprListDelete(pParse->db, pList);
  }
}
        break;
      case 194: /* expr ::= expr AND expr */
{yymsp[-2].minor.yy528=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
        break;
      case 195: /* expr ::= expr OR expr */
      case 196: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==196);
      case 197: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==197);
      case 198: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==198);
      case 199: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==199);
      case 200: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==200);
      case 201: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==201);
{yymsp[-2].minor.yy528=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
        break;
      case 202: /* likeop ::= NOT LIKE_KW|MATCH */
{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
        break;
      case 203: /* expr ::= expr likeop expr */
{
  ExprList *pList;
  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  yymsp[-1].minor.yy0.n &= 0x7fffffff;
  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy528);
  yymsp[-2].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
  if( bNot ) yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy528, 0);
  if( yymsp[-2].minor.yy528 ) yymsp[-2].minor.yy528->flags |= EP_InfixFunc;
}
        break;
      case 204: /* expr ::= expr likeop expr ESCAPE expr */
{
  ExprList *pList;
  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  yymsp[-3].minor.yy0.n &= 0x7fffffff;
  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy528);
  yymsp[-4].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
  if( bNot ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  if( yymsp[-4].minor.yy528 ) yymsp[-4].minor.yy528->flags |= EP_InfixFunc;
}
        break;
      case 205: /* expr ::= expr ISNULL|NOTNULL */
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy528,0);}
        break;
      case 206: /* expr ::= expr NOT NULL */
{yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy528,0);}
        break;
      case 207: /* expr ::= expr IS expr */
{
  yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-2].minor.yy528, TK_ISNULL);
}
        break;
      case 208: /* expr ::= expr IS NOT expr */
{
  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-3].minor.yy528, TK_NOTNULL);
}
        break;
      case 209: /* expr ::= expr IS NOT DISTINCT FROM expr */
{
  yymsp[-5].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-5].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-5].minor.yy528, TK_ISNULL);
}
        break;
      case 210: /* expr ::= expr IS DISTINCT FROM expr */
{
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-4].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-4].minor.yy528, TK_NOTNULL);
}
        break;
      case 211: /* expr ::= NOT expr */
      case 212: /* expr ::= BITNOT expr */ yytestcase(yyruleno==212);
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy528, 0);/*A-overwrites-B*/}
        break;
      case 213: /* expr ::= PLUS|MINUS expr */
{
  yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy528, 0);
  /*A-overwrites-B*/
}
        break;
      case 214: /* expr ::= expr PTR expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy528);
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
}
  yymsp[-2].minor.yy528 = yylhsminor.yy528;
        break;
      case 215: /* between_op ::= BETWEEN */
      case 218: /* in_op ::= IN */ yytestcase(yyruleno==218);
{yymsp[0].minor.yy394 = 0;}
        break;
      case 217: /* expr ::= expr between_op expr AND expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy528);
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy528, 0);
  if( yymsp[-4].minor.yy528 ){
    yymsp[-4].minor.yy528->x.pList = pList;
  }else{
    sqlite3ExprListDelete(pParse->db, pList);
  }
  if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
}
        break;
      case 220: /* expr ::= expr in_op LP exprlist RP */
{
    if( yymsp[-1].minor.yy322==0 ){
      /* Expressions of the form
      **
      **      expr1 IN ()
      **      expr1 NOT IN ()
      **







|




|





|





|





|






|






|





|













|


|
|
|
|
|
|
|


|


|











|












|


|


|





|





|





|





|
|


|





|







|
|


|












|







172063
172064
172065
172066
172067
172068
172069
172070
172071
172072
172073
172074
172075
172076
172077
172078
172079
172080
172081
172082
172083
172084
172085
172086
172087
172088
172089
172090
172091
172092
172093
172094
172095
172096
172097
172098
172099
172100
172101
172102
172103
172104
172105
172106
172107
172108
172109
172110
172111
172112
172113
172114
172115
172116
172117
172118
172119
172120
172121
172122
172123
172124
172125
172126
172127
172128
172129
172130
172131
172132
172133
172134
172135
172136
172137
172138
172139
172140
172141
172142
172143
172144
172145
172146
172147
172148
172149
172150
172151
172152
172153
172154
172155
172156
172157
172158
172159
172160
172161
172162
172163
172164
172165
172166
172167
172168
172169
172170
172171
172172
172173
172174
172175
172176
172177
172178
172179
172180
172181
172182
172183
172184
172185
172186
172187
172188
172189
172190
172191
172192
172193
172194
172195
172196
172197
172198
172199
172200
172201
172202
172203
172204
172205
172206
172207
172208
172209
172210
172211
172212
172213
172214
172215
172216
172217
172218
172219
172220
172221
172222
172223
172224
172225
172226
172227
172228
172229
172230
172231
172232
172233
172234
172235
172236
172237
172238
172239
    }else{
      yymsp[0].minor.yy528 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
      if( yymsp[0].minor.yy528 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy528->iTable);
    }
  }
}
        break;
      case 185: /* expr ::= expr COLLATE ID|STRING */
{
  yymsp[-2].minor.yy528 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy528, &yymsp[0].minor.yy0, 1);
}
        break;
      case 186: /* expr ::= CAST LP expr AS typetoken RP */
{
  yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy528, yymsp[-3].minor.yy528, 0);
}
        break;
      case 187: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy394);
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
      case 188: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
}
  yymsp[-3].minor.yy528 = yylhsminor.yy528;
        break;
      case 189: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy322, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy394);
  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
}
  yymsp[-5].minor.yy528 = yylhsminor.yy528;
        break;
      case 190: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
      case 191: /* term ::= CTIME_KW */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
}
  yymsp[0].minor.yy528 = yylhsminor.yy528;
        break;
      case 192: /* expr ::= LP nexprlist COMMA expr RP */
{
  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528);
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  if( yymsp[-4].minor.yy528 ){
    yymsp[-4].minor.yy528->x.pList = pList;
    if( ALWAYS(pList->nExpr) ){
      yymsp[-4].minor.yy528->flags |= pList->a[0].pExpr->flags & EP_Propagate;
    }
  }else{
    sqlite3ExprListDelete(pParse->db, pList);
  }
}
        break;
      case 193: /* expr ::= expr AND expr */
{yymsp[-2].minor.yy528=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
        break;
      case 194: /* expr ::= expr OR expr */
      case 195: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==195);
      case 196: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==196);
      case 197: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==197);
      case 198: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==198);
      case 199: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==199);
      case 200: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==200);
{yymsp[-2].minor.yy528=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
        break;
      case 201: /* likeop ::= NOT LIKE_KW|MATCH */
{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
        break;
      case 202: /* expr ::= expr likeop expr */
{
  ExprList *pList;
  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  yymsp[-1].minor.yy0.n &= 0x7fffffff;
  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy528);
  yymsp[-2].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
  if( bNot ) yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy528, 0);
  if( yymsp[-2].minor.yy528 ) yymsp[-2].minor.yy528->flags |= EP_InfixFunc;
}
        break;
      case 203: /* expr ::= expr likeop expr ESCAPE expr */
{
  ExprList *pList;
  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  yymsp[-3].minor.yy0.n &= 0x7fffffff;
  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy528);
  yymsp[-4].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
  if( bNot ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  if( yymsp[-4].minor.yy528 ) yymsp[-4].minor.yy528->flags |= EP_InfixFunc;
}
        break;
      case 204: /* expr ::= expr ISNULL|NOTNULL */
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy528,0);}
        break;
      case 205: /* expr ::= expr NOT NULL */
{yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy528,0);}
        break;
      case 206: /* expr ::= expr IS expr */
{
  yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-2].minor.yy528, TK_ISNULL);
}
        break;
      case 207: /* expr ::= expr IS NOT expr */
{
  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-3].minor.yy528, TK_NOTNULL);
}
        break;
      case 208: /* expr ::= expr IS NOT DISTINCT FROM expr */
{
  yymsp[-5].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-5].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-5].minor.yy528, TK_ISNULL);
}
        break;
      case 209: /* expr ::= expr IS DISTINCT FROM expr */
{
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-4].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-4].minor.yy528, TK_NOTNULL);
}
        break;
      case 210: /* expr ::= NOT expr */
      case 211: /* expr ::= BITNOT expr */ yytestcase(yyruleno==211);
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy528, 0);/*A-overwrites-B*/}
        break;
      case 212: /* expr ::= PLUS|MINUS expr */
{
  yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy528, 0);
  /*A-overwrites-B*/
}
        break;
      case 213: /* expr ::= expr PTR expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy528);
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
}
  yymsp[-2].minor.yy528 = yylhsminor.yy528;
        break;
      case 214: /* between_op ::= BETWEEN */
      case 217: /* in_op ::= IN */ yytestcase(yyruleno==217);
{yymsp[0].minor.yy394 = 0;}
        break;
      case 216: /* expr ::= expr between_op expr AND expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy528);
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy528, 0);
  if( yymsp[-4].minor.yy528 ){
    yymsp[-4].minor.yy528->x.pList = pList;
  }else{
    sqlite3ExprListDelete(pParse->db, pList);
  }
  if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
}
        break;
      case 219: /* expr ::= expr in_op LP exprlist RP */
{
    if( yymsp[-1].minor.yy322==0 ){
      /* Expressions of the form
      **
      **      expr1 IN ()
      **      expr1 NOT IN ()
      **
171335
171336
171337
171338
171339
171340
171341
171342
171343
171344
171345
171346
171347
171348
171349
171350
171351
171352
171353
171354
171355
171356
171357
171358
171359
171360
171361
171362
171363
171364
171365
171366
171367
171368
171369
171370
171371
171372
171373
171374
171375
171376
171377
171378
171379
171380
171381
171382
171383
171384
171385
171386
171387
171388
171389
171390
171391
171392
171393
171394
171395
171396
171397
171398
171399
171400
171401
171402
171403
171404
171405
171406
171407
171408
171409
171410
171411
171412
171413
171414
171415
171416
171417
171418
171419
171420
171421
171422
171423
171424
171425
171426
171427
171428
171429
171430
171431
171432
171433
171434
171435
171436
171437
171438
171439
171440
171441
171442
171443
171444
171445
171446
171447
171448
171449
171450
171451
171452
171453
171454
171455
171456
171457
171458
171459
171460
171461
171462
171463
171464
171465
171466
171467
171468
171469
171470
171471
171472
171473
171474
171475
171476
171477
171478
171479
171480
171481
171482
171483
171484
171485
171486
171487
171488
171489
171490
171491
171492
171493
171494
171495
171496
171497
171498
171499
171500
171501
171502
171503
171504
171505
171506
171507
171508
171509
171510
171511
171512
171513
171514
171515
171516
171517
171518
171519
171520
171521
171522
171523
171524
171525
171526
171527
171528
171529
171530
171531
171532
171533
171534
171535
171536
171537
171538
171539
171540
171541
171542
171543
171544
171545
171546
171547
171548
171549
171550
171551
171552
171553
171554
171555
171556
171557
171558
171559
171560
171561
171562
171563
171564
171565
171566
171567
171568
171569
171570
171571
171572
171573
171574
171575
171576
171577
171578
171579
171580
171581
171582
171583
171584
171585
171586
171587
171588
171589
171590
171591
171592
171593
171594
171595
171596
171597
171598
171599
171600
171601
171602
171603
171604
171605
171606
171607
171608
171609
171610
171611
171612
171613
171614
171615
171616
171617
171618
171619
171620
171621
171622
171623
171624
171625
171626
171627
171628
171629
171630
171631
171632
171633
171634
171635
171636
171637
171638
171639
171640
171641
171642
171643
171644
171645
171646
171647
171648
171649
171650
171651
171652
171653
171654
171655
171656
171657
171658
171659
171660
171661
171662
171663
171664
171665
171666
171667
171668
171669
171670
171671
171672
171673
171674
171675
171676
171677
171678
171679
171680
171681
171682
171683
171684
171685
171686
171687
171688
171689
171690
171691
171692
171693
171694
171695
171696
171697
171698
171699
171700
171701
171702
171703
171704
171705
171706
171707
171708
171709
171710
171711
171712
171713
171714
171715
171716
171717
171718
171719
171720
171721
171722
171723
171724
171725
171726
171727
171728
171729
171730
171731
171732
171733
171734
171735
171736
171737
171738
171739
171740
171741
171742
171743
171744
171745
171746
171747
171748
171749
171750
171751
171752
171753
171754
171755
171756
171757
171758
171759
171760
171761
171762
171763
171764
171765
171766
171767
171768
171769
171770
171771
171772
171773
171774
171775
171776
171777
171778
171779
171780
171781
171782
171783
171784
171785
171786
171787
171788
171789
171790
171791
171792
171793
171794
171795
171796
171797
171798
171799
171800
171801
171802
171803
171804
171805
171806
171807
171808
171809
171810
171811
171812
171813
171814
171815
171816
171817
171818
171819
171820
171821
171822
171823
171824
171825
171826
171827
171828
171829
171830
171831
171832
171833
171834
171835
171836
171837
171838
171839
171840
171841
171842
171843
171844
171845
171846
171847
171848
171849
171850
171851
171852
171853
171854
171855
171856
171857
171858
171859
171860

171861
171862
171863
171864
171865
171866
171867
171868
171869
171870
171871
171872
171873
171874
171875
171876
171877
171878
171879
171880
171881
171882
171883
171884
171885
171886
171887
171888
171889
          sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
        }
      }
      if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
    }
  }
        break;
      case 221: /* expr ::= LP select RP */
{
    yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy528, yymsp[-1].minor.yy47);
  }
        break;
      case 222: /* expr ::= expr in_op LP select RP */
{
    yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, yymsp[-1].minor.yy47);
    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  }
        break;
      case 223: /* expr ::= expr in_op nm dbnm paren_exprlist */
{
    SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
    if( yymsp[0].minor.yy322 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy322);
    yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, pSelect);
    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  }
        break;
      case 224: /* expr ::= EXISTS LP select RP */
{
    Expr *p;
    p = yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy47);
  }
        break;
      case 225: /* expr ::= CASE case_operand case_exprlist case_else END */
{
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy528, 0);
  if( yymsp[-4].minor.yy528 ){
    yymsp[-4].minor.yy528->x.pList = yymsp[-1].minor.yy528 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[-1].minor.yy528) : yymsp[-2].minor.yy322;
    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
  }else{
    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
  }
}
        break;
      case 226: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
{
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[0].minor.yy528);
}
        break;
      case 227: /* case_exprlist ::= WHEN expr THEN expr */
{
  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, yymsp[0].minor.yy528);
}
        break;
      case 230: /* case_operand ::= expr */
{yymsp[0].minor.yy528 = yymsp[0].minor.yy528; /*A-overwrites-X*/}
        break;
      case 233: /* nexprlist ::= nexprlist COMMA expr */
{yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy528);}
        break;
      case 234: /* nexprlist ::= expr */
{yymsp[0].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy528); /*A-overwrites-Y*/}
        break;
      case 236: /* paren_exprlist ::= LP exprlist RP */
      case 241: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==241);
{yymsp[-2].minor.yy322 = yymsp[-1].minor.yy322;}
        break;
      case 237: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
{
  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy394,
                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy528, SQLITE_SO_ASC, yymsp[-8].minor.yy394, SQLITE_IDXTYPE_APPDEF);
  if( IN_RENAME_OBJECT && pParse->pNewIndex ){
    sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
  }
}
        break;
      case 238: /* uniqueflag ::= UNIQUE */
      case 280: /* raisetype ::= ABORT */ yytestcase(yyruleno==280);
{yymsp[0].minor.yy394 = OE_Abort;}
        break;
      case 239: /* uniqueflag ::= */
{yymsp[1].minor.yy394 = OE_None;}
        break;
      case 242: /* eidlist ::= eidlist COMMA nm collate sortorder */
{
  yymsp[-4].minor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394);
}
        break;
      case 243: /* eidlist ::= nm collate sortorder */
{
  yymsp[-2].minor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394); /*A-overwrites-Y*/
}
        break;
      case 246: /* cmd ::= DROP INDEX ifexists fullname */
{sqlite3DropIndex(pParse, yymsp[0].minor.yy131, yymsp[-1].minor.yy394);}
        break;
      case 247: /* cmd ::= VACUUM vinto */
{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy528);}
        break;
      case 248: /* cmd ::= VACUUM nm vinto */
{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy528);}
        break;
      case 251: /* cmd ::= PRAGMA nm dbnm */
{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
        break;
      case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
        break;
      case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
        break;
      case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
        break;
      case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
        break;
      case 258: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
{
  Token all;
  all.z = yymsp[-3].minor.yy0.z;
  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy33, &all);
}
        break;
      case 259: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
{
  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy394, yymsp[-4].minor.yy180.a, yymsp[-4].minor.yy180.b, yymsp[-2].minor.yy131, yymsp[0].minor.yy528, yymsp[-10].minor.yy394, yymsp[-8].minor.yy394);
  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
}
        break;
      case 260: /* trigger_time ::= BEFORE|AFTER */
{ yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/ }
        break;
      case 261: /* trigger_time ::= INSTEAD OF */
{ yymsp[-1].minor.yy394 = TK_INSTEAD;}
        break;
      case 262: /* trigger_time ::= */
{ yymsp[1].minor.yy394 = TK_BEFORE; }
        break;
      case 263: /* trigger_event ::= DELETE|INSERT */
      case 264: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==264);
{yymsp[0].minor.yy180.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy180.b = 0;}
        break;
      case 265: /* trigger_event ::= UPDATE OF idlist */
{yymsp[-2].minor.yy180.a = TK_UPDATE; yymsp[-2].minor.yy180.b = yymsp[0].minor.yy254;}
        break;
      case 266: /* when_clause ::= */
      case 285: /* key_opt ::= */ yytestcase(yyruleno==285);
{ yymsp[1].minor.yy528 = 0; }
        break;
      case 267: /* when_clause ::= WHEN expr */
      case 286: /* key_opt ::= KEY expr */ yytestcase(yyruleno==286);
{ yymsp[-1].minor.yy528 = yymsp[0].minor.yy528; }
        break;
      case 268: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
{
  assert( yymsp[-2].minor.yy33!=0 );
  yymsp[-2].minor.yy33->pLast->pNext = yymsp[-1].minor.yy33;
  yymsp[-2].minor.yy33->pLast = yymsp[-1].minor.yy33;
}
        break;
      case 269: /* trigger_cmd_list ::= trigger_cmd SEMI */
{
  assert( yymsp[-1].minor.yy33!=0 );
  yymsp[-1].minor.yy33->pLast = yymsp[-1].minor.yy33;
}
        break;
      case 270: /* trnm ::= nm DOT nm */
{
  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  sqlite3ErrorMsg(pParse,
        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
        "statements within triggers");
}
        break;
      case 271: /* tridxby ::= INDEXED BY nm */
{
  sqlite3ErrorMsg(pParse,
        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}
        break;
      case 272: /* tridxby ::= NOT INDEXED */
{
  sqlite3ErrorMsg(pParse,
        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}
        break;
      case 273: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
{yylhsminor.yy33 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy131, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528, yymsp[-7].minor.yy394, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy522);}
  yymsp[-8].minor.yy33 = yylhsminor.yy33;
        break;
      case 274: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
{
   yylhsminor.yy33 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy254,yymsp[-2].minor.yy47,yymsp[-6].minor.yy394,yymsp[-1].minor.yy444,yymsp[-7].minor.yy522,yymsp[0].minor.yy522);/*yylhsminor.yy33-overwrites-yymsp[-6].minor.yy394*/
}
  yymsp[-7].minor.yy33 = yylhsminor.yy33;
        break;
      case 275: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
{yylhsminor.yy33 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy528, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy522);}
  yymsp[-5].minor.yy33 = yylhsminor.yy33;
        break;
      case 276: /* trigger_cmd ::= scanpt select scanpt */
{yylhsminor.yy33 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy47, yymsp[-2].minor.yy522, yymsp[0].minor.yy522); /*yylhsminor.yy33-overwrites-yymsp[-1].minor.yy47*/}
  yymsp[-2].minor.yy33 = yylhsminor.yy33;
        break;
      case 277: /* expr ::= RAISE LP IGNORE RP */
{
  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  if( yymsp[-3].minor.yy528 ){
    yymsp[-3].minor.yy528->affExpr = OE_Ignore;
  }
}
        break;
      case 278: /* expr ::= RAISE LP raisetype COMMA nm RP */
{
  yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  if( yymsp[-5].minor.yy528 ) {
    yymsp[-5].minor.yy528->affExpr = (char)yymsp[-3].minor.yy394;
  }
}
        break;
      case 279: /* raisetype ::= ROLLBACK */
{yymsp[0].minor.yy394 = OE_Rollback;}
        break;
      case 281: /* raisetype ::= FAIL */
{yymsp[0].minor.yy394 = OE_Fail;}
        break;
      case 282: /* cmd ::= DROP TRIGGER ifexists fullname */
{
  sqlite3DropTrigger(pParse,yymsp[0].minor.yy131,yymsp[-1].minor.yy394);
}
        break;
      case 283: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
{
  sqlite3Attach(pParse, yymsp[-3].minor.yy528, yymsp[-1].minor.yy528, yymsp[0].minor.yy528);
}
        break;
      case 284: /* cmd ::= DETACH database_kw_opt expr */
{
  sqlite3Detach(pParse, yymsp[0].minor.yy528);
}
        break;
      case 287: /* cmd ::= REINDEX */
{sqlite3Reindex(pParse, 0, 0);}
        break;
      case 288: /* cmd ::= REINDEX nm dbnm */
{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
        break;
      case 289: /* cmd ::= ANALYZE */
{sqlite3Analyze(pParse, 0, 0);}
        break;
      case 290: /* cmd ::= ANALYZE nm dbnm */
{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
        break;
      case 291: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
{
  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy131,&yymsp[0].minor.yy0);
}
        break;
      case 292: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
{
  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
}
        break;
      case 293: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
{
  sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy131, &yymsp[0].minor.yy0);
}
        break;
      case 294: /* add_column_fullname ::= fullname */
{
  disableLookaside(pParse);
  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy131);
}
        break;
      case 295: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
{
  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy131, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
}
        break;
      case 296: /* cmd ::= create_vtab */
{sqlite3VtabFinishParse(pParse,0);}
        break;
      case 297: /* cmd ::= create_vtab LP vtabarglist RP */
{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
        break;
      case 298: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
{
    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy394);
}
        break;
      case 299: /* vtabarg ::= */
{sqlite3VtabArgInit(pParse);}
        break;
      case 300: /* vtabargtoken ::= ANY */
      case 301: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==301);
      case 302: /* lp ::= LP */ yytestcase(yyruleno==302);
{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
        break;
      case 303: /* with ::= WITH wqlist */
      case 304: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==304);
{ sqlite3WithPush(pParse, yymsp[0].minor.yy521, 1); }
        break;
      case 305: /* wqas ::= AS */
{yymsp[0].minor.yy516 = M10d_Any;}
        break;
      case 306: /* wqas ::= AS MATERIALIZED */
{yymsp[-1].minor.yy516 = M10d_Yes;}
        break;
      case 307: /* wqas ::= AS NOT MATERIALIZED */
{yymsp[-2].minor.yy516 = M10d_No;}
        break;
      case 308: /* wqitem ::= nm eidlist_opt wqas LP select RP */
{
  yymsp[-5].minor.yy385 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy47, yymsp[-3].minor.yy516); /*A-overwrites-X*/
}
        break;
      case 309: /* wqlist ::= wqitem */
{
  yymsp[0].minor.yy521 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy385); /*A-overwrites-X*/
}
        break;
      case 310: /* wqlist ::= wqlist COMMA wqitem */
{
  yymsp[-2].minor.yy521 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy521, yymsp[0].minor.yy385);
}
        break;
      case 311: /* windowdefn_list ::= windowdefn */
{ yylhsminor.yy41 = yymsp[0].minor.yy41; }
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
      case 312: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
{
  assert( yymsp[0].minor.yy41!=0 );
  sqlite3WindowChain(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy41);
  yymsp[0].minor.yy41->pNextWin = yymsp[-2].minor.yy41;
  yylhsminor.yy41 = yymsp[0].minor.yy41;
}
  yymsp[-2].minor.yy41 = yylhsminor.yy41;
        break;
      case 313: /* windowdefn ::= nm AS LP window RP */
{
  if( ALWAYS(yymsp[-1].minor.yy41) ){
    yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
  }
  yylhsminor.yy41 = yymsp[-1].minor.yy41;
}
  yymsp[-4].minor.yy41 = yylhsminor.yy41;
        break;
      case 314: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
{
  yymsp[-4].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, 0);
}
        break;
      case 315: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, &yymsp[-5].minor.yy0);
}
  yymsp[-5].minor.yy41 = yylhsminor.yy41;
        break;
      case 316: /* window ::= ORDER BY sortlist frame_opt */
{
  yymsp[-3].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, 0);
}
        break;
      case 317: /* window ::= nm ORDER BY sortlist frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
}
  yymsp[-4].minor.yy41 = yylhsminor.yy41;
        break;
      case 318: /* window ::= frame_opt */
      case 337: /* filter_over ::= over_clause */ yytestcase(yyruleno==337);
{
  yylhsminor.yy41 = yymsp[0].minor.yy41;
}
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
      case 319: /* window ::= nm frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, 0, &yymsp[-1].minor.yy0);
}
  yymsp[-1].minor.yy41 = yylhsminor.yy41;
        break;
      case 320: /* frame_opt ::= */
{
  yymsp[1].minor.yy41 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
}
        break;
      case 321: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
{
  yylhsminor.yy41 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy394, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy516);
}
  yymsp[-2].minor.yy41 = yylhsminor.yy41;
        break;
      case 322: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
{
  yylhsminor.yy41 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy394, yymsp[-3].minor.yy595.eType, yymsp[-3].minor.yy595.pExpr, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, yymsp[0].minor.yy516);
}
  yymsp[-5].minor.yy41 = yylhsminor.yy41;
        break;
      case 324: /* frame_bound_s ::= frame_bound */
      case 326: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==326);
{yylhsminor.yy595 = yymsp[0].minor.yy595;}
  yymsp[0].minor.yy595 = yylhsminor.yy595;
        break;
      case 325: /* frame_bound_s ::= UNBOUNDED PRECEDING */
      case 327: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==327);
      case 329: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==329);
{yylhsminor.yy595.eType = yymsp[-1].major; yylhsminor.yy595.pExpr = 0;}
  yymsp[-1].minor.yy595 = yylhsminor.yy595;
        break;
      case 328: /* frame_bound ::= expr PRECEDING|FOLLOWING */
{yylhsminor.yy595.eType = yymsp[0].major; yylhsminor.yy595.pExpr = yymsp[-1].minor.yy528;}
  yymsp[-1].minor.yy595 = yylhsminor.yy595;
        break;
      case 330: /* frame_exclude_opt ::= */
{yymsp[1].minor.yy516 = 0;}
        break;
      case 331: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
{yymsp[-1].minor.yy516 = yymsp[0].minor.yy516;}
        break;
      case 332: /* frame_exclude ::= NO OTHERS */
      case 333: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==333);
{yymsp[-1].minor.yy516 = yymsp[-1].major; /*A-overwrites-X*/}
        break;
      case 334: /* frame_exclude ::= GROUP|TIES */
{yymsp[0].minor.yy516 = yymsp[0].major; /*A-overwrites-X*/}
        break;
      case 335: /* window_clause ::= WINDOW windowdefn_list */
{ yymsp[-1].minor.yy41 = yymsp[0].minor.yy41; }
        break;
      case 336: /* filter_over ::= filter_clause over_clause */
{
  if( yymsp[0].minor.yy41 ){
    yymsp[0].minor.yy41->pFilter = yymsp[-1].minor.yy528;
  }else{
    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
  }
  yylhsminor.yy41 = yymsp[0].minor.yy41;
}
  yymsp[-1].minor.yy41 = yylhsminor.yy41;
        break;
      case 338: /* filter_over ::= filter_clause */
{
  yylhsminor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  if( yylhsminor.yy41 ){
    yylhsminor.yy41->eFrmType = TK_FILTER;
    yylhsminor.yy41->pFilter = yymsp[0].minor.yy528;
  }else{
    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy528);
  }
}
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
      case 339: /* over_clause ::= OVER LP window RP */
{
  yymsp[-3].minor.yy41 = yymsp[-1].minor.yy41;
  assert( yymsp[-3].minor.yy41!=0 );
}
        break;
      case 340: /* over_clause ::= OVER nm */
{
  yymsp[-1].minor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  if( yymsp[-1].minor.yy41 ){
    yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
  }
}
        break;
      case 341: /* filter_clause ::= FILTER LP WHERE expr RP */
{ yymsp[-4].minor.yy528 = yymsp[-1].minor.yy528; }
        break;
      default:
      /* (342) input ::= cmdlist */ yytestcase(yyruleno==342);
      /* (343) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==343);
      /* (344) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=344);
      /* (345) ecmd ::= SEMI */ yytestcase(yyruleno==345);
      /* (346) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==346);
      /* (347) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=347);
      /* (348) trans_opt ::= */ yytestcase(yyruleno==348);
      /* (349) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==349);
      /* (350) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==350);
      /* (351) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==351);
      /* (352) savepoint_opt ::= */ yytestcase(yyruleno==352);
      /* (353) cmd ::= create_table create_table_args */ yytestcase(yyruleno==353);
      /* (354) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=354);
      /* (355) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==355);
      /* (356) columnlist ::= columnname carglist */ yytestcase(yyruleno==356);
      /* (357) nm ::= ID|INDEXED */ yytestcase(yyruleno==357);
      /* (358) nm ::= STRING */ yytestcase(yyruleno==358);
      /* (359) nm ::= JOIN_KW */ yytestcase(yyruleno==359);
      /* (360) typetoken ::= typename */ yytestcase(yyruleno==360);
      /* (361) typename ::= ID|STRING */ yytestcase(yyruleno==361);
      /* (362) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=362);
      /* (363) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=363);
      /* (364) carglist ::= carglist ccons */ yytestcase(yyruleno==364);
      /* (365) carglist ::= */ yytestcase(yyruleno==365);
      /* (366) ccons ::= NULL onconf */ yytestcase(yyruleno==366);
      /* (367) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==367);
      /* (368) ccons ::= AS generated */ yytestcase(yyruleno==368);
      /* (369) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==369);
      /* (370) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==370);
      /* (371) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=371);
      /* (372) tconscomma ::= */ yytestcase(yyruleno==372);
      /* (373) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=373);
      /* (374) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=374);
      /* (375) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=375);
      /* (376) oneselect ::= values */ yytestcase(yyruleno==376);
      /* (377) sclp ::= selcollist COMMA */ yytestcase(yyruleno==377);
      /* (378) as ::= ID|STRING */ yytestcase(yyruleno==378);
      /* (379) indexed_opt ::= indexed_by (OPTIMIZED OUT) */ assert(yyruleno!=379);
      /* (380) returning ::= */ yytestcase(yyruleno==380);
      /* (381) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=381);
      /* (382) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==382);

      /* (383) exprlist ::= nexprlist */ yytestcase(yyruleno==383);
      /* (384) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=384);
      /* (385) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=385);
      /* (386) nmnum ::= ON */ yytestcase(yyruleno==386);
      /* (387) nmnum ::= DELETE */ yytestcase(yyruleno==387);
      /* (388) nmnum ::= DEFAULT */ yytestcase(yyruleno==388);
      /* (389) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==389);
      /* (390) foreach_clause ::= */ yytestcase(yyruleno==390);
      /* (391) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==391);
      /* (392) trnm ::= nm */ yytestcase(yyruleno==392);
      /* (393) tridxby ::= */ yytestcase(yyruleno==393);
      /* (394) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==394);
      /* (395) database_kw_opt ::= */ yytestcase(yyruleno==395);
      /* (396) kwcolumn_opt ::= */ yytestcase(yyruleno==396);
      /* (397) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==397);
      /* (398) vtabarglist ::= vtabarg */ yytestcase(yyruleno==398);
      /* (399) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==399);
      /* (400) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==400);
      /* (401) anylist ::= */ yytestcase(yyruleno==401);
      /* (402) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==402);
      /* (403) anylist ::= anylist ANY */ yytestcase(yyruleno==403);
      /* (404) with ::= */ yytestcase(yyruleno==404);
        break;
/********** End reduce actions ************************************************/
  };
  assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
  yygoto = yyRuleInfoLhs[yyruleno];
  yysize = yyRuleInfoNRhs[yyruleno];
  yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);







|





|






|









|






|











|





|





<
<
<
|


|


|
|


|









|
|


|


|




|




|


|


|


|


|


|


|


|


|







|





|


|


|


|
|


|


|
|


|
|


|






|





|







|






|






|



|





|



|



|







|







|


|


|




|




|




|


|


|


|


|




|





|




|





|




|


|


|




|


|
|
|


|
|


|


|


|


|




|




|




|



|








|








|




|





|




|





|
|





|





|




|





|





|
|



|
|
|



|



|


|


|
|


|


|


|










|











|





|







|



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







172271
172272
172273
172274
172275
172276
172277
172278
172279
172280
172281
172282
172283
172284
172285
172286
172287
172288
172289
172290
172291
172292
172293
172294
172295
172296
172297
172298
172299
172300
172301
172302
172303
172304
172305
172306
172307
172308
172309
172310
172311
172312
172313
172314
172315
172316
172317
172318
172319
172320
172321
172322
172323
172324
172325
172326
172327
172328
172329
172330
172331



172332
172333
172334
172335
172336
172337
172338
172339
172340
172341
172342
172343
172344
172345
172346
172347
172348
172349
172350
172351
172352
172353
172354
172355
172356
172357
172358
172359
172360
172361
172362
172363
172364
172365
172366
172367
172368
172369
172370
172371
172372
172373
172374
172375
172376
172377
172378
172379
172380
172381
172382
172383
172384
172385
172386
172387
172388
172389
172390
172391
172392
172393
172394
172395
172396
172397
172398
172399
172400
172401
172402
172403
172404
172405
172406
172407
172408
172409
172410
172411
172412
172413
172414
172415
172416
172417
172418
172419
172420
172421
172422
172423
172424
172425
172426
172427
172428
172429
172430
172431
172432
172433
172434
172435
172436
172437
172438
172439
172440
172441
172442
172443
172444
172445
172446
172447
172448
172449
172450
172451
172452
172453
172454
172455
172456
172457
172458
172459
172460
172461
172462
172463
172464
172465
172466
172467
172468
172469
172470
172471
172472
172473
172474
172475
172476
172477
172478
172479
172480
172481
172482
172483
172484
172485
172486
172487
172488
172489
172490
172491
172492
172493
172494
172495
172496
172497
172498
172499
172500
172501
172502
172503
172504
172505
172506
172507
172508
172509
172510
172511
172512
172513
172514
172515
172516
172517
172518
172519
172520
172521
172522
172523
172524
172525
172526
172527
172528
172529
172530
172531
172532
172533
172534
172535
172536
172537
172538
172539
172540
172541
172542
172543
172544
172545
172546
172547
172548
172549
172550
172551
172552
172553
172554
172555
172556
172557
172558
172559
172560
172561
172562
172563
172564
172565
172566
172567
172568
172569
172570
172571
172572
172573
172574
172575
172576
172577
172578
172579
172580
172581
172582
172583
172584
172585
172586
172587
172588
172589
172590
172591
172592
172593
172594
172595
172596
172597
172598
172599
172600
172601
172602
172603
172604
172605
172606
172607
172608
172609
172610
172611
172612
172613
172614
172615
172616
172617
172618
172619
172620
172621
172622
172623
172624
172625
172626
172627
172628
172629
172630
172631
172632
172633
172634
172635
172636
172637
172638
172639
172640
172641
172642
172643
172644
172645
172646
172647
172648
172649
172650
172651
172652
172653
172654
172655
172656
172657
172658
172659
172660
172661
172662
172663
172664
172665
172666
172667
172668
172669
172670
172671
172672
172673
172674
172675
172676
172677
172678
172679
172680
172681
172682
172683
172684
172685
172686
172687
172688
172689
172690
172691
172692
172693
172694
172695
172696
172697
172698
172699
172700
172701
172702
172703
172704
172705
172706
172707
172708
172709
172710
172711
172712
172713
172714
172715
172716
172717
172718
172719
172720
172721
172722
172723
172724
172725
172726
172727
172728
172729
172730
172731
172732
172733
172734
172735
172736
172737
172738
172739
172740
172741
172742
172743
172744
172745
172746
172747
172748
172749
172750
172751
172752
172753
172754
172755
172756
172757
172758
172759
172760
172761
172762
172763
172764
172765
172766
172767
172768
172769

172770
172771
172772
172773
172774
172775
172776
172777
172778
172779
172780
172781
172782
172783
172784
172785
172786
172787
172788
172789
172790
172791
172792
172793
172794
172795
172796
172797
172798
172799
172800
172801
172802
172803
172804
172805
172806
172807
172808
172809
172810
172811
172812
172813
172814
172815
172816
172817
172818
172819
172820
172821
172822
          sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
        }
      }
      if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
    }
  }
        break;
      case 220: /* expr ::= LP select RP */
{
    yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy528, yymsp[-1].minor.yy47);
  }
        break;
      case 221: /* expr ::= expr in_op LP select RP */
{
    yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, yymsp[-1].minor.yy47);
    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  }
        break;
      case 222: /* expr ::= expr in_op nm dbnm paren_exprlist */
{
    SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
    if( yymsp[0].minor.yy322 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy322);
    yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, pSelect);
    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  }
        break;
      case 223: /* expr ::= EXISTS LP select RP */
{
    Expr *p;
    p = yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy47);
  }
        break;
      case 224: /* expr ::= CASE case_operand case_exprlist case_else END */
{
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy528, 0);
  if( yymsp[-4].minor.yy528 ){
    yymsp[-4].minor.yy528->x.pList = yymsp[-1].minor.yy528 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[-1].minor.yy528) : yymsp[-2].minor.yy322;
    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
  }else{
    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
  }
}
        break;
      case 225: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
{
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[0].minor.yy528);
}
        break;
      case 226: /* case_exprlist ::= WHEN expr THEN expr */
{
  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, yymsp[0].minor.yy528);
}
        break;



      case 231: /* nexprlist ::= nexprlist COMMA expr */
{yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy528);}
        break;
      case 232: /* nexprlist ::= expr */
{yymsp[0].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy528); /*A-overwrites-Y*/}
        break;
      case 234: /* paren_exprlist ::= LP exprlist RP */
      case 239: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==239);
{yymsp[-2].minor.yy322 = yymsp[-1].minor.yy322;}
        break;
      case 235: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
{
  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy394,
                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy528, SQLITE_SO_ASC, yymsp[-8].minor.yy394, SQLITE_IDXTYPE_APPDEF);
  if( IN_RENAME_OBJECT && pParse->pNewIndex ){
    sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
  }
}
        break;
      case 236: /* uniqueflag ::= UNIQUE */
      case 278: /* raisetype ::= ABORT */ yytestcase(yyruleno==278);
{yymsp[0].minor.yy394 = OE_Abort;}
        break;
      case 237: /* uniqueflag ::= */
{yymsp[1].minor.yy394 = OE_None;}
        break;
      case 240: /* eidlist ::= eidlist COMMA nm collate sortorder */
{
  yymsp[-4].minor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394);
}
        break;
      case 241: /* eidlist ::= nm collate sortorder */
{
  yymsp[-2].minor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394); /*A-overwrites-Y*/
}
        break;
      case 244: /* cmd ::= DROP INDEX ifexists fullname */
{sqlite3DropIndex(pParse, yymsp[0].minor.yy131, yymsp[-1].minor.yy394);}
        break;
      case 245: /* cmd ::= VACUUM vinto */
{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy528);}
        break;
      case 246: /* cmd ::= VACUUM nm vinto */
{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy528);}
        break;
      case 249: /* cmd ::= PRAGMA nm dbnm */
{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
        break;
      case 250: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
        break;
      case 251: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
        break;
      case 252: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
        break;
      case 253: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
        break;
      case 256: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
{
  Token all;
  all.z = yymsp[-3].minor.yy0.z;
  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy33, &all);
}
        break;
      case 257: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
{
  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy394, yymsp[-4].minor.yy180.a, yymsp[-4].minor.yy180.b, yymsp[-2].minor.yy131, yymsp[0].minor.yy528, yymsp[-10].minor.yy394, yymsp[-8].minor.yy394);
  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
}
        break;
      case 258: /* trigger_time ::= BEFORE|AFTER */
{ yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/ }
        break;
      case 259: /* trigger_time ::= INSTEAD OF */
{ yymsp[-1].minor.yy394 = TK_INSTEAD;}
        break;
      case 260: /* trigger_time ::= */
{ yymsp[1].minor.yy394 = TK_BEFORE; }
        break;
      case 261: /* trigger_event ::= DELETE|INSERT */
      case 262: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==262);
{yymsp[0].minor.yy180.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy180.b = 0;}
        break;
      case 263: /* trigger_event ::= UPDATE OF idlist */
{yymsp[-2].minor.yy180.a = TK_UPDATE; yymsp[-2].minor.yy180.b = yymsp[0].minor.yy254;}
        break;
      case 264: /* when_clause ::= */
      case 283: /* key_opt ::= */ yytestcase(yyruleno==283);
{ yymsp[1].minor.yy528 = 0; }
        break;
      case 265: /* when_clause ::= WHEN expr */
      case 284: /* key_opt ::= KEY expr */ yytestcase(yyruleno==284);
{ yymsp[-1].minor.yy528 = yymsp[0].minor.yy528; }
        break;
      case 266: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
{
  assert( yymsp[-2].minor.yy33!=0 );
  yymsp[-2].minor.yy33->pLast->pNext = yymsp[-1].minor.yy33;
  yymsp[-2].minor.yy33->pLast = yymsp[-1].minor.yy33;
}
        break;
      case 267: /* trigger_cmd_list ::= trigger_cmd SEMI */
{
  assert( yymsp[-1].minor.yy33!=0 );
  yymsp[-1].minor.yy33->pLast = yymsp[-1].minor.yy33;
}
        break;
      case 268: /* trnm ::= nm DOT nm */
{
  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  sqlite3ErrorMsg(pParse,
        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
        "statements within triggers");
}
        break;
      case 269: /* tridxby ::= INDEXED BY nm */
{
  sqlite3ErrorMsg(pParse,
        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}
        break;
      case 270: /* tridxby ::= NOT INDEXED */
{
  sqlite3ErrorMsg(pParse,
        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}
        break;
      case 271: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
{yylhsminor.yy33 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy131, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528, yymsp[-7].minor.yy394, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy522);}
  yymsp[-8].minor.yy33 = yylhsminor.yy33;
        break;
      case 272: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
{
   yylhsminor.yy33 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy254,yymsp[-2].minor.yy47,yymsp[-6].minor.yy394,yymsp[-1].minor.yy444,yymsp[-7].minor.yy522,yymsp[0].minor.yy522);/*yylhsminor.yy33-overwrites-yymsp[-6].minor.yy394*/
}
  yymsp[-7].minor.yy33 = yylhsminor.yy33;
        break;
      case 273: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
{yylhsminor.yy33 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy528, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy522);}
  yymsp[-5].minor.yy33 = yylhsminor.yy33;
        break;
      case 274: /* trigger_cmd ::= scanpt select scanpt */
{yylhsminor.yy33 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy47, yymsp[-2].minor.yy522, yymsp[0].minor.yy522); /*yylhsminor.yy33-overwrites-yymsp[-1].minor.yy47*/}
  yymsp[-2].minor.yy33 = yylhsminor.yy33;
        break;
      case 275: /* expr ::= RAISE LP IGNORE RP */
{
  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  if( yymsp[-3].minor.yy528 ){
    yymsp[-3].minor.yy528->affExpr = OE_Ignore;
  }
}
        break;
      case 276: /* expr ::= RAISE LP raisetype COMMA nm RP */
{
  yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  if( yymsp[-5].minor.yy528 ) {
    yymsp[-5].minor.yy528->affExpr = (char)yymsp[-3].minor.yy394;
  }
}
        break;
      case 277: /* raisetype ::= ROLLBACK */
{yymsp[0].minor.yy394 = OE_Rollback;}
        break;
      case 279: /* raisetype ::= FAIL */
{yymsp[0].minor.yy394 = OE_Fail;}
        break;
      case 280: /* cmd ::= DROP TRIGGER ifexists fullname */
{
  sqlite3DropTrigger(pParse,yymsp[0].minor.yy131,yymsp[-1].minor.yy394);
}
        break;
      case 281: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
{
  sqlite3Attach(pParse, yymsp[-3].minor.yy528, yymsp[-1].minor.yy528, yymsp[0].minor.yy528);
}
        break;
      case 282: /* cmd ::= DETACH database_kw_opt expr */
{
  sqlite3Detach(pParse, yymsp[0].minor.yy528);
}
        break;
      case 285: /* cmd ::= REINDEX */
{sqlite3Reindex(pParse, 0, 0);}
        break;
      case 286: /* cmd ::= REINDEX nm dbnm */
{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
        break;
      case 287: /* cmd ::= ANALYZE */
{sqlite3Analyze(pParse, 0, 0);}
        break;
      case 288: /* cmd ::= ANALYZE nm dbnm */
{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
        break;
      case 289: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
{
  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy131,&yymsp[0].minor.yy0);
}
        break;
      case 290: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
{
  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
}
        break;
      case 291: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
{
  sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy131, &yymsp[0].minor.yy0);
}
        break;
      case 292: /* add_column_fullname ::= fullname */
{
  disableLookaside(pParse);
  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy131);
}
        break;
      case 293: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
{
  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy131, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
}
        break;
      case 294: /* cmd ::= create_vtab */
{sqlite3VtabFinishParse(pParse,0);}
        break;
      case 295: /* cmd ::= create_vtab LP vtabarglist RP */
{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
        break;
      case 296: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
{
    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy394);
}
        break;
      case 297: /* vtabarg ::= */
{sqlite3VtabArgInit(pParse);}
        break;
      case 298: /* vtabargtoken ::= ANY */
      case 299: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==299);
      case 300: /* lp ::= LP */ yytestcase(yyruleno==300);
{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
        break;
      case 301: /* with ::= WITH wqlist */
      case 302: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==302);
{ sqlite3WithPush(pParse, yymsp[0].minor.yy521, 1); }
        break;
      case 303: /* wqas ::= AS */
{yymsp[0].minor.yy516 = M10d_Any;}
        break;
      case 304: /* wqas ::= AS MATERIALIZED */
{yymsp[-1].minor.yy516 = M10d_Yes;}
        break;
      case 305: /* wqas ::= AS NOT MATERIALIZED */
{yymsp[-2].minor.yy516 = M10d_No;}
        break;
      case 306: /* wqitem ::= nm eidlist_opt wqas LP select RP */
{
  yymsp[-5].minor.yy385 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy47, yymsp[-3].minor.yy516); /*A-overwrites-X*/
}
        break;
      case 307: /* wqlist ::= wqitem */
{
  yymsp[0].minor.yy521 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy385); /*A-overwrites-X*/
}
        break;
      case 308: /* wqlist ::= wqlist COMMA wqitem */
{
  yymsp[-2].minor.yy521 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy521, yymsp[0].minor.yy385);
}
        break;
      case 309: /* windowdefn_list ::= windowdefn */
{ yylhsminor.yy41 = yymsp[0].minor.yy41; }
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
      case 310: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
{
  assert( yymsp[0].minor.yy41!=0 );
  sqlite3WindowChain(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy41);
  yymsp[0].minor.yy41->pNextWin = yymsp[-2].minor.yy41;
  yylhsminor.yy41 = yymsp[0].minor.yy41;
}
  yymsp[-2].minor.yy41 = yylhsminor.yy41;
        break;
      case 311: /* windowdefn ::= nm AS LP window RP */
{
  if( ALWAYS(yymsp[-1].minor.yy41) ){
    yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
  }
  yylhsminor.yy41 = yymsp[-1].minor.yy41;
}
  yymsp[-4].minor.yy41 = yylhsminor.yy41;
        break;
      case 312: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
{
  yymsp[-4].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, 0);
}
        break;
      case 313: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, &yymsp[-5].minor.yy0);
}
  yymsp[-5].minor.yy41 = yylhsminor.yy41;
        break;
      case 314: /* window ::= ORDER BY sortlist frame_opt */
{
  yymsp[-3].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, 0);
}
        break;
      case 315: /* window ::= nm ORDER BY sortlist frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
}
  yymsp[-4].minor.yy41 = yylhsminor.yy41;
        break;
      case 316: /* window ::= frame_opt */
      case 335: /* filter_over ::= over_clause */ yytestcase(yyruleno==335);
{
  yylhsminor.yy41 = yymsp[0].minor.yy41;
}
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
      case 317: /* window ::= nm frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, 0, &yymsp[-1].minor.yy0);
}
  yymsp[-1].minor.yy41 = yylhsminor.yy41;
        break;
      case 318: /* frame_opt ::= */
{
  yymsp[1].minor.yy41 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
}
        break;
      case 319: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
{
  yylhsminor.yy41 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy394, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy516);
}
  yymsp[-2].minor.yy41 = yylhsminor.yy41;
        break;
      case 320: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
{
  yylhsminor.yy41 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy394, yymsp[-3].minor.yy595.eType, yymsp[-3].minor.yy595.pExpr, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, yymsp[0].minor.yy516);
}
  yymsp[-5].minor.yy41 = yylhsminor.yy41;
        break;
      case 322: /* frame_bound_s ::= frame_bound */
      case 324: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==324);
{yylhsminor.yy595 = yymsp[0].minor.yy595;}
  yymsp[0].minor.yy595 = yylhsminor.yy595;
        break;
      case 323: /* frame_bound_s ::= UNBOUNDED PRECEDING */
      case 325: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==325);
      case 327: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==327);
{yylhsminor.yy595.eType = yymsp[-1].major; yylhsminor.yy595.pExpr = 0;}
  yymsp[-1].minor.yy595 = yylhsminor.yy595;
        break;
      case 326: /* frame_bound ::= expr PRECEDING|FOLLOWING */
{yylhsminor.yy595.eType = yymsp[0].major; yylhsminor.yy595.pExpr = yymsp[-1].minor.yy528;}
  yymsp[-1].minor.yy595 = yylhsminor.yy595;
        break;
      case 328: /* frame_exclude_opt ::= */
{yymsp[1].minor.yy516 = 0;}
        break;
      case 329: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
{yymsp[-1].minor.yy516 = yymsp[0].minor.yy516;}
        break;
      case 330: /* frame_exclude ::= NO OTHERS */
      case 331: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==331);
{yymsp[-1].minor.yy516 = yymsp[-1].major; /*A-overwrites-X*/}
        break;
      case 332: /* frame_exclude ::= GROUP|TIES */
{yymsp[0].minor.yy516 = yymsp[0].major; /*A-overwrites-X*/}
        break;
      case 333: /* window_clause ::= WINDOW windowdefn_list */
{ yymsp[-1].minor.yy41 = yymsp[0].minor.yy41; }
        break;
      case 334: /* filter_over ::= filter_clause over_clause */
{
  if( yymsp[0].minor.yy41 ){
    yymsp[0].minor.yy41->pFilter = yymsp[-1].minor.yy528;
  }else{
    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
  }
  yylhsminor.yy41 = yymsp[0].minor.yy41;
}
  yymsp[-1].minor.yy41 = yylhsminor.yy41;
        break;
      case 336: /* filter_over ::= filter_clause */
{
  yylhsminor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  if( yylhsminor.yy41 ){
    yylhsminor.yy41->eFrmType = TK_FILTER;
    yylhsminor.yy41->pFilter = yymsp[0].minor.yy528;
  }else{
    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy528);
  }
}
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
      case 337: /* over_clause ::= OVER LP window RP */
{
  yymsp[-3].minor.yy41 = yymsp[-1].minor.yy41;
  assert( yymsp[-3].minor.yy41!=0 );
}
        break;
      case 338: /* over_clause ::= OVER nm */
{
  yymsp[-1].minor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  if( yymsp[-1].minor.yy41 ){
    yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
  }
}
        break;
      case 339: /* filter_clause ::= FILTER LP WHERE expr RP */
{ yymsp[-4].minor.yy528 = yymsp[-1].minor.yy528; }
        break;
      default:
      /* (340) input ::= cmdlist */ yytestcase(yyruleno==340);
      /* (341) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==341);
      /* (342) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=342);
      /* (343) ecmd ::= SEMI */ yytestcase(yyruleno==343);
      /* (344) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==344);
      /* (345) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=345);
      /* (346) trans_opt ::= */ yytestcase(yyruleno==346);
      /* (347) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==347);
      /* (348) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==348);
      /* (349) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==349);
      /* (350) savepoint_opt ::= */ yytestcase(yyruleno==350);
      /* (351) cmd ::= create_table create_table_args */ yytestcase(yyruleno==351);
      /* (352) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=352);
      /* (353) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==353);
      /* (354) columnlist ::= columnname carglist */ yytestcase(yyruleno==354);
      /* (355) nm ::= ID|INDEXED|JOIN_KW */ yytestcase(yyruleno==355);
      /* (356) nm ::= STRING */ yytestcase(yyruleno==356);

      /* (357) typetoken ::= typename */ yytestcase(yyruleno==357);
      /* (358) typename ::= ID|STRING */ yytestcase(yyruleno==358);
      /* (359) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=359);
      /* (360) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=360);
      /* (361) carglist ::= carglist ccons */ yytestcase(yyruleno==361);
      /* (362) carglist ::= */ yytestcase(yyruleno==362);
      /* (363) ccons ::= NULL onconf */ yytestcase(yyruleno==363);
      /* (364) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==364);
      /* (365) ccons ::= AS generated */ yytestcase(yyruleno==365);
      /* (366) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==366);
      /* (367) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==367);
      /* (368) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=368);
      /* (369) tconscomma ::= */ yytestcase(yyruleno==369);
      /* (370) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=370);
      /* (371) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=371);
      /* (372) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=372);
      /* (373) oneselect ::= values */ yytestcase(yyruleno==373);
      /* (374) sclp ::= selcollist COMMA */ yytestcase(yyruleno==374);
      /* (375) as ::= ID|STRING */ yytestcase(yyruleno==375);
      /* (376) indexed_opt ::= indexed_by (OPTIMIZED OUT) */ assert(yyruleno!=376);
      /* (377) returning ::= */ yytestcase(yyruleno==377);
      /* (378) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=378);
      /* (379) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==379);
      /* (380) case_operand ::= expr */ yytestcase(yyruleno==380);
      /* (381) exprlist ::= nexprlist */ yytestcase(yyruleno==381);
      /* (382) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=382);
      /* (383) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=383);
      /* (384) nmnum ::= ON */ yytestcase(yyruleno==384);
      /* (385) nmnum ::= DELETE */ yytestcase(yyruleno==385);
      /* (386) nmnum ::= DEFAULT */ yytestcase(yyruleno==386);
      /* (387) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==387);
      /* (388) foreach_clause ::= */ yytestcase(yyruleno==388);
      /* (389) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==389);
      /* (390) trnm ::= nm */ yytestcase(yyruleno==390);
      /* (391) tridxby ::= */ yytestcase(yyruleno==391);
      /* (392) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==392);
      /* (393) database_kw_opt ::= */ yytestcase(yyruleno==393);
      /* (394) kwcolumn_opt ::= */ yytestcase(yyruleno==394);
      /* (395) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==395);
      /* (396) vtabarglist ::= vtabarg */ yytestcase(yyruleno==396);
      /* (397) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==397);
      /* (398) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==398);
      /* (399) anylist ::= */ yytestcase(yyruleno==399);
      /* (400) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==400);
      /* (401) anylist ::= anylist ANY */ yytestcase(yyruleno==401);
      /* (402) with ::= */ yytestcase(yyruleno==402);
        break;
/********** End reduce actions ************************************************/
  };
  assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
  yygoto = yyRuleInfoLhs[yyruleno];
  yysize = yyRuleInfoNRhs[yyruleno];
  yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
172451
172452
172453
172454
172455
172456
172457
172458
172459
172460
172461
172462
172463
172464
172465
172466
172467
172468
172469
172470
172471
172472
172473
172474
172475
172476
172477
172478
172479
172480
172481
172482
172483
172484
172485
172486
172487
172488
172489
172490
172491
172492
172493
172494
172495
172496
172497
172498
172499
172500
172501
172502
172503
172504
172505
172506
172507
172508
172509
172510
172511
    50, 124,   0, 100,   0,  18, 121, 144,  56, 130, 139,  88,  83,
    37,  30, 126,   0,   0, 108,  51, 131, 128,   0,  34,   0,   0,
   132,   0,  98,  38,  39,   0,  20,  45, 117,  93,
};
/* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
** then the i-th keyword has no more hash collisions.  Otherwise,
** the next keyword with the same hash is aKWHash[i]-1. */
static const unsigned char aKWNext[147] = {
     0,   0,   0,   0,   4,   0,  43,   0,   0, 106, 114,   0,   0,
     0,   2,   0,   0, 143,   0,   0,   0,  13,   0,   0,   0,   0,
   141,   0,   0, 119,  52,   0,   0, 137,  12,   0,   0,  62,   0,
   138,   0, 133,   0,   0,  36,   0,   0,  28,  77,   0,   0,   0,
     0,  59,   0,  47,   0,   0,   0,   0,   0,   0,   0,   0,   0,
     0,  69,   0,   0,   0,   0,   0, 146,   3,   0,  58,   0,   1,
    75,   0,   0,   0,  31,   0,   0,   0,   0,   0, 127,   0, 104,
     0,  64,  66,  63,   0,   0,   0,   0,   0,  46,   0,  16,   8,
     0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  81, 101,   0,
   112,  21,   7,  67,   0,  79,  96, 118,   0,   0,  68,   0,   0,
    99,  44,   0,  55,   0,  76,   0,  95,  32,  33,  57,  25,   0,
   102,   0,   0,  87,
};
/* aKWLen[i] is the length (in bytes) of the i-th keyword */
static const unsigned char aKWLen[147] = {
     7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
     7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   7,
     6,   9,   4,   2,   6,   5,   9,   9,   4,   7,   3,   2,   4,
     4,   6,  11,   6,   2,   7,   5,   5,   9,   6,  10,   4,   6,
     2,   3,   7,   5,   9,   6,   6,   4,   5,   5,  10,   6,   5,
     7,   4,   5,   7,   6,   7,   7,   6,   5,   7,   3,   7,   4,
     7,   6,  12,   9,   4,   6,   5,   4,   7,   6,  12,   8,   8,
     2,   6,   6,   7,   6,   4,   5,   9,   5,   5,   6,   3,   4,
     9,  13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   9,
     4,   4,   6,   7,   5,   9,   4,   4,   5,   2,   5,   8,   6,
     4,   9,   5,   8,   4,   3,   9,   5,   5,   6,   4,   6,   2,
     2,   9,   3,   7,
};
/* aKWOffset[i] is the index into zKWText[] of the start of
** the text for the i-th keyword. */
static const unsigned short int aKWOffset[147] = {
     0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
    36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
    86,  90,  90,  94,  99, 101, 105, 111, 119, 123, 123, 123, 126,
   129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184,
   184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239,
   244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295,
   299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 359, 370, 377,
   378, 385, 391, 397, 402, 408, 412, 415, 424, 429, 433, 439, 441,
   444, 453, 455, 457, 466, 470, 476, 482, 490, 495, 495, 495, 511,
   520, 523, 527, 532, 539, 544, 553, 557, 560, 565, 567, 571, 579,
   585, 588, 597, 602, 610, 610, 614, 623, 628, 633, 639, 642, 645,
   648, 650, 655, 659,
};
/* aKWCode[i] is the parser symbol code for the i-th keyword */
static const unsigned char aKWCode[147] = {
  TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
  TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
  TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
  TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
  TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
  TK_EXCLUDE,    TK_DELETE,     TK_TEMP,       TK_TEMP,       TK_OR,
  TK_ISNULL,     TK_NULLS,      TK_SAVEPOINT,  TK_INTERSECT,  TK_TIES,







|














|















|














|







173384
173385
173386
173387
173388
173389
173390
173391
173392
173393
173394
173395
173396
173397
173398
173399
173400
173401
173402
173403
173404
173405
173406
173407
173408
173409
173410
173411
173412
173413
173414
173415
173416
173417
173418
173419
173420
173421
173422
173423
173424
173425
173426
173427
173428
173429
173430
173431
173432
173433
173434
173435
173436
173437
173438
173439
173440
173441
173442
173443
173444
    50, 124,   0, 100,   0,  18, 121, 144,  56, 130, 139,  88,  83,
    37,  30, 126,   0,   0, 108,  51, 131, 128,   0,  34,   0,   0,
   132,   0,  98,  38,  39,   0,  20,  45, 117,  93,
};
/* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
** then the i-th keyword has no more hash collisions.  Otherwise,
** the next keyword with the same hash is aKWHash[i]-1. */
static const unsigned char aKWNext[148] = {0,
     0,   0,   0,   0,   4,   0,  43,   0,   0, 106, 114,   0,   0,
     0,   2,   0,   0, 143,   0,   0,   0,  13,   0,   0,   0,   0,
   141,   0,   0, 119,  52,   0,   0, 137,  12,   0,   0,  62,   0,
   138,   0, 133,   0,   0,  36,   0,   0,  28,  77,   0,   0,   0,
     0,  59,   0,  47,   0,   0,   0,   0,   0,   0,   0,   0,   0,
     0,  69,   0,   0,   0,   0,   0, 146,   3,   0,  58,   0,   1,
    75,   0,   0,   0,  31,   0,   0,   0,   0,   0, 127,   0, 104,
     0,  64,  66,  63,   0,   0,   0,   0,   0,  46,   0,  16,   8,
     0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  81, 101,   0,
   112,  21,   7,  67,   0,  79,  96, 118,   0,   0,  68,   0,   0,
    99,  44,   0,  55,   0,  76,   0,  95,  32,  33,  57,  25,   0,
   102,   0,   0,  87,
};
/* aKWLen[i] is the length (in bytes) of the i-th keyword */
static const unsigned char aKWLen[148] = {0,
     7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
     7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   7,
     6,   9,   4,   2,   6,   5,   9,   9,   4,   7,   3,   2,   4,
     4,   6,  11,   6,   2,   7,   5,   5,   9,   6,  10,   4,   6,
     2,   3,   7,   5,   9,   6,   6,   4,   5,   5,  10,   6,   5,
     7,   4,   5,   7,   6,   7,   7,   6,   5,   7,   3,   7,   4,
     7,   6,  12,   9,   4,   6,   5,   4,   7,   6,  12,   8,   8,
     2,   6,   6,   7,   6,   4,   5,   9,   5,   5,   6,   3,   4,
     9,  13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   9,
     4,   4,   6,   7,   5,   9,   4,   4,   5,   2,   5,   8,   6,
     4,   9,   5,   8,   4,   3,   9,   5,   5,   6,   4,   6,   2,
     2,   9,   3,   7,
};
/* aKWOffset[i] is the index into zKWText[] of the start of
** the text for the i-th keyword. */
static const unsigned short int aKWOffset[148] = {0,
     0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
    36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
    86,  90,  90,  94,  99, 101, 105, 111, 119, 123, 123, 123, 126,
   129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184,
   184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239,
   244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295,
   299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 359, 370, 377,
   378, 385, 391, 397, 402, 408, 412, 415, 424, 429, 433, 439, 441,
   444, 453, 455, 457, 466, 470, 476, 482, 490, 495, 495, 495, 511,
   520, 523, 527, 532, 539, 544, 553, 557, 560, 565, 567, 571, 579,
   585, 588, 597, 602, 610, 610, 614, 623, 628, 633, 639, 642, 645,
   648, 650, 655, 659,
};
/* aKWCode[i] is the parser symbol code for the i-th keyword */
static const unsigned char aKWCode[148] = {0,
  TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
  TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
  TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
  TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
  TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
  TK_EXCLUDE,    TK_DELETE,     TK_TEMP,       TK_TEMP,       TK_OR,
  TK_ISNULL,     TK_NULLS,      TK_SAVEPOINT,  TK_INTERSECT,  TK_TIES,
172666
172667
172668
172669
172670
172671
172672
172673
172674
172675
172676
172677
172678
172679
172680
172681
172682
172683
172684
172685
172686
172687
172688
172689
172690
172691
172692
172693
172694
172695
172696
172697
172698
172699
172700
172701
172702
172703
172704
172705
172706
172707
172708
172709
172710
172711
172712
172713
172714
172715
172716
172717
172718
172719
172720
172721
172722
172723
172724
172725
172726
172727
172728
172729
172730
172731
172732
172733
172734
172735
172736
172737
172738
172739
172740
172741
172742
172743
172744
172745
172746
172747
172748
172749
172750
172751
172752
172753
172754
172755
172756
172757
172758
172759
172760
172761
172762
172763
172764
172765
172766
172767
172768
172769
172770
172771
172772
172773
172774
172775
172776
172777
172778
172779
172780
172781
172782
172783
172784
172785
172786
172787
172788
172789
172790
172791
172792
172793
172794
172795
172796
172797
172798
172799
172800
172801
172802
172803
172804
172805
172806
172807
172808
172809
172810
172811
172812
172813
172814
172815
172816
172817
172818
172819
172820
172821
172822
172823
172824
172825
172826
172827
172828
172829
172830
172831
172832
172833
172834
172835

172836
172837
172838
172839
172840
172841
172842
172843
172844
172845
172846
172847
172848
172849

172850
172851
172852
172853
172854
172855
172856
** parser symbol code for that keyword into *pType.  Always
** return the integer n (the length of the token). */
static int keywordCode(const char *z, int n, int *pType){
  int i, j;
  const char *zKW;
  if( n>=2 ){
    i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n*1) % 127;
    for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
      if( aKWLen[i]!=n ) continue;
      zKW = &zKWText[aKWOffset[i]];
#ifdef SQLITE_ASCII
      if( (z[0]&~0x20)!=zKW[0] ) continue;
      if( (z[1]&~0x20)!=zKW[1] ) continue;
      j = 2;
      while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
#endif
#ifdef SQLITE_EBCDIC
      if( toupper(z[0])!=zKW[0] ) continue;
      if( toupper(z[1])!=zKW[1] ) continue;
      j = 2;
      while( j<n && toupper(z[j])==zKW[j] ){ j++; }
#endif
      if( j<n ) continue;
      testcase( i==0 ); /* REINDEX */
      testcase( i==1 ); /* INDEXED */
      testcase( i==2 ); /* INDEX */
      testcase( i==3 ); /* DESC */
      testcase( i==4 ); /* ESCAPE */
      testcase( i==5 ); /* EACH */
      testcase( i==6 ); /* CHECK */
      testcase( i==7 ); /* KEY */
      testcase( i==8 ); /* BEFORE */
      testcase( i==9 ); /* FOREIGN */
      testcase( i==10 ); /* FOR */
      testcase( i==11 ); /* IGNORE */
      testcase( i==12 ); /* REGEXP */
      testcase( i==13 ); /* EXPLAIN */
      testcase( i==14 ); /* INSTEAD */
      testcase( i==15 ); /* ADD */
      testcase( i==16 ); /* DATABASE */
      testcase( i==17 ); /* AS */
      testcase( i==18 ); /* SELECT */
      testcase( i==19 ); /* TABLE */
      testcase( i==20 ); /* LEFT */
      testcase( i==21 ); /* THEN */
      testcase( i==22 ); /* END */
      testcase( i==23 ); /* DEFERRABLE */
      testcase( i==24 ); /* ELSE */
      testcase( i==25 ); /* EXCLUDE */
      testcase( i==26 ); /* DELETE */
      testcase( i==27 ); /* TEMPORARY */
      testcase( i==28 ); /* TEMP */
      testcase( i==29 ); /* OR */
      testcase( i==30 ); /* ISNULL */
      testcase( i==31 ); /* NULLS */
      testcase( i==32 ); /* SAVEPOINT */
      testcase( i==33 ); /* INTERSECT */
      testcase( i==34 ); /* TIES */
      testcase( i==35 ); /* NOTNULL */
      testcase( i==36 ); /* NOT */
      testcase( i==37 ); /* NO */
      testcase( i==38 ); /* NULL */
      testcase( i==39 ); /* LIKE */
      testcase( i==40 ); /* EXCEPT */
      testcase( i==41 ); /* TRANSACTION */
      testcase( i==42 ); /* ACTION */
      testcase( i==43 ); /* ON */
      testcase( i==44 ); /* NATURAL */
      testcase( i==45 ); /* ALTER */
      testcase( i==46 ); /* RAISE */
      testcase( i==47 ); /* EXCLUSIVE */
      testcase( i==48 ); /* EXISTS */
      testcase( i==49 ); /* CONSTRAINT */
      testcase( i==50 ); /* INTO */
      testcase( i==51 ); /* OFFSET */
      testcase( i==52 ); /* OF */
      testcase( i==53 ); /* SET */
      testcase( i==54 ); /* TRIGGER */
      testcase( i==55 ); /* RANGE */
      testcase( i==56 ); /* GENERATED */
      testcase( i==57 ); /* DETACH */
      testcase( i==58 ); /* HAVING */
      testcase( i==59 ); /* GLOB */
      testcase( i==60 ); /* BEGIN */
      testcase( i==61 ); /* INNER */
      testcase( i==62 ); /* REFERENCES */
      testcase( i==63 ); /* UNIQUE */
      testcase( i==64 ); /* QUERY */
      testcase( i==65 ); /* WITHOUT */
      testcase( i==66 ); /* WITH */
      testcase( i==67 ); /* OUTER */
      testcase( i==68 ); /* RELEASE */
      testcase( i==69 ); /* ATTACH */
      testcase( i==70 ); /* BETWEEN */
      testcase( i==71 ); /* NOTHING */
      testcase( i==72 ); /* GROUPS */
      testcase( i==73 ); /* GROUP */
      testcase( i==74 ); /* CASCADE */
      testcase( i==75 ); /* ASC */
      testcase( i==76 ); /* DEFAULT */
      testcase( i==77 ); /* CASE */
      testcase( i==78 ); /* COLLATE */
      testcase( i==79 ); /* CREATE */
      testcase( i==80 ); /* CURRENT_DATE */
      testcase( i==81 ); /* IMMEDIATE */
      testcase( i==82 ); /* JOIN */
      testcase( i==83 ); /* INSERT */
      testcase( i==84 ); /* MATCH */
      testcase( i==85 ); /* PLAN */
      testcase( i==86 ); /* ANALYZE */
      testcase( i==87 ); /* PRAGMA */
      testcase( i==88 ); /* MATERIALIZED */
      testcase( i==89 ); /* DEFERRED */
      testcase( i==90 ); /* DISTINCT */
      testcase( i==91 ); /* IS */
      testcase( i==92 ); /* UPDATE */
      testcase( i==93 ); /* VALUES */
      testcase( i==94 ); /* VIRTUAL */
      testcase( i==95 ); /* ALWAYS */
      testcase( i==96 ); /* WHEN */
      testcase( i==97 ); /* WHERE */
      testcase( i==98 ); /* RECURSIVE */
      testcase( i==99 ); /* ABORT */
      testcase( i==100 ); /* AFTER */
      testcase( i==101 ); /* RENAME */
      testcase( i==102 ); /* AND */
      testcase( i==103 ); /* DROP */
      testcase( i==104 ); /* PARTITION */
      testcase( i==105 ); /* AUTOINCREMENT */
      testcase( i==106 ); /* TO */
      testcase( i==107 ); /* IN */
      testcase( i==108 ); /* CAST */
      testcase( i==109 ); /* COLUMN */
      testcase( i==110 ); /* COMMIT */
      testcase( i==111 ); /* CONFLICT */
      testcase( i==112 ); /* CROSS */
      testcase( i==113 ); /* CURRENT_TIMESTAMP */
      testcase( i==114 ); /* CURRENT_TIME */
      testcase( i==115 ); /* CURRENT */
      testcase( i==116 ); /* PRECEDING */
      testcase( i==117 ); /* FAIL */
      testcase( i==118 ); /* LAST */
      testcase( i==119 ); /* FILTER */
      testcase( i==120 ); /* REPLACE */
      testcase( i==121 ); /* FIRST */
      testcase( i==122 ); /* FOLLOWING */
      testcase( i==123 ); /* FROM */
      testcase( i==124 ); /* FULL */
      testcase( i==125 ); /* LIMIT */
      testcase( i==126 ); /* IF */
      testcase( i==127 ); /* ORDER */
      testcase( i==128 ); /* RESTRICT */
      testcase( i==129 ); /* OTHERS */
      testcase( i==130 ); /* OVER */
      testcase( i==131 ); /* RETURNING */
      testcase( i==132 ); /* RIGHT */
      testcase( i==133 ); /* ROLLBACK */
      testcase( i==134 ); /* ROWS */
      testcase( i==135 ); /* ROW */
      testcase( i==136 ); /* UNBOUNDED */
      testcase( i==137 ); /* UNION */
      testcase( i==138 ); /* USING */
      testcase( i==139 ); /* VACUUM */
      testcase( i==140 ); /* VIEW */
      testcase( i==141 ); /* WINDOW */
      testcase( i==142 ); /* DO */
      testcase( i==143 ); /* BY */
      testcase( i==144 ); /* INITIALLY */
      testcase( i==145 ); /* ALL */
      testcase( i==146 ); /* PRIMARY */

      *pType = aKWCode[i];
      break;
    }
  }
  return n;
}
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  int id = TK_ID;
  keywordCode((char*)z, n, &id);
  return id;
}
#define SQLITE_N_KEYWORD 147
SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
  if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;

  *pzName = zKWText + aKWOffset[i];
  *pnName = aKWLen[i];
  return SQLITE_OK;
}
SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
  return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);







|















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














>







173599
173600
173601
173602
173603
173604
173605
173606
173607
173608
173609
173610
173611
173612
173613
173614
173615
173616
173617
173618
173619
173620
173621

173622
173623
173624
173625
173626
173627
173628
173629
173630
173631
173632
173633
173634
173635
173636
173637
173638
173639
173640
173641
173642
173643
173644
173645
173646
173647
173648
173649
173650
173651
173652
173653
173654
173655
173656
173657
173658
173659
173660
173661
173662
173663
173664
173665
173666
173667
173668
173669
173670
173671
173672
173673
173674
173675
173676
173677
173678
173679
173680
173681
173682
173683
173684
173685
173686
173687
173688
173689
173690
173691
173692
173693
173694
173695
173696
173697
173698
173699
173700
173701
173702
173703
173704
173705
173706
173707
173708
173709
173710
173711
173712
173713
173714
173715
173716
173717
173718
173719
173720
173721
173722
173723
173724
173725
173726
173727
173728
173729
173730
173731
173732
173733
173734
173735
173736
173737
173738
173739
173740
173741
173742
173743
173744
173745
173746
173747
173748
173749
173750
173751
173752
173753
173754
173755
173756
173757
173758
173759
173760
173761
173762
173763
173764
173765
173766
173767
173768
173769
173770
173771
173772
173773
173774
173775
173776
173777
173778
173779
173780
173781
173782
173783
173784
173785
173786
173787
173788
173789
173790
** parser symbol code for that keyword into *pType.  Always
** return the integer n (the length of the token). */
static int keywordCode(const char *z, int n, int *pType){
  int i, j;
  const char *zKW;
  if( n>=2 ){
    i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n*1) % 127;
    for(i=(int)aKWHash[i]; i>0; i=aKWNext[i]){
      if( aKWLen[i]!=n ) continue;
      zKW = &zKWText[aKWOffset[i]];
#ifdef SQLITE_ASCII
      if( (z[0]&~0x20)!=zKW[0] ) continue;
      if( (z[1]&~0x20)!=zKW[1] ) continue;
      j = 2;
      while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
#endif
#ifdef SQLITE_EBCDIC
      if( toupper(z[0])!=zKW[0] ) continue;
      if( toupper(z[1])!=zKW[1] ) continue;
      j = 2;
      while( j<n && toupper(z[j])==zKW[j] ){ j++; }
#endif
      if( j<n ) continue;

      testcase( i==1 ); /* REINDEX */
      testcase( i==2 ); /* INDEXED */
      testcase( i==3 ); /* INDEX */
      testcase( i==4 ); /* DESC */
      testcase( i==5 ); /* ESCAPE */
      testcase( i==6 ); /* EACH */
      testcase( i==7 ); /* CHECK */
      testcase( i==8 ); /* KEY */
      testcase( i==9 ); /* BEFORE */
      testcase( i==10 ); /* FOREIGN */
      testcase( i==11 ); /* FOR */
      testcase( i==12 ); /* IGNORE */
      testcase( i==13 ); /* REGEXP */
      testcase( i==14 ); /* EXPLAIN */
      testcase( i==15 ); /* INSTEAD */
      testcase( i==16 ); /* ADD */
      testcase( i==17 ); /* DATABASE */
      testcase( i==18 ); /* AS */
      testcase( i==19 ); /* SELECT */
      testcase( i==20 ); /* TABLE */
      testcase( i==21 ); /* LEFT */
      testcase( i==22 ); /* THEN */
      testcase( i==23 ); /* END */
      testcase( i==24 ); /* DEFERRABLE */
      testcase( i==25 ); /* ELSE */
      testcase( i==26 ); /* EXCLUDE */
      testcase( i==27 ); /* DELETE */
      testcase( i==28 ); /* TEMPORARY */
      testcase( i==29 ); /* TEMP */
      testcase( i==30 ); /* OR */
      testcase( i==31 ); /* ISNULL */
      testcase( i==32 ); /* NULLS */
      testcase( i==33 ); /* SAVEPOINT */
      testcase( i==34 ); /* INTERSECT */
      testcase( i==35 ); /* TIES */
      testcase( i==36 ); /* NOTNULL */
      testcase( i==37 ); /* NOT */
      testcase( i==38 ); /* NO */
      testcase( i==39 ); /* NULL */
      testcase( i==40 ); /* LIKE */
      testcase( i==41 ); /* EXCEPT */
      testcase( i==42 ); /* TRANSACTION */
      testcase( i==43 ); /* ACTION */
      testcase( i==44 ); /* ON */
      testcase( i==45 ); /* NATURAL */
      testcase( i==46 ); /* ALTER */
      testcase( i==47 ); /* RAISE */
      testcase( i==48 ); /* EXCLUSIVE */
      testcase( i==49 ); /* EXISTS */
      testcase( i==50 ); /* CONSTRAINT */
      testcase( i==51 ); /* INTO */
      testcase( i==52 ); /* OFFSET */
      testcase( i==53 ); /* OF */
      testcase( i==54 ); /* SET */
      testcase( i==55 ); /* TRIGGER */
      testcase( i==56 ); /* RANGE */
      testcase( i==57 ); /* GENERATED */
      testcase( i==58 ); /* DETACH */
      testcase( i==59 ); /* HAVING */
      testcase( i==60 ); /* GLOB */
      testcase( i==61 ); /* BEGIN */
      testcase( i==62 ); /* INNER */
      testcase( i==63 ); /* REFERENCES */
      testcase( i==64 ); /* UNIQUE */
      testcase( i==65 ); /* QUERY */
      testcase( i==66 ); /* WITHOUT */
      testcase( i==67 ); /* WITH */
      testcase( i==68 ); /* OUTER */
      testcase( i==69 ); /* RELEASE */
      testcase( i==70 ); /* ATTACH */
      testcase( i==71 ); /* BETWEEN */
      testcase( i==72 ); /* NOTHING */
      testcase( i==73 ); /* GROUPS */
      testcase( i==74 ); /* GROUP */
      testcase( i==75 ); /* CASCADE */
      testcase( i==76 ); /* ASC */
      testcase( i==77 ); /* DEFAULT */
      testcase( i==78 ); /* CASE */
      testcase( i==79 ); /* COLLATE */
      testcase( i==80 ); /* CREATE */
      testcase( i==81 ); /* CURRENT_DATE */
      testcase( i==82 ); /* IMMEDIATE */
      testcase( i==83 ); /* JOIN */
      testcase( i==84 ); /* INSERT */
      testcase( i==85 ); /* MATCH */
      testcase( i==86 ); /* PLAN */
      testcase( i==87 ); /* ANALYZE */
      testcase( i==88 ); /* PRAGMA */
      testcase( i==89 ); /* MATERIALIZED */
      testcase( i==90 ); /* DEFERRED */
      testcase( i==91 ); /* DISTINCT */
      testcase( i==92 ); /* IS */
      testcase( i==93 ); /* UPDATE */
      testcase( i==94 ); /* VALUES */
      testcase( i==95 ); /* VIRTUAL */
      testcase( i==96 ); /* ALWAYS */
      testcase( i==97 ); /* WHEN */
      testcase( i==98 ); /* WHERE */
      testcase( i==99 ); /* RECURSIVE */
      testcase( i==100 ); /* ABORT */
      testcase( i==101 ); /* AFTER */
      testcase( i==102 ); /* RENAME */
      testcase( i==103 ); /* AND */
      testcase( i==104 ); /* DROP */
      testcase( i==105 ); /* PARTITION */
      testcase( i==106 ); /* AUTOINCREMENT */
      testcase( i==107 ); /* TO */
      testcase( i==108 ); /* IN */
      testcase( i==109 ); /* CAST */
      testcase( i==110 ); /* COLUMN */
      testcase( i==111 ); /* COMMIT */
      testcase( i==112 ); /* CONFLICT */
      testcase( i==113 ); /* CROSS */
      testcase( i==114 ); /* CURRENT_TIMESTAMP */
      testcase( i==115 ); /* CURRENT_TIME */
      testcase( i==116 ); /* CURRENT */
      testcase( i==117 ); /* PRECEDING */
      testcase( i==118 ); /* FAIL */
      testcase( i==119 ); /* LAST */
      testcase( i==120 ); /* FILTER */
      testcase( i==121 ); /* REPLACE */
      testcase( i==122 ); /* FIRST */
      testcase( i==123 ); /* FOLLOWING */
      testcase( i==124 ); /* FROM */
      testcase( i==125 ); /* FULL */
      testcase( i==126 ); /* LIMIT */
      testcase( i==127 ); /* IF */
      testcase( i==128 ); /* ORDER */
      testcase( i==129 ); /* RESTRICT */
      testcase( i==130 ); /* OTHERS */
      testcase( i==131 ); /* OVER */
      testcase( i==132 ); /* RETURNING */
      testcase( i==133 ); /* RIGHT */
      testcase( i==134 ); /* ROLLBACK */
      testcase( i==135 ); /* ROWS */
      testcase( i==136 ); /* ROW */
      testcase( i==137 ); /* UNBOUNDED */
      testcase( i==138 ); /* UNION */
      testcase( i==139 ); /* USING */
      testcase( i==140 ); /* VACUUM */
      testcase( i==141 ); /* VIEW */
      testcase( i==142 ); /* WINDOW */
      testcase( i==143 ); /* DO */
      testcase( i==144 ); /* BY */
      testcase( i==145 ); /* INITIALLY */
      testcase( i==146 ); /* ALL */
      testcase( i==147 ); /* PRIMARY */
      *pType = aKWCode[i];
      break;
    }
  }
  return n;
}
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  int id = TK_ID;
  keywordCode((char*)z, n, &id);
  return id;
}
#define SQLITE_N_KEYWORD 147
SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
  if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
  i++;
  *pzName = zKWText + aKWOffset[i];
  *pnName = aKWLen[i];
  return SQLITE_OK;
}
SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
  return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
174381
174382
174383
174384
174385
174386
174387
174388
174389


174390










174391
174392
174393
174394
174395
174396
174397
** threadsafe.  Failure to heed these warnings can lead to unpredictable
** behavior.
*/
SQLITE_API int sqlite3_config(int op, ...){
  va_list ap;
  int rc = SQLITE_OK;

  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  ** the SQLite library is in use. */


  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;











  va_start(ap, op);
  switch( op ){

    /* Mutex configuration options are only available in a threadsafe
    ** compile.
    */







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







175315
175316
175317
175318
175319
175320
175321
175322
175323
175324
175325
175326
175327
175328
175329
175330
175331
175332
175333
175334
175335
175336
175337
175338
175339
175340
175341
175342
175343
** threadsafe.  Failure to heed these warnings can lead to unpredictable
** behavior.
*/
SQLITE_API int sqlite3_config(int op, ...){
  va_list ap;
  int rc = SQLITE_OK;

  /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
  ** the SQLite library is in use.  Except, a few selected opcodes
  ** are allowed.
  */
  if( sqlite3GlobalConfig.isInit ){
    static const u64 mAnytimeConfigOption = 0
       | MASKBIT64( SQLITE_CONFIG_LOG )
       | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ )
    ;
    if( op<0 || op>63 || (MASKBIT64(op) & mAnytimeConfigOption)==0 ){
      return SQLITE_MISUSE_BKPT;
    }
    testcase( op==SQLITE_CONFIG_LOG );
    testcase( op==SQLITE_CONFIG_PCACHE_HDRSZ );
  }

  va_start(ap, op);
  switch( op ){

    /* Mutex configuration options are only available in a threadsafe
    ** compile.
    */
174452
174453
174454
174455
174456
174457
174458

174459
174460
174461
174462
174463
174464
174465
      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
      ** filled with the currently defined memory allocation routines. */
      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
      break;
    }
    case SQLITE_CONFIG_MEMSTATUS: {

      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
      ** single argument of type int, interpreted as a boolean, which enables
      ** or disables the collection of memory allocation statistics. */
      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
      break;
    }
    case SQLITE_CONFIG_SMALL_MALLOC: {







>







175398
175399
175400
175401
175402
175403
175404
175405
175406
175407
175408
175409
175410
175411
175412
      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
      ** filled with the currently defined memory allocation routines. */
      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
      break;
    }
    case SQLITE_CONFIG_MEMSTATUS: {
      assert( !sqlite3GlobalConfig.isInit );  /* Cannot change at runtime */
      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
      ** single argument of type int, interpreted as a boolean, which enables
      ** or disables the collection of memory allocation statistics. */
      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
      break;
    }
    case SQLITE_CONFIG_SMALL_MALLOC: {
174575
174576
174577
174578
174579
174580
174581
174582
174583


174584
174585
174586
174587
174588
174589
174590
174591
174592
174593
174594
174595
174596
174597

174598
174599
174600
174601
174602
174603
174604
    */
    case SQLITE_CONFIG_LOG: {
      /* MSVC is picky about pulling func ptrs from va lists.
      ** http://support.microsoft.com/kb/47961
      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
      */
      typedef void(*LOGFUNC_t)(void*,int,const char*);
      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);


      break;
    }

    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
    ** can be changed at start-time using the
    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
    */
    case SQLITE_CONFIG_URI: {
      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
      ** argument of type int. If non-zero, then URI handling is globally
      ** enabled. If the parameter is zero, then URI handling is globally
      ** disabled. */
      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);

      break;
    }

    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
      ** option takes a single integer argument which is interpreted as a
      ** boolean in order to enable or disable the use of covering indices for







|
|
>
>













|
>







175522
175523
175524
175525
175526
175527
175528
175529
175530
175531
175532
175533
175534
175535
175536
175537
175538
175539
175540
175541
175542
175543
175544
175545
175546
175547
175548
175549
175550
175551
175552
175553
175554
    */
    case SQLITE_CONFIG_LOG: {
      /* MSVC is picky about pulling func ptrs from va lists.
      ** http://support.microsoft.com/kb/47961
      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
      */
      typedef void(*LOGFUNC_t)(void*,int,const char*);
      LOGFUNC_t xLog = va_arg(ap, LOGFUNC_t);
      void *pLogArg = va_arg(ap, void*);
      AtomicStore(&sqlite3GlobalConfig.xLog, xLog);
      AtomicStore(&sqlite3GlobalConfig.pLogArg, pLogArg);
      break;
    }

    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
    ** can be changed at start-time using the
    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
    */
    case SQLITE_CONFIG_URI: {
      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
      ** argument of type int. If non-zero, then URI handling is globally
      ** enabled. If the parameter is zero, then URI handling is globally
      ** disabled. */
      int bOpenUri = va_arg(ap, int);
      AtomicStore(&sqlite3GlobalConfig.bOpenUri, bOpenUri);
      break;
    }

    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
      ** option takes a single integer argument which is interpreted as a
      ** boolean in order to enable or disable the use of covering indices for
174905
174906
174907
174908
174909
174910
174911


174912
174913
174914
174915
174916
174917
174918
        { SQLITE_DBCONFIG_WRITABLE_SCHEMA,       SQLITE_WriteSchema|
                                                 SQLITE_NoSchemaError  },
        { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },
        { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },
        { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },
        { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },
        { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },


      };
      unsigned int i;
      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
      for(i=0; i<ArraySize(aFlagOp); i++){
        if( aFlagOp[i].op==op ){
          int onoff = va_arg(ap, int);
          int *pRes = va_arg(ap, int*);







>
>







175855
175856
175857
175858
175859
175860
175861
175862
175863
175864
175865
175866
175867
175868
175869
175870
        { SQLITE_DBCONFIG_WRITABLE_SCHEMA,       SQLITE_WriteSchema|
                                                 SQLITE_NoSchemaError  },
        { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },
        { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },
        { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },
        { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },
        { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },
        { SQLITE_DBCONFIG_STMT_SCANSTATUS,       SQLITE_StmtScanStatus },
        { SQLITE_DBCONFIG_REVERSE_SCANORDER,     SQLITE_ReverseOrder   },
      };
      unsigned int i;
      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
      for(i=0; i<ArraySize(aFlagOp); i++){
        if( aFlagOp[i].op==op ){
          int onoff = va_arg(ap, int);
          int *pRes = va_arg(ap, int*);
176890
176891
176892
176893
176894
176895
176896
176897
176898
176899
176900
176901
176902
176903
176904
176905
176906
  const char *zVfs = zDefaultVfs;
  char *zFile;
  char c;
  int nUri = sqlite3Strlen30(zUri);

  assert( *pzErrMsg==0 );

  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
   && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  ){
    char *zOpt;
    int eState;                   /* Parser state when parsing URI */
    int iIn;                      /* Input character index */
    int iOut = 0;                 /* Output character index */
    u64 nByte = nUri+8;           /* Bytes of space to allocate */








|
|
|







177842
177843
177844
177845
177846
177847
177848
177849
177850
177851
177852
177853
177854
177855
177856
177857
177858
  const char *zVfs = zDefaultVfs;
  char *zFile;
  char c;
  int nUri = sqlite3Strlen30(zUri);

  assert( *pzErrMsg==0 );

  if( ((flags & SQLITE_OPEN_URI)                     /* IMP: R-48725-32206 */
       || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
   && nUri>=5 && memcmp(zUri, "file:", 5)==0         /* IMP: R-57884-37496 */
  ){
    char *zOpt;
    int eState;                   /* Parser state when parsing URI */
    int iIn;                      /* Input character index */
    int iOut = 0;                 /* Output character index */
    u64 nByte = nUri+8;           /* Bytes of space to allocate */

177298
177299
177300
177301
177302
177303
177304



177305
177306
177307
177308
177309
177310
177311
                 | SQLITE_EnableQPSG
#endif
#if defined(SQLITE_DEFAULT_DEFENSIVE)
                 | SQLITE_Defensive
#endif
#if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
                 | SQLITE_LegacyAlter



#endif
      ;
  sqlite3HashInit(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3HashInit(&db->aModule);
#endif








>
>
>







178250
178251
178252
178253
178254
178255
178256
178257
178258
178259
178260
178261
178262
178263
178264
178265
178266
                 | SQLITE_EnableQPSG
#endif
#if defined(SQLITE_DEFAULT_DEFENSIVE)
                 | SQLITE_Defensive
#endif
#if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
                 | SQLITE_LegacyAlter
#endif
#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
                 | SQLITE_StmtScanStatus
#endif
      ;
  sqlite3HashInit(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3HashInit(&db->aModule);
#endif

177863
177864
177865
177866
177867
177868
177869
177870
177871
177872
177873
177874
177875
177876
177877
  int rc;
  pVfs = sqlite3_vfs_find(0);
  if( pVfs==0 ) return 0;

  /* This function works in milliseconds, but the underlying OsSleep()
  ** API uses microseconds. Hence the 1000's.
  */
  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  return rc;
}

/*
** Enable or disable the extended result codes.
*/
SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){







|







178818
178819
178820
178821
178822
178823
178824
178825
178826
178827
178828
178829
178830
178831
178832
  int rc;
  pVfs = sqlite3_vfs_find(0);
  if( pVfs==0 ) return 0;

  /* This function works in milliseconds, but the underlying OsSleep()
  ** API uses microseconds. Hence the 1000's.
  */
  rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
  return rc;
}

/*
** Enable or disable the extended result codes.
*/
SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
193067
193068
193069
193070
193071
193072
193073
193074
193075
193076
193077
193078
193079

193080
193081
193082
193083

193084
193085
193086
193087
193088
193089
193090
** trying to resize the buffer, return SQLITE_NOMEM.
*/
static int fts3MsrBufferData(
  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
  char *pList,
  i64 nList
){
  if( nList>pMsr->nBuffer ){
    char *pNew;
    pMsr->nBuffer = nList*2;
    pNew = (char *)sqlite3_realloc64(pMsr->aBuffer, pMsr->nBuffer);
    if( !pNew ) return SQLITE_NOMEM;
    pMsr->aBuffer = pNew;

  }

  assert( nList>0 );
  memcpy(pMsr->aBuffer, pList, nList);

  return SQLITE_OK;
}

SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  Fts3Table *p,                   /* Virtual table handle */
  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
  sqlite3_int64 *piDocid,         /* OUT: Docid value */







|

|
|


>




>







194022
194023
194024
194025
194026
194027
194028
194029
194030
194031
194032
194033
194034
194035
194036
194037
194038
194039
194040
194041
194042
194043
194044
194045
194046
194047
** trying to resize the buffer, return SQLITE_NOMEM.
*/
static int fts3MsrBufferData(
  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
  char *pList,
  i64 nList
){
  if( (nList+FTS3_NODE_PADDING)>pMsr->nBuffer ){
    char *pNew;
    int nNew = nList*2 + FTS3_NODE_PADDING;
    pNew = (char *)sqlite3_realloc64(pMsr->aBuffer, nNew);
    if( !pNew ) return SQLITE_NOMEM;
    pMsr->aBuffer = pNew;
    pMsr->nBuffer = nNew;
  }

  assert( nList>0 );
  memcpy(pMsr->aBuffer, pList, nList);
  memset(&pMsr->aBuffer[nList], 0, FTS3_NODE_PADDING);
  return SQLITE_OK;
}

SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  Fts3Table *p,                   /* Virtual table handle */
  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
  sqlite3_int64 *piDocid,         /* OUT: Docid value */
198865
198866
198867
198868
198869
198870
198871

198872
198873
198874
198875
198876
198877
198878
#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
#define JNODE_REMOVE  0x04         /* Do not output */
#define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
#define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
#define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
#define JNODE_LABEL   0x40         /* Is a label of an object */



/* A single node of parsed JSON
*/
struct JsonNode {
  u8 eType;              /* One of the JSON_ type values */
  u8 jnFlags;            /* JNODE flags */







>







199822
199823
199824
199825
199826
199827
199828
199829
199830
199831
199832
199833
199834
199835
199836
#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
#define JNODE_REMOVE  0x04         /* Do not output */
#define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
#define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
#define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
#define JNODE_LABEL   0x40         /* Is a label of an object */
#define JNODE_JSON5   0x80         /* Node contains JSON5 enhancements */


/* A single node of parsed JSON
*/
struct JsonNode {
  u8 eType;              /* One of the JSON_ type values */
  u8 jnFlags;            /* JNODE flags */
198891
198892
198893
198894
198895
198896
198897
198898
198899
198900

198901

198902
198903
198904
198905
198906
198907
198908
198909
198910
198911
198912
198913
198914
198915
198916
198917
198918
198919
*/
struct JsonParse {
  u32 nNode;         /* Number of slots of aNode[] used */
  u32 nAlloc;        /* Number of slots of aNode[] allocated */
  JsonNode *aNode;   /* Array of nodes containing the parse */
  const char *zJson; /* Original JSON string */
  u32 *aUp;          /* Index of parent of each node */
  u8 oom;            /* Set to true if out of memory */
  u8 nErr;           /* Number of errors seen */
  u16 iDepth;        /* Nesting depth */

  int nJson;         /* Length of the zJson string in bytes */

  u32 iHold;         /* Replace cache line with the lowest iHold value */
};

/*
** Maximum nesting depth of JSON for this implementation.
**
** This limit is needed to avoid a stack overflow in the recursive
** descent parser.  A depth of 2000 is far deeper than any sane JSON
** should go.
*/
#define JSON_MAX_DEPTH  2000

/**************************************************************************
** Utility routines for dealing with JsonString objects
**************************************************************************/

/* Set the JsonString object to an empty string
*/







|

|
>

>







|
|

|







199849
199850
199851
199852
199853
199854
199855
199856
199857
199858
199859
199860
199861
199862
199863
199864
199865
199866
199867
199868
199869
199870
199871
199872
199873
199874
199875
199876
199877
199878
199879
*/
struct JsonParse {
  u32 nNode;         /* Number of slots of aNode[] used */
  u32 nAlloc;        /* Number of slots of aNode[] allocated */
  JsonNode *aNode;   /* Array of nodes containing the parse */
  const char *zJson; /* Original JSON string */
  u32 *aUp;          /* Index of parent of each node */
  u16 iDepth;        /* Nesting depth */
  u8 nErr;           /* Number of errors seen */
  u8 oom;            /* Set to true if out of memory */
  u8 hasNonstd;      /* True if input uses non-standard features like JSON5 */
  int nJson;         /* Length of the zJson string in bytes */
  u32 iErr;          /* Error location in zJson[] */
  u32 iHold;         /* Replace cache line with the lowest iHold value */
};

/*
** Maximum nesting depth of JSON for this implementation.
**
** This limit is needed to avoid a stack overflow in the recursive
** descent parser.  A depth of 1000 is far deeper than any sane JSON
** should go.  Historical note: This limit was 2000 prior to version 3.42.0
*/
#define JSON_MAX_DEPTH  1000

/**************************************************************************
** Utility routines for dealing with JsonString objects
**************************************************************************/

/* Set the JsonString object to an empty string
*/
199054
199055
199056
199057
199058
199059
199060



























































































































199061
199062
199063
199064
199065
199066
199067
199068
199069
199070
199071
199072
199073
199074
199075



199076
199077
199078
199079
199080
199081
199082
199083
      c = "0123456789abcdef"[c&0xf];
    }
    p->zBuf[p->nUsed++] = c;
  }
  p->zBuf[p->nUsed++] = '"';
  assert( p->nUsed<p->nAlloc );
}




























































































































/*
** Append a function parameter value to the JSON string under
** construction.
*/
static void jsonAppendValue(
  JsonString *p,                 /* Append to this JSON string */
  sqlite3_value *pValue          /* Value to append */
){
  switch( sqlite3_value_type(pValue) ){
    case SQLITE_NULL: {
      jsonAppendRaw(p, "null", 4);
      break;
    }
    case SQLITE_INTEGER:



    case SQLITE_FLOAT: {
      const char *z = (const char*)sqlite3_value_text(pValue);
      u32 n = (u32)sqlite3_value_bytes(pValue);
      jsonAppendRaw(p, z, n);
      break;
    }
    case SQLITE_TEXT: {
      const char *z = (const char*)sqlite3_value_text(pValue);







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














|
>
>
>
|







200014
200015
200016
200017
200018
200019
200020
200021
200022
200023
200024
200025
200026
200027
200028
200029
200030
200031
200032
200033
200034
200035
200036
200037
200038
200039
200040
200041
200042
200043
200044
200045
200046
200047
200048
200049
200050
200051
200052
200053
200054
200055
200056
200057
200058
200059
200060
200061
200062
200063
200064
200065
200066
200067
200068
200069
200070
200071
200072
200073
200074
200075
200076
200077
200078
200079
200080
200081
200082
200083
200084
200085
200086
200087
200088
200089
200090
200091
200092
200093
200094
200095
200096
200097
200098
200099
200100
200101
200102
200103
200104
200105
200106
200107
200108
200109
200110
200111
200112
200113
200114
200115
200116
200117
200118
200119
200120
200121
200122
200123
200124
200125
200126
200127
200128
200129
200130
200131
200132
200133
200134
200135
200136
200137
200138
200139
200140
200141
200142
200143
200144
200145
200146
200147
200148
200149
200150
200151
200152
200153
200154
200155
200156
200157
200158
200159
200160
200161
200162
200163
200164
200165
200166
200167
200168
200169
      c = "0123456789abcdef"[c&0xf];
    }
    p->zBuf[p->nUsed++] = c;
  }
  p->zBuf[p->nUsed++] = '"';
  assert( p->nUsed<p->nAlloc );
}

/*
** The zIn[0..N] string is a JSON5 string literal.  Append to p a translation
** of the string literal that standard JSON and that omits all JSON5
** features.
*/
static void jsonAppendNormalizedString(JsonString *p, const char *zIn, u32 N){
  u32 i;
  jsonAppendChar(p, '"');
  zIn++;
  N -= 2;
  while( N>0 ){
    for(i=0; i<N && zIn[i]!='\\'; i++){}
    if( i>0 ){
      jsonAppendRaw(p, zIn, i);
      zIn += i;
      N -= i;
      if( N==0 ) break;
    }
    assert( zIn[0]=='\\' );
    switch( (u8)zIn[1] ){
      case '\'':
        jsonAppendChar(p, '\'');
        break;
      case 'v':
        jsonAppendRaw(p, "\\u0009", 6);
        break;
      case 'x':
        jsonAppendRaw(p, "\\u00", 4);
        jsonAppendRaw(p, &zIn[2], 2);
        zIn += 2;
        N -= 2;
        break;
      case '0':
        jsonAppendRaw(p, "\\u0000", 6);
        break;
      case '\r':
        if( zIn[2]=='\n' ){
          zIn++;
          N--;
        }
        break;
      case '\n':
        break;
      case 0xe2:
        assert( N>=4 );
        assert( 0x80==(u8)zIn[2] );
        assert( 0xa8==(u8)zIn[3] || 0xa9==(u8)zIn[3] );
        zIn += 2;
        N -= 2;
        break;
      default:
        jsonAppendRaw(p, zIn, 2);
        break;
    }
    zIn += 2;
    N -= 2;
  }
  jsonAppendChar(p, '"');
}

/*
** The zIn[0..N] string is a JSON5 integer literal.  Append to p a translation
** of the string literal that standard JSON and that omits all JSON5
** features.
*/
static void jsonAppendNormalizedInt(JsonString *p, const char *zIn, u32 N){
  if( zIn[0]=='+' ){
    zIn++;
    N--;
  }else if( zIn[0]=='-' ){
    jsonAppendChar(p, '-');
    zIn++;
    N--;
  }
  if( zIn[0]=='0' && (zIn[1]=='x' || zIn[1]=='X') ){
    sqlite3_int64 i = 0;
    int rc = sqlite3DecOrHexToI64(zIn, &i);
    if( rc<=1 ){
      jsonPrintf(100,p,"%lld",i);
    }else{
      assert( rc==2 );
      jsonAppendRaw(p, "9.0e999", 7);
    }
    return;
  }
  jsonAppendRaw(p, zIn, N);
}

/*
** The zIn[0..N] string is a JSON5 real literal.  Append to p a translation
** of the string literal that standard JSON and that omits all JSON5
** features.
*/
static void jsonAppendNormalizedReal(JsonString *p, const char *zIn, u32 N){
  u32 i;
  if( zIn[0]=='+' ){
    zIn++;
    N--;
  }else if( zIn[0]=='-' ){
    jsonAppendChar(p, '-');
    zIn++;
    N--;
  }
  if( zIn[0]=='.' ){
    jsonAppendChar(p, '0');
  }
  for(i=0; i<N; i++){
    if( zIn[i]=='.' && (i+1==N || !sqlite3Isdigit(zIn[i+1])) ){
      i++;
      jsonAppendRaw(p, zIn, i);
      zIn += i;
      N -= i;
      jsonAppendChar(p, '0');
      break;
    }
  }
  if( N>0 ){
    jsonAppendRaw(p, zIn, N);
  }
}



/*
** Append a function parameter value to the JSON string under
** construction.
*/
static void jsonAppendValue(
  JsonString *p,                 /* Append to this JSON string */
  sqlite3_value *pValue          /* Value to append */
){
  switch( sqlite3_value_type(pValue) ){
    case SQLITE_NULL: {
      jsonAppendRaw(p, "null", 4);
      break;
    }
    case SQLITE_FLOAT: {
      jsonPrintf(100, p, "%!0.15g", sqlite3_value_double(pValue));
      break;
    }
    case SQLITE_INTEGER: {
      const char *z = (const char*)sqlite3_value_text(pValue);
      u32 n = (u32)sqlite3_value_bytes(pValue);
      jsonAppendRaw(p, z, n);
      break;
    }
    case SQLITE_TEXT: {
      const char *z = (const char*)sqlite3_value_text(pValue);
199182
199183
199184
199185
199186
199187
199188

199189
199190




199191



199192

199193
199194
199195
199196








199197
199198



199199

199200
199201
199202
199203
199204
199205
199206
      break;
    }
    case JSON_FALSE: {
      jsonAppendRaw(pOut, "false", 5);
      break;
    }
    case JSON_STRING: {

      if( pNode->jnFlags & JNODE_RAW ){
        assert( pNode->eU==1 );




        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);



        break;

      }
      /* no break */ deliberate_fall_through
    }
    case JSON_REAL:








    case JSON_INT: {
      assert( pNode->eU==1 );



      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);

      break;
    }
    case JSON_ARRAY: {
      u32 j = 1;
      jsonAppendChar(pOut, '[');
      for(;;){
        while( j<=pNode->n ){







>

|
>
>
>
>
|
>
>
>
|
>

|

|
>
>
>
>
>
>
>
>


>
>
>
|
>







200268
200269
200270
200271
200272
200273
200274
200275
200276
200277
200278
200279
200280
200281
200282
200283
200284
200285
200286
200287
200288
200289
200290
200291
200292
200293
200294
200295
200296
200297
200298
200299
200300
200301
200302
200303
200304
200305
200306
200307
200308
200309
200310
200311
200312
200313
      break;
    }
    case JSON_FALSE: {
      jsonAppendRaw(pOut, "false", 5);
      break;
    }
    case JSON_STRING: {
      assert( pNode->eU==1 );
      if( pNode->jnFlags & JNODE_RAW ){
        if( pNode->jnFlags & JNODE_LABEL ){
          jsonAppendChar(pOut, '"');
          jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
          jsonAppendChar(pOut, '"');
        }else{
          jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
        }
      }else if( pNode->jnFlags & JNODE_JSON5 ){
        jsonAppendNormalizedString(pOut, pNode->u.zJContent, pNode->n);
      }else{
        jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
      }
      break;
    }
    case JSON_REAL: {
      assert( pNode->eU==1 );
      if( pNode->jnFlags & JNODE_JSON5 ){
        jsonAppendNormalizedReal(pOut, pNode->u.zJContent, pNode->n);
      }else{
        jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
      }
      break;
    }
    case JSON_INT: {
      assert( pNode->eU==1 );
      if( pNode->jnFlags & JNODE_JSON5 ){
        jsonAppendNormalizedInt(pOut, pNode->u.zJContent, pNode->n);
      }else{
        jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
      }
      break;
    }
    case JSON_ARRAY: {
      u32 j = 1;
      jsonAppendChar(pOut, '[');
      for(;;){
        while( j<=pNode->n ){
199308
199309
199310
199311
199312
199313
199314


199315


199316
199317
199318
199319
199320
199321
199322
199323
199324
199325

199326
199327
199328
199329
199330
199331
199332
199333
199334
199335
199336
199337
199338
199339
199340
199341
199342
199343
199344
199345
199346

199347
199348
199349
199350
199351
199352
199353
199354
199355
199356
199357
199358
199359
199360
199361
199362
199363
199364
199365
199366
199367
199368
199369
199370
199371
199372
199373
199374
199375
199376
199377
199378

199379
199380
199381
199382
199383
199384
199385
199386
199387
199388
199389
199390
199391
199392
199393
199394
199395
199396
199397
    }
    case JSON_FALSE: {
      sqlite3_result_int(pCtx, 0);
      break;
    }
    case JSON_INT: {
      sqlite3_int64 i = 0;


      const char *z;


      assert( pNode->eU==1 );
      z = pNode->u.zJContent;
      if( z[0]=='-' ){ z++; }
      while( z[0]>='0' && z[0]<='9' ){
        unsigned v = *(z++) - '0';
        if( i>=LARGEST_INT64/10 ){
          if( i>LARGEST_INT64/10 ) goto int_as_real;
          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
          if( v==9 ) goto int_as_real;
          if( v==8 ){

            if( pNode->u.zJContent[0]=='-' ){
              sqlite3_result_int64(pCtx, SMALLEST_INT64);
              goto int_done;
            }else{
              goto int_as_real;
            }
          }
        }
        i = i*10 + v;
      }
      if( pNode->u.zJContent[0]=='-' ){ i = -i; }
      sqlite3_result_int64(pCtx, i);
      int_done:
      break;
      int_as_real: ; /* no break */ deliberate_fall_through
    }
    case JSON_REAL: {
      double r;
#ifdef SQLITE_AMALGAMATION
      const char *z;
      assert( pNode->eU==1 );

      z = pNode->u.zJContent;
      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
#else
      assert( pNode->eU==1 );
      r = strtod(pNode->u.zJContent, 0);
#endif
      sqlite3_result_double(pCtx, r);
      break;
    }
    case JSON_STRING: {
#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
      ** json_insert() and json_replace() and those routines do not
      ** call jsonReturn() */
      if( pNode->jnFlags & JNODE_RAW ){
        assert( pNode->eU==1 );
        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
                            SQLITE_TRANSIENT);
      }else
#endif
      assert( (pNode->jnFlags & JNODE_RAW)==0 );
      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
        /* JSON formatted without any backslash-escapes */
        assert( pNode->eU==1 );
        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
                            SQLITE_TRANSIENT);
      }else{
        /* Translate JSON formatted string into raw text */
        u32 i;
        u32 n = pNode->n;
        const char *z;
        char *zOut;
        u32 j;

        assert( pNode->eU==1 );
        z = pNode->u.zJContent;
        zOut = sqlite3_malloc( n+1 );
        if( zOut==0 ){
          sqlite3_result_error_nomem(pCtx);
          break;
        }
        for(i=1, j=0; i<n-1; i++){
          char c = z[i];
          if( c!='\\' ){
            zOut[j++] = c;
          }else{
            c = z[++i];
            if( c=='u' ){
              u32 v = jsonHexToInt4(z+i+1);
              i += 4;
              if( v==0 ) break;
              if( v<=0x7f ){
                zOut[j++] = (char)v;







>
>

>
>


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

<



<


>


<
<
<
<




<
<
<




<
<
<
|











>


|






|
<
<







200415
200416
200417
200418
200419
200420
200421
200422
200423
200424
200425
200426
200427
200428
200429
200430
200431




200432
200433
200434
200435

200436
200437
200438







200439

200440
200441
200442

200443
200444
200445
200446
200447




200448
200449
200450
200451



200452
200453
200454
200455



200456
200457
200458
200459
200460
200461
200462
200463
200464
200465
200466
200467
200468
200469
200470
200471
200472
200473
200474
200475
200476
200477
200478


200479
200480
200481
200482
200483
200484
200485
    }
    case JSON_FALSE: {
      sqlite3_result_int(pCtx, 0);
      break;
    }
    case JSON_INT: {
      sqlite3_int64 i = 0;
      int rc;
      int bNeg = 0;
      const char *z;


      assert( pNode->eU==1 );
      z = pNode->u.zJContent;
      if( z[0]=='-' ){ z++; bNeg = 1; }
      else if( z[0]=='+' ){ z++; }
      rc = sqlite3DecOrHexToI64(z, &i);




      if( rc<=1 ){
        sqlite3_result_int64(pCtx, bNeg ? -i : i);
      }else if( rc==3 && bNeg ){
        sqlite3_result_int64(pCtx, SMALLEST_INT64);

      }else{
        goto to_double;
      }







      break;

    }
    case JSON_REAL: {
      double r;

      const char *z;
      assert( pNode->eU==1 );
    to_double:
      z = pNode->u.zJContent;
      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);




      sqlite3_result_double(pCtx, r);
      break;
    }
    case JSON_STRING: {



      if( pNode->jnFlags & JNODE_RAW ){
        assert( pNode->eU==1 );
        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
                            SQLITE_TRANSIENT);



      }else if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
        /* JSON formatted without any backslash-escapes */
        assert( pNode->eU==1 );
        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
                            SQLITE_TRANSIENT);
      }else{
        /* Translate JSON formatted string into raw text */
        u32 i;
        u32 n = pNode->n;
        const char *z;
        char *zOut;
        u32 j;
        u32 nOut = n;
        assert( pNode->eU==1 );
        z = pNode->u.zJContent;
        zOut = sqlite3_malloc( nOut+1 );
        if( zOut==0 ){
          sqlite3_result_error_nomem(pCtx);
          break;
        }
        for(i=1, j=0; i<n-1; i++){
          char c = z[i];
          if( c=='\\' ){


            c = z[++i];
            if( c=='u' ){
              u32 v = jsonHexToInt4(z+i+1);
              i += 4;
              if( v==0 ) break;
              if( v<=0x7f ){
                zOut[j++] = (char)v;
199415
199416
199417
199418
199419
199420
199421
199422
199423
199424
199425
199426
199427
199428
199429
199430
199431
199432



















199433

199434
199435
199436
199437
199438
199439
199440
199441
199442
199443
199444
                  zOut[j++] = 0x80 | (v&0x3f);
                }else{
                  zOut[j++] = 0xe0 | (v>>12);
                  zOut[j++] = 0x80 | ((v>>6)&0x3f);
                  zOut[j++] = 0x80 | (v&0x3f);
                }
              }
            }else{
              if( c=='b' ){
                c = '\b';
              }else if( c=='f' ){
                c = '\f';
              }else if( c=='n' ){
                c = '\n';
              }else if( c=='r' ){
                c = '\r';
              }else if( c=='t' ){
                c = '\t';



















              }

              zOut[j++] = c;
            }
          }
        }
        zOut[j] = 0;
        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
      }
      break;
    }
    case JSON_ARRAY:
    case JSON_OBJECT: {







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







200503
200504
200505
200506
200507
200508
200509
200510
200511
200512
200513
200514
200515
200516
200517
200518
200519
200520
200521
200522
200523
200524
200525
200526
200527
200528
200529
200530
200531
200532
200533
200534
200535
200536
200537
200538
200539
200540
200541
200542
200543


200544
200545
200546
200547
200548
200549
200550
                  zOut[j++] = 0x80 | (v&0x3f);
                }else{
                  zOut[j++] = 0xe0 | (v>>12);
                  zOut[j++] = 0x80 | ((v>>6)&0x3f);
                  zOut[j++] = 0x80 | (v&0x3f);
                }
              }
              continue;
            }else if( c=='b' ){
              c = '\b';
            }else if( c=='f' ){
              c = '\f';
            }else if( c=='n' ){
              c = '\n';
            }else if( c=='r' ){
              c = '\r';
            }else if( c=='t' ){
              c = '\t';
            }else if( c=='v' ){
              c = '\v';
            }else if( c=='\'' || c=='"' || c=='/' || c=='\\' ){
              /* pass through unchanged */
            }else if( c=='0' ){
              c = 0;
            }else if( c=='x' ){
              c = (jsonHexToInt(z[i+1])<<4) | jsonHexToInt(z[i+2]);
              i += 2;
            }else if( c=='\r' && z[i+1]=='\n' ){
              i++;
              continue;
            }else if( 0xe2==(u8)c ){
              assert( 0x80==(u8)z[i+1] );
              assert( 0xa8==(u8)z[i+2] || 0xa9==(u8)z[i+2] );
              i += 2;
              continue;
            }else{
              continue;
            }
          } /* end if( c=='\\' ) */
          zOut[j++] = c;
        } /* end for() */


        zOut[j] = 0;
        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
      }
      break;
    }
    case JSON_ARRAY:
    case JSON_OBJECT: {
199498
199499
199500
199501
199502
199503
199504
199505
199506
199507
199508
199509
199510
199511







199512
199513
199514
199515
199516























































199517





199518

































































199519
199520



















199521
199522
199523
199524
199525
199526
199527


199528



199529
199530
199531
199532
199533
199534
199535
199536

199537
199538
199539
199540
199541




199542
199543
199544
199545
199546

199547
199548

















199549
199550

199551
199552
199553



199554
199555



199556

199557
199558











199559

199560
199561

199562





199563

199564
199565
199566
199567
199568














199569

199570

199571
199572
199573
199574




199575
199576
199577
199578
199579
199580
199581
199582





199583
199584
199585





199586

199587
199588
199589
199590
199591














199592

199593







199594
199595
199596


199597
199598
199599
199600
199601

199602
199603
199604
199605
199606
199607
199608
199609










199610

199611
199612
199613
199614
199615
199616
199617
199618
199619
199620

199621
199622
199623
199624
199625

199626
199627


199628
199629
199630




199631




199632
199633






199634
199635
199636










199637


199638
199639
199640




199641




















199642












199643
199644


199645











199646
199647
199648
199649
199650

199651

199652
199653
199654
199655
199656








199657




199658
199659
199660
199661
199662
199663
199664
















































































199665
199666
199667
199668
199669
199670
199671


199672
199673
199674
199675
199676
199677
199678

199679
199680
199681

199682
199683
199684
199685
199686
199687
199688
  const char *zContent      /* Content */
){
  JsonNode *p;
  if( pParse->aNode==0 || pParse->nNode>=pParse->nAlloc ){
    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  }
  p = &pParse->aNode[pParse->nNode];
  p->eType = (u8)eType;
  p->jnFlags = 0;
  VVA( p->eU = zContent ? 1 : 0 );
  p->n = n;
  p->u.zJContent = zContent;
  return pParse->nNode++;
}








/*
** Return true if z[] begins with 4 (or more) hexadecimal digits
*/
static int jsonIs4Hex(const char *z){























































  int i;





  for(i=0; i<4; i++) if( !sqlite3Isxdigit(z[i]) ) return 0;

































































  return 1;
}




















/*
** Parse a single JSON value which begins at pParse->zJson[i].  Return the
** index of the first character past the end of the value parsed.
**
** Return negative for a syntax error.  Special cases:  return -2 if the
** first non-whitespace character is '}' and return -3 if the first


** non-whitespace character is ']'.



*/
static int jsonParseValue(JsonParse *pParse, u32 i){
  char c;
  u32 j;
  int iThis;
  int x;
  JsonNode *pNode;
  const char *z = pParse->zJson;

  while( fast_isspace(z[i]) ){ i++; }
  if( (c = z[i])=='{' ){
    /* Parse object */
    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
    if( iThis<0 ) return -1;




    for(j=i+1;;j++){
      while( fast_isspace(z[j]) ){ j++; }
      if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
      x = jsonParseValue(pParse, j);
      if( x<0 ){

        pParse->iDepth--;
        if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;

















        return -1;
      }

      if( pParse->oom ) return -1;
      pNode = &pParse->aNode[pParse->nNode-1];
      if( pNode->eType!=JSON_STRING ) return -1;



      pNode->jnFlags |= JNODE_LABEL;
      j = x;



      while( fast_isspace(z[j]) ){ j++; }

      if( z[j]!=':' ) return -1;
      j++;











      x = jsonParseValue(pParse, j);

      pParse->iDepth--;
      if( x<0 ) return -1;

      j = x;





      while( fast_isspace(z[j]) ){ j++; }

      c = z[j];
      if( c==',' ) continue;
      if( c!='}' ) return -1;
      break;
    }














    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;

    return j+1;

  }else if( c=='[' ){
    /* Parse array */
    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
    if( iThis<0 ) return -1;




    memset(&pParse->aNode[iThis].u, 0, sizeof(pParse->aNode[iThis].u));
    for(j=i+1;;j++){
      while( fast_isspace(z[j]) ){ j++; }
      if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
      x = jsonParseValue(pParse, j);
      pParse->iDepth--;
      if( x<0 ){
        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;





        return -1;
      }
      j = x;





      while( fast_isspace(z[j]) ){ j++; }

      c = z[j];
      if( c==',' ) continue;
      if( c!=']' ) return -1;
      break;
    }














    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;

    return j+1;







  }else if( c=='"' ){
    /* Parse string */
    u8 jnFlags = 0;


    j = i+1;
    for(;;){
      c = z[j];
      if( (c & ~0x1f)==0 ){
        /* Control characters are not allowed in strings */

        return -1;
      }
      if( c=='\\' ){
        c = z[++j];
        if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
           || c=='n' || c=='r' || c=='t'
           || (c=='u' && jsonIs4Hex(z+j+1)) ){
          jnFlags = JNODE_ESCAPE;










        }else{

          return -1;
        }
      }else if( c=='"' ){
        break;
      }
      j++;
    }
    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
    return j+1;

  }else if( c=='n'
         && strncmp(z+i,"null",4)==0
         && !sqlite3Isalnum(z[i+4]) ){
    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
    return i+4;

  }else if( c=='t'
         && strncmp(z+i,"true",4)==0


         && !sqlite3Isalnum(z[i+4]) ){
    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
    return i+4;




  }else if( c=='f'




         && strncmp(z+i,"false",5)==0
         && !sqlite3Isalnum(z[i+5]) ){






    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
    return i+5;
  }else if( c=='-' || (c>='0' && c<='9') ){










    /* Parse number */


    u8 seenDP = 0;
    u8 seenE = 0;
    assert( '-' < '0' );




    if( c<='0' ){




















      j = c=='-' ? i+1 : i;












      if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
    }


    j = i+1;











    for(;; j++){
      c = z[j];
      if( c>='0' && c<='9' ) continue;
      if( c=='.' ){
        if( z[j-1]=='-' ) return -1;

        if( seenDP ) return -1;

        seenDP = 1;
        continue;
      }
      if( c=='e' || c=='E' ){
        if( z[j-1]<'0' ) return -1;








        if( seenE ) return -1;




        seenDP = seenE = 1;
        c = z[j+1];
        if( c=='+' || c=='-' ){
          j++;
          c = z[j+1];
        }
        if( c<'0' || c>'9' ) return -1;
















































































        continue;
      }
      break;
    }
    if( z[j-1]<'0' ) return -1;
    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
                        j - i, &z[i]);


    return j;
  }else if( c=='}' ){
    return -2;  /* End of {...} */
  }else if( c==']' ){
    return -3;  /* End of [...] */
  }else if( c==0 ){
    return 0;   /* End of file */

  }else{
    return -1;  /* Syntax error */
  }

}

/*
** Parse a complete JSON string.  Return 0 on success or non-zero if there
** are any errors.  If an error occurs, free all memory associated with
** pParse.
**







|
|





>
>
>
>
>
>
>





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

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





|
|
>
>
|
>
>
>








>
|
|



>
>
>
>

<
|

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

|
|
>
>
>


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

>
|
|
>

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

>

>
|



>
>
>
>


<
<

<
|
|
>
>
>
>
>



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

>

>
>
>
>
>
>
>
|

|
>
>





>






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

>


|




|
<

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

>
>
|
|

>
>
>
>

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

|

|
>
|
>
|



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





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


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


>







200604
200605
200606
200607
200608
200609
200610
200611
200612
200613
200614
200615
200616
200617
200618
200619
200620
200621
200622
200623
200624
200625
200626
200627
200628
200629
200630
200631
200632
200633
200634
200635
200636
200637
200638
200639
200640
200641
200642
200643
200644
200645
200646
200647
200648
200649
200650
200651
200652
200653
200654
200655
200656
200657
200658
200659
200660
200661
200662
200663
200664
200665
200666
200667
200668
200669
200670
200671
200672
200673
200674
200675
200676
200677
200678
200679
200680
200681
200682
200683
200684
200685
200686
200687
200688
200689
200690
200691
200692
200693
200694
200695
200696
200697
200698
200699
200700
200701
200702
200703
200704
200705
200706
200707
200708
200709
200710
200711
200712
200713
200714
200715
200716
200717
200718
200719
200720
200721
200722
200723
200724
200725
200726
200727
200728
200729
200730
200731
200732
200733
200734
200735
200736
200737
200738
200739
200740
200741
200742
200743
200744
200745
200746
200747
200748
200749
200750
200751
200752
200753
200754
200755
200756
200757
200758
200759
200760
200761
200762
200763
200764
200765
200766
200767
200768
200769
200770
200771
200772
200773
200774
200775
200776
200777
200778
200779
200780
200781
200782
200783
200784
200785
200786
200787
200788
200789
200790
200791
200792
200793
200794
200795
200796
200797
200798
200799
200800
200801
200802
200803
200804
200805
200806
200807
200808
200809

200810
200811
200812
200813
200814
200815
200816
200817
200818
200819
200820
200821
200822
200823
200824
200825
200826
200827
200828
200829
200830
200831
200832
200833
200834
200835
200836
200837
200838
200839
200840
200841
200842
200843
200844
200845
200846
200847
200848
200849
200850
200851
200852
200853
200854
200855
200856
200857
200858
200859
200860
200861
200862
200863
200864
200865
200866
200867
200868
200869
200870
200871
200872
200873
200874
200875
200876
200877
200878
200879
200880
200881
200882
200883
200884
200885
200886
200887
200888
200889
200890
200891
200892
200893
200894
200895
200896
200897
200898
200899
200900
200901
200902
200903
200904
200905
200906
200907


200908

200909
200910
200911
200912
200913
200914
200915
200916
200917
200918
200919
200920
200921
200922
200923
200924
200925
200926
200927
200928
200929
200930
200931
200932
200933
200934
200935
200936
200937
200938
200939
200940
200941
200942
200943
200944
200945
200946
200947
200948
200949
200950
200951
200952
200953
200954
200955
200956
200957
200958
200959
200960
200961
200962
200963
200964
200965
200966
200967
200968
200969
200970
200971
200972
200973
200974
200975
200976
200977
200978
200979
200980
200981
200982
200983
200984
200985
200986
200987
200988
200989
200990
200991
200992
200993

200994
200995
200996

200997
200998
200999
201000
201001
201002
201003
201004
201005
201006
201007
201008
201009
201010
201011
201012
201013
201014
201015
201016
201017
201018
201019
201020
201021
201022
201023
201024
201025
201026
201027
201028
201029
201030
201031
201032
201033
201034
201035
201036
201037
201038
201039
201040
201041
201042
201043
201044
201045
201046
201047
201048
201049
201050
201051
201052
201053
201054
201055
201056
201057
201058
201059
201060
201061
201062
201063
201064
201065
201066
201067
201068
201069
201070
201071
201072
201073
201074
201075
201076
201077
201078
201079
201080
201081
201082
201083
201084
201085
201086
201087
201088
201089
201090
201091
201092
201093
201094
201095
201096
201097
201098
201099
201100
201101
201102
201103
201104
201105
201106
201107
201108
201109
201110
201111
201112
201113
201114
201115
201116
201117
201118
201119
201120
201121
201122
201123
201124
201125
201126
201127
201128
201129
201130
201131
201132
201133
201134
201135
201136
201137
201138
201139
201140
201141
201142
201143
201144
201145
201146
201147
201148
201149
201150
201151
201152
201153
201154
201155
201156
201157
201158
201159
201160
201161
201162
201163
201164
201165
201166
201167
201168
201169
201170
201171
201172
201173
201174
201175
201176
201177
201178
201179
201180
201181
201182
201183
201184
201185
201186
201187
201188
201189
201190
201191
201192
201193
201194
201195
201196
201197
201198
201199
201200
201201
201202
201203
201204
201205
201206
201207
201208
201209
201210
201211
201212


201213
201214

201215
201216
201217






201218
201219
201220
201221
201222
201223
201224
201225
201226
201227
201228
201229
  const char *zContent      /* Content */
){
  JsonNode *p;
  if( pParse->aNode==0 || pParse->nNode>=pParse->nAlloc ){
    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  }
  p = &pParse->aNode[pParse->nNode];
  p->eType = (u8)(eType & 0xff);
  p->jnFlags = (u8)(eType >> 8);
  VVA( p->eU = zContent ? 1 : 0 );
  p->n = n;
  p->u.zJContent = zContent;
  return pParse->nNode++;
}

/*
** Return true if z[] begins with 2 (or more) hexadecimal digits
*/
static int jsonIs2Hex(const char *z){
  return sqlite3Isxdigit(z[0]) && sqlite3Isxdigit(z[1]);
}

/*
** Return true if z[] begins with 4 (or more) hexadecimal digits
*/
static int jsonIs4Hex(const char *z){
  return jsonIs2Hex(z) && jsonIs2Hex(&z[2]);
}

/*
** Return the number of bytes of JSON5 whitespace at the beginning of
** the input string z[].
**
** JSON5 whitespace consists of any of the following characters:
**
**    Unicode  UTF-8         Name
**    U+0009   09            horizontal tab
**    U+000a   0a            line feed
**    U+000b   0b            vertical tab
**    U+000c   0c            form feed
**    U+000d   0d            carriage return
**    U+0020   20            space
**    U+00a0   c2 a0         non-breaking space
**    U+1680   e1 9a 80      ogham space mark
**    U+2000   e2 80 80      en quad
**    U+2001   e2 80 81      em quad
**    U+2002   e2 80 82      en space
**    U+2003   e2 80 83      em space
**    U+2004   e2 80 84      three-per-em space
**    U+2005   e2 80 85      four-per-em space
**    U+2006   e2 80 86      six-per-em space
**    U+2007   e2 80 87      figure space
**    U+2008   e2 80 88      punctuation space
**    U+2009   e2 80 89      thin space
**    U+200a   e2 80 8a      hair space
**    U+2028   e2 80 a8      line separator
**    U+2029   e2 80 a9      paragraph separator
**    U+202f   e2 80 af      narrow no-break space (NNBSP)
**    U+205f   e2 81 9f      medium mathematical space (MMSP)
**    U+3000   e3 80 80      ideographical space
**    U+FEFF   ef bb bf      byte order mark
**
** In addition, comments between '/', '*' and '*', '/' and
** from '/', '/' to end-of-line are also considered to be whitespace.
*/
static int json5Whitespace(const char *zIn){
  int n = 0;
  const u8 *z = (u8*)zIn;
  while( 1 /*exit by "goto whitespace_done"*/ ){
    switch( z[n] ){
      case 0x09:
      case 0x0a:
      case 0x0b:
      case 0x0c:
      case 0x0d:
      case 0x20: {
        n++;
        break;
      }
      case '/': {
        if( z[n+1]=='*' && z[n+2]!=0 ){
          int j;
          for(j=n+3; z[j]!='/' || z[j-1]!='*'; j++){
            if( z[j]==0 ) goto whitespace_done;
          }
          n = j+1;
          break;
        }else if( z[n+1]=='/' ){
          int j;
          char c;
          for(j=n+2; (c = z[j])!=0; j++){
            if( c=='\n' || c=='\r' ) break;
            if( 0xe2==(u8)c && 0x80==(u8)z[j+1]
             && (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2])
            ){
              j += 2;
              break;
            }
          }
          n = j;
          if( z[n] ) n++;
          break;
        }
        goto whitespace_done;
      }
      case 0xc2: {
        if( z[n+1]==0xa0 ){
          n += 2;
          break;
        }
        goto whitespace_done;
      }
      case 0xe1: {
        if( z[n+1]==0x9a && z[n+2]==0x80 ){
          n += 3;
          break;
        }
        goto whitespace_done;
      }
      case 0xe2: {
        if( z[n+1]==0x80 ){
          u8 c = z[n+2];
          if( c<0x80 ) goto whitespace_done;
          if( c<=0x8a || c==0xa8 || c==0xa9 || c==0xaf ){
            n += 3;
            break;
          }
        }else if( z[n+1]==0x81 && z[n+2]==0x9f ){
          n += 3;
          break;
        }
        goto whitespace_done;
      }
      case 0xe3: {
        if( z[n+1]==0x80 && z[n+2]==0x80 ){
          n += 3;
          break;
        }
        goto whitespace_done;
      }
      case 0xef: {
        if( z[n+1]==0xbb && z[n+2]==0xbf ){
          n += 3;
          break;
        }
        goto whitespace_done;
      }
      default: {
        goto whitespace_done;
      }
    }
  }
  whitespace_done:
  return n;
}

/*
** Extra floating-point literals to allow in JSON.
*/
static const struct NanInfName {
  char c1;
  char c2;
  char n;
  char eType;
  char nRepl;
  char *zMatch;
  char *zRepl;
} aNanInfName[] = {
  { 'i', 'I', 3, JSON_REAL, 7, "inf", "9.0e999" },
  { 'i', 'I', 8, JSON_REAL, 7, "infinity", "9.0e999" },
  { 'n', 'N', 3, JSON_NULL, 4, "NaN", "null" },
  { 'q', 'Q', 4, JSON_NULL, 4, "QNaN", "null" },
  { 's', 'S', 4, JSON_NULL, 4, "SNaN", "null" },
};

/*
** Parse a single JSON value which begins at pParse->zJson[i].  Return the
** index of the first character past the end of the value parsed.
**
** Special return values:
**
**      0    End if input
**     -1    Syntax error
**     -2    '}' seen
**     -3    ']' seen
**     -4    ',' seen
**     -5    ':' seen
*/
static int jsonParseValue(JsonParse *pParse, u32 i){
  char c;
  u32 j;
  int iThis;
  int x;
  JsonNode *pNode;
  const char *z = pParse->zJson;
json_parse_restart:
  switch( (u8)z[i] ){
  case '{': {
    /* Parse object */
    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
    if( iThis<0 ) return -1;
    if( ++pParse->iDepth > JSON_MAX_DEPTH ){
      pParse->iErr = i;
      return -1;
    }
    for(j=i+1;;j++){

      u32 nNode = pParse->nNode;
      x = jsonParseValue(pParse, j);
      if( x<=0 ){
        if( x==(-2) ){
          j = pParse->iErr;
          if( pParse->nNode!=(u32)iThis+1 ) pParse->hasNonstd = 1;
          break;
        }
        j += json5Whitespace(&z[j]);
        if( sqlite3JsonId1(z[j])
         || (z[j]=='\\' && z[j+1]=='u' && jsonIs4Hex(&z[j+2]))
        ){
          int k = j+1;
          while( (sqlite3JsonId2(z[k]) && json5Whitespace(&z[k])==0)
            || (z[k]=='\\' && z[k+1]=='u' && jsonIs4Hex(&z[k+2]))
          ){
            k++;
          }
          jsonParseAddNode(pParse, JSON_STRING | (JNODE_RAW<<8), k-j, &z[j]);
          pParse->hasNonstd = 1;
          x = k;
        }else{
          if( x!=-1 ) pParse->iErr = j;
          return -1;
        }
      }
      if( pParse->oom ) return -1;
      pNode = &pParse->aNode[nNode];
      if( pNode->eType!=JSON_STRING ){
        pParse->iErr = j;
        return -1;
      }
      pNode->jnFlags |= JNODE_LABEL;
      j = x;
      if( z[j]==':' ){
        j++;
      }else{
        if( fast_isspace(z[j]) ){
          do{ j++; }while( fast_isspace(z[j]) );
          if( z[j]==':' ){
            j++;
            goto parse_object_value;
          }
        }
        x = jsonParseValue(pParse, j);
        if( x!=(-5) ){
          if( x!=(-1) ) pParse->iErr = j;
          return -1;
        }
        j = pParse->iErr+1;
      }
    parse_object_value:
      x = jsonParseValue(pParse, j);
      if( x<=0 ){
        if( x!=(-1) ) pParse->iErr = j;
        return -1;
      }
      j = x;
      if( z[j]==',' ){
        continue;
      }else if( z[j]=='}' ){
        break;
      }else{
        if( fast_isspace(z[j]) ){
          do{ j++; }while( fast_isspace(z[j]) );
          if( z[j]==',' ){
            continue;
          }else if( z[j]=='}' ){
            break;
          }
        }
        x = jsonParseValue(pParse, j);
        if( x==(-4) ){
          j = pParse->iErr;
          continue;
        }
        if( x==(-2) ){
          j = pParse->iErr;
          break;
        }
      }
      pParse->iErr = j;
      return -1;
    }
    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
    pParse->iDepth--;
    return j+1;
  }
  case '[': {
    /* Parse array */
    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
    if( iThis<0 ) return -1;
    if( ++pParse->iDepth > JSON_MAX_DEPTH ){
      pParse->iErr = i;
      return -1;
    }
    memset(&pParse->aNode[iThis].u, 0, sizeof(pParse->aNode[iThis].u));
    for(j=i+1;;j++){


      x = jsonParseValue(pParse, j);

      if( x<=0 ){
        if( x==(-3) ){
          j = pParse->iErr;
          if( pParse->nNode!=(u32)iThis+1 ) pParse->hasNonstd = 1;
          break;
        }
        if( x!=(-1) ) pParse->iErr = j;
        return -1;
      }
      j = x;
      if( z[j]==',' ){
        continue;
      }else if( z[j]==']' ){
        break;
      }else{
        if( fast_isspace(z[j]) ){
          do{ j++; }while( fast_isspace(z[j]) );
          if( z[j]==',' ){
            continue;
          }else if( z[j]==']' ){
            break;
          }
        }
        x = jsonParseValue(pParse, j);
        if( x==(-4) ){
          j = pParse->iErr;
          continue;
        }
        if( x==(-3) ){
          j = pParse->iErr;
          break;
        }
      }
      pParse->iErr = j;
      return -1;
    }
    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
    pParse->iDepth--;
    return j+1;
  }
  case '\'': {
    u8 jnFlags;
    char cDelim;
    pParse->hasNonstd = 1;
    jnFlags = JNODE_JSON5;
    goto parse_string;
  case '"':
    /* Parse string */
    jnFlags = 0;
  parse_string:
    cDelim = z[i];
    j = i+1;
    for(;;){
      c = z[j];
      if( (c & ~0x1f)==0 ){
        /* Control characters are not allowed in strings */
        pParse->iErr = j;
        return -1;
      }
      if( c=='\\' ){
        c = z[++j];
        if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
           || c=='n' || c=='r' || c=='t'
           || (c=='u' && jsonIs4Hex(&z[j+1])) ){
          jnFlags |= JNODE_ESCAPE;
        }else if( c=='\'' || c=='0' || c=='v' || c=='\n'
           || (0xe2==(u8)c && 0x80==(u8)z[j+1]
                && (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2]))
           || (c=='x' && jsonIs2Hex(&z[j+1])) ){
          jnFlags |= (JNODE_ESCAPE|JNODE_JSON5);
          pParse->hasNonstd = 1;
        }else if( c=='\r' ){
          if( z[j+1]=='\n' ) j++;
          jnFlags |= (JNODE_ESCAPE|JNODE_JSON5);
          pParse->hasNonstd = 1;
        }else{
          pParse->iErr = j;
          return -1;
        }
      }else if( c==cDelim ){
        break;
      }
      j++;
    }
    jsonParseAddNode(pParse, JSON_STRING | (jnFlags<<8), j+1-i, &z[i]);

    return j+1;
  }
  case 't': {

    if( strncmp(z+i,"true",4)==0 && !sqlite3Isalnum(z[i+4]) ){
      jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
      return i+4;
    }
    pParse->iErr = i;
    return -1;
  }
  case 'f': {
    if( strncmp(z+i,"false",5)==0 && !sqlite3Isalnum(z[i+5]) ){
      jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
      return i+5;
    }
    pParse->iErr = i;
    return -1;
  }
  case '+': {
    u8 seenDP, seenE, jnFlags;
    pParse->hasNonstd = 1;
    jnFlags = JNODE_JSON5;
    goto parse_number;
  case '.':
    if( sqlite3Isdigit(z[i+1]) ){
      pParse->hasNonstd = 1;
      jnFlags = JNODE_JSON5;
      seenE = 0;
      seenDP = JSON_REAL;
      goto parse_number_2;
    }
    pParse->iErr = i;
    return -1;
  case '-':
  case '0':
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9':
    /* Parse number */
    jnFlags = 0;
  parse_number:
    seenDP = JSON_INT;
    seenE = 0;
    assert( '-' < '0' );
    assert( '+' < '0' );
    assert( '.' < '0' );
    c = z[i];

    if( c<='0' ){
      if( c=='0' ){
        if( (z[i+1]=='x' || z[i+1]=='X') && sqlite3Isxdigit(z[i+2]) ){
          assert( seenDP==JSON_INT );
          pParse->hasNonstd = 1;
          jnFlags |= JNODE_JSON5;
          for(j=i+3; sqlite3Isxdigit(z[j]); j++){}
          goto parse_number_finish;
        }else if( sqlite3Isdigit(z[i+1]) ){
          pParse->iErr = i+1;
          return -1;
        }
      }else{
        if( !sqlite3Isdigit(z[i+1]) ){
          /* JSON5 allows for "+Infinity" and "-Infinity" using exactly
          ** that case.  SQLite also allows these in any case and it allows
          ** "+inf" and "-inf". */
          if( (z[i+1]=='I' || z[i+1]=='i')
           && sqlite3StrNICmp(&z[i+1], "inf",3)==0
          ){
            pParse->hasNonstd = 1;
            if( z[i]=='-' ){
              jsonParseAddNode(pParse, JSON_REAL, 8, "-9.0e999");
            }else{
              jsonParseAddNode(pParse, JSON_REAL, 7, "9.0e999");
            }
            return i + (sqlite3StrNICmp(&z[i+4],"inity",5)==0 ? 9 : 4);
          }
          if( z[i+1]=='.' ){
            pParse->hasNonstd = 1;
            jnFlags |= JNODE_JSON5;
            goto parse_number_2;
          }
          pParse->iErr = i;
          return -1;
        }
        if( z[i+1]=='0' ){
          if( sqlite3Isdigit(z[i+2]) ){
            pParse->iErr = i+1;
            return -1;
          }else if( (z[i+2]=='x' || z[i+2]=='X') && sqlite3Isxdigit(z[i+3]) ){
            pParse->hasNonstd = 1;
            jnFlags |= JNODE_JSON5;
            for(j=i+4; sqlite3Isxdigit(z[j]); j++){}
            goto parse_number_finish;
          }
        }
      }
    }
  parse_number_2:
    for(j=i+1;; j++){
      c = z[j];
      if( sqlite3Isdigit(c) ) continue;
      if( c=='.' ){
        if( seenDP==JSON_REAL ){
          pParse->iErr = j;
          return -1;
        }
        seenDP = JSON_REAL;
        continue;
      }
      if( c=='e' || c=='E' ){
        if( z[j-1]<'0' ){
          if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){
            pParse->hasNonstd = 1;
            jnFlags |= JNODE_JSON5;
          }else{
            pParse->iErr = j;
            return -1;
          }
        }
        if( seenE ){
          pParse->iErr = j;
          return -1;
        }
        seenDP = JSON_REAL;
        seenE = 1;
        c = z[j+1];
        if( c=='+' || c=='-' ){
          j++;
          c = z[j+1];
        }
        if( c<'0' || c>'9' ){
          pParse->iErr = j;
          return -1;
        }
        continue;
      }
      break;
    }
    if( z[j-1]<'0' ){
      if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){
        pParse->hasNonstd = 1;
        jnFlags |= JNODE_JSON5;
      }else{
        pParse->iErr = j;
        return -1;
      }
    }
  parse_number_finish:
    jsonParseAddNode(pParse, seenDP | (jnFlags<<8), j - i, &z[i]);
    return j;
  }
  case '}': {
    pParse->iErr = i;
    return -2;  /* End of {...} */
  }
  case ']': {
    pParse->iErr = i;
    return -3;  /* End of [...] */
  }
  case ',': {
    pParse->iErr = i;
    return -4;  /* List separator */
  }
  case ':': {
    pParse->iErr = i;
    return -5;  /* Object label/value separator */
  }
  case 0: {
    return 0;   /* End of file */
  }
  case 0x09:
  case 0x0a:
  case 0x0d:
  case 0x20: {
    do{
      i++;
    }while( fast_isspace(z[i]) );
    goto json_parse_restart;
  }
  case 0x0b:
  case 0x0c:
  case '/':
  case 0xc2:
  case 0xe1:
  case 0xe2:
  case 0xe3:
  case 0xef: {
    j = json5Whitespace(&z[i]);
    if( j>0 ){
      i += j;
      pParse->hasNonstd = 1;
      goto json_parse_restart;
    }
    pParse->iErr = i;
    return -1;
  }
  case 'n': {
    if( strncmp(z+i,"null",4)==0 && !sqlite3Isalnum(z[i+4]) ){
      jsonParseAddNode(pParse, JSON_NULL, 0, 0);
      return i+4;
    }
    /* fall-through into the default case that checks for NaN */
  }
  default: {
    u32 k;
    int nn;
    c = z[i];
    for(k=0; k<sizeof(aNanInfName)/sizeof(aNanInfName[0]); k++){
      if( c!=aNanInfName[k].c1 && c!=aNanInfName[k].c2 ) continue;
      nn = aNanInfName[k].n;
      if( sqlite3StrNICmp(&z[i], aNanInfName[k].zMatch, nn)!=0 ){
        continue;
      }


      if( sqlite3Isalnum(z[i+nn]) ) continue;
      jsonParseAddNode(pParse, aNanInfName[k].eType,

          aNanInfName[k].nRepl, aNanInfName[k].zRepl);
      pParse->hasNonstd = 1;
      return i + nn;






    }
    pParse->iErr = i;
    return -1;  /* Syntax error */
  }
  } /* End switch(z[i]) */
}

/*
** Parse a complete JSON string.  Return 0 on success or non-zero if there
** are any errors.  If an error occurs, free all memory associated with
** pParse.
**
199698
199699
199700
199701
199702
199703
199704
199705







199706
199707
199708
199709
199710
199711
199712
  if( zJson==0 ) return 1;
  pParse->zJson = zJson;
  i = jsonParseValue(pParse, 0);
  if( pParse->oom ) i = -1;
  if( i>0 ){
    assert( pParse->iDepth==0 );
    while( fast_isspace(zJson[i]) ) i++;
    if( zJson[i] ) i = -1;







  }
  if( i<=0 ){
    if( pCtx!=0 ){
      if( pParse->oom ){
        sqlite3_result_error_nomem(pCtx);
      }else{
        sqlite3_result_error(pCtx, "malformed JSON", -1);







|
>
>
>
>
>
>
>







201239
201240
201241
201242
201243
201244
201245
201246
201247
201248
201249
201250
201251
201252
201253
201254
201255
201256
201257
201258
201259
201260
  if( zJson==0 ) return 1;
  pParse->zJson = zJson;
  i = jsonParseValue(pParse, 0);
  if( pParse->oom ) i = -1;
  if( i>0 ){
    assert( pParse->iDepth==0 );
    while( fast_isspace(zJson[i]) ) i++;
    if( zJson[i] ){
      i += json5Whitespace(&zJson[i]);
      if( zJson[i] ){
        jsonParseReset(pParse);
        return 1;
      }
      pParse->hasNonstd = 1;
    }
  }
  if( i<=0 ){
    if( pCtx!=0 ){
      if( pParse->oom ){
        sqlite3_result_error_nomem(pCtx);
      }else{
        sqlite3_result_error(pCtx, "malformed JSON", -1);
199769
199770
199771
199772
199773
199774
199775









199776
199777
199778
199779
199780
199781
199782
/*
** Obtain a complete parse of the JSON found in the first argument
** of the argv array.  Use the sqlite3_get_auxdata() cache for this
** parse if it is available.  If the cache is not available or if it
** is no longer valid, parse the JSON again and return the new parse,
** and also register the new parse so that it will be available for
** future sqlite3_get_auxdata() calls.









*/
static JsonParse *jsonParseCached(
  sqlite3_context *pCtx,
  sqlite3_value **argv,
  sqlite3_context *pErrCtx
){
  const char *zJson = (const char*)sqlite3_value_text(argv[0]);







>
>
>
>
>
>
>
>
>







201317
201318
201319
201320
201321
201322
201323
201324
201325
201326
201327
201328
201329
201330
201331
201332
201333
201334
201335
201336
201337
201338
201339
/*
** Obtain a complete parse of the JSON found in the first argument
** of the argv array.  Use the sqlite3_get_auxdata() cache for this
** parse if it is available.  If the cache is not available or if it
** is no longer valid, parse the JSON again and return the new parse,
** and also register the new parse so that it will be available for
** future sqlite3_get_auxdata() calls.
**
** If an error occurs and pErrCtx!=0 then report the error on pErrCtx
** and return NULL.
**
** If an error occurs and pErrCtx==0 then return the Parse object with
** JsonParse.nErr non-zero.  If the caller invokes this routine with
** pErrCtx==0 and it gets back a JsonParse with nErr!=0, then the caller
** is responsible for invoking jsonParseFree() on the returned value.
** But the caller may invoke jsonParseFree() *only* if pParse->nErr!=0.
*/
static JsonParse *jsonParseCached(
  sqlite3_context *pCtx,
  sqlite3_value **argv,
  sqlite3_context *pErrCtx
){
  const char *zJson = (const char*)sqlite3_value_text(argv[0]);
199818
199819
199820
199821
199822
199823
199824




199825
199826
199827
199828
199829
199830
199831
199832
199833
199834
199835
199836
199837
199838
199839
199840
199841
199842
199843
199844
199845
199846
199847









199848
199849
199850
199851
199852
199853
199854
    sqlite3_result_error_nomem(pCtx);
    return 0;
  }
  memset(p, 0, sizeof(*p));
  p->zJson = (char*)&p[1];
  memcpy((char*)p->zJson, zJson, nJson+1);
  if( jsonParse(p, pErrCtx, p->zJson) ){




    sqlite3_free(p);
    return 0;
  }
  p->nJson = nJson;
  p->iHold = iMaxHold+1;
  sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
                      (void(*)(void*))jsonParseFree);
  return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
}

/*
** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
** a match.
*/
static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  assert( pNode->eU==1 );
  if( pNode->jnFlags & JNODE_RAW ){
    if( pNode->n!=nKey ) return 0;
    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  }else{
    if( pNode->n!=nKey+2 ) return 0;
    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  }









}

/* forward declaration */
static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);

/*
** Search along zPath to find the node specified.  Return a pointer







>
>
>
>














|








>
>
>
>
>
>
>
>
>







201375
201376
201377
201378
201379
201380
201381
201382
201383
201384
201385
201386
201387
201388
201389
201390
201391
201392
201393
201394
201395
201396
201397
201398
201399
201400
201401
201402
201403
201404
201405
201406
201407
201408
201409
201410
201411
201412
201413
201414
201415
201416
201417
201418
201419
201420
201421
201422
201423
201424
    sqlite3_result_error_nomem(pCtx);
    return 0;
  }
  memset(p, 0, sizeof(*p));
  p->zJson = (char*)&p[1];
  memcpy((char*)p->zJson, zJson, nJson+1);
  if( jsonParse(p, pErrCtx, p->zJson) ){
    if( pErrCtx==0 ){
      p->nErr = 1;
      return p;
    }
    sqlite3_free(p);
    return 0;
  }
  p->nJson = nJson;
  p->iHold = iMaxHold+1;
  sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
                      (void(*)(void*))jsonParseFree);
  return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
}

/*
** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
** a match.
*/
static int jsonLabelCompare(const JsonNode *pNode, const char *zKey, u32 nKey){
  assert( pNode->eU==1 );
  if( pNode->jnFlags & JNODE_RAW ){
    if( pNode->n!=nKey ) return 0;
    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  }else{
    if( pNode->n!=nKey+2 ) return 0;
    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  }
}
static int jsonSameLabel(const JsonNode *p1, const JsonNode *p2){
  if( p1->jnFlags & JNODE_RAW ){
    return jsonLabelCompare(p2, p1->u.zJContent, p1->n);
  }else if( p2->jnFlags & JNODE_RAW ){
    return jsonLabelCompare(p1, p2->u.zJContent, p2->n);
  }else{
    return p1->n==p2->n && strncmp(p1->u.zJContent,p2->u.zJContent,p1->n)==0;
  }
}

/* forward declaration */
static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);

/*
** Search along zPath to find the node specified.  Return a pointer
200312
200313
200314
200315
200316
200317
200318
200319
200320
200321
200322
200323
200324
200325
200326
  p = jsonParseCached(ctx, argv, ctx);
  if( p==0 ) return;
  if( argc==2 ){
    /* With a single PATH argument */
    zPath = (const char*)sqlite3_value_text(argv[1]);
    if( zPath==0 ) return;
    if( flags & JSON_ABPATH ){
      if( zPath[0]!='$' ){
        /* The -> and ->> operators accept abbreviated PATH arguments.  This
        ** is mostly for compatibility with PostgreSQL, but also for
        ** convenience.
        **
        **     NUMBER   ==>  $[NUMBER]     // PG compatible
        **     LABEL    ==>  $.LABEL       // PG compatible
        **     [NUMBER] ==>  $[NUMBER]     // Not PG.  Purely for convenience







|







201882
201883
201884
201885
201886
201887
201888
201889
201890
201891
201892
201893
201894
201895
201896
  p = jsonParseCached(ctx, argv, ctx);
  if( p==0 ) return;
  if( argc==2 ){
    /* With a single PATH argument */
    zPath = (const char*)sqlite3_value_text(argv[1]);
    if( zPath==0 ) return;
    if( flags & JSON_ABPATH ){
      if( zPath[0]!='$' || (zPath[1]!='.' && zPath[1]!='[' && zPath[1]!=0) ){
        /* The -> and ->> operators accept abbreviated PATH arguments.  This
        ** is mostly for compatibility with PostgreSQL, but also for
        ** convenience.
        **
        **     NUMBER   ==>  $[NUMBER]     // PG compatible
        **     LABEL    ==>  $.LABEL       // PG compatible
        **     [NUMBER] ==>  $[NUMBER]     // Not PG.  Purely for convenience
200403
200404
200405
200406
200407
200408
200409
200410
200411
200412
200413
200414
200415
200416
200417
200418
200419
200420
200421
200422
    u32 nKey;
    const char *zKey;
    assert( pPatch[i].eType==JSON_STRING );
    assert( pPatch[i].jnFlags & JNODE_LABEL );
    assert( pPatch[i].eU==1 );
    nKey = pPatch[i].n;
    zKey = pPatch[i].u.zJContent;
    assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
    for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
      assert( pTarget[j].eType==JSON_STRING );
      assert( pTarget[j].jnFlags & JNODE_LABEL );
      assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
      if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
        if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
        if( pPatch[i+1].eType==JSON_NULL ){
          pTarget[j+1].jnFlags |= JNODE_REMOVE;
        }else{
          JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
          if( pNew==0 ) return 0;
          pTarget = &pParse->aNode[iTarget];







<



|
<







201973
201974
201975
201976
201977
201978
201979

201980
201981
201982
201983

201984
201985
201986
201987
201988
201989
201990
    u32 nKey;
    const char *zKey;
    assert( pPatch[i].eType==JSON_STRING );
    assert( pPatch[i].jnFlags & JNODE_LABEL );
    assert( pPatch[i].eU==1 );
    nKey = pPatch[i].n;
    zKey = pPatch[i].u.zJContent;

    for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
      assert( pTarget[j].eType==JSON_STRING );
      assert( pTarget[j].jnFlags & JNODE_LABEL );
      if( jsonSameLabel(&pPatch[i], &pTarget[j]) ){

        if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
        if( pPatch[i+1].eType==JSON_NULL ){
          pTarget[j+1].jnFlags |= JNODE_REMOVE;
        }else{
          JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
          if( pNew==0 ) return 0;
          pTarget = &pParse->aNode[iTarget];
200695
200696
200697
200698
200699
200700
200701
200702
200703
200704
200705
200706
200707
200708
200709
200710
200711

200712


















































200713










200714
200715
200716
200717
200718
200719
200720
    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  }
}

/*
** json_valid(JSON)
**
** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
** Return 0 otherwise.
*/
static void jsonValidFunc(
  sqlite3_context *ctx,
  int argc,
  sqlite3_value **argv
){
  JsonParse *p;          /* The parse */
  UNUSED_PARAMETER(argc);

  p = jsonParseCached(ctx, argv, 0);


















































  sqlite3_result_int(ctx, p!=0);










}


/****************************************************************************
** Aggregate SQL function implementations
****************************************************************************/
/*







|
|








>

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







202263
202264
202265
202266
202267
202268
202269
202270
202271
202272
202273
202274
202275
202276
202277
202278
202279
202280
202281
202282
202283
202284
202285
202286
202287
202288
202289
202290
202291
202292
202293
202294
202295
202296
202297
202298
202299
202300
202301
202302
202303
202304
202305
202306
202307
202308
202309
202310
202311
202312
202313
202314
202315
202316
202317
202318
202319
202320
202321
202322
202323
202324
202325
202326
202327
202328
202329
202330
202331
202332
202333
202334
202335
202336
202337
202338
202339
202340
202341
202342
202343
202344
202345
202346
202347
202348
202349
    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  }
}

/*
** json_valid(JSON)
**
** Return 1 if JSON is a well-formed canonical JSON string according
** to RFC-7159. Return 0 otherwise.
*/
static void jsonValidFunc(
  sqlite3_context *ctx,
  int argc,
  sqlite3_value **argv
){
  JsonParse *p;          /* The parse */
  UNUSED_PARAMETER(argc);
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  p = jsonParseCached(ctx, argv, 0);
  if( p==0 || p->oom ){
    sqlite3_result_error_nomem(ctx);
    sqlite3_free(p);
  }else{
    sqlite3_result_int(ctx, p->nErr==0 && p->hasNonstd==0);
    if( p->nErr ) jsonParseFree(p);
  }
}

/*
** json_error_position(JSON)
**
** If the argument is not an interpretable JSON string, then return the 1-based
** character position at which the parser first recognized that the input
** was in error.  The left-most character is 1.  If the string is valid
** JSON, then return 0.
**
** Note that json_valid() is only true for strictly conforming canonical JSON.
** But this routine returns zero if the input contains extension.  Thus:
**
** (1) If the input X is strictly conforming canonical JSON:
**
**         json_valid(X) returns true
**         json_error_position(X) returns 0
**
** (2) If the input X is JSON but it includes extension (such as JSON5) that
**     are not part of RFC-8259:
**
**         json_valid(X) returns false
**         json_error_position(X) return 0
**
** (3) If the input X cannot be interpreted as JSON even taking extensions
**     into account:
**
**         json_valid(X) return false
**         json_error_position(X) returns 1 or more
*/
static void jsonErrorFunc(
  sqlite3_context *ctx,
  int argc,
  sqlite3_value **argv
){
  JsonParse *p;          /* The parse */
  UNUSED_PARAMETER(argc);
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  p = jsonParseCached(ctx, argv, 0);
  if( p==0 || p->oom ){
    sqlite3_result_error_nomem(ctx);
    sqlite3_free(p);
  }else if( p->nErr==0 ){
    sqlite3_result_int(ctx, 0);
  }else{
    int n = 1;
    u32 i;
    const char *z = p->zJson;
    for(i=0; i<p->iErr && ALWAYS(z[i]); i++){
      if( (z[i]&0xc0)!=0x80 ) n++;
    }
    sqlite3_result_int(ctx, n);
    jsonParseFree(p);
  }
}


/****************************************************************************
** Aggregate SQL function implementations
****************************************************************************/
/*
201050
201051
201052
201053
201054
201055
201056

201057
201058
201059
201060
201061
201062
201063
201064

201065
201066
201067
201068
201069
201070
201071
  int jj, nn;
  const char *z;
  assert( pNode->eType==JSON_STRING );
  assert( pNode->jnFlags & JNODE_LABEL );
  assert( pNode->eU==1 );
  z = pNode->u.zJContent;
  nn = pNode->n;

  assert( nn>=2 );
  assert( z[0]=='"' );
  assert( z[nn-1]=='"' );
  if( nn>2 && sqlite3Isalpha(z[1]) ){
    for(jj=2; jj<nn-1 && sqlite3Isalnum(z[jj]); jj++){}
    if( jj==nn-1 ){
      z++;
      nn -= 2;

    }
  }
  jsonPrintf(nn+2, pStr, ".%.*s", nn, z);
}

/* Append the name of the path for element i to pStr
*/







>
|
|
|
|
|
|
|
|
>







202679
202680
202681
202682
202683
202684
202685
202686
202687
202688
202689
202690
202691
202692
202693
202694
202695
202696
202697
202698
202699
202700
202701
202702
  int jj, nn;
  const char *z;
  assert( pNode->eType==JSON_STRING );
  assert( pNode->jnFlags & JNODE_LABEL );
  assert( pNode->eU==1 );
  z = pNode->u.zJContent;
  nn = pNode->n;
  if( (pNode->jnFlags & JNODE_RAW)==0 ){
    assert( nn>=2 );
    assert( z[0]=='"' || z[0]=='\'' );
    assert( z[nn-1]=='"' || z[0]=='\'' );
    if( nn>2 && sqlite3Isalpha(z[1]) ){
      for(jj=2; jj<nn-1 && sqlite3Isalnum(z[jj]); jj++){}
      if( jj==nn-1 ){
        z++;
        nn -= 2;
      }
    }
  }
  jsonPrintf(nn+2, pStr, ".%.*s", nn, z);
}

/* Append the name of the path for element i to pStr
*/
201417
201418
201419
201420
201421
201422
201423

201424
201425
201426
201427
201428
201429
201430
SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){
#ifndef SQLITE_OMIT_JSON
  static FuncDef aJsonFunc[] = {
    JFUNCTION(json,               1, 0,  jsonRemoveFunc),
    JFUNCTION(json_array,        -1, 0,  jsonArrayFunc),
    JFUNCTION(json_array_length,  1, 0,  jsonArrayLengthFunc),
    JFUNCTION(json_array_length,  2, 0,  jsonArrayLengthFunc),

    JFUNCTION(json_extract,      -1, 0,  jsonExtractFunc),
    JFUNCTION(->,                 2, JSON_JSON, jsonExtractFunc),
    JFUNCTION(->>,                2, JSON_SQL, jsonExtractFunc),
    JFUNCTION(json_insert,       -1, 0,  jsonSetFunc),
    JFUNCTION(json_object,       -1, 0,  jsonObjectFunc),
    JFUNCTION(json_patch,         2, 0,  jsonPatchFunc),
    JFUNCTION(json_quote,         1, 0,  jsonQuoteFunc),







>







203048
203049
203050
203051
203052
203053
203054
203055
203056
203057
203058
203059
203060
203061
203062
SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){
#ifndef SQLITE_OMIT_JSON
  static FuncDef aJsonFunc[] = {
    JFUNCTION(json,               1, 0,  jsonRemoveFunc),
    JFUNCTION(json_array,        -1, 0,  jsonArrayFunc),
    JFUNCTION(json_array_length,  1, 0,  jsonArrayLengthFunc),
    JFUNCTION(json_array_length,  2, 0,  jsonArrayLengthFunc),
    JFUNCTION(json_error_position,1, 0,  jsonErrorFunc),
    JFUNCTION(json_extract,      -1, 0,  jsonExtractFunc),
    JFUNCTION(->,                 2, JSON_JSON, jsonExtractFunc),
    JFUNCTION(->>,                2, JSON_SQL, jsonExtractFunc),
    JFUNCTION(json_insert,       -1, 0,  jsonSetFunc),
    JFUNCTION(json_object,       -1, 0,  jsonObjectFunc),
    JFUNCTION(json_patch,         2, 0,  jsonPatchFunc),
    JFUNCTION(json_quote,         1, 0,  jsonQuoteFunc),
201941
201942
201943
201944
201945
201946
201947
201948
201949
201950
201951
201952
201953

201954
201955
201956
201957
201958
201959
201960
201961
201962
201963
201964
**
** For best performance, an attempt is made to guess at the byte-order
** using C-preprocessor macros.  If that is unsuccessful, or if
** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
** at run-time.
*/
#ifndef SQLITE_BYTEORDER
#if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
    defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
    defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
    defined(__arm__)
# define SQLITE_BYTEORDER    1234
#elif defined(sparc)    || defined(__ppc__)

# define SQLITE_BYTEORDER    4321
#else
# define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
#endif
#endif


/* What version of MSVC is being used.  0 means MSVC is not being used */
#ifndef MSVC_VERSION
#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
# define MSVC_VERSION _MSC_VER







|
|
|
|
|
|
>
|
|
|
|







203573
203574
203575
203576
203577
203578
203579
203580
203581
203582
203583
203584
203585
203586
203587
203588
203589
203590
203591
203592
203593
203594
203595
203596
203597
**
** For best performance, an attempt is made to guess at the byte-order
** using C-preprocessor macros.  If that is unsuccessful, or if
** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
** at run-time.
*/
#ifndef SQLITE_BYTEORDER
# if defined(i386)      || defined(__i386__)      || defined(_M_IX86) ||    \
     defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \
     defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \
     defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
#   define SQLITE_BYTEORDER    1234
# elif defined(sparc)     || defined(__ppc__) || \
       defined(__ARMEB__) || defined(__AARCH64EB__)
#   define SQLITE_BYTEORDER    4321
# else
#   define SQLITE_BYTEORDER 0
# endif
#endif


/* What version of MSVC is being used.  0 means MSVC is not being used */
#ifndef MSVC_VERSION
#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
# define MSVC_VERSION _MSC_VER
212495
212496
212497
212498
212499
212500
212501





212502
212503
212504
212505
212506
212507
212508
212509



212510



212511





212512
212513
212514
212515
212516
212517
212518
212519
  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  if( p->rc ) return;

  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
}







/*
** Take an EXCLUSIVE lock on the database file. Return SQLITE_OK if
** successful, or an SQLite error code otherwise.
*/
static int rbuLockDatabase(sqlite3 *db){
  int rc = SQLITE_OK;
  sqlite3_file *fd = 0;



  sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);









  if( fd->pMethods ){
    rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
    if( rc==SQLITE_OK ){
      rc = fd->pMethods->xLock(fd, SQLITE_LOCK_EXCLUSIVE);
    }
  }
  return rc;
}







>
>
>
>
>








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







214128
214129
214130
214131
214132
214133
214134
214135
214136
214137
214138
214139
214140
214141
214142
214143
214144
214145
214146
214147
214148
214149
214150
214151
214152
214153
214154
214155
214156
214157
214158
214159
214160
214161
214162
214163
214164
214165
214166
214167
214168
  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  if( p->rc ) return;

  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
}

/*
** This value is copied from the definition of ZIPVFS_CTRL_FILE_POINTER
** in zipvfs.h.
*/
#define RBU_ZIPVFS_CTRL_FILE_POINTER 230439

/*
** Take an EXCLUSIVE lock on the database file. Return SQLITE_OK if
** successful, or an SQLite error code otherwise.
*/
static int rbuLockDatabase(sqlite3 *db){
  int rc = SQLITE_OK;
  sqlite3_file *fd = 0;

  sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
  if( fd ){
    sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
    rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
    if( rc==SQLITE_OK ){
      rc = fd->pMethods->xUnlock(fd, SQLITE_LOCK_NONE);
    }
    sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
  }else{
    sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
  }

  if( rc==SQLITE_OK && fd->pMethods ){
    rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
    if( rc==SQLITE_OK ){
      rc = fd->pMethods->xLock(fd, SQLITE_LOCK_EXCLUSIVE);
    }
  }
  return rc;
}
215742
215743
215744
215745
215746
215747
215748

215749
215750
215751
215752
215753
215754
215755
  int rc = SQLITE_OK;
  (void)pAux;
  (void)argc;
  (void)argv;
  (void)pzErr;

  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);

  rc = sqlite3_declare_vtab(db,
          "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  if( rc==SQLITE_OK ){
    pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  }








>







217391
217392
217393
217394
217395
217396
217397
217398
217399
217400
217401
217402
217403
217404
217405
  int rc = SQLITE_OK;
  (void)pAux;
  (void)argc;
  (void)argv;
  (void)pzErr;

  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
  rc = sqlite3_declare_vtab(db,
          "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  if( rc==SQLITE_OK ){
    pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  }

215825
215826
215827
215828
215829
215830
215831
215832
215833
215834
215835
215836
215837
215838
215839

  if( pIdxInfo->nOrderBy>=1
   && pIdxInfo->aOrderBy[0].iColumn<=0
   && pIdxInfo->aOrderBy[0].desc==0
  ){
    pIdxInfo->orderByConsumed = 1;
  }
  sqlite3VtabUsesAllSchemas(pIdxInfo);
  return SQLITE_OK;
}

/*
** Open a new dbpagevfs cursor.
*/
static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){







<







217475
217476
217477
217478
217479
217480
217481

217482
217483
217484
217485
217486
217487
217488

  if( pIdxInfo->nOrderBy>=1
   && pIdxInfo->aOrderBy[0].iColumn<=0
   && pIdxInfo->aOrderBy[0].desc==0
  ){
    pIdxInfo->orderByConsumed = 1;
  }

  return SQLITE_OK;
}

/*
** Open a new dbpagevfs cursor.
*/
static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
216125
216126
216127
216128
216129
216130
216131


216132
216133
216134
216135
216136
216137
216138
#ifndef SESSIONS_STRM_CHUNK_SIZE
# ifdef SQLITE_TEST
#   define SESSIONS_STRM_CHUNK_SIZE 64
# else
#   define SESSIONS_STRM_CHUNK_SIZE 1024
# endif
#endif



static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;

typedef struct SessionHook SessionHook;
struct SessionHook {
  void *pCtx;
  int (*xOld)(void*,int,sqlite3_value**);







>
>







217774
217775
217776
217777
217778
217779
217780
217781
217782
217783
217784
217785
217786
217787
217788
217789
#ifndef SESSIONS_STRM_CHUNK_SIZE
# ifdef SQLITE_TEST
#   define SESSIONS_STRM_CHUNK_SIZE 64
# else
#   define SESSIONS_STRM_CHUNK_SIZE 1024
# endif
#endif

#define SESSIONS_ROWID "_rowid_"

static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;

typedef struct SessionHook SessionHook;
struct SessionHook {
  void *pCtx;
  int (*xOld)(void*,int,sqlite3_value**);
216147
216148
216149
216150
216151
216152
216153

216154
216155
216156
216157
216158
216159
216160
struct sqlite3_session {
  sqlite3 *db;                    /* Database handle session is attached to */
  char *zDb;                      /* Name of database session is attached to */
  int bEnableSize;                /* True if changeset_size() enabled */
  int bEnable;                    /* True if currently recording */
  int bIndirect;                  /* True if all changes are indirect */
  int bAutoAttach;                /* True to auto-attach tables */

  int rc;                         /* Non-zero if an error has occurred */
  void *pFilterCtx;               /* First argument to pass to xTableFilter */
  int (*xTableFilter)(void *pCtx, const char *zTab);
  i64 nMalloc;                    /* Number of bytes of data allocated */
  i64 nMaxChangesetSize;
  sqlite3_value *pZeroBlob;       /* Value containing X'' */
  sqlite3_session *pNext;         /* Next session object on same db. */







>







217798
217799
217800
217801
217802
217803
217804
217805
217806
217807
217808
217809
217810
217811
217812
struct sqlite3_session {
  sqlite3 *db;                    /* Database handle session is attached to */
  char *zDb;                      /* Name of database session is attached to */
  int bEnableSize;                /* True if changeset_size() enabled */
  int bEnable;                    /* True if currently recording */
  int bIndirect;                  /* True if all changes are indirect */
  int bAutoAttach;                /* True to auto-attach tables */
  int bImplicitPK;                /* True to handle tables with implicit PK */
  int rc;                         /* Non-zero if an error has occurred */
  void *pFilterCtx;               /* First argument to pass to xTableFilter */
  int (*xTableFilter)(void *pCtx, const char *zTab);
  i64 nMalloc;                    /* Number of bytes of data allocated */
  i64 nMaxChangesetSize;
  sqlite3_value *pZeroBlob;       /* Value containing X'' */
  sqlite3_session *pNext;         /* Next session object on same db. */
216223
216224
216225
216226
216227
216228
216229

216230
216231
216232
216233
216234
216235
216236
** start of the session. Or no initial values if the row was inserted.
*/
struct SessionTable {
  SessionTable *pNext;
  char *zName;                    /* Local name of table */
  int nCol;                       /* Number of columns in table zName */
  int bStat1;                     /* True if this is sqlite_stat1 */

  const char **azCol;             /* Column names */
  u8 *abPK;                       /* Array of primary key flags */
  int nEntry;                     /* Total number of entries in hash table */
  int nChange;                    /* Size of apChange[] array */
  SessionChange **apChange;       /* Hash table buckets */
};








>







217875
217876
217877
217878
217879
217880
217881
217882
217883
217884
217885
217886
217887
217888
217889
** start of the session. Or no initial values if the row was inserted.
*/
struct SessionTable {
  SessionTable *pNext;
  char *zName;                    /* Local name of table */
  int nCol;                       /* Number of columns in table zName */
  int bStat1;                     /* True if this is sqlite_stat1 */
  int bRowid;                     /* True if this table uses rowid for PK */
  const char **azCol;             /* Column names */
  u8 *abPK;                       /* Array of primary key flags */
  int nEntry;                     /* Total number of entries in hash table */
  int nChange;                    /* Size of apChange[] array */
  SessionChange **apChange;       /* Hash table buckets */
};

216615
216616
216617
216618
216619
216620
216621

216622
216623
216624
216625
216626
216627
216628
216629




216630
216631
216632
216633
216634
216635
216636
216637
216638
216639
216640
216641
216642
216643
216644
216645
216646
216647
216648
216649
216650
216651
216652
216653
216654
216655
216656
216657
216658
216659
216660
216661
216662
216663
216664
216665
216666
216667
216668
216669
216670
216671

216672
216673
216674
216675
216676
216677
216678
**
** If an error occurs, an SQLite error code is returned and the final values
** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
** and the output variables are set as described above.
*/
static int sessionPreupdateHash(
  sqlite3_session *pSession,      /* Session object that owns pTab */

  SessionTable *pTab,             /* Session table handle */
  int bNew,                       /* True to hash the new.* PK */
  int *piHash,                    /* OUT: Hash value */
  int *pbNullPK                   /* OUT: True if there are NULL values in PK */
){
  unsigned int h = 0;             /* Hash value to return */
  int i;                          /* Used to iterate through columns */





  assert( *pbNullPK==0 );
  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  for(i=0; i<pTab->nCol; i++){
    if( pTab->abPK[i] ){
      int rc;
      int eType;
      sqlite3_value *pVal;

      if( bNew ){
        rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
      }else{
        rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
      }
      if( rc!=SQLITE_OK ) return rc;

      eType = sqlite3_value_type(pVal);
      h = sessionHashAppendType(h, eType);
      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
        i64 iVal;
        if( eType==SQLITE_INTEGER ){
          iVal = sqlite3_value_int64(pVal);
        }else{
          double rVal = sqlite3_value_double(pVal);
          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
          memcpy(&iVal, &rVal, 8);
        }
        h = sessionHashAppendI64(h, iVal);
      }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
        const u8 *z;
        int n;
        if( eType==SQLITE_TEXT ){
          z = (const u8 *)sqlite3_value_text(pVal);
        }else{
          z = (const u8 *)sqlite3_value_blob(pVal);
        }
        n = sqlite3_value_bytes(pVal);
        if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
        h = sessionHashAppendBlob(h, n, z);
      }else{
        assert( eType==SQLITE_NULL );
        assert( pTab->bStat1==0 || i!=1 );
        *pbNullPK = 1;

      }
    }
  }

  *piHash = (h % pTab->nChange);
  return SQLITE_OK;
}







>








>
>
>
>
|
|
|
|
|
|
|

|
|
|
|
|
|

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







218268
218269
218270
218271
218272
218273
218274
218275
218276
218277
218278
218279
218280
218281
218282
218283
218284
218285
218286
218287
218288
218289
218290
218291
218292
218293
218294
218295
218296
218297
218298
218299
218300
218301
218302
218303
218304
218305
218306
218307
218308
218309
218310
218311
218312
218313
218314
218315
218316
218317
218318
218319
218320
218321
218322
218323
218324
218325
218326
218327
218328
218329
218330
218331
218332
218333
218334
218335
218336
218337
**
** If an error occurs, an SQLite error code is returned and the final values
** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
** and the output variables are set as described above.
*/
static int sessionPreupdateHash(
  sqlite3_session *pSession,      /* Session object that owns pTab */
  i64 iRowid,
  SessionTable *pTab,             /* Session table handle */
  int bNew,                       /* True to hash the new.* PK */
  int *piHash,                    /* OUT: Hash value */
  int *pbNullPK                   /* OUT: True if there are NULL values in PK */
){
  unsigned int h = 0;             /* Hash value to return */
  int i;                          /* Used to iterate through columns */

  if( pTab->bRowid ){
    assert( pTab->nCol-1==pSession->hook.xCount(pSession->hook.pCtx) );
    h = sessionHashAppendI64(h, iRowid);
  }else{
    assert( *pbNullPK==0 );
    assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
    for(i=0; i<pTab->nCol; i++){
      if( pTab->abPK[i] ){
        int rc;
        int eType;
        sqlite3_value *pVal;

        if( bNew ){
          rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
        }else{
          rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
        }
        if( rc!=SQLITE_OK ) return rc;

        eType = sqlite3_value_type(pVal);
        h = sessionHashAppendType(h, eType);
        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
          i64 iVal;
          if( eType==SQLITE_INTEGER ){
            iVal = sqlite3_value_int64(pVal);
          }else{
            double rVal = sqlite3_value_double(pVal);
            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
            memcpy(&iVal, &rVal, 8);
          }
          h = sessionHashAppendI64(h, iVal);
        }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
          const u8 *z;
          int n;
          if( eType==SQLITE_TEXT ){
            z = (const u8 *)sqlite3_value_text(pVal);
          }else{
            z = (const u8 *)sqlite3_value_blob(pVal);
          }
          n = sqlite3_value_bytes(pVal);
          if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
          h = sessionHashAppendBlob(h, n, z);
        }else{
          assert( eType==SQLITE_NULL );
          assert( pTab->bStat1==0 || i!=1 );
          *pbNullPK = 1;
        }
      }
    }
  }

  *piHash = (h % pTab->nChange);
  return SQLITE_OK;
}
216947
216948
216949
216950
216951
216952
216953

216954
216955
216956
216957
216958
216959





216960
216961
216962
216963
216964
216965
216966
** It determines if the current pre-update-hook change affects the same row
** as the change stored in argument pChange. If so, it returns true. Otherwise
** if the pre-update-hook does not affect the same row as pChange, it returns
** false.
*/
static int sessionPreupdateEqual(
  sqlite3_session *pSession,      /* Session object that owns SessionTable */

  SessionTable *pTab,             /* Table associated with change */
  SessionChange *pChange,         /* Change to compare to */
  int op                          /* Current pre-update operation */
){
  int iCol;                       /* Used to iterate through columns */
  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */






  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  for(iCol=0; iCol<pTab->nCol; iCol++){
    if( !pTab->abPK[iCol] ){
      a += sessionSerialLen(a);
    }else{
      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */







>






>
>
>
>
>







218606
218607
218608
218609
218610
218611
218612
218613
218614
218615
218616
218617
218618
218619
218620
218621
218622
218623
218624
218625
218626
218627
218628
218629
218630
218631
** It determines if the current pre-update-hook change affects the same row
** as the change stored in argument pChange. If so, it returns true. Otherwise
** if the pre-update-hook does not affect the same row as pChange, it returns
** false.
*/
static int sessionPreupdateEqual(
  sqlite3_session *pSession,      /* Session object that owns SessionTable */
  i64 iRowid,                     /* Rowid value if pTab->bRowid */
  SessionTable *pTab,             /* Table associated with change */
  SessionChange *pChange,         /* Change to compare to */
  int op                          /* Current pre-update operation */
){
  int iCol;                       /* Used to iterate through columns */
  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */

  if( pTab->bRowid ){
    if( a[0]!=SQLITE_INTEGER ) return 0;
    return sessionGetI64(&a[1])==iRowid;
  }

  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  for(iCol=0; iCol<pTab->nCol; iCol++){
    if( !pTab->abPK[iCol] ){
      a += sessionSerialLen(a);
    }else{
      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
217098
217099
217100
217101
217102
217103
217104
217105

217106
217107
217108
217109
217110
217111
217112
217113
217114
217115
217116

217117
217118
217119
217120
217121
217122
217123
  sqlite3_session *pSession,      /* For memory accounting. May be NULL */
  sqlite3 *db,                    /* Database connection */
  const char *zDb,                /* Name of attached database (e.g. "main") */
  const char *zThis,              /* Table name */
  int *pnCol,                     /* OUT: number of columns */
  const char **pzTab,             /* OUT: Copy of zThis */
  const char ***pazCol,           /* OUT: Array of column names for table */
  u8 **pabPK                      /* OUT: Array of booleans - true for PK col */

){
  char *zPragma;
  sqlite3_stmt *pStmt;
  int rc;
  sqlite3_int64 nByte;
  int nDbCol = 0;
  int nThis;
  int i;
  u8 *pAlloc = 0;
  char **azCol = 0;
  u8 *abPK = 0;


  assert( pazCol && pabPK );

  nThis = sqlite3Strlen30(zThis);
  if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
    rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
    if( rc==SQLITE_OK ){







|
>











>







218763
218764
218765
218766
218767
218768
218769
218770
218771
218772
218773
218774
218775
218776
218777
218778
218779
218780
218781
218782
218783
218784
218785
218786
218787
218788
218789
218790
  sqlite3_session *pSession,      /* For memory accounting. May be NULL */
  sqlite3 *db,                    /* Database connection */
  const char *zDb,                /* Name of attached database (e.g. "main") */
  const char *zThis,              /* Table name */
  int *pnCol,                     /* OUT: number of columns */
  const char **pzTab,             /* OUT: Copy of zThis */
  const char ***pazCol,           /* OUT: Array of column names for table */
  u8 **pabPK,                     /* OUT: Array of booleans - true for PK col */
  int *pbRowid                    /* OUT: True if only PK is a rowid */
){
  char *zPragma;
  sqlite3_stmt *pStmt;
  int rc;
  sqlite3_int64 nByte;
  int nDbCol = 0;
  int nThis;
  int i;
  u8 *pAlloc = 0;
  char **azCol = 0;
  u8 *abPK = 0;
  int bRowid = 0;                 /* Set to true to use rowid as PK */

  assert( pazCol && pabPK );

  nThis = sqlite3Strlen30(zThis);
  if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
    rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
    if( rc==SQLITE_OK ){
217154
217155
217156
217157
217158
217159
217160

217161
217162
217163

217164



217165
217166
217167
217168
217169
217170
217171
    *pabPK = 0;
    *pnCol = 0;
    if( pzTab ) *pzTab = 0;
    return rc;
  }

  nByte = nThis + 1;

  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    nByte += sqlite3_column_bytes(pStmt, 1);
    nDbCol++;

  }



  rc = sqlite3_reset(pStmt);

  if( rc==SQLITE_OK ){
    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
    pAlloc = sessionMalloc64(pSession, nByte);
    if( pAlloc==0 ){
      rc = SQLITE_NOMEM;







>



>

>
>
>







218821
218822
218823
218824
218825
218826
218827
218828
218829
218830
218831
218832
218833
218834
218835
218836
218837
218838
218839
218840
218841
218842
218843
    *pabPK = 0;
    *pnCol = 0;
    if( pzTab ) *pzTab = 0;
    return rc;
  }

  nByte = nThis + 1;
  bRowid = (pbRowid!=0);
  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    nByte += sqlite3_column_bytes(pStmt, 1);
    nDbCol++;
    if( sqlite3_column_int(pStmt, 5) ) bRowid = 0;
  }
  if( nDbCol==0 ) bRowid = 0;
  nDbCol += bRowid;
  nByte += strlen(SESSIONS_ROWID);
  rc = sqlite3_reset(pStmt);

  if( rc==SQLITE_OK ){
    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
    pAlloc = sessionMalloc64(pSession, nByte);
    if( pAlloc==0 ){
      rc = SQLITE_NOMEM;
217179
217180
217181
217182
217183
217184
217185








217186
217187
217188
217189
217190
217191
217192
217193
217194
217195
217196
217197
217198
217199
217200
217201
217202
217203
217204
217205
217206
217207
217208
217209
217210
217211
217212
217213

217214
217215
217216
217217
217218
217219
217220
    if( pzTab ){
      memcpy(pAlloc, zThis, nThis+1);
      *pzTab = (char *)pAlloc;
      pAlloc += nThis+1;
    }

    i = 0;








    while( SQLITE_ROW==sqlite3_step(pStmt) ){
      int nName = sqlite3_column_bytes(pStmt, 1);
      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
      if( zName==0 ) break;
      memcpy(pAlloc, zName, nName+1);
      azCol[i] = (char *)pAlloc;
      pAlloc += nName+1;
      abPK[i] = sqlite3_column_int(pStmt, 5);
      i++;
    }
    rc = sqlite3_reset(pStmt);

  }

  /* If successful, populate the output variables. Otherwise, zero them and
  ** free any allocation made. An error code will be returned in this case.
  */
  if( rc==SQLITE_OK ){
    *pazCol = (const char **)azCol;
    *pabPK = abPK;
    *pnCol = nDbCol;
  }else{
    *pazCol = 0;
    *pabPK = 0;
    *pnCol = 0;
    if( pzTab ) *pzTab = 0;
    sessionFree(pSession, azCol);
  }

  sqlite3_finalize(pStmt);
  return rc;
}

/*
** This function is only called from within a pre-update handler for a
** write to table pTab, part of session pSession. If this is the first







>
>
>
>
>
>
>
>











<
















>







218851
218852
218853
218854
218855
218856
218857
218858
218859
218860
218861
218862
218863
218864
218865
218866
218867
218868
218869
218870
218871
218872
218873
218874
218875
218876

218877
218878
218879
218880
218881
218882
218883
218884
218885
218886
218887
218888
218889
218890
218891
218892
218893
218894
218895
218896
218897
218898
218899
218900
    if( pzTab ){
      memcpy(pAlloc, zThis, nThis+1);
      *pzTab = (char *)pAlloc;
      pAlloc += nThis+1;
    }

    i = 0;
    if( bRowid ){
      size_t nName = strlen(SESSIONS_ROWID);
      memcpy(pAlloc, SESSIONS_ROWID, nName+1);
      azCol[i] = (char*)pAlloc;
      pAlloc += nName+1;
      abPK[i] = 1;
      i++;
    }
    while( SQLITE_ROW==sqlite3_step(pStmt) ){
      int nName = sqlite3_column_bytes(pStmt, 1);
      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
      if( zName==0 ) break;
      memcpy(pAlloc, zName, nName+1);
      azCol[i] = (char *)pAlloc;
      pAlloc += nName+1;
      abPK[i] = sqlite3_column_int(pStmt, 5);
      i++;
    }
    rc = sqlite3_reset(pStmt);

  }

  /* If successful, populate the output variables. Otherwise, zero them and
  ** free any allocation made. An error code will be returned in this case.
  */
  if( rc==SQLITE_OK ){
    *pazCol = (const char **)azCol;
    *pabPK = abPK;
    *pnCol = nDbCol;
  }else{
    *pazCol = 0;
    *pabPK = 0;
    *pnCol = 0;
    if( pzTab ) *pzTab = 0;
    sessionFree(pSession, azCol);
  }
  if( pbRowid ) *pbRowid = bRowid;
  sqlite3_finalize(pStmt);
  return rc;
}

/*
** This function is only called from within a pre-update handler for a
** write to table pTab, part of session pSession. If this is the first
217228
217229
217230
217231
217232
217233
217234
217235

217236
217237
217238
217239
217240
217241
217242
** is set to NULL in this case.
*/
static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  if( pTab->nCol==0 ){
    u8 *abPK;
    assert( pTab->azCol==0 || pTab->abPK==0 );
    pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb,
        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK

    );
    if( pSession->rc==SQLITE_OK ){
      int i;
      for(i=0; i<pTab->nCol; i++){
        if( abPK[i] ){
          pTab->abPK = abPK;
          break;







|
>







218908
218909
218910
218911
218912
218913
218914
218915
218916
218917
218918
218919
218920
218921
218922
218923
** is set to NULL in this case.
*/
static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  if( pTab->nCol==0 ){
    u8 *abPK;
    assert( pTab->azCol==0 || pTab->abPK==0 );
    pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb,
        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK,
        (pSession->bImplicitPK ? &pTab->bRowid : 0)
    );
    if( pSession->rc==SQLITE_OK ){
      int i;
      for(i=0; i<pTab->nCol; i++){
        if( abPK[i] ){
          pTab->abPK = abPK;
          break;
217300
217301
217302
217303
217304
217305
217306

217307
217308
217309
217310
217311
217312
217313
217314
217315
217316
217317
217318
217319
217320
217321
217322




217323
217324
217325
217326
217327
217328
217329
217330
217331
217332
217333
217334
217335
  int op,
  sqlite3_session *pSession,      /* Session object pTab is attached to */
  SessionTable *pTab,             /* Table that change applies to */
  SessionChange *pC               /* Update pC->nMaxSize */
){
  i64 nNew = 2;
  if( pC->op==SQLITE_INSERT ){

    if( op!=SQLITE_DELETE ){
      int ii;
      for(ii=0; ii<pTab->nCol; ii++){
        sqlite3_value *p = 0;
        pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
        sessionSerializeValue(0, p, &nNew);
      }
    }
  }else if( op==SQLITE_DELETE ){
    nNew += pC->nRecord;
    if( sqlite3_preupdate_blobwrite(pSession->db)>=0 ){
      nNew += pC->nRecord;
    }
  }else{
    int ii;
    u8 *pCsr = pC->aRecord;




    for(ii=0; ii<pTab->nCol; ii++){
      int bChanged = 1;
      int nOld = 0;
      int eType;
      sqlite3_value *p = 0;
      pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
      if( p==0 ){
        return SQLITE_NOMEM;
      }

      eType = *pCsr++;
      switch( eType ){
        case SQLITE_NULL:







>
















>
>
>
>
|




|







218981
218982
218983
218984
218985
218986
218987
218988
218989
218990
218991
218992
218993
218994
218995
218996
218997
218998
218999
219000
219001
219002
219003
219004
219005
219006
219007
219008
219009
219010
219011
219012
219013
219014
219015
219016
219017
219018
219019
219020
219021
  int op,
  sqlite3_session *pSession,      /* Session object pTab is attached to */
  SessionTable *pTab,             /* Table that change applies to */
  SessionChange *pC               /* Update pC->nMaxSize */
){
  i64 nNew = 2;
  if( pC->op==SQLITE_INSERT ){
    if( pTab->bRowid ) nNew += 9;
    if( op!=SQLITE_DELETE ){
      int ii;
      for(ii=0; ii<pTab->nCol; ii++){
        sqlite3_value *p = 0;
        pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
        sessionSerializeValue(0, p, &nNew);
      }
    }
  }else if( op==SQLITE_DELETE ){
    nNew += pC->nRecord;
    if( sqlite3_preupdate_blobwrite(pSession->db)>=0 ){
      nNew += pC->nRecord;
    }
  }else{
    int ii;
    u8 *pCsr = pC->aRecord;
    if( pTab->bRowid ){
      nNew += 9 + 1;
      pCsr += 9;
    }
    for(ii=pTab->bRowid; ii<pTab->nCol; ii++){
      int bChanged = 1;
      int nOld = 0;
      int eType;
      sqlite3_value *p = 0;
      pSession->hook.xNew(pSession->hook.pCtx, ii-pTab->bRowid, &p);
      if( p==0 ){
        return SQLITE_NOMEM;
      }

      eType = *pCsr++;
      switch( eType ){
        case SQLITE_NULL:
217400
217401
217402
217403
217404
217405
217406

217407
217408
217409
217410
217411
217412
217413
217414
217415
217416
217417
217418
217419
217420
217421
217422
217423
217424
217425
217426
217427
217428
217429
** (UPDATE, INSERT, DELETE) is specified by the first argument.
**
** Unless one is already present or an error occurs, an entry is added
** to the changed-rows hash table associated with table pTab.
*/
static void sessionPreupdateOneChange(
  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */

  sqlite3_session *pSession,      /* Session object pTab is attached to */
  SessionTable *pTab              /* Table that change applies to */
){
  int iHash;
  int bNull = 0;
  int rc = SQLITE_OK;
  SessionStat1Ctx stat1 = {{0,0,0,0,0},0};

  if( pSession->rc ) return;

  /* Load table details if required */
  if( sessionInitTable(pSession, pTab) ) return;

  /* Check the number of columns in this xPreUpdate call matches the
  ** number of columns in the table.  */
  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
    pSession->rc = SQLITE_SCHEMA;
    return;
  }

  /* Grow the hash table if required */
  if( sessionGrowHash(pSession, 0, pTab) ){
    pSession->rc = SQLITE_NOMEM;







>















|







219086
219087
219088
219089
219090
219091
219092
219093
219094
219095
219096
219097
219098
219099
219100
219101
219102
219103
219104
219105
219106
219107
219108
219109
219110
219111
219112
219113
219114
219115
219116
** (UPDATE, INSERT, DELETE) is specified by the first argument.
**
** Unless one is already present or an error occurs, an entry is added
** to the changed-rows hash table associated with table pTab.
*/
static void sessionPreupdateOneChange(
  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
  i64 iRowid,
  sqlite3_session *pSession,      /* Session object pTab is attached to */
  SessionTable *pTab              /* Table that change applies to */
){
  int iHash;
  int bNull = 0;
  int rc = SQLITE_OK;
  SessionStat1Ctx stat1 = {{0,0,0,0,0},0};

  if( pSession->rc ) return;

  /* Load table details if required */
  if( sessionInitTable(pSession, pTab) ) return;

  /* Check the number of columns in this xPreUpdate call matches the
  ** number of columns in the table.  */
  if( (pTab->nCol-pTab->bRowid)!=pSession->hook.xCount(pSession->hook.pCtx) ){
    pSession->rc = SQLITE_SCHEMA;
    return;
  }

  /* Grow the hash table if required */
  if( sessionGrowHash(pSession, 0, pTab) ){
    pSession->rc = SQLITE_NOMEM;
217448
217449
217450
217451
217452
217453
217454
217455


217456
217457
217458
217459
217460
217461
217462
217463
217464
217465
217466
217467
217468
217469
217470
217471
217472
217473
217474
217475
217476
217477
217478
217479
217480
217481
217482
217483
217484
217485
217486
217487
217488
217489
217490
217491



217492
217493
217494
217495
217496
217497
217498
217499
217500
217501
217502
217503
217504
217505
217506
217507





217508
217509
217510
217511
217512
217513
217514
217515
      pSession->pZeroBlob = p;
    }
  }

  /* Calculate the hash-key for this change. If the primary key of the row
  ** includes a NULL value, exit early. Such changes are ignored by the
  ** session module. */
  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);


  if( rc!=SQLITE_OK ) goto error_out;

  if( bNull==0 ){
    /* Search the hash table for an existing record for this row. */
    SessionChange *pC;
    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
      if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
    }

    if( pC==0 ){
      /* Create a new change object containing all the old values (if
      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
      ** values (if this is an INSERT). */
      sqlite3_int64 nByte;    /* Number of bytes to allocate */
      int i;                  /* Used to iterate through columns */

      assert( rc==SQLITE_OK );
      pTab->nEntry++;

      /* Figure out how large an allocation is required */
      nByte = sizeof(SessionChange);
      for(i=0; i<pTab->nCol; i++){
        sqlite3_value *p = 0;
        if( op!=SQLITE_INSERT ){
          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
          assert( trc==SQLITE_OK );
        }else if( pTab->abPK[i] ){
          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
          assert( trc==SQLITE_OK );
        }

        /* This may fail if SQLite value p contains a utf-16 string that must
        ** be converted to utf-8 and an OOM error occurs while doing so. */
        rc = sessionSerializeValue(0, p, &nByte);
        if( rc!=SQLITE_OK ) goto error_out;
      }




      /* Allocate the change object */
      pC = (SessionChange *)sessionMalloc64(pSession, nByte);
      if( !pC ){
        rc = SQLITE_NOMEM;
        goto error_out;
      }else{
        memset(pC, 0, sizeof(SessionChange));
        pC->aRecord = (u8 *)&pC[1];
      }

      /* Populate the change object. None of the preupdate_old(),
      ** preupdate_new() or SerializeValue() calls below may fail as all
      ** required values and encodings have already been cached in memory.
      ** It is not possible for an OOM to occur in this block. */
      nByte = 0;





      for(i=0; i<pTab->nCol; i++){
        sqlite3_value *p = 0;
        if( op!=SQLITE_INSERT ){
          pSession->hook.xOld(pSession->hook.pCtx, i, &p);
        }else if( pTab->abPK[i] ){
          pSession->hook.xNew(pSession->hook.pCtx, i, &p);
        }
        sessionSerializeValue(&pC->aRecord[nByte], p, &nByte);







|
>
>






|














|














>
>
>
















>
>
>
>
>
|







219135
219136
219137
219138
219139
219140
219141
219142
219143
219144
219145
219146
219147
219148
219149
219150
219151
219152
219153
219154
219155
219156
219157
219158
219159
219160
219161
219162
219163
219164
219165
219166
219167
219168
219169
219170
219171
219172
219173
219174
219175
219176
219177
219178
219179
219180
219181
219182
219183
219184
219185
219186
219187
219188
219189
219190
219191
219192
219193
219194
219195
219196
219197
219198
219199
219200
219201
219202
219203
219204
219205
219206
219207
219208
219209
219210
219211
219212
      pSession->pZeroBlob = p;
    }
  }

  /* Calculate the hash-key for this change. If the primary key of the row
  ** includes a NULL value, exit early. Such changes are ignored by the
  ** session module. */
  rc = sessionPreupdateHash(
      pSession, iRowid, pTab, op==SQLITE_INSERT, &iHash, &bNull
  );
  if( rc!=SQLITE_OK ) goto error_out;

  if( bNull==0 ){
    /* Search the hash table for an existing record for this row. */
    SessionChange *pC;
    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
      if( sessionPreupdateEqual(pSession, iRowid, pTab, pC, op) ) break;
    }

    if( pC==0 ){
      /* Create a new change object containing all the old values (if
      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
      ** values (if this is an INSERT). */
      sqlite3_int64 nByte;    /* Number of bytes to allocate */
      int i;                  /* Used to iterate through columns */

      assert( rc==SQLITE_OK );
      pTab->nEntry++;

      /* Figure out how large an allocation is required */
      nByte = sizeof(SessionChange);
      for(i=0; i<(pTab->nCol-pTab->bRowid); i++){
        sqlite3_value *p = 0;
        if( op!=SQLITE_INSERT ){
          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
          assert( trc==SQLITE_OK );
        }else if( pTab->abPK[i] ){
          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
          assert( trc==SQLITE_OK );
        }

        /* This may fail if SQLite value p contains a utf-16 string that must
        ** be converted to utf-8 and an OOM error occurs while doing so. */
        rc = sessionSerializeValue(0, p, &nByte);
        if( rc!=SQLITE_OK ) goto error_out;
      }
      if( pTab->bRowid ){
        nByte += 9;               /* Size of rowid field - an integer */
      }

      /* Allocate the change object */
      pC = (SessionChange *)sessionMalloc64(pSession, nByte);
      if( !pC ){
        rc = SQLITE_NOMEM;
        goto error_out;
      }else{
        memset(pC, 0, sizeof(SessionChange));
        pC->aRecord = (u8 *)&pC[1];
      }

      /* Populate the change object. None of the preupdate_old(),
      ** preupdate_new() or SerializeValue() calls below may fail as all
      ** required values and encodings have already been cached in memory.
      ** It is not possible for an OOM to occur in this block. */
      nByte = 0;
      if( pTab->bRowid ){
        pC->aRecord[0] = SQLITE_INTEGER;
        sessionPutI64(&pC->aRecord[1], iRowid);
        nByte = 9;
      }
      for(i=0; i<(pTab->nCol-pTab->bRowid); i++){
        sqlite3_value *p = 0;
        if( op!=SQLITE_INSERT ){
          pSession->hook.xOld(pSession->hook.pCtx, i, &p);
        }else if( pTab->abPK[i] ){
          pSession->hook.xNew(pSession->hook.pCtx, i, &p);
        }
        sessionSerializeValue(&pC->aRecord[nByte], p, &nByte);
217616
217617
217618
217619
217620
217621
217622

217623
217624
217625
217626
217627
217628
217629
217630
217631
217632
    if( pSession->bEnable==0 ) continue;
    if( pSession->rc ) continue;
    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;

    pSession->rc = sessionFindTable(pSession, zName, &pTab);
    if( pTab ){
      assert( pSession->rc==SQLITE_OK );

      sessionPreupdateOneChange(op, pSession, pTab);
      if( op==SQLITE_UPDATE ){
        sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
      }
    }
  }
}

/*
** The pre-update hook implementations.







>
|

|







219313
219314
219315
219316
219317
219318
219319
219320
219321
219322
219323
219324
219325
219326
219327
219328
219329
219330
    if( pSession->bEnable==0 ) continue;
    if( pSession->rc ) continue;
    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;

    pSession->rc = sessionFindTable(pSession, zName, &pTab);
    if( pTab ){
      assert( pSession->rc==SQLITE_OK );
      assert( op==SQLITE_UPDATE || iKey1==iKey2 );
      sessionPreupdateOneChange(op, iKey1, pSession, pTab);
      if( op==SQLITE_UPDATE ){
        sessionPreupdateOneChange(SQLITE_INSERT, iKey2, pSession, pTab);
      }
    }
  }
}

/*
** The pre-update hook implementations.
217657
217658
217659
217660
217661
217662
217663

217664
217665
217666
217667
217668
217669
217670
217671
217672
217673
217674
217675
217676
217677
217678
217679
217680
217681
217682
217683
217684
217685
217686
217687
217688
217689
  pSession->hook.xCount = sessionPreupdateCount;
  pSession->hook.xDepth = sessionPreupdateDepth;
}

typedef struct SessionDiffCtx SessionDiffCtx;
struct SessionDiffCtx {
  sqlite3_stmt *pStmt;

  int nOldOff;
};

/*
** The diff hook implementations.
*/
static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  return SQLITE_OK;
}
static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  *ppVal = sqlite3_column_value(p->pStmt, iVal);
   return SQLITE_OK;
}
static int sessionDiffCount(void *pCtx){
  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
}
static int sessionDiffDepth(void *pCtx){
  (void)pCtx;
  return 0;
}

/*







>








|




|




|







219355
219356
219357
219358
219359
219360
219361
219362
219363
219364
219365
219366
219367
219368
219369
219370
219371
219372
219373
219374
219375
219376
219377
219378
219379
219380
219381
219382
219383
219384
219385
219386
219387
219388
  pSession->hook.xCount = sessionPreupdateCount;
  pSession->hook.xDepth = sessionPreupdateDepth;
}

typedef struct SessionDiffCtx SessionDiffCtx;
struct SessionDiffCtx {
  sqlite3_stmt *pStmt;
  int bRowid;
  int nOldOff;
};

/*
** The diff hook implementations.
*/
static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff+p->bRowid);
  return SQLITE_OK;
}
static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->bRowid);
   return SQLITE_OK;
}
static int sessionDiffCount(void *pCtx){
  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  return (p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt)) - p->bRowid;
}
static int sessionDiffDepth(void *pCtx){
  (void)pCtx;
  return 0;
}

/*
217754
217755
217756
217757
217758
217759
217760

217761
217762
217763

217764
217765
217766
217767
217768
217769
217770
217771
217772
217773
217774
217775
217776
217777
217778
217779
217780
217781
217782


217783
217784
217785
217786
217787
217788
217789
217790
217791
217792

217793

217794
217795
217796
217797
217798
217799
217800
217801
217802





















217803
217804
217805
217806
217807
217808
217809
217810
217811
217812
217813
217814
217815
217816
217817


217818
217819
217820
217821
217822
217823
217824
217825
217826
217827
217828
217829
217830
217831
217832

217833
217834
217835
217836
217837
217838



217839
217840
217841
217842
217843
217844
217845

  return zRet;
}

static char *sessionSelectFindNew(
  const char *zDb1,      /* Pick rows in this db only */
  const char *zDb2,      /* But not in this one */

  const char *zTbl,      /* Table name */
  const char *zExpr
){

  char *zRet = sqlite3_mprintf(
      "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
      "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
      ")",
      zDb1, zTbl, zDb2, zTbl, zExpr
  );
  return zRet;
}

static int sessionDiffFindNew(
  int op,
  sqlite3_session *pSession,
  SessionTable *pTab,
  const char *zDb1,
  const char *zDb2,
  char *zExpr
){
  int rc = SQLITE_OK;
  char *zStmt = sessionSelectFindNew(zDb1, zDb2, pTab->zName,zExpr);



  if( zStmt==0 ){
    rc = SQLITE_NOMEM;
  }else{
    sqlite3_stmt *pStmt;
    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
    if( rc==SQLITE_OK ){
      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
      pDiffCtx->pStmt = pStmt;
      pDiffCtx->nOldOff = 0;

      while( SQLITE_ROW==sqlite3_step(pStmt) ){

        sessionPreupdateOneChange(op, pSession, pTab);
      }
      rc = sqlite3_finalize(pStmt);
    }
    sqlite3_free(zStmt);
  }

  return rc;
}






















static int sessionDiffFindModified(
  sqlite3_session *pSession,
  SessionTable *pTab,
  const char *zFrom,
  const char *zExpr
){
  int rc = SQLITE_OK;

  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  );
  if( zExpr2==0 ){
    rc = SQLITE_NOMEM;
  }else{


    char *zStmt = sqlite3_mprintf(
        "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
        pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
    );
    if( zStmt==0 ){
      rc = SQLITE_NOMEM;
    }else{
      sqlite3_stmt *pStmt;
      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);

      if( rc==SQLITE_OK ){
        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
        pDiffCtx->pStmt = pStmt;
        pDiffCtx->nOldOff = pTab->nCol;
        while( SQLITE_ROW==sqlite3_step(pStmt) ){

          sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
        }
        rc = sqlite3_finalize(pStmt);
      }
      sqlite3_free(zStmt);
    }



  }

  return rc;
}

SQLITE_API int sqlite3session_diff(
  sqlite3_session *pSession,







>



>

|


|













|
>
>










>

>
|








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















>
>

|
|

|










>
|



<

>
>
>







219453
219454
219455
219456
219457
219458
219459
219460
219461
219462
219463
219464
219465
219466
219467
219468
219469
219470
219471
219472
219473
219474
219475
219476
219477
219478
219479
219480
219481
219482
219483
219484
219485
219486
219487
219488
219489
219490
219491
219492
219493
219494
219495
219496
219497
219498
219499
219500
219501
219502
219503
219504
219505
219506
219507
219508
219509
219510
219511
219512
219513
219514
219515
219516
219517
219518
219519
219520
219521
219522
219523
219524
219525
219526
219527
219528
219529
219530
219531
219532
219533
219534
219535
219536
219537
219538
219539
219540
219541
219542
219543
219544
219545
219546
219547
219548
219549
219550
219551
219552
219553
219554
219555
219556
219557
219558
219559
219560
219561
219562
219563
219564
219565

219566
219567
219568
219569
219570
219571
219572
219573
219574
219575
219576

  return zRet;
}

static char *sessionSelectFindNew(
  const char *zDb1,      /* Pick rows in this db only */
  const char *zDb2,      /* But not in this one */
  int bRowid,
  const char *zTbl,      /* Table name */
  const char *zExpr
){
  const char *zSel = (bRowid ? SESSIONS_ROWID ", *" : "*");
  char *zRet = sqlite3_mprintf(
      "SELECT %s FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
      "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
      ")",
      zSel, zDb1, zTbl, zDb2, zTbl, zExpr
  );
  return zRet;
}

static int sessionDiffFindNew(
  int op,
  sqlite3_session *pSession,
  SessionTable *pTab,
  const char *zDb1,
  const char *zDb2,
  char *zExpr
){
  int rc = SQLITE_OK;
  char *zStmt = sessionSelectFindNew(
      zDb1, zDb2, pTab->bRowid, pTab->zName, zExpr
  );

  if( zStmt==0 ){
    rc = SQLITE_NOMEM;
  }else{
    sqlite3_stmt *pStmt;
    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
    if( rc==SQLITE_OK ){
      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
      pDiffCtx->pStmt = pStmt;
      pDiffCtx->nOldOff = 0;
      pDiffCtx->bRowid = pTab->bRowid;
      while( SQLITE_ROW==sqlite3_step(pStmt) ){
        i64 iRowid = (pTab->bRowid ? sqlite3_column_int64(pStmt, 0) : 0);
        sessionPreupdateOneChange(op, iRowid, pSession, pTab);
      }
      rc = sqlite3_finalize(pStmt);
    }
    sqlite3_free(zStmt);
  }

  return rc;
}

/*
** Return a comma-separated list of the fully-qualified (with both database
** and table name) column names from table pTab. e.g.
**
**    "main"."t1"."a", "main"."t1"."b", "main"."t1"."c"
*/
static char *sessionAllCols(
  const char *zDb,
  SessionTable *pTab
){
  int ii;
  char *zRet = 0;
  for(ii=0; ii<pTab->nCol; ii++){
    zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"",
        zRet, (zRet ? ", " : ""), zDb, pTab->zName, pTab->azCol[ii]
    );
    if( !zRet ) break;
  }
  return zRet;
}

static int sessionDiffFindModified(
  sqlite3_session *pSession,
  SessionTable *pTab,
  const char *zFrom,
  const char *zExpr
){
  int rc = SQLITE_OK;

  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  );
  if( zExpr2==0 ){
    rc = SQLITE_NOMEM;
  }else{
    char *z1 = sessionAllCols(pSession->zDb, pTab);
    char *z2 = sessionAllCols(zFrom, pTab);
    char *zStmt = sqlite3_mprintf(
        "SELECT %s,%s FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
        z1, z2, pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
    );
    if( zStmt==0 || z1==0 || z2==0 ){
      rc = SQLITE_NOMEM;
    }else{
      sqlite3_stmt *pStmt;
      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);

      if( rc==SQLITE_OK ){
        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
        pDiffCtx->pStmt = pStmt;
        pDiffCtx->nOldOff = pTab->nCol;
        while( SQLITE_ROW==sqlite3_step(pStmt) ){
          i64 iRowid = (pTab->bRowid ? sqlite3_column_int64(pStmt, 0) : 0);
          sessionPreupdateOneChange(SQLITE_UPDATE, iRowid, pSession, pTab);
        }
        rc = sqlite3_finalize(pStmt);
      }

    }
    sqlite3_free(zStmt);
    sqlite3_free(z1);
    sqlite3_free(z2);
  }

  return rc;
}

SQLITE_API int sqlite3session_diff(
  sqlite3_session *pSession,
217870
217871
217872
217873
217874
217875
217876

217877
217878
217879


217880
217881
217882
217883
217884
217885
217886
    }

    /* Check the table schemas match */
    if( rc==SQLITE_OK ){
      int bHasPk = 0;
      int bMismatch = 0;
      int nCol;                   /* Columns in zFrom.zTbl */

      u8 *abPK;
      const char **azCol = 0;
      rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);


      if( rc==SQLITE_OK ){
        if( pTo->nCol!=nCol ){
          bMismatch = 1;
        }else{
          int i;
          for(i=0; i<nCol; i++){
            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;







>


|
>
>







219601
219602
219603
219604
219605
219606
219607
219608
219609
219610
219611
219612
219613
219614
219615
219616
219617
219618
219619
219620
    }

    /* Check the table schemas match */
    if( rc==SQLITE_OK ){
      int bHasPk = 0;
      int bMismatch = 0;
      int nCol;                   /* Columns in zFrom.zTbl */
      int bRowid = 0;
      u8 *abPK;
      const char **azCol = 0;
      rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, &abPK,
          pSession->bImplicitPK ? &bRowid : 0
      );
      if( rc==SQLITE_OK ){
        if( pTo->nCol!=nCol ){
          bMismatch = 1;
        }else{
          int i;
          for(i=0; i<nCol; i++){
            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
218214
218215
218216
218217
218218
218219
218220
218221
218222
218223

218224
218225
218226
218227
218228
218229
218230
218231
218232
218233
218234
218235
218236
218237
218238
218239
218240
218241
218242
218243





















218244
218245
218246
218247
218248
218249
218250
218251
218252
218253
218254
218255
218256
218257
218258
218259
218260
218261
218262
218263
218264
218265
218266
218267
218268
218269

218270
218271
218272
218273
218274
218275
218276
*/
static void sessionAppendStr(
  SessionBuffer *p,
  const char *zStr,
  int *pRc
){
  int nStr = sqlite3Strlen30(zStr);
  if( 0==sessionBufferGrow(p, nStr, pRc) ){
    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
    p->nBuf += nStr;

  }
}

/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string representation of integer iVal
** to the buffer. No nul-terminator is written.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendInteger(
  SessionBuffer *p,               /* Buffer to append to */
  int iVal,                       /* Value to write the string rep. of */
  int *pRc                        /* IN/OUT: Error code */
){
  char aBuf[24];
  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  sessionAppendStr(p, aBuf, pRc);
}






















/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string zStr enclosed in quotes (") and
** with any embedded quote characters escaped to the buffer. No
** nul-terminator byte is written.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendIdent(
  SessionBuffer *p,               /* Buffer to a append to */
  const char *zStr,               /* String to quote, escape and append */
  int *pRc                        /* IN/OUT: Error code */
){
  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  if( 0==sessionBufferGrow(p, nStr, pRc) ){
    char *zOut = (char *)&p->aBuf[p->nBuf];
    const char *zIn = zStr;
    *zOut++ = '"';
    while( *zIn ){
      if( *zIn=='"' ) *zOut++ = '"';
      *zOut++ = *(zIn++);
    }
    *zOut++ = '"';
    p->nBuf = (int)((u8 *)zOut - p->aBuf);

  }
}

/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwse, it appends the serialized version of the value stored
** in column iCol of the row that SQL statement pStmt currently points







|


>




















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















|










>







219948
219949
219950
219951
219952
219953
219954
219955
219956
219957
219958
219959
219960
219961
219962
219963
219964
219965
219966
219967
219968
219969
219970
219971
219972
219973
219974
219975
219976
219977
219978
219979
219980
219981
219982
219983
219984
219985
219986
219987
219988
219989
219990
219991
219992
219993
219994
219995
219996
219997
219998
219999
220000
220001
220002
220003
220004
220005
220006
220007
220008
220009
220010
220011
220012
220013
220014
220015
220016
220017
220018
220019
220020
220021
220022
220023
220024
220025
220026
220027
220028
220029
220030
220031
220032
220033
*/
static void sessionAppendStr(
  SessionBuffer *p,
  const char *zStr,
  int *pRc
){
  int nStr = sqlite3Strlen30(zStr);
  if( 0==sessionBufferGrow(p, nStr+1, pRc) ){
    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
    p->nBuf += nStr;
    p->aBuf[p->nBuf] = 0x00;
  }
}

/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string representation of integer iVal
** to the buffer. No nul-terminator is written.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendInteger(
  SessionBuffer *p,               /* Buffer to append to */
  int iVal,                       /* Value to write the string rep. of */
  int *pRc                        /* IN/OUT: Error code */
){
  char aBuf[24];
  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  sessionAppendStr(p, aBuf, pRc);
}

static void sessionAppendPrintf(
  SessionBuffer *p,               /* Buffer to append to */
  int *pRc,
  const char *zFmt,
  ...
){
  if( *pRc==SQLITE_OK ){
    char *zApp = 0;
    va_list ap;
    va_start(ap, zFmt);
    zApp = sqlite3_vmprintf(zFmt, ap);
    if( zApp==0 ){
      *pRc = SQLITE_NOMEM;
    }else{
      sessionAppendStr(p, zApp, pRc);
    }
    va_end(ap);
    sqlite3_free(zApp);
  }
}

/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string zStr enclosed in quotes (") and
** with any embedded quote characters escaped to the buffer. No
** nul-terminator byte is written.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendIdent(
  SessionBuffer *p,               /* Buffer to a append to */
  const char *zStr,               /* String to quote, escape and append */
  int *pRc                        /* IN/OUT: Error code */
){
  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 2;
  if( 0==sessionBufferGrow(p, nStr, pRc) ){
    char *zOut = (char *)&p->aBuf[p->nBuf];
    const char *zIn = zStr;
    *zOut++ = '"';
    while( *zIn ){
      if( *zIn=='"' ) *zOut++ = '"';
      *zOut++ = *(zIn++);
    }
    *zOut++ = '"';
    p->nBuf = (int)((u8 *)zOut - p->aBuf);
    p->aBuf[p->nBuf] = 0x00;
  }
}

/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwse, it appends the serialized version of the value stored
** in column iCol of the row that SQL statement pStmt currently points
218398
218399
218400
218401
218402
218403
218404
218405
218406
218407
218408
218409
218410
218411
218412
        bChanged = 1;
      }
    }

    /* If at least one field has been modified, this is not a no-op. */
    if( bChanged ) bNoop = 0;

    /* Add a field to the old.* record. This is omitted if this modules is
    ** currently generating a patchset. */
    if( bPatchset==0 ){
      if( bChanged || abPK[i] ){
        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
      }else{
        sessionAppendByte(pBuf, 0, &rc);
      }







|







220155
220156
220157
220158
220159
220160
220161
220162
220163
220164
220165
220166
220167
220168
220169
        bChanged = 1;
      }
    }

    /* If at least one field has been modified, this is not a no-op. */
    if( bChanged ) bNoop = 0;

    /* Add a field to the old.* record. This is omitted if this module is
    ** currently generating a patchset. */
    if( bPatchset==0 ){
      if( bChanged || abPK[i] ){
        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
      }else{
        sessionAppendByte(pBuf, 0, &rc);
      }
218487
218488
218489
218490
218491
218492
218493
218494






218495
218496
218497

218498
218499

218500
218501
218502
218503
218504
218505
218506


218507

218508







































218509
218510
218511
218512
218513
218514
218515
218516
218517
218518
218519
218520
218521
218522
218523
218524
218525
218526
218527
218528
218529
218530
218531
218532
218533
218534
218535
218536

218537
218538
218539
218540
218541



218542
218543
218544
218545
218546
218547
218548
  return rc;
}

/*
** Formulate and prepare a SELECT statement to retrieve a row from table
** zTab in database zDb based on its primary key. i.e.
**
**   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...






*/
static int sessionSelectStmt(
  sqlite3 *db,                    /* Database handle */

  const char *zDb,                /* Database name */
  const char *zTab,               /* Table name */

  int nCol,                       /* Number of columns in table */
  const char **azCol,             /* Names of table columns */
  u8 *abPK,                       /* PRIMARY KEY  array */
  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
){
  int rc = SQLITE_OK;
  char *zSql = 0;


  int nSql = -1;









































  if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
    zSql = sqlite3_mprintf(
        "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
        "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
    );
    if( zSql==0 ) rc = SQLITE_NOMEM;
  }else{
    int i;
    const char *zSep = "";
    SessionBuffer buf = {0, 0, 0};

    sessionAppendStr(&buf, "SELECT * FROM ", &rc);
    sessionAppendIdent(&buf, zDb, &rc);
    sessionAppendStr(&buf, ".", &rc);
    sessionAppendIdent(&buf, zTab, &rc);
    sessionAppendStr(&buf, " WHERE ", &rc);
    for(i=0; i<nCol; i++){
      if( abPK[i] ){
        sessionAppendStr(&buf, zSep, &rc);
        sessionAppendIdent(&buf, azCol[i], &rc);
        sessionAppendStr(&buf, " IS ?", &rc);
        sessionAppendInteger(&buf, i+1, &rc);
        zSep = " AND ";
      }
    }
    zSql = (char*)buf.aBuf;
    nSql = buf.nBuf;
  }


  if( rc==SQLITE_OK ){
    rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  }
  sqlite3_free(zSql);



  return rc;
}

/*
** Bind the PRIMARY KEY values from the change passed in argument pChange
** to the SELECT statement passed as the first argument. The SELECT statement
** is as prepared by function sessionSelectStmt().







|
>
>
>
>
>
>



>


>







>
>

>

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







<




















>





>
>
>







220244
220245
220246
220247
220248
220249
220250
220251
220252
220253
220254
220255
220256
220257
220258
220259
220260
220261
220262
220263
220264
220265
220266
220267
220268
220269
220270
220271
220272
220273
220274
220275
220276
220277
220278
220279
220280
220281
220282
220283
220284
220285
220286
220287
220288
220289
220290
220291
220292
220293
220294
220295
220296
220297
220298
220299
220300
220301
220302
220303
220304
220305
220306
220307
220308
220309
220310
220311
220312
220313
220314
220315
220316
220317
220318
220319
220320
220321
220322

220323
220324
220325
220326
220327
220328
220329
220330
220331
220332
220333
220334
220335
220336
220337
220338
220339
220340
220341
220342
220343
220344
220345
220346
220347
220348
220349
220350
220351
220352
220353
220354
220355
220356
220357
220358
  return rc;
}

/*
** Formulate and prepare a SELECT statement to retrieve a row from table
** zTab in database zDb based on its primary key. i.e.
**
**   SELECT *, <noop-test> FROM zDb.zTab WHERE (pk1, pk2,...) IS (?1, ?2,...)
**
** where <noop-test> is:
**
**   1 AND (?A OR ?1 IS <column>) AND ...
**
** for each non-pk <column>.
*/
static int sessionSelectStmt(
  sqlite3 *db,                    /* Database handle */
  int bIgnoreNoop,
  const char *zDb,                /* Database name */
  const char *zTab,               /* Table name */
  int bRowid,
  int nCol,                       /* Number of columns in table */
  const char **azCol,             /* Names of table columns */
  u8 *abPK,                       /* PRIMARY KEY  array */
  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
){
  int rc = SQLITE_OK;
  char *zSql = 0;
  const char *zSep = "";
  const char *zCols = bRowid ? SESSIONS_ROWID ", *" : "*";
  int nSql = -1;
  int i;

  SessionBuffer nooptest = {0, 0, 0};
  SessionBuffer pkfield = {0, 0, 0};
  SessionBuffer pkvar = {0, 0, 0};

  sessionAppendStr(&nooptest, ", 1", &rc);

  if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
    sessionAppendStr(&nooptest, " AND (?6 OR ?3 IS stat)", &rc);
    sessionAppendStr(&pkfield, "tbl, idx", &rc);
    sessionAppendStr(&pkvar,
        "?1, (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", &rc
    );
    zCols = "tbl, ?2, stat";
  }else{
    for(i=0; i<nCol; i++){
      if( abPK[i] ){
        sessionAppendStr(&pkfield, zSep, &rc);
        sessionAppendStr(&pkvar, zSep, &rc);
        zSep = ", ";
        sessionAppendIdent(&pkfield, azCol[i], &rc);
        sessionAppendPrintf(&pkvar, &rc, "?%d", i+1);
      }else{
        sessionAppendPrintf(&nooptest, &rc,
            " AND (?%d OR ?%d IS %w.%w)", i+1+nCol, i+1, zTab, azCol[i]
        );
      }
    }
  }

  if( rc==SQLITE_OK ){
    zSql = sqlite3_mprintf(
        "SELECT %s%s FROM %Q.%Q WHERE (%s) IS (%s)",
        zCols, (bIgnoreNoop ? (char*)nooptest.aBuf : ""),
        zDb, zTab, (char*)pkfield.aBuf, (char*)pkvar.aBuf
    );
    if( zSql==0 ) rc = SQLITE_NOMEM;
  }

#if 0
  if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
    zSql = sqlite3_mprintf(
        "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
        "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
    );
    if( zSql==0 ) rc = SQLITE_NOMEM;
  }else{

    const char *zSep = "";
    SessionBuffer buf = {0, 0, 0};

    sessionAppendStr(&buf, "SELECT * FROM ", &rc);
    sessionAppendIdent(&buf, zDb, &rc);
    sessionAppendStr(&buf, ".", &rc);
    sessionAppendIdent(&buf, zTab, &rc);
    sessionAppendStr(&buf, " WHERE ", &rc);
    for(i=0; i<nCol; i++){
      if( abPK[i] ){
        sessionAppendStr(&buf, zSep, &rc);
        sessionAppendIdent(&buf, azCol[i], &rc);
        sessionAppendStr(&buf, " IS ?", &rc);
        sessionAppendInteger(&buf, i+1, &rc);
        zSep = " AND ";
      }
    }
    zSql = (char*)buf.aBuf;
    nSql = buf.nBuf;
  }
#endif

  if( rc==SQLITE_OK ){
    rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  }
  sqlite3_free(zSql);
  sqlite3_free(nooptest.aBuf);
  sqlite3_free(pkfield.aBuf);
  sqlite3_free(pkvar.aBuf);
  return rc;
}

/*
** Bind the PRIMARY KEY values from the change passed in argument pChange
** to the SELECT statement passed as the first argument. The SELECT statement
** is as prepared by function sessionSelectStmt().
218681
218682
218683
218684
218685
218686
218687

218688
218689
218690






218691

218692
218693
218694
218695
218696
218697
218698
218699
218700
218701

218702
218703
218704
218705
218706
218707
218708
      int nCol = 0;               /* Number of columns in table */
      u8 *abPK = 0;               /* Primary key array */
      const char **azCol = 0;     /* Table columns */
      int i;                      /* Used to iterate through hash buckets */
      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
      int nRewind = buf.nBuf;     /* Initial size of write buffer */
      int nNoop;                  /* Size of buffer after writing tbl header */


      /* Check the table schema is still Ok. */
      rc = sessionTableInfo(0, db, pSession->zDb, zName, &nCol, 0,&azCol,&abPK);






      if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){

        rc = SQLITE_SCHEMA;
      }

      /* Write a table header */
      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);

      /* Build and compile a statement to execute: */
      if( rc==SQLITE_OK ){
        rc = sessionSelectStmt(
            db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);

      }

      nNoop = buf.nBuf;
      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
        SessionChange *p;         /* Used to iterate through changes */

        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){







>


|
>
>
>
>
>
>
|
>









|
>







220491
220492
220493
220494
220495
220496
220497
220498
220499
220500
220501
220502
220503
220504
220505
220506
220507
220508
220509
220510
220511
220512
220513
220514
220515
220516
220517
220518
220519
220520
220521
220522
220523
220524
220525
220526
220527
      int nCol = 0;               /* Number of columns in table */
      u8 *abPK = 0;               /* Primary key array */
      const char **azCol = 0;     /* Table columns */
      int i;                      /* Used to iterate through hash buckets */
      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
      int nRewind = buf.nBuf;     /* Initial size of write buffer */
      int nNoop;                  /* Size of buffer after writing tbl header */
      int bRowid = 0;

      /* Check the table schema is still Ok. */
      rc = sessionTableInfo(
          0, db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK,
          (pSession->bImplicitPK ? &bRowid : 0)
      );
      if( rc==SQLITE_OK && (
          pTab->nCol!=nCol
       || pTab->bRowid!=bRowid
       || memcmp(abPK, pTab->abPK, nCol)
      )){
        rc = SQLITE_SCHEMA;
      }

      /* Write a table header */
      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);

      /* Build and compile a statement to execute: */
      if( rc==SQLITE_OK ){
        rc = sessionSelectStmt(
            db, 0, pSession->zDb, zName, bRowid, nCol, azCol, abPK, &pSel
        );
      }

      nNoop = buf.nBuf;
      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
        SessionChange *p;         /* Used to iterate through changes */

        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
218777
218778
218779
218780
218781
218782
218783
218784
218785
218786
218787
218788
218789
218790
218791
  sqlite3_session *pSession,      /* Session object */
  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
  void **ppChangeset              /* OUT: Buffer containing changeset */
){
  int rc;

  if( pnChangeset==0 || ppChangeset==0 ) return SQLITE_MISUSE;
  rc = sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset,ppChangeset);
  assert( rc || pnChangeset==0
       || pSession->bEnableSize==0 || *pnChangeset<=pSession->nMaxChangesetSize
  );
  return rc;
}

/*







|







220596
220597
220598
220599
220600
220601
220602
220603
220604
220605
220606
220607
220608
220609
220610
  sqlite3_session *pSession,      /* Session object */
  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
  void **ppChangeset              /* OUT: Buffer containing changeset */
){
  int rc;

  if( pnChangeset==0 || ppChangeset==0 ) return SQLITE_MISUSE;
  rc = sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  assert( rc || pnChangeset==0
       || pSession->bEnableSize==0 || *pnChangeset<=pSession->nMaxChangesetSize
  );
  return rc;
}

/*
218894
218895
218896
218897
218898
218899
218900













218901
218902
218903
218904
218905
218906
218907
        }else{
          pSession->bEnableSize = (iArg!=0);
        }
      }
      *(int*)pArg = pSession->bEnableSize;
      break;
    }














    default:
      rc = SQLITE_MISUSE;
  }

  return rc;
}







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







220713
220714
220715
220716
220717
220718
220719
220720
220721
220722
220723
220724
220725
220726
220727
220728
220729
220730
220731
220732
220733
220734
220735
220736
220737
220738
220739
        }else{
          pSession->bEnableSize = (iArg!=0);
        }
      }
      *(int*)pArg = pSession->bEnableSize;
      break;
    }

    case SQLITE_SESSION_OBJCONFIG_ROWID: {
      int iArg = *(int*)pArg;
      if( iArg>=0 ){
        if( pSession->pTable ){
          rc = SQLITE_MISUSE;
        }else{
          pSession->bImplicitPK = (iArg!=0);
        }
      }
      *(int*)pArg = pSession->bImplicitPK;
      break;
    }

    default:
      rc = SQLITE_MISUSE;
  }

  return rc;
}
219883
219884
219885
219886
219887
219888
219889


219890
219891
219892
219893
219894
219895
219896
  int bStat1;                     /* True if table is sqlite_stat1 */
  int bDeferConstraints;          /* True to defer constraints */
  int bInvertConstraints;         /* Invert when iterating constraints buffer */
  SessionBuffer constraints;      /* Deferred constraints are stored here */
  SessionBuffer rebase;           /* Rebase information (if any) here */
  u8 bRebaseStarted;              /* If table header is already in rebase */
  u8 bRebase;                     /* True to collect rebase information */


};

/* Number of prepared UPDATE statements to cache. */
#define SESSION_UPDATE_CACHE_SZ 12

/*
** Find a prepared UPDATE statement suitable for the UPDATE step currently







>
>







221715
221716
221717
221718
221719
221720
221721
221722
221723
221724
221725
221726
221727
221728
221729
221730
  int bStat1;                     /* True if table is sqlite_stat1 */
  int bDeferConstraints;          /* True to defer constraints */
  int bInvertConstraints;         /* Invert when iterating constraints buffer */
  SessionBuffer constraints;      /* Deferred constraints are stored here */
  SessionBuffer rebase;           /* Rebase information (if any) here */
  u8 bRebaseStarted;              /* If table header is already in rebase */
  u8 bRebase;                     /* True to collect rebase information */
  u8 bIgnoreNoop;                 /* True to ignore no-op conflicts */
  int bRowid;
};

/* Number of prepared UPDATE statements to cache. */
#define SESSION_UPDATE_CACHE_SZ 12

/*
** Find a prepared UPDATE statement suitable for the UPDATE step currently
220133
220134
220135
220136
220137
220138
220139

220140
220141

220142
220143
220144
220145
220146
220147
220148
** pointing to the prepared version of the SQL statement.
*/
static int sessionSelectRow(
  sqlite3 *db,                    /* Database handle */
  const char *zTab,               /* Table name */
  SessionApplyCtx *p              /* Session changeset-apply context */
){

  return sessionSelectStmt(
      db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);

}

/*
** Formulate and prepare an INSERT statement to add a record to table zTab.
** For example:
**
**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);







>
|
|
>







221967
221968
221969
221970
221971
221972
221973
221974
221975
221976
221977
221978
221979
221980
221981
221982
221983
221984
** pointing to the prepared version of the SQL statement.
*/
static int sessionSelectRow(
  sqlite3 *db,                    /* Database handle */
  const char *zTab,               /* Table name */
  SessionApplyCtx *p              /* Session changeset-apply context */
){
  /* TODO */
  return sessionSelectStmt(db, p->bIgnoreNoop,
      "main", zTab, p->bRowid, p->nCol, p->azCol, p->abPK, &p->pSelect
  );
}

/*
** Formulate and prepare an INSERT statement to add a record to table zTab.
** For example:
**
**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
220293
220294
220295
220296
220297
220298
220299
220300
220301
220302

220303
220304
220305
220306
220307

220308
220309
220310
220311
220312












220313
220314
220315
220316
220317
220318
220319
**
** If the iterator currently points to an INSERT record, bind values from the
** new.* record to the SELECT statement. Or, if it points to a DELETE or
** UPDATE, bind values from the old.* record.
*/
static int sessionSeekToRow(
  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
  u8 *abPK,                       /* Primary key flags array */
  sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
){

  int rc;                         /* Return code */
  int nCol;                       /* Number of columns in table */
  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
  const char *zDummy;             /* Unused */


  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  rc = sessionBindRow(pIter,
      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
      nCol, abPK, pSelect
  );













  if( rc==SQLITE_OK ){
    rc = sqlite3_step(pSelect);
    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  }

  return rc;







<
|

>





>



|

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







222129
222130
222131
222132
222133
222134
222135

222136
222137
222138
222139
222140
222141
222142
222143
222144
222145
222146
222147
222148
222149
222150
222151
222152
222153
222154
222155
222156
222157
222158
222159
222160
222161
222162
222163
222164
222165
222166
222167
222168
**
** If the iterator currently points to an INSERT record, bind values from the
** new.* record to the SELECT statement. Or, if it points to a DELETE or
** UPDATE, bind values from the old.* record.
*/
static int sessionSeekToRow(
  sqlite3_changeset_iter *pIter,  /* Changeset iterator */

  SessionApplyCtx *p
){
  sqlite3_stmt *pSelect = p->pSelect;
  int rc;                         /* Return code */
  int nCol;                       /* Number of columns in table */
  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
  const char *zDummy;             /* Unused */

  sqlite3_clear_bindings(pSelect);
  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  rc = sessionBindRow(pIter,
      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
      nCol, p->abPK, pSelect
  );

  if( op!=SQLITE_DELETE && p->bIgnoreNoop ){
    int ii;
    for(ii=0; rc==SQLITE_OK && ii<nCol; ii++){
      if( p->abPK[ii]==0 ){
        sqlite3_value *pVal = 0;
        sqlite3changeset_new(pIter, ii, &pVal);
        sqlite3_bind_int(pSelect, ii+1+nCol, (pVal==0));
        if( pVal ) rc = sessionBindValue(pSelect, ii+1, pVal);
      }
    }
  }

  if( rc==SQLITE_OK ){
    rc = sqlite3_step(pSelect);
    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  }

  return rc;
220421
220422
220423
220424
220425
220426
220427
220428
220429
220430
220431
220432
220433
220434





220435
220436
220437

220438
220439
220440
220441
220442
220443
220444

  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );

  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  if( pbReplace ){
    rc = sessionSeekToRow(pIter, p->abPK, p->pSelect);
  }else{
    rc = SQLITE_OK;
  }

  if( rc==SQLITE_ROW ){
    /* There exists another row with the new.* primary key. */





    pIter->pConflict = p->pSelect;
    res = xConflict(pCtx, eType, pIter);
    pIter->pConflict = 0;

    rc = sqlite3_reset(p->pSelect);
  }else if( rc==SQLITE_OK ){
    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
      /* Instead of invoking the conflict handler, append the change blob
      ** to the SessionApplyCtx.constraints buffer. */
      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
      int nBlob = pIter->in.iNext - pIter->in.iCurrent;







|






>
>
>
>
>
|
|
|
>







222270
222271
222272
222273
222274
222275
222276
222277
222278
222279
222280
222281
222282
222283
222284
222285
222286
222287
222288
222289
222290
222291
222292
222293
222294
222295
222296
222297
222298
222299

  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );

  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  if( pbReplace ){
    rc = sessionSeekToRow(pIter, p);
  }else{
    rc = SQLITE_OK;
  }

  if( rc==SQLITE_ROW ){
    /* There exists another row with the new.* primary key. */
    if( p->bIgnoreNoop
     && sqlite3_column_int(p->pSelect, sqlite3_column_count(p->pSelect)-1)
    ){
      res = SQLITE_CHANGESET_OMIT;
    }else{
      pIter->pConflict = p->pSelect;
      res = xConflict(pCtx, eType, pIter);
      pIter->pConflict = 0;
    }
    rc = sqlite3_reset(p->pSelect);
  }else if( rc==SQLITE_OK ){
    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
      /* Instead of invoking the conflict handler, append the change blob
      ** to the SessionApplyCtx.constraints buffer. */
      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
      int nBlob = pIter->in.iNext - pIter->in.iCurrent;
220538
220539
220540
220541
220542
220543
220544
220545
220546
220547
220548
220549
220550
220551
220552
    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
    }
    if( rc!=SQLITE_OK ) return rc;

    sqlite3_step(p->pDelete);
    rc = sqlite3_reset(p->pDelete);
    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
      rc = sessionConflictHandler(
          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
      );
    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
      rc = sessionConflictHandler(
          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
      );







|







222393
222394
222395
222396
222397
222398
222399
222400
222401
222402
222403
222404
222405
222406
222407
    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
    }
    if( rc!=SQLITE_OK ) return rc;

    sqlite3_step(p->pDelete);
    rc = sqlite3_reset(p->pDelete);
    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 && p->bIgnoreNoop==0 ){
      rc = sessionConflictHandler(
          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
      );
    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
      rc = sessionConflictHandler(
          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
      );
220595
220596
220597
220598
220599
220600
220601
220602
220603
220604
220605
220606
220607
220608
220609

  }else{
    assert( op==SQLITE_INSERT );
    if( p->bStat1 ){
      /* Check if there is a conflicting row. For sqlite_stat1, this needs
      ** to be done using a SELECT, as there is no PRIMARY KEY in the
      ** database schema to throw an exception if a duplicate is inserted.  */
      rc = sessionSeekToRow(pIter, p->abPK, p->pSelect);
      if( rc==SQLITE_ROW ){
        rc = SQLITE_CONSTRAINT;
        sqlite3_reset(p->pSelect);
      }
    }

    if( rc==SQLITE_OK ){







|







222450
222451
222452
222453
222454
222455
222456
222457
222458
222459
222460
222461
222462
222463
222464

  }else{
    assert( op==SQLITE_INSERT );
    if( p->bStat1 ){
      /* Check if there is a conflicting row. For sqlite_stat1, this needs
      ** to be done using a SELECT, as there is no PRIMARY KEY in the
      ** database schema to throw an exception if a duplicate is inserted.  */
      rc = sessionSeekToRow(pIter, p);
      if( rc==SQLITE_ROW ){
        rc = SQLITE_CONSTRAINT;
        sqlite3_reset(p->pSelect);
      }
    }

    if( rc==SQLITE_OK ){
220772
220773
220774
220775
220776
220777
220778

220779
220780
220781
220782
220783
220784
220785

  assert( xConflict!=0 );

  pIter->in.bNoDiscard = 1;
  memset(&sApply, 0, sizeof(sApply));
  sApply.bRebase = (ppRebase && pnRebase);
  sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);

  sqlite3_mutex_enter(sqlite3_db_mutex(db));
  if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
    rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  }







>







222627
222628
222629
222630
222631
222632
222633
222634
222635
222636
222637
222638
222639
222640
222641

  assert( xConflict!=0 );

  pIter->in.bNoDiscard = 1;
  memset(&sApply, 0, sizeof(sApply));
  sApply.bRebase = (ppRebase && pnRebase);
  sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  sApply.bIgnoreNoop = !!(flags & SQLITE_CHANGESETAPPLY_IGNORENOOP);
  sqlite3_mutex_enter(sqlite3_db_mutex(db));
  if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
    rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  }
220809
220810
220811
220812
220813
220814
220815

220816
220817
220818
220819
220820
220821
220822
220823
220824
220825
220826
220827
220828
220829
220830
220831
220832
220833
220834
220835
220836
220837
220838
220839
220840
220841
220842
220843
      sApply.pSelect = 0;
      sApply.nCol = 0;
      sApply.azCol = 0;
      sApply.abPK = 0;
      sApply.bStat1 = 0;
      sApply.bDeferConstraints = 1;
      sApply.bRebaseStarted = 0;

      memset(&sApply.constraints, 0, sizeof(SessionBuffer));

      /* If an xFilter() callback was specified, invoke it now. If the
      ** xFilter callback returns zero, skip this table. If it returns
      ** non-zero, proceed. */
      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
      if( schemaMismatch ){
        zTab = sqlite3_mprintf("%s", zNew);
        if( zTab==0 ){
          rc = SQLITE_NOMEM;
          break;
        }
        nTab = (int)strlen(zTab);
        sApply.azCol = (const char **)zTab;
      }else{
        int nMinCol = 0;
        int i;

        sqlite3changeset_pk(pIter, &abPK, 0);
        rc = sessionTableInfo(0,
            db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
        );
        if( rc!=SQLITE_OK ) break;
        for(i=0; i<sApply.nCol; i++){
          if( sApply.abPK[i] ) nMinCol = i+1;
        }

        if( sApply.nCol==0 ){







>



















|
|







222665
222666
222667
222668
222669
222670
222671
222672
222673
222674
222675
222676
222677
222678
222679
222680
222681
222682
222683
222684
222685
222686
222687
222688
222689
222690
222691
222692
222693
222694
222695
222696
222697
222698
222699
222700
      sApply.pSelect = 0;
      sApply.nCol = 0;
      sApply.azCol = 0;
      sApply.abPK = 0;
      sApply.bStat1 = 0;
      sApply.bDeferConstraints = 1;
      sApply.bRebaseStarted = 0;
      sApply.bRowid = 0;
      memset(&sApply.constraints, 0, sizeof(SessionBuffer));

      /* If an xFilter() callback was specified, invoke it now. If the
      ** xFilter callback returns zero, skip this table. If it returns
      ** non-zero, proceed. */
      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
      if( schemaMismatch ){
        zTab = sqlite3_mprintf("%s", zNew);
        if( zTab==0 ){
          rc = SQLITE_NOMEM;
          break;
        }
        nTab = (int)strlen(zTab);
        sApply.azCol = (const char **)zTab;
      }else{
        int nMinCol = 0;
        int i;

        sqlite3changeset_pk(pIter, &abPK, 0);
        rc = sessionTableInfo(0, db, "main", zNew,
            &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK, &sApply.bRowid
        );
        if( rc!=SQLITE_OK ) break;
        for(i=0; i<sApply.nCol; i++){
          if( sApply.abPK[i] ) nMinCol = i+1;
        }

        if( sApply.nCol==0 ){
222711
222712
222713
222714
222715
222716
222717

222718
222719
222720
222721
222722
222723
222724
222725

222726
222727
222728
222729
222730
222731
222732
222733
222734
222735


222736

222737
222738
222739
222740
222741
222742
222743
  char *zContentExprlist;
  Fts5Tokenizer *pTok;
  fts5_tokenizer *pTokApi;
  int bLock;                      /* True when table is preparing statement */
  int ePattern;                   /* FTS_PATTERN_XXX constant */

  /* Values loaded from the %_config table */

  int iCookie;                    /* Incremented when %_config is modified */
  int pgsz;                       /* Approximate page size used in %_data */
  int nAutomerge;                 /* 'automerge' setting */
  int nCrisisMerge;               /* Maximum allowed segments per level */
  int nUsermerge;                 /* 'usermerge' setting */
  int nHashSize;                  /* Bytes of memory for in-memory hash */
  char *zRank;                    /* Name of rank function */
  char *zRankArgs;                /* Arguments to rank function */


  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  char **pzErrmsg;

#ifdef SQLITE_DEBUG
  int bPrefixIndex;               /* True to use prefix-indexes */
#endif
};

/* Current expected value of %_config table 'version' field */


#define FTS5_CURRENT_VERSION  4


#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







>








>









|
>
>
|
>







224568
224569
224570
224571
224572
224573
224574
224575
224576
224577
224578
224579
224580
224581
224582
224583
224584
224585
224586
224587
224588
224589
224590
224591
224592
224593
224594
224595
224596
224597
224598
224599
224600
224601
224602
224603
224604
224605
  char *zContentExprlist;
  Fts5Tokenizer *pTok;
  fts5_tokenizer *pTokApi;
  int bLock;                      /* True when table is preparing statement */
  int ePattern;                   /* FTS_PATTERN_XXX constant */

  /* Values loaded from the %_config table */
  int iVersion;                   /* fts5 file format 'version' */
  int iCookie;                    /* Incremented when %_config is modified */
  int pgsz;                       /* Approximate page size used in %_data */
  int nAutomerge;                 /* 'automerge' setting */
  int nCrisisMerge;               /* Maximum allowed segments per level */
  int nUsermerge;                 /* 'usermerge' setting */
  int nHashSize;                  /* Bytes of memory for in-memory hash */
  char *zRank;                    /* Name of rank function */
  char *zRankArgs;                /* Arguments to rank function */
  int bSecureDelete;              /* 'secure-delete' */

  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  char **pzErrmsg;

#ifdef SQLITE_DEBUG
  int bPrefixIndex;               /* True to use prefix-indexes */
#endif
};

/* 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
222895
222896
222897
222898
222899
222900
222901

222902
222903
222904
222905
222906
222907
222908
#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */

/* The following are used internally by the fts5_index.c module. They are
** defined here only to make it easier to avoid clashes with the flags
** above. */
#define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
#define FTS5INDEX_QUERY_NOOUTPUT   0x0020


/*
** Create/destroy an Fts5Index object.
*/
static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
static int sqlite3Fts5IndexClose(Fts5Index *p);








>







224757
224758
224759
224760
224761
224762
224763
224764
224765
224766
224767
224768
224769
224770
224771
#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */

/* The following are used internally by the fts5_index.c module. They are
** defined here only to make it easier to avoid clashes with the flags
** above. */
#define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
#define FTS5INDEX_QUERY_NOOUTPUT   0x0020
#define FTS5INDEX_QUERY_SKIPHASH   0x0040

/*
** Create/destroy an Fts5Index object.
*/
static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
static int sqlite3Fts5IndexClose(Fts5Index *p);

223049
223050
223051
223052
223053
223054
223055
223056
223057
223058
223059
223060
223061
223062
223063
** Interface to code in fts5_varint.c.
*/
static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
static int sqlite3Fts5GetVarintLen(u32 iVal);
static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);

#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
#define fts5GetVarint    sqlite3Fts5GetVarint

#define fts5FastGetVarint32(a, iOff, nVal) {      \
  nVal = (a)[iOff++];                             \
  if( nVal & 0x80 ){                              \
    iOff--;                                       \
    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \







|







224912
224913
224914
224915
224916
224917
224918
224919
224920
224921
224922
224923
224924
224925
224926
** Interface to code in fts5_varint.c.
*/
static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
static int sqlite3Fts5GetVarintLen(u32 iVal);
static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);

#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&(b))
#define fts5GetVarint    sqlite3Fts5GetVarint

#define fts5FastGetVarint32(a, iOff, nVal) {      \
  nVal = (a)[iOff++];                             \
  if( nVal & 0x80 ){                              \
    iOff--;                                       \
    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
225028
225029
225030
225031
225032
225033
225034
225035
225036
225037
225038
225039
225040
225041
225042
225043
225044
225045
225046
225047
225048
225049
225050
225051
225052
225053
225054
225055
225056
225057
225058
225059
225060
225061
225062
225063
225064
225065
  int iPos;

  UNUSED_PARAM2(pToken, nToken);

  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  iPos = p->iPos++;

  if( p->iRangeEnd>0 ){
    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  }

  if( iPos==p->iter.iStart ){
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
    fts5HighlightAppend(&rc, p, p->zOpen, -1);
    p->iOff = iStartOff;
  }

  if( iPos==p->iter.iEnd ){
    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
      fts5HighlightAppend(&rc, p, p->zOpen, -1);
    }
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
    fts5HighlightAppend(&rc, p, p->zClose, -1);
    p->iOff = iEndOff;
    if( rc==SQLITE_OK ){
      rc = fts5CInstIterNext(&p->iter);
    }
  }

  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
    p->iOff = iEndOff;
    if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
      fts5HighlightAppend(&rc, p, p->zClose, -1);
    }
  }








|











|










|







226891
226892
226893
226894
226895
226896
226897
226898
226899
226900
226901
226902
226903
226904
226905
226906
226907
226908
226909
226910
226911
226912
226913
226914
226915
226916
226917
226918
226919
226920
226921
226922
226923
226924
226925
226926
226927
226928
  int iPos;

  UNUSED_PARAM2(pToken, nToken);

  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  iPos = p->iPos++;

  if( p->iRangeEnd>=0 ){
    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  }

  if( iPos==p->iter.iStart ){
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
    fts5HighlightAppend(&rc, p, p->zOpen, -1);
    p->iOff = iStartOff;
  }

  if( iPos==p->iter.iEnd ){
    if( p->iRangeEnd>=0 && p->iter.iStart<p->iRangeStart ){
      fts5HighlightAppend(&rc, p, p->zOpen, -1);
    }
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
    fts5HighlightAppend(&rc, p, p->zClose, -1);
    p->iOff = iEndOff;
    if( rc==SQLITE_OK ){
      rc = fts5CInstIterNext(&p->iter);
    }
  }

  if( p->iRangeEnd>=0 && iPos==p->iRangeEnd ){
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
    p->iOff = iEndOff;
    if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
      fts5HighlightAppend(&rc, p, p->zClose, -1);
    }
  }

225086
225087
225088
225089
225090
225091
225092

225093
225094
225095
225096
225097
225098
225099
    return;
  }

  iCol = sqlite3_value_int(apVal[0]);
  memset(&ctx, 0, sizeof(HighlightContext));
  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);

  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);

  if( ctx.zIn ){
    if( rc==SQLITE_OK ){
      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
    }








>







226949
226950
226951
226952
226953
226954
226955
226956
226957
226958
226959
226960
226961
226962
226963
    return;
  }

  iCol = sqlite3_value_int(apVal[0]);
  memset(&ctx, 0, sizeof(HighlightContext));
  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  ctx.iRangeEnd = -1;
  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);

  if( ctx.zIn ){
    if( rc==SQLITE_OK ){
      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
    }

225271
225272
225273
225274
225275
225276
225277

225278
225279
225280
225281
225282
225283
225284
  }

  nCol = pApi->xColumnCount(pFts);
  memset(&ctx, 0, sizeof(HighlightContext));
  iCol = sqlite3_value_int(apVal[0]);
  ctx.zOpen = fts5ValueToText(apVal[1]);
  ctx.zClose = fts5ValueToText(apVal[2]);

  zEllips = fts5ValueToText(apVal[3]);
  nToken = sqlite3_value_int(apVal[4]);

  iBestCol = (iCol>=0 ? iCol : 0);
  nPhrase = pApi->xPhraseCount(pFts);
  aSeen = sqlite3_malloc(nPhrase);
  if( aSeen==0 ){







>







227135
227136
227137
227138
227139
227140
227141
227142
227143
227144
227145
227146
227147
227148
227149
  }

  nCol = pApi->xColumnCount(pFts);
  memset(&ctx, 0, sizeof(HighlightContext));
  iCol = sqlite3_value_int(apVal[0]);
  ctx.zOpen = fts5ValueToText(apVal[1]);
  ctx.zClose = fts5ValueToText(apVal[2]);
  ctx.iRangeEnd = -1;
  zEllips = fts5ValueToText(apVal[3]);
  nToken = sqlite3_value_int(apVal[4]);

  iBestCol = (iCol>=0 ? iCol : 0);
  nPhrase = pApi->xPhraseCount(pFts);
  aSeen = sqlite3_malloc(nPhrase);
  if( aSeen==0 ){
226539
226540
226541
226542
226543
226544
226545

226546
226547
226548
226549
226550
226551
226552
  pRet->bPrefixIndex = 1;
#endif
  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
    rc = SQLITE_ERROR;
  }


  for(i=3; rc==SQLITE_OK && i<nArg; i++){
    const char *zOrig = azArg[i];
    const char *z;
    char *zOne = 0;
    char *zTwo = 0;
    int bOption = 0;
    int bMustBeCol = 0;







>







228404
228405
228406
228407
228408
228409
228410
228411
228412
228413
228414
228415
228416
228417
228418
  pRet->bPrefixIndex = 1;
#endif
  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
    rc = SQLITE_ERROR;
  }

  assert( (pRet->abUnindexed && pRet->azCol) || rc!=SQLITE_OK );
  for(i=3; rc==SQLITE_OK && i<nArg; i++){
    const char *zOrig = azArg[i];
    const char *z;
    char *zOne = 0;
    char *zTwo = 0;
    int bOption = 0;
    int bMustBeCol = 0;
226892
226893
226894
226895
226896
226897
226898












226899
226900
226901
226902
226903
226904
226905
      sqlite3_free(pConfig->zRankArgs);
      pConfig->zRank = zRank;
      pConfig->zRankArgs = zRankArgs;
    }else if( rc==SQLITE_ERROR ){
      rc = SQLITE_OK;
      *pbBadkey = 1;
    }












  }else{
    *pbBadkey = 1;
  }
  return rc;
}

/*







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







228758
228759
228760
228761
228762
228763
228764
228765
228766
228767
228768
228769
228770
228771
228772
228773
228774
228775
228776
228777
228778
228779
228780
228781
228782
228783
      sqlite3_free(pConfig->zRankArgs);
      pConfig->zRank = zRank;
      pConfig->zRankArgs = zRankArgs;
    }else if( rc==SQLITE_ERROR ){
      rc = SQLITE_OK;
      *pbBadkey = 1;
    }
  }

  else if( 0==sqlite3_stricmp(zKey, "secure-delete") ){
    int bVal = -1;
    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
      bVal = sqlite3_value_int(pVal);
    }
    if( bVal<0 ){
      *pbBadkey = 1;
    }else{
      pConfig->bSecureDelete = (bVal ? 1 : 0);
    }
  }else{
    *pbBadkey = 1;
  }
  return rc;
}

/*
226936
226937
226938
226939
226940
226941
226942

226943


226944
226945
226946
226947
226948
226949
226950
226951


226952
226953
226954
226955
226956
226957
226958
        int bDummy = 0;
        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
      }
    }
    rc = sqlite3_finalize(p);
  }


  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){


    rc = SQLITE_ERROR;
    if( pConfig->pzErrmsg ){
      assert( 0==*pConfig->pzErrmsg );
      *pConfig->pzErrmsg = sqlite3_mprintf(
          "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
          iVersion, FTS5_CURRENT_VERSION
      );
    }


  }

  if( rc==SQLITE_OK ){
    pConfig->iCookie = iCookie;
  }
  return rc;
}







>
|
>
>



|
|
|


>
>







228814
228815
228816
228817
228818
228819
228820
228821
228822
228823
228824
228825
228826
228827
228828
228829
228830
228831
228832
228833
228834
228835
228836
228837
228838
228839
228840
228841
        int bDummy = 0;
        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
      }
    }
    rc = sqlite3_finalize(p);
  }

  if( rc==SQLITE_OK
   && iVersion!=FTS5_CURRENT_VERSION
   && iVersion!=FTS5_CURRENT_VERSION_SECUREDELETE
  ){
    rc = SQLITE_ERROR;
    if( pConfig->pzErrmsg ){
      assert( 0==*pConfig->pzErrmsg );
      *pConfig->pzErrmsg = sqlite3_mprintf("invalid fts5 file format "
          "(found %d, expected %d or %d) - run 'rebuild'",
          iVersion, FTS5_CURRENT_VERSION, FTS5_CURRENT_VERSION_SECUREDELETE
      );
    }
  }else{
    pConfig->iVersion = iVersion;
  }

  if( rc==SQLITE_OK ){
    pConfig->iCookie = iCookie;
  }
  return rc;
}
226971
226972
226973
226974
226975
226976
226977




226978
226979
226980
226981
226982
226983
226984
**
*/



/* #include "fts5Int.h" */
/* #include "fts5parse.h" */





/*
** All token types in the generated fts5parse.h file are greater than 0.
*/
#define FTS5_EOF 0

#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))







>
>
>
>







228854
228855
228856
228857
228858
228859
228860
228861
228862
228863
228864
228865
228866
228867
228868
228869
228870
228871
**
*/



/* #include "fts5Int.h" */
/* #include "fts5parse.h" */

#ifndef SQLITE_FTS5_MAX_EXPR_DEPTH
# define SQLITE_FTS5_MAX_EXPR_DEPTH 256
#endif

/*
** All token types in the generated fts5parse.h file are greater than 0.
*/
#define FTS5_EOF 0

#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
227012
227013
227014
227015
227016
227017
227018





227019
227020
227021
227022
227023

227024
227025
227026
227027
227028
227029
227030
**   Expression node type. Always one of:
**
**       FTS5_AND                 (nChild, apChild valid)
**       FTS5_OR                  (nChild, apChild valid)
**       FTS5_NOT                 (nChild, apChild valid)
**       FTS5_STRING              (pNear valid)
**       FTS5_TERM                (pNear valid)





*/
struct Fts5ExprNode {
  int eType;                      /* Node type */
  int bEof;                       /* True at EOF */
  int bNomatch;                   /* True if entry is not a match */


  /* Next method for this node. */
  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);

  i64 iRowid;                     /* Current rowid */
  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */








>
>
>
>
>





>







228899
228900
228901
228902
228903
228904
228905
228906
228907
228908
228909
228910
228911
228912
228913
228914
228915
228916
228917
228918
228919
228920
228921
228922
228923
**   Expression node type. Always one of:
**
**       FTS5_AND                 (nChild, apChild valid)
**       FTS5_OR                  (nChild, apChild valid)
**       FTS5_NOT                 (nChild, apChild valid)
**       FTS5_STRING              (pNear valid)
**       FTS5_TERM                (pNear valid)
**
** iHeight:
**   Distance from this node to furthest leaf. This is always 0 for nodes
**   of type FTS5_STRING and FTS5_TERM. For all other nodes it is one
**   greater than the largest child value.
*/
struct Fts5ExprNode {
  int eType;                      /* Node type */
  int bEof;                       /* True at EOF */
  int bNomatch;                   /* True if entry is not a match */
  int iHeight;                    /* Distance to tree leaf nodes */

  /* Next method for this node. */
  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);

  i64 iRowid;                     /* Current rowid */
  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */

227086
227087
227088
227089
227090
227091
227092

























227093
227094
227095
227096
227097
227098
227099
  int rc;
  int nPhrase;                    /* Size of apPhrase array */
  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
  Fts5ExprNode *pExpr;            /* Result of a successful parse */
  int bPhraseToAnd;               /* Convert "a+b" to "a AND b" */
};


























static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  va_list ap;
  va_start(ap, zFmt);
  if( pParse->rc==SQLITE_OK ){
    assert( pParse->zErr==0 );
    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
    pParse->rc = SQLITE_ERROR;







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







228979
228980
228981
228982
228983
228984
228985
228986
228987
228988
228989
228990
228991
228992
228993
228994
228995
228996
228997
228998
228999
229000
229001
229002
229003
229004
229005
229006
229007
229008
229009
229010
229011
229012
229013
229014
229015
229016
229017
  int rc;
  int nPhrase;                    /* Size of apPhrase array */
  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
  Fts5ExprNode *pExpr;            /* Result of a successful parse */
  int bPhraseToAnd;               /* Convert "a+b" to "a AND b" */
};

/*
** Check that the Fts5ExprNode.iHeight variables are set correctly in
** the expression tree passed as the only argument.
*/
#ifndef NDEBUG
static void assert_expr_depth_ok(int rc, Fts5ExprNode *p){
  if( rc==SQLITE_OK ){
    if( p->eType==FTS5_TERM || p->eType==FTS5_STRING || p->eType==0 ){
      assert( p->iHeight==0 );
    }else{
      int ii;
      int iMaxChild = 0;
      for(ii=0; ii<p->nChild; ii++){
        Fts5ExprNode *pChild = p->apChild[ii];
        iMaxChild = MAX(iMaxChild, pChild->iHeight);
        assert_expr_depth_ok(SQLITE_OK, pChild);
      }
      assert( p->iHeight==iMaxChild+1 );
    }
  }
}
#else
# define assert_expr_depth_ok(rc, p)
#endif

static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  va_list ap;
  va_start(ap, zFmt);
  if( pParse->rc==SQLITE_OK ){
    assert( pParse->zErr==0 );
    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
    pParse->rc = SQLITE_ERROR;
227199
227200
227201
227202
227203
227204
227205


227206
227207
227208
227209
227210
227211
227212
  sParse.pConfig = pConfig;

  do {
    t = fts5ExprGetToken(&sParse, &z, &token);
    sqlite3Fts5Parser(pEngine, t, token, &sParse);
  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);



  /* If the LHS of the MATCH expression was a user column, apply the
  ** implicit column-filter.  */
  if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
    int n = sizeof(Fts5Colset);
    Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
    if( pColset ){







>
>







229117
229118
229119
229120
229121
229122
229123
229124
229125
229126
229127
229128
229129
229130
229131
229132
  sParse.pConfig = pConfig;

  do {
    t = fts5ExprGetToken(&sParse, &z, &token);
    sqlite3Fts5Parser(pEngine, t, token, &sParse);
  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);

  assert_expr_depth_ok(sParse.rc, sParse.pExpr);

  /* If the LHS of the MATCH expression was a user column, apply the
  ** implicit column-filter.  */
  if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
    int n = sizeof(Fts5Colset);
    Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
    if( pColset ){
227362
227363
227364
227365
227366
227367
227368
227369
227370
227371
227372
227373
227374
227375
227376
  }
}

static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){
  Fts5Parse sParse;
  memset(&sParse, 0, sizeof(sParse));

  if( *pp1 ){
    Fts5Expr *p1 = *pp1;
    int nPhrase = p1->nPhrase + p2->nPhrase;

    p1->pRoot = sqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0);
    p2->pRoot = 0;

    if( sParse.rc==SQLITE_OK ){







|







229282
229283
229284
229285
229286
229287
229288
229289
229290
229291
229292
229293
229294
229295
229296
  }
}

static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){
  Fts5Parse sParse;
  memset(&sParse, 0, sizeof(sParse));

  if( *pp1 && p2 ){
    Fts5Expr *p1 = *pp1;
    int nPhrase = p1->nPhrase + p2->nPhrase;

    p1->pRoot = sqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0);
    p2->pRoot = 0;

    if( sParse.rc==SQLITE_OK ){
227387
227388
227389
227390
227391
227392
227393
227394
227395
227396
227397
227398
227399
227400
227401
        }
        p1->nPhrase = nPhrase;
        p1->apExprPhrase = ap;
      }
    }
    sqlite3_free(p2->apExprPhrase);
    sqlite3_free(p2);
  }else{
    *pp1 = p2;
  }

  return sParse.rc;
}

/*







|







229307
229308
229309
229310
229311
229312
229313
229314
229315
229316
229317
229318
229319
229320
229321
        }
        p1->nPhrase = nPhrase;
        p1->apExprPhrase = ap;
      }
    }
    sqlite3_free(p2->apExprPhrase);
    sqlite3_free(p2);
  }else if( p2 ){
    *pp1 = p2;
  }

  return sParse.rc;
}

/*
229161
229162
229163
229164
229165
229166
229167

229168
229169
229170
229171
229172
229173
229174
229175



229176
229177
229178
229179
229180
229181
229182
      pNode->xNext = fts5ExprNodeNext_NOT;
      break;
    };
  }
}

static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){

  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
    p->nChild += pSub->nChild;
    sqlite3_free(pSub);
  }else{
    p->apChild[p->nChild++] = pSub;
  }



}

/*
** This function is used when parsing LIKE or GLOB patterns against
** trigram indexes that specify either detail=column or detail=none.
** It converts a phrase:
**







>








>
>
>







231081
231082
231083
231084
231085
231086
231087
231088
231089
231090
231091
231092
231093
231094
231095
231096
231097
231098
231099
231100
231101
231102
231103
231104
231105
231106
      pNode->xNext = fts5ExprNodeNext_NOT;
      break;
    };
  }
}

static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  int ii = p->nChild;
  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
    p->nChild += pSub->nChild;
    sqlite3_free(pSub);
  }else{
    p->apChild[p->nChild++] = pSub;
  }
  for( ; ii<p->nChild; ii++){
    p->iHeight = MAX(p->iHeight, p->apChild[ii]->iHeight + 1);
  }
}

/*
** This function is used when parsing LIKE or GLOB patterns against
** trigram indexes that specify either detail=column or detail=none.
** It converts a phrase:
**
229199
229200
229201
229202
229203
229204
229205

229206
229207
229208
229209
229210
229211
229212
  assert( pParse->bPhraseToAnd );

  nByte = sizeof(Fts5ExprNode) + nTerm*sizeof(Fts5ExprNode*);
  pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  if( pRet ){
    pRet->eType = FTS5_AND;
    pRet->nChild = nTerm;

    fts5ExprAssignXNext(pRet);
    pParse->nPhrase--;
    for(ii=0; ii<nTerm; ii++){
      Fts5ExprPhrase *pPhrase = (Fts5ExprPhrase*)sqlite3Fts5MallocZero(
          &pParse->rc, sizeof(Fts5ExprPhrase)
      );
      if( pPhrase ){







>







231123
231124
231125
231126
231127
231128
231129
231130
231131
231132
231133
231134
231135
231136
231137
  assert( pParse->bPhraseToAnd );

  nByte = sizeof(Fts5ExprNode) + nTerm*sizeof(Fts5ExprNode*);
  pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  if( pRet ){
    pRet->eType = FTS5_AND;
    pRet->nChild = nTerm;
    pRet->iHeight = 1;
    fts5ExprAssignXNext(pRet);
    pParse->nPhrase--;
    for(ii=0; ii<nTerm; ii++){
      Fts5ExprPhrase *pPhrase = (Fts5ExprPhrase*)sqlite3Fts5MallocZero(
          &pParse->rc, sizeof(Fts5ExprPhrase)
      );
      if( pPhrase ){
229304
229305
229306
229307
229308
229309
229310








229311
229312
229313
229314
229315
229316
229317
              sqlite3_free(pRet);
              pRet = 0;
            }
          }
        }else{
          fts5ExprAddChildren(pRet, pLeft);
          fts5ExprAddChildren(pRet, pRight);








        }
      }
    }
  }

  if( pRet==0 ){
    assert( pParse->rc!=SQLITE_OK );







>
>
>
>
>
>
>
>







231229
231230
231231
231232
231233
231234
231235
231236
231237
231238
231239
231240
231241
231242
231243
231244
231245
231246
231247
231248
231249
231250
              sqlite3_free(pRet);
              pRet = 0;
            }
          }
        }else{
          fts5ExprAddChildren(pRet, pLeft);
          fts5ExprAddChildren(pRet, pRight);
          if( pRet->iHeight>SQLITE_FTS5_MAX_EXPR_DEPTH ){
            sqlite3Fts5ParseError(pParse,
                "fts5 expression tree is too large (maximum depth %d)",
                SQLITE_FTS5_MAX_EXPR_DEPTH
            );
            sqlite3_free(pRet);
            pRet = 0;
          }
        }
      }
    }
  }

  if( pRet==0 ){
    assert( pParse->rc!=SQLITE_OK );
230904
230905
230906
230907
230908
230909
230910


230911
230912
230913
230914
230915
230916
230917
  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=?" */
  sqlite3_stmt *pIdxSelect;
  int nRead;                      /* Total number of blocks read */



  sqlite3_stmt *pDataVersion;
  i64 iStructVersion;             /* data_version when pStruct read */
  Fts5Structure *pStruct;         /* Current db structure (or NULL) */
};

struct Fts5DoclistIter {
  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */







>
>







232837
232838
232839
232840
232841
232842
232843
232844
232845
232846
232847
232848
232849
232850
232851
232852
  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=?" */
  sqlite3_stmt *pIdxSelect;
  int nRead;                      /* Total number of blocks read */

  sqlite3_stmt *pDeleteFromIdx;

  sqlite3_stmt *pDataVersion;
  i64 iStructVersion;             /* data_version when pStruct read */
  Fts5Structure *pStruct;         /* Current db structure (or NULL) */
};

struct Fts5DoclistIter {
  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
230996
230997
230998
230999
231000
231001
231002
231003
231004
231005
231006
231007
231008
231009
231010
231011
231012
**
** iLeafPgno:
**   Current leaf page number within segment.
**
** iLeafOffset:
**   Byte offset within the current leaf that is the first byte of the
**   position list data (one byte passed the position-list size field).
**   rowid field of the current entry. Usually this is the size field of the
**   position list data. The exception is if the rowid for the current entry
**   is the last thing on the leaf page.
**
** pLeaf:
**   Buffer containing current leaf page data. Set to NULL at EOF.
**
** iTermLeafPgno, iTermLeafOffset:
**   Leaf page number containing the last term read from the segment. And
**   the offset immediately following the term data.







<
<
<







232931
232932
232933
232934
232935
232936
232937



232938
232939
232940
232941
232942
232943
232944
**
** iLeafPgno:
**   Current leaf page number within segment.
**
** iLeafOffset:
**   Byte offset within the current leaf that is the first byte of the
**   position list data (one byte passed the position-list size field).



**
** pLeaf:
**   Buffer containing current leaf page data. Set to NULL at EOF.
**
** iTermLeafPgno, iTermLeafOffset:
**   Leaf page number containing the last term read from the segment. And
**   the offset immediately following the term data.
231557
231558
231559
231560
231561
231562
231563

231564
231565
231566
231567
231568
231569
231570
        pLvl->nSeg = nTotal;
        for(iSeg=0; iSeg<nTotal; iSeg++){
          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
          if( i>=nData ){
            rc = FTS5_CORRUPT;
            break;
          }

          i += fts5GetVarint32(&pData[i], pSeg->iSegid);
          i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
          i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
          if( pSeg->pgnoLast<pSeg->pgnoFirst ){
            rc = FTS5_CORRUPT;
            break;
          }







>







233489
233490
233491
233492
233493
233494
233495
233496
233497
233498
233499
233500
233501
233502
233503
        pLvl->nSeg = nTotal;
        for(iSeg=0; iSeg<nTotal; iSeg++){
          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
          if( i>=nData ){
            rc = FTS5_CORRUPT;
            break;
          }
          assert( pSeg!=0 );
          i += fts5GetVarint32(&pData[i], pSeg->iSegid);
          i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
          i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
          if( pSeg->pgnoLast<pSeg->pgnoFirst ){
            rc = FTS5_CORRUPT;
            break;
          }
231587
231588
231589
231590
231591
231592
231593

231594
231595
231596
231597
231598
231599
231600

/*
** Add a level to the Fts5Structure.aLevel[] array of structure object
** (*ppStruct).
*/
static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  fts5StructureMakeWritable(pRc, ppStruct);

  if( *pRc==SQLITE_OK ){
    Fts5Structure *pStruct = *ppStruct;
    int nLevel = pStruct->nLevel;
    sqlite3_int64 nByte = (
        sizeof(Fts5Structure) +                  /* Main structure */
        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
    );







>







233520
233521
233522
233523
233524
233525
233526
233527
233528
233529
233530
233531
233532
233533
233534

/*
** Add a level to the Fts5Structure.aLevel[] array of structure object
** (*ppStruct).
*/
static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  fts5StructureMakeWritable(pRc, ppStruct);
  assert( (ppStruct!=0 && (*ppStruct)!=0) || (*pRc)!=SQLITE_OK );
  if( *pRc==SQLITE_OK ){
    Fts5Structure *pStruct = *ppStruct;
    int nLevel = pStruct->nLevel;
    sqlite3_int64 nByte = (
        sizeof(Fts5Structure) +                  /* Main structure */
        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
    );
232045
232046
232047
232048
232049
232050
232051
232052
232053

232054
232055
232056
232057
232058
232059
232060
232061
232062
232063
232064
232065
232066
232067
232068
232069
232070
232071
232072

232073
232074
232075
232076
232077
232078
232079
232080
232081
232082
232083
232084
232085
232086

232087

232088
232089
232090
232091
232092
232093
232094
  int iOff = pLvl->iOff;

  assert( pLvl->bEof==0 );
  if( iOff<=pLvl->iFirstOff ){
    pLvl->bEof = 1;
  }else{
    u8 *a = pLvl->pData->p;
    i64 iVal;
    int iLimit;

    int ii;
    int nZero = 0;

    /* Currently iOff points to the first byte of a varint. This block
    ** decrements iOff until it points to the first byte of the previous
    ** varint. Taking care not to read any memory locations that occur
    ** before the buffer in memory.  */
    iLimit = (iOff>9 ? iOff-9 : 0);
    for(iOff--; iOff>iLimit; iOff--){
      if( (a[iOff-1] & 0x80)==0 ) break;
    }

    fts5GetVarint(&a[iOff], (u64*)&iVal);
    pLvl->iRowid -= iVal;
    pLvl->iLeafPgno--;

    /* Skip backwards past any 0x00 varints. */
    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
      nZero++;

    }
    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
      /* The byte immediately before the last 0x00 byte has the 0x80 bit
      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
      ** bytes before a[ii]. */
      int bZero = 0;              /* True if last 0x00 counts */
      if( (ii-8)>=pLvl->iFirstOff ){
        int j;
        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
        bZero = (j>8);
      }
      if( bZero==0 ) nZero--;
    }
    pLvl->iLeafPgno -= nZero;

    pLvl->iOff = iOff - nZero;

  }

  return pLvl->bEof;
}

static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];







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

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







233979
233980
233981
233982
233983
233984
233985
233986
233987
233988
233989
233990
233991








233992



233993

233994
233995
233996
233997



233998





233999
234000

234001
234002
234003
234004
234005
234006
234007
234008
234009
234010
234011
  int iOff = pLvl->iOff;

  assert( pLvl->bEof==0 );
  if( iOff<=pLvl->iFirstOff ){
    pLvl->bEof = 1;
  }else{
    u8 *a = pLvl->pData->p;

    pLvl->iOff = 0;
    fts5DlidxLvlNext(pLvl);
    while( 1 ){
      int nZero = 0;
      int ii = pLvl->iOff;








      u64 delta = 0;





      while( a[ii]==0 ){
        nZero++;
        ii++;
      }



      ii += sqlite3Fts5GetVarint(&a[ii], &delta);






      if( ii>=iOff ) break;

      pLvl->iLeafPgno += nZero+1;
      pLvl->iRowid += delta;
      pLvl->iOff = ii;
    }
  }

  return pLvl->bEof;
}

static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
232276
232277
232278
232279
232280
232281
232282
232283
232284
232285
232286
232287
232288
232289
232290
}

static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
  i64 iOff = pIter->iLeafOffset;

  ASSERT_SZLEAF_OK(pIter->pLeaf);
  if( iOff>=pIter->pLeaf->szLeaf ){
    fts5SegIterNextPage(p, pIter);
    if( pIter->pLeaf==0 ){
      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
      return;
    }
    iOff = 4;
    a = pIter->pLeaf->p;







|







234193
234194
234195
234196
234197
234198
234199
234200
234201
234202
234203
234204
234205
234206
234207
}

static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
  i64 iOff = pIter->iLeafOffset;

  ASSERT_SZLEAF_OK(pIter->pLeaf);
  while( iOff>=pIter->pLeaf->szLeaf ){
    fts5SegIterNextPage(p, pIter);
    if( pIter->pLeaf==0 ){
      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
      return;
    }
    iOff = 4;
    a = pIter->pLeaf->p;
232375
232376
232377
232378
232379
232380
232381

232382

232383
232384
232385
232386
232387
232388
232389
232390
232391
232392
  }

  if( p->rc==SQLITE_OK ){
    memset(pIter, 0, sizeof(*pIter));
    fts5SegIterSetNext(p, pIter);
    pIter->pSeg = pSeg;
    pIter->iLeafPgno = pSeg->pgnoFirst-1;

    fts5SegIterNextPage(p, pIter);

  }

  if( p->rc==SQLITE_OK ){
    pIter->iLeafOffset = 4;
    assert( pIter->pLeaf!=0 );
    assert_nc( pIter->pLeaf->nn>4 );
    assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
    fts5SegIterLoadTerm(p, pIter, 0);
    fts5SegIterLoadNPos(p, pIter);







>
|
>


|







234292
234293
234294
234295
234296
234297
234298
234299
234300
234301
234302
234303
234304
234305
234306
234307
234308
234309
234310
234311
  }

  if( p->rc==SQLITE_OK ){
    memset(pIter, 0, sizeof(*pIter));
    fts5SegIterSetNext(p, pIter);
    pIter->pSeg = pSeg;
    pIter->iLeafPgno = pSeg->pgnoFirst-1;
    do {
      fts5SegIterNextPage(p, pIter);
    }while( p->rc==SQLITE_OK && pIter->pLeaf && pIter->pLeaf->nn==4 );
  }

  if( p->rc==SQLITE_OK && pIter->pLeaf ){
    pIter->iLeafOffset = 4;
    assert( pIter->pLeaf!=0 );
    assert_nc( pIter->pLeaf->nn>4 );
    assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
    fts5SegIterLoadTerm(p, pIter, 0);
    fts5SegIterLoadNPos(p, pIter);
232572
232573
232574
232575
232576
232577
232578
232579
232580
232581
232582
232583
232584
232585
232586
  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );

  ASSERT_SZLEAF_OK(pIter->pLeaf);
  iOff = pIter->iLeafOffset;

  /* Next entry is on the next page */
  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
    fts5SegIterNextPage(p, pIter);
    if( p->rc || pIter->pLeaf==0 ) return;
    pIter->iRowid = 0;
    iOff = 4;
  }

  if( iOff<pIter->iEndofDoclist ){







|







234491
234492
234493
234494
234495
234496
234497
234498
234499
234500
234501
234502
234503
234504
234505
  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );

  ASSERT_SZLEAF_OK(pIter->pLeaf);
  iOff = pIter->iLeafOffset;

  /* Next entry is on the next page */
  while( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
    fts5SegIterNextPage(p, pIter);
    if( p->rc || pIter->pLeaf==0 ) return;
    pIter->iRowid = 0;
    iOff = 4;
  }

  if( iOff<pIter->iEndofDoclist ){
232765
232766
232767
232768
232769
232770
232771
232772
232773
232774
232775
232776
232777
232778
232779
** the doclist.
*/
static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  Fts5DlidxIter *pDlidx = pIter->pDlidx;
  Fts5Data *pLast = 0;
  int pgnoLast = 0;

  if( pDlidx ){
    int iSegid = pIter->pSeg->iSegid;
    pgnoLast = fts5DlidxIterPgno(pDlidx);
    pLast = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  }else{
    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */

    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of







|







234684
234685
234686
234687
234688
234689
234690
234691
234692
234693
234694
234695
234696
234697
234698
** the doclist.
*/
static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  Fts5DlidxIter *pDlidx = pIter->pDlidx;
  Fts5Data *pLast = 0;
  int pgnoLast = 0;

  if( pDlidx && p->pConfig->iVersion==FTS5_CURRENT_VERSION ){
    int iSegid = pIter->pSeg->iSegid;
    pgnoLast = fts5DlidxIterPgno(pDlidx);
    pLast = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  }else{
    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */

    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
233326
233327
233328
233329
233330
233331
233332
233333

233334
233335
233336
233337
233338
233339
233340
233341
233342
233343
233344
233345
233346
233347
233348
233349
233350
233351
233352




233353
233354
233355
233356
233357
233358
233359
233360
233361
233362


233363
233364
233365
233366
233367
233368
233369

  pRes->iFirst = (u16)iRes;
  return 0;
}

/*
** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
** It is an error if leaf iLeafPgno does not exist or contains no rowids.

*/
static void fts5SegIterGotoPage(
  Fts5Index *p,                   /* FTS5 backend object */
  Fts5SegIter *pIter,             /* Iterator to advance */
  int iLeafPgno
){
  assert( iLeafPgno>pIter->iLeafPgno );

  if( iLeafPgno>pIter->pSeg->pgnoLast ){
    p->rc = FTS5_CORRUPT;
  }else{
    fts5DataRelease(pIter->pNextLeaf);
    pIter->pNextLeaf = 0;
    pIter->iLeafPgno = iLeafPgno-1;
    fts5SegIterNextPage(p, pIter);
    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );

    if( p->rc==SQLITE_OK && ALWAYS(pIter->pLeaf!=0) ){
      int iOff;




      u8 *a = pIter->pLeaf->p;
      int n = pIter->pLeaf->szLeaf;

      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
      if( iOff<4 || iOff>=n ){
        p->rc = FTS5_CORRUPT;
      }else{
        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
        pIter->iLeafOffset = iOff;
        fts5SegIterLoadNPos(p, pIter);


      }
    }
  }
}

/*
** Advance the iterator passed as the second argument until it is at or







|
>














<
<

|

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







235245
235246
235247
235248
235249
235250
235251
235252
235253
235254
235255
235256
235257
235258
235259
235260
235261
235262
235263
235264
235265
235266
235267


235268
235269
235270
235271
235272
235273
235274
235275
235276


235277
235278
235279
235280
235281
235282
235283
235284
235285
235286
235287
235288
235289
235290
235291

  pRes->iFirst = (u16)iRes;
  return 0;
}

/*
** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
** It is an error if leaf iLeafPgno does not exist. Unless the db is
** a 'secure-delete' db, if it contains no rowids then this is also an error.
*/
static void fts5SegIterGotoPage(
  Fts5Index *p,                   /* FTS5 backend object */
  Fts5SegIter *pIter,             /* Iterator to advance */
  int iLeafPgno
){
  assert( iLeafPgno>pIter->iLeafPgno );

  if( iLeafPgno>pIter->pSeg->pgnoLast ){
    p->rc = FTS5_CORRUPT;
  }else{
    fts5DataRelease(pIter->pNextLeaf);
    pIter->pNextLeaf = 0;
    pIter->iLeafPgno = iLeafPgno-1;



    while( p->rc==SQLITE_OK ){
      int iOff;
      fts5SegIterNextPage(p, pIter);
      if( pIter->pLeaf==0 ) break;
      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
      if( iOff>0 ){
        u8 *a = pIter->pLeaf->p;
        int n = pIter->pLeaf->szLeaf;


        if( iOff<4 || iOff>=n ){
          p->rc = FTS5_CORRUPT;
        }else{
          iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
          pIter->iLeafOffset = iOff;
          fts5SegIterLoadNPos(p, pIter);
        }
        break;
      }
    }
  }
}

/*
** Advance the iterator passed as the second argument until it is at or
234070
234071
234072
234073
234074
234075
234076
234077
234078
234079
234080
234081
234082
234083
234084
234085
234086
234087
234088
234089
234090
234091
234092
234093
234094
234095
234096
234097
234098
234099
234100
234101
234102
234103
234104
234105
  assert( (pTerm==0 && nTerm==0) || iLevel<0 );

  /* Allocate space for the new multi-seg-iterator. */
  if( p->rc==SQLITE_OK ){
    if( iLevel<0 ){
      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
      nSeg = pStruct->nSegment;
      nSeg += (p->pHash ? 1 : 0);
    }else{
      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
    }
  }
  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  if( pNew==0 ){
    assert( p->rc!=SQLITE_OK );
    goto fts5MultiIterNew_post_check;
  }
  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  pNew->pColset = pColset;
  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
    fts5IterSetOutputCb(&p->rc, pNew);
  }

  /* Initialize each of the component segment iterators. */
  if( p->rc==SQLITE_OK ){
    if( iLevel<0 ){
      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
      if( p->pHash ){
        /* Add a segment iterator for the current contents of the hash table. */
        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
      }
      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];







|




















|







235992
235993
235994
235995
235996
235997
235998
235999
236000
236001
236002
236003
236004
236005
236006
236007
236008
236009
236010
236011
236012
236013
236014
236015
236016
236017
236018
236019
236020
236021
236022
236023
236024
236025
236026
236027
  assert( (pTerm==0 && nTerm==0) || iLevel<0 );

  /* Allocate space for the new multi-seg-iterator. */
  if( p->rc==SQLITE_OK ){
    if( iLevel<0 ){
      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
      nSeg = pStruct->nSegment;
      nSeg += (p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH));
    }else{
      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
    }
  }
  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  if( pNew==0 ){
    assert( p->rc!=SQLITE_OK );
    goto fts5MultiIterNew_post_check;
  }
  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  pNew->pColset = pColset;
  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
    fts5IterSetOutputCb(&p->rc, pNew);
  }

  /* Initialize each of the component segment iterators. */
  if( p->rc==SQLITE_OK ){
    if( iLevel<0 ){
      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
      if( p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH) ){
        /* Add a segment iterator for the current contents of the hash table. */
        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
      }
      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
234846
234847
234848
234849
234850
234851
234852
234853
234854
234855
234856
234857
234858
234859
234860
          p->rc = FTS5_CORRUPT;
        }else{
          fts5BufferZero(&buf);
          fts5BufferGrow(&p->rc, &buf, pData->nn);
          fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
          fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
          fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
          fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]);
          if( p->rc==SQLITE_OK ){
            /* Set the szLeaf field */
            fts5PutU16(&buf.p[2], (u16)buf.n);
          }

          /* Set up the new page-index array */
          fts5BufferAppendVarint(&p->rc, &buf, 4);







|







236768
236769
236770
236771
236772
236773
236774
236775
236776
236777
236778
236779
236780
236781
236782
          p->rc = FTS5_CORRUPT;
        }else{
          fts5BufferZero(&buf);
          fts5BufferGrow(&p->rc, &buf, pData->nn);
          fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
          fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
          fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
          fts5BufferAppendBlob(&p->rc, &buf,pData->szLeaf-iOff,&pData->p[iOff]);
          if( p->rc==SQLITE_OK ){
            /* Set the szLeaf field */
            fts5PutU16(&buf.p[2], (u16)buf.n);
          }

          /* Set up the new page-index array */
          fts5BufferAppendVarint(&p->rc, &buf, 4);
235124
235125
235126
235127
235128
235129
235130

235131
235132
235133
235134
235135
235136
235137
235138
235139
235140

235141
235142
235143
235144
235145
235146
235147

static void fts5IndexCrisismerge(
  Fts5Index *p,                   /* FTS5 backend object */
  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
){
  const int nCrisis = p->pConfig->nCrisisMerge;
  Fts5Structure *pStruct = *ppStruct;

  int iLvl = 0;

  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
    fts5StructurePromote(p, iLvl+1, pStruct);
    iLvl++;
  }
  *ppStruct = pStruct;

}

static int fts5IndexReturn(Fts5Index *p){
  int rc = p->rc;
  p->rc = SQLITE_OK;
  return rc;
}







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







237046
237047
237048
237049
237050
237051
237052
237053
237054


237055
237056
237057
237058
237059
237060
237061
237062
237063
237064
237065
237066
237067
237068
237069

static void fts5IndexCrisismerge(
  Fts5Index *p,                   /* FTS5 backend object */
  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
){
  const int nCrisis = p->pConfig->nCrisisMerge;
  Fts5Structure *pStruct = *ppStruct;
  if( pStruct && pStruct->nLevel>0 ){
    int iLvl = 0;


    while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
      fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
      assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
      fts5StructurePromote(p, iLvl+1, pStruct);
      iLvl++;
    }
    *ppStruct = pStruct;
  }
}

static int fts5IndexReturn(Fts5Index *p){
  int rc = p->rc;
  p->rc = SQLITE_OK;
  return rc;
}
235166
235167
235168
235169
235170
235171
235172























































































































































































































































































































































































































235173
235174
235175
235176
235177
235178
235179
      int i = fts5GetVarint32(&aBuf[ret], dummy);
      if( (ret + i) > nMax ) break;
      ret += i;
    }
  }
  return ret;
}
























































































































































































































































































































































































































/*
** Flush the contents of in-memory hash table iHash to a new level-0
** segment on disk. Also update the corresponding structure record.
**
** If an error occurs, set the Fts5Index.rc error code. If an error has
** already occurred, this function is a no-op.







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







237088
237089
237090
237091
237092
237093
237094
237095
237096
237097
237098
237099
237100
237101
237102
237103
237104
237105
237106
237107
237108
237109
237110
237111
237112
237113
237114
237115
237116
237117
237118
237119
237120
237121
237122
237123
237124
237125
237126
237127
237128
237129
237130
237131
237132
237133
237134
237135
237136
237137
237138
237139
237140
237141
237142
237143
237144
237145
237146
237147
237148
237149
237150
237151
237152
237153
237154
237155
237156
237157
237158
237159
237160
237161
237162
237163
237164
237165
237166
237167
237168
237169
237170
237171
237172
237173
237174
237175
237176
237177
237178
237179
237180
237181
237182
237183
237184
237185
237186
237187
237188
237189
237190
237191
237192
237193
237194
237195
237196
237197
237198
237199
237200
237201
237202
237203
237204
237205
237206
237207
237208
237209
237210
237211
237212
237213
237214
237215
237216
237217
237218
237219
237220
237221
237222
237223
237224
237225
237226
237227
237228
237229
237230
237231
237232
237233
237234
237235
237236
237237
237238
237239
237240
237241
237242
237243
237244
237245
237246
237247
237248
237249
237250
237251
237252
237253
237254
237255
237256
237257
237258
237259
237260
237261
237262
237263
237264
237265
237266
237267
237268
237269
237270
237271
237272
237273
237274
237275
237276
237277
237278
237279
237280
237281
237282
237283
237284
237285
237286
237287
237288
237289
237290
237291
237292
237293
237294
237295
237296
237297
237298
237299
237300
237301
237302
237303
237304
237305
237306
237307
237308
237309
237310
237311
237312
237313
237314
237315
237316
237317
237318
237319
237320
237321
237322
237323
237324
237325
237326
237327
237328
237329
237330
237331
237332
237333
237334
237335
237336
237337
237338
237339
237340
237341
237342
237343
237344
237345
237346
237347
237348
237349
237350
237351
237352
237353
237354
237355
237356
237357
237358
237359
237360
237361
237362
237363
237364
237365
237366
237367
237368
237369
237370
237371
237372
237373
237374
237375
237376
237377
237378
237379
237380
237381
237382
237383
237384
237385
237386
237387
237388
237389
237390
237391
237392
237393
237394
237395
237396
237397
237398
237399
237400
237401
237402
237403
237404
237405
237406
237407
237408
237409
237410
237411
237412
237413
237414
237415
237416
237417
237418
237419
237420
237421
237422
237423
237424
237425
237426
237427
237428
237429
237430
237431
237432
237433
237434
237435
237436
237437
237438
237439
237440
237441
237442
237443
237444
237445
237446
237447
237448
237449
237450
237451
237452
237453
237454
237455
237456
237457
237458
237459
237460
237461
237462
237463
237464
237465
237466
237467
237468
237469
237470
237471
237472
237473
237474
237475
237476
237477
237478
237479
237480
237481
237482
237483
237484
237485
237486
237487
237488
237489
237490
237491
237492
237493
237494
237495
237496
237497
237498
237499
237500
237501
237502
237503
237504
237505
237506
237507
237508
      int i = fts5GetVarint32(&aBuf[ret], dummy);
      if( (ret + i) > nMax ) break;
      ret += i;
    }
  }
  return ret;
}

/*
** Execute the SQL statement:
**
**    DELETE FROM %_idx WHERE (segid, (pgno/2)) = ($iSegid, $iPgno);
**
** This is used when a secure-delete operation removes the last term
** from a segment leaf page. In that case the %_idx entry is removed
** too. This is done to ensure that if all instances of a token are
** removed from an fts5 database in secure-delete mode, no trace of
** the token itself remains in the database.
*/
static void fts5SecureDeleteIdxEntry(
  Fts5Index *p,                   /* FTS5 backend object */
  int iSegid,                     /* Id of segment to delete entry for */
  int iPgno                       /* Page number within segment */
){
  if( iPgno!=1 ){
    assert( p->pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE );
    if( p->pDeleteFromIdx==0 ){
      fts5IndexPrepareStmt(p, &p->pDeleteFromIdx, sqlite3_mprintf(
          "DELETE FROM '%q'.'%q_idx' WHERE (segid, (pgno/2)) = (?1, ?2)",
          p->pConfig->zDb, p->pConfig->zName
      ));
    }
    if( p->rc==SQLITE_OK ){
      sqlite3_bind_int(p->pDeleteFromIdx, 1, iSegid);
      sqlite3_bind_int(p->pDeleteFromIdx, 2, iPgno);
      sqlite3_step(p->pDeleteFromIdx);
      p->rc = sqlite3_reset(p->pDeleteFromIdx);
    }
  }
}

/*
** This is called when a secure-delete operation removes a position-list
** that overflows onto segment page iPgno of segment pSeg. This function
** rewrites node iPgno, and possibly one or more of its right-hand peers,
** to remove this portion of the position list.
**
** Output variable (*pbLastInDoclist) is set to true if the position-list
** removed is followed by a new term or the end-of-segment, or false if
** it is followed by another rowid/position list.
*/
static void fts5SecureDeleteOverflow(
  Fts5Index *p,
  Fts5StructureSegment *pSeg,
  int iPgno,
  int *pbLastInDoclist
){
  const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
  int pgno;
  Fts5Data *pLeaf = 0;
  assert( iPgno!=1 );

  *pbLastInDoclist = 1;
  for(pgno=iPgno; p->rc==SQLITE_OK && pgno<=pSeg->pgnoLast; pgno++){
    i64 iRowid = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
    int iNext = 0;
    u8 *aPg = 0;

    pLeaf = fts5DataRead(p, iRowid);
    if( pLeaf==0 ) break;
    aPg = pLeaf->p;

    iNext = fts5GetU16(&aPg[0]);
    if( iNext!=0 ){
      *pbLastInDoclist = 0;
    }
    if( iNext==0 && pLeaf->szLeaf!=pLeaf->nn ){
      fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext);
    }

    if( iNext==0 ){
      /* The page contains no terms or rowids. Replace it with an empty
      ** page and move on to the right-hand peer.  */
      const u8 aEmpty[] = {0x00, 0x00, 0x00, 0x04};
      assert_nc( bDetailNone==0 || pLeaf->nn==4 );
      if( bDetailNone==0 ) fts5DataWrite(p, iRowid, aEmpty, sizeof(aEmpty));
      fts5DataRelease(pLeaf);
      pLeaf = 0;
    }else if( bDetailNone ){
      break;
    }else if( iNext>=pLeaf->szLeaf || iNext<4 ){
      p->rc = FTS5_CORRUPT;
      break;
    }else{
      int nShift = iNext - 4;
      int nPg;

      int nIdx = 0;
      u8 *aIdx = 0;

      /* Unless the current page footer is 0 bytes in size (in which case
      ** the new page footer will be as well), allocate and populate a
      ** buffer containing the new page footer. Set stack variables aIdx
      ** and nIdx accordingly.  */
      if( pLeaf->nn>pLeaf->szLeaf ){
        int iFirst = 0;
        int i1 = pLeaf->szLeaf;
        int i2 = 0;

        aIdx = sqlite3Fts5MallocZero(&p->rc, (pLeaf->nn-pLeaf->szLeaf)+2);
        if( aIdx==0 ) break;
        i1 += fts5GetVarint32(&aPg[i1], iFirst);
        i2 = sqlite3Fts5PutVarint(aIdx, iFirst-nShift);
        if( i1<pLeaf->nn ){
          memcpy(&aIdx[i2], &aPg[i1], pLeaf->nn-i1);
          i2 += (pLeaf->nn-i1);
        }
        nIdx = i2;
      }

      /* Modify the contents of buffer aPg[]. Set nPg to the new size
      ** in bytes. The new page is always smaller than the old.  */
      nPg = pLeaf->szLeaf - nShift;
      memmove(&aPg[4], &aPg[4+nShift], nPg-4);
      fts5PutU16(&aPg[2], nPg);
      if( fts5GetU16(&aPg[0]) ) fts5PutU16(&aPg[0], 4);
      if( nIdx>0 ){
        memcpy(&aPg[nPg], aIdx, nIdx);
        nPg += nIdx;
      }
      sqlite3_free(aIdx);

      /* Write the new page to disk and exit the loop */
      assert( nPg>4 || fts5GetU16(aPg)==0 );
      fts5DataWrite(p, iRowid, aPg, nPg);
      break;
    }
  }
  fts5DataRelease(pLeaf);
}

/*
** Completely remove the entry that pSeg currently points to from
** the database.
*/
static void fts5DoSecureDelete(
  Fts5Index *p,
  Fts5SegIter *pSeg
){
  const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
  int iSegid = pSeg->pSeg->iSegid;
  u8 *aPg = pSeg->pLeaf->p;
  int nPg = pSeg->pLeaf->nn;
  int iPgIdx = pSeg->pLeaf->szLeaf;

  u64 iDelta = 0;
  u64 iNextDelta = 0;
  int iNextOff = 0;
  int iOff = 0;
  int nIdx = 0;
  u8 *aIdx = 0;
  int bLastInDoclist = 0;
  int iIdx = 0;
  int iStart = 0;
  int iKeyOff = 0;
  int iPrevKeyOff = 0;
  int iDelKeyOff = 0;       /* Offset of deleted key, if any */

  nIdx = nPg-iPgIdx;
  aIdx = sqlite3Fts5MallocZero(&p->rc, nIdx+16);
  if( p->rc ) return;
  memcpy(aIdx, &aPg[iPgIdx], nIdx);

  /* At this point segment iterator pSeg points to the entry
  ** this function should remove from the b-tree segment.
  **
  ** In detail=full or detail=column mode, pSeg->iLeafOffset is the
  ** offset of the first byte in the position-list for the entry to
  ** remove. Immediately before this comes two varints that will also
  ** need to be removed:
  **
  **     + the rowid or delta rowid value for the entry, and
  **     + the size of the position list in bytes.
  **
  ** Or, in detail=none mode, there is a single varint prior to
  ** pSeg->iLeafOffset - the rowid or delta rowid value.
  **
  ** This block sets the following variables:
  **
  **   iStart:
  **   iDelta:
  */
  {
    int iSOP;
    if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
      iStart = pSeg->iTermLeafOffset;
    }else{
      iStart = fts5GetU16(&aPg[0]);
    }

    iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
    assert_nc( iSOP<=pSeg->iLeafOffset );

    if( bDetailNone ){
      while( iSOP<pSeg->iLeafOffset ){
        if( aPg[iSOP]==0x00 ) iSOP++;
        if( aPg[iSOP]==0x00 ) iSOP++;
        iStart = iSOP;
        iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
      }

      iNextOff = iSOP;
      if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;
      if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;

    }else{
      int nPos = 0;
      iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
      while( iSOP<pSeg->iLeafOffset ){
        iStart = iSOP + (nPos/2);
        iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
        iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
      }
      assert_nc( iSOP==pSeg->iLeafOffset );
      iNextOff = pSeg->iLeafOffset + pSeg->nPos;
    }
  }

  iOff = iStart;
  if( iNextOff>=iPgIdx ){
    int pgno = pSeg->iLeafPgno+1;
    fts5SecureDeleteOverflow(p, pSeg->pSeg, pgno, &bLastInDoclist);
    iNextOff = iPgIdx;
  }else{
    /* Set bLastInDoclist to true if the entry being removed is the last
    ** in its doclist.  */
    for(iIdx=0, iKeyOff=0; iIdx<nIdx; /* no-op */){
      u32 iVal = 0;
      iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
      iKeyOff += iVal;
      if( iKeyOff==iNextOff ){
        bLastInDoclist = 1;
      }
    }
  }

  if( fts5GetU16(&aPg[0])==iStart && (bLastInDoclist||iNextOff==iPgIdx) ){
    fts5PutU16(&aPg[0], 0);
  }

  if( bLastInDoclist==0 ){
    if( iNextOff!=iPgIdx ){
      iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
      iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
    }
  }else if(
      iStart==pSeg->iTermLeafOffset && pSeg->iLeafPgno==pSeg->iTermLeafPgno
  ){
    /* The entry being removed was the only position list in its
    ** doclist. Therefore the term needs to be removed as well. */
    int iKey = 0;
    for(iIdx=0, iKeyOff=0; iIdx<nIdx; iKey++){
      u32 iVal = 0;
      iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
      if( (iKeyOff+iVal)>(u32)iStart ) break;
      iKeyOff += iVal;
    }

    iDelKeyOff = iOff = iKeyOff;
    if( iNextOff!=iPgIdx ){
      int nPrefix = 0;
      int nSuffix = 0;
      int nPrefix2 = 0;
      int nSuffix2 = 0;

      iDelKeyOff = iNextOff;
      iNextOff += fts5GetVarint32(&aPg[iNextOff], nPrefix2);
      iNextOff += fts5GetVarint32(&aPg[iNextOff], nSuffix2);

      if( iKey!=1 ){
        iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nPrefix);
      }
      iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nSuffix);

      nPrefix = MIN(nPrefix, nPrefix2);
      nSuffix = (nPrefix2 + nSuffix2) - nPrefix;

      if( (iKeyOff+nSuffix)>iPgIdx || (iNextOff+nSuffix2)>iPgIdx ){
        p->rc = FTS5_CORRUPT;
      }else{
        if( iKey!=1 ){
          iOff += sqlite3Fts5PutVarint(&aPg[iOff], nPrefix);
        }
        iOff += sqlite3Fts5PutVarint(&aPg[iOff], nSuffix);
        if( nPrefix2>nPrefix ){
          memcpy(&aPg[iOff], &pSeg->term.p[nPrefix], nPrefix2-nPrefix);
          iOff += (nPrefix2-nPrefix);
        }
        memmove(&aPg[iOff], &aPg[iNextOff], nSuffix2);
        iOff += nSuffix2;
        iNextOff += nSuffix2;
      }
    }
  }else if( iStart==4 ){
      int iPgno;

      assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
      /* The entry being removed may be the only position list in
      ** its doclist. */
      for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
        Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
        int bEmpty = (pPg && pPg->nn==4);
        fts5DataRelease(pPg);
        if( bEmpty==0 ) break;
      }

      if( iPgno==pSeg->iTermLeafPgno ){
        i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
        Fts5Data *pTerm = fts5DataRead(p, iId);
        if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
          u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
          int nTermIdx = pTerm->nn - pTerm->szLeaf;
          int iTermIdx = 0;
          int iTermOff = 0;

          while( 1 ){
            u32 iVal = 0;
            int nByte = fts5GetVarint32(&aTermIdx[iTermIdx], iVal);
            iTermOff += iVal;
            if( (iTermIdx+nByte)>=nTermIdx ) break;
            iTermIdx += nByte;
          }
          nTermIdx = iTermIdx;

          memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx);
          fts5PutU16(&pTerm->p[2], iTermOff);

          fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx);
          if( nTermIdx==0 ){
            fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno);
          }
        }
        fts5DataRelease(pTerm);
      }
    }

    if( p->rc==SQLITE_OK ){
      const int nMove = nPg - iNextOff;
      int nShift = 0;

      memmove(&aPg[iOff], &aPg[iNextOff], nMove);
      iPgIdx -= (iNextOff - iOff);
      nPg = iPgIdx;
      fts5PutU16(&aPg[2], iPgIdx);

      nShift = iNextOff - iOff;
      for(iIdx=0, iKeyOff=0, iPrevKeyOff=0; iIdx<nIdx; /* no-op */){
        u32 iVal = 0;
        iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
        iKeyOff += iVal;
        if( iKeyOff!=iDelKeyOff ){
          if( iKeyOff>iOff ){
            iKeyOff -= nShift;
            nShift = 0;
          }
          nPg += sqlite3Fts5PutVarint(&aPg[nPg], iKeyOff - iPrevKeyOff);
          iPrevKeyOff = iKeyOff;
        }
      }

      if( iPgIdx==nPg && nIdx>0 && pSeg->iLeafPgno!=1 ){
        fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iLeafPgno);
      }

      assert_nc( nPg>4 || fts5GetU16(aPg)==0 );
      fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg,nPg);
    }
    sqlite3_free(aIdx);
}

/*
** This is called as part of flushing a delete to disk in 'secure-delete'
** mode. It edits the segments within the database described by argument
** pStruct to remove the entries for term zTerm, rowid iRowid.
*/
static void fts5FlushSecureDelete(
  Fts5Index *p,
  Fts5Structure *pStruct,
  const char *zTerm,
  i64 iRowid
){
  const int f = FTS5INDEX_QUERY_SKIPHASH;
  int nTerm = (int)strlen(zTerm);
  Fts5Iter *pIter = 0;            /* Used to find term instance */

  fts5MultiIterNew(p, pStruct, f, 0, (const u8*)zTerm, nTerm, -1, 0, &pIter);
  if( fts5MultiIterEof(p, pIter)==0 ){
    i64 iThis = fts5MultiIterRowid(pIter);
    if( iThis<iRowid ){
      fts5MultiIterNextFrom(p, pIter, iRowid);
    }

    if( p->rc==SQLITE_OK
     && fts5MultiIterEof(p, pIter)==0
     && iRowid==fts5MultiIterRowid(pIter)
    ){
      Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
      fts5DoSecureDelete(p, pSeg);
    }
  }

  fts5MultiIterFree(pIter);
}


/*
** Flush the contents of in-memory hash table iHash to a new level-0
** segment on disk. Also update the corresponding structure record.
**
** If an error occurs, set the Fts5Index.rc error code. If an error has
** already occurred, this function is a no-op.
235189
235190
235191
235192
235193
235194
235195

235196
235197
235198
235199
235200
235201
235202
  pStruct = fts5StructureRead(p);
  iSegid = fts5AllocateSegid(p, pStruct);
  fts5StructureInvalidate(p);

  if( iSegid ){
    const int pgsz = p->pConfig->pgsz;
    int eDetail = p->pConfig->eDetail;

    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */

    Fts5SegWriter writer;
    fts5WriteInit(p, &writer, iSegid);








>







237518
237519
237520
237521
237522
237523
237524
237525
237526
237527
237528
237529
237530
237531
237532
  pStruct = fts5StructureRead(p);
  iSegid = fts5AllocateSegid(p, pStruct);
  fts5StructureInvalidate(p);

  if( iSegid ){
    const int pgsz = p->pConfig->pgsz;
    int eDetail = p->pConfig->eDetail;
    int bSecureDelete = p->pConfig->bSecureDelete;
    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */

    Fts5SegWriter writer;
    fts5WriteInit(p, &writer, iSegid);

235211
235212
235213
235214
235215
235216
235217

235218
235219
235220
235221
235222


235223
235224

235225
235226
235227
235228
235229
235230

235231
235232
235233
235234
235235
235236
235237
235238

235239
235240






























235241
235242
235243
235244
235245
235246
235247
235248
235249
235250

235251

235252
235253
235254
235255
235256
235257
235258
    /* Begin scanning through hash table entries. This loop runs once for each
    ** term/doclist currently stored within the hash table. */
    if( p->rc==SQLITE_OK ){
      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
    }
    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
      const char *zTerm;          /* Buffer containing term */

      const u8 *pDoclist;         /* Pointer to doclist for this term */
      int nDoclist;               /* Size of doclist in bytes */

      /* Write the term for this entry to disk. */
      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);


      fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
      if( p->rc!=SQLITE_OK ) break;


      assert( writer.bFirstRowidInPage==0 );
      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
        /* The entire doclist will fit on the current leaf. */
        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
      }else{

        i64 iRowid = 0;
        u64 iDelta = 0;
        int iOff = 0;

        /* The entire doclist will not fit on this leaf. The following
        ** loop iterates through the poslists that make up the current
        ** doclist.  */
        while( p->rc==SQLITE_OK && iOff<nDoclist ){

          iOff += fts5GetVarint(&pDoclist[iOff], &iDelta);
          iRowid += iDelta;































          if( writer.bFirstRowidInPage ){
            fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
            writer.bFirstRowidInPage = 0;
            fts5WriteDlidxAppend(p, &writer, iRowid);
            if( p->rc!=SQLITE_OK ) break;
          }else{
            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
          }

          assert( pBuf->n<=pBuf->nSpace );


          if( eDetail==FTS5_DETAIL_NONE ){
            if( iOff<nDoclist && pDoclist[iOff]==0 ){
              pBuf->p[pBuf->n++] = 0;
              iOff++;
              if( iOff<nDoclist && pDoclist[iOff]==0 ){
                pBuf->p[pBuf->n++] = 0;







>



|

>
>
|
|
>
|
|
|



>

|






>


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






<

|

>

>







237541
237542
237543
237544
237545
237546
237547
237548
237549
237550
237551
237552
237553
237554
237555
237556
237557
237558
237559
237560
237561
237562
237563
237564
237565
237566
237567
237568
237569
237570
237571
237572
237573
237574
237575
237576
237577
237578
237579
237580
237581
237582
237583
237584
237585
237586
237587
237588
237589
237590
237591
237592
237593
237594
237595
237596
237597
237598
237599
237600
237601
237602
237603
237604
237605
237606
237607
237608
237609
237610
237611
237612

237613
237614
237615
237616
237617
237618
237619
237620
237621
237622
237623
237624
237625
    /* Begin scanning through hash table entries. This loop runs once for each
    ** term/doclist currently stored within the hash table. */
    if( p->rc==SQLITE_OK ){
      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
    }
    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
      const char *zTerm;          /* Buffer containing term */
      int nTerm;                  /* Size of zTerm in bytes */
      const u8 *pDoclist;         /* Pointer to doclist for this term */
      int nDoclist;               /* Size of doclist in bytes */

      /* Get the term and doclist for this entry. */
      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
      nTerm = (int)strlen(zTerm);
      if( bSecureDelete==0 ){
        fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
        if( p->rc!=SQLITE_OK ) break;
        assert( writer.bFirstRowidInPage==0 );
      }

      if( !bSecureDelete && pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
        /* The entire doclist will fit on the current leaf. */
        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
      }else{
        int bTermWritten = !bSecureDelete;
        i64 iRowid = 0;
        i64 iPrev = 0;
        int iOff = 0;

        /* The entire doclist will not fit on this leaf. The following
        ** loop iterates through the poslists that make up the current
        ** doclist.  */
        while( p->rc==SQLITE_OK && iOff<nDoclist ){
          u64 iDelta = 0;
          iOff += fts5GetVarint(&pDoclist[iOff], &iDelta);
          iRowid += iDelta;

          /* If in secure delete mode, and if this entry in the poslist is
          ** in fact a delete, then edit the existing segments directly
          ** using fts5FlushSecureDelete().  */
          if( bSecureDelete ){
            if( eDetail==FTS5_DETAIL_NONE ){
              if( iOff<nDoclist && pDoclist[iOff]==0x00 ){
                fts5FlushSecureDelete(p, pStruct, zTerm, iRowid);
                iOff++;
                if( iOff<nDoclist && pDoclist[iOff]==0x00 ){
                  iOff++;
                  nDoclist = 0;
                }else{
                  continue;
                }
              }
            }else if( (pDoclist[iOff] & 0x01) ){
              fts5FlushSecureDelete(p, pStruct, zTerm, iRowid);
              if( p->rc!=SQLITE_OK || pDoclist[iOff]==0x01 ){
                iOff++;
                continue;
              }
            }
          }

          if( p->rc==SQLITE_OK && bTermWritten==0 ){
            fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
            bTermWritten = 1;
            assert( p->rc!=SQLITE_OK || writer.bFirstRowidInPage==0 );
          }

          if( writer.bFirstRowidInPage ){
            fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
            writer.bFirstRowidInPage = 0;
            fts5WriteDlidxAppend(p, &writer, iRowid);

          }else{
            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid-iPrev);
          }
          if( p->rc!=SQLITE_OK ) break;
          assert( pBuf->n<=pBuf->nSpace );
          iPrev = iRowid;

          if( eDetail==FTS5_DETAIL_NONE ){
            if( iOff<nDoclist && pDoclist[iOff]==0 ){
              pBuf->p[pBuf->n++] = 0;
              iOff++;
              if( iOff<nDoclist && pDoclist[iOff]==0 ){
                pBuf->p[pBuf->n++] = 0;
235303
235304
235305
235306
235307
235308
235309


235310
235311
235312
235313
235314
235315
235316
235317
235318
235319
235320
235321
235322
235323

235324
235325
235326
235327
235328
235329
235330
      /* pBuf->p[pBuf->n++] = '\0'; */
      assert( pBuf->n<=pBuf->nSpace );
      if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
    }
    sqlite3Fts5HashClear(pHash);
    fts5WriteFinish(p, &writer, &pgnoLast);



    /* Update the Fts5Structure. It is written back to the database by the
    ** fts5StructureRelease() call below.  */
    if( pStruct->nLevel==0 ){
      fts5StructureAddLevel(&p->rc, &pStruct);
    }
    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
    if( p->rc==SQLITE_OK ){
      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
      pSeg->iSegid = iSegid;
      pSeg->pgnoFirst = 1;
      pSeg->pgnoLast = pgnoLast;
      pStruct->nSegment++;
    }
    fts5StructurePromote(p, 0, pStruct);

  }

  fts5IndexAutomerge(p, &pStruct, pgnoLast);
  fts5IndexCrisismerge(p, &pStruct);
  fts5StructureWrite(p, pStruct);
  fts5StructureRelease(pStruct);
}







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







237670
237671
237672
237673
237674
237675
237676
237677
237678
237679
237680
237681
237682
237683
237684
237685
237686
237687
237688
237689
237690
237691
237692
237693
237694
237695
237696
237697
237698
237699
237700
      /* pBuf->p[pBuf->n++] = '\0'; */
      assert( pBuf->n<=pBuf->nSpace );
      if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
    }
    sqlite3Fts5HashClear(pHash);
    fts5WriteFinish(p, &writer, &pgnoLast);

    assert( p->rc!=SQLITE_OK || bSecureDelete || pgnoLast>0 );
    if( pgnoLast>0 ){
      /* Update the Fts5Structure. It is written back to the database by the
      ** fts5StructureRelease() call below.  */
      if( pStruct->nLevel==0 ){
        fts5StructureAddLevel(&p->rc, &pStruct);
      }
      fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
      if( p->rc==SQLITE_OK ){
        pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
        pSeg->iSegid = iSegid;
        pSeg->pgnoFirst = 1;
        pSeg->pgnoLast = pgnoLast;
        pStruct->nSegment++;
      }
      fts5StructurePromote(p, 0, pStruct);
    }
  }

  fts5IndexAutomerge(p, &pStruct, pgnoLast);
  fts5IndexCrisismerge(p, &pStruct);
  fts5StructureWrite(p, pStruct);
  fts5StructureRelease(pStruct);
}
236057
236058
236059
236060
236061
236062
236063

236064
236065
236066
236067
236068
236069
236070
    fts5StructureInvalidate(p);
    sqlite3_finalize(p->pWriter);
    sqlite3_finalize(p->pDeleter);
    sqlite3_finalize(p->pIdxWriter);
    sqlite3_finalize(p->pIdxDeleter);
    sqlite3_finalize(p->pIdxSelect);
    sqlite3_finalize(p->pDataVersion);

    sqlite3Fts5HashFree(p->pHash);
    sqlite3_free(p->zDataTbl);
    sqlite3_free(p);
  }
  return rc;
}








>







238427
238428
238429
238430
238431
238432
238433
238434
238435
238436
238437
238438
238439
238440
238441
    fts5StructureInvalidate(p);
    sqlite3_finalize(p->pWriter);
    sqlite3_finalize(p->pDeleter);
    sqlite3_finalize(p->pIdxWriter);
    sqlite3_finalize(p->pIdxDeleter);
    sqlite3_finalize(p->pIdxSelect);
    sqlite3_finalize(p->pDataVersion);
    sqlite3_finalize(p->pDeleteFromIdx);
    sqlite3Fts5HashFree(p->pHash);
    sqlite3_free(p->zDataTbl);
    sqlite3_free(p);
  }
  return rc;
}

236687
236688
236689
236690
236691
236692
236693

236694
236695
236696
236697
236698
236699
236700
}

static void fts5IndexIntegrityCheckSegment(
  Fts5Index *p,                   /* FTS5 backend object */
  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
){
  Fts5Config *pConfig = p->pConfig;

  sqlite3_stmt *pStmt = 0;
  int rc2;
  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  int iDlidxPrevLeaf = pSeg->pgnoLast;

  if( pSeg->pgnoFirst==0 ) return;








>







239058
239059
239060
239061
239062
239063
239064
239065
239066
239067
239068
239069
239070
239071
239072
}

static void fts5IndexIntegrityCheckSegment(
  Fts5Index *p,                   /* FTS5 backend object */
  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
){
  Fts5Config *pConfig = p->pConfig;
  int bSecureDelete = (pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE);
  sqlite3_stmt *pStmt = 0;
  int rc2;
  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  int iDlidxPrevLeaf = pSeg->pgnoLast;

  if( pSeg->pgnoFirst==0 ) return;

236722
236723
236724
236725
236726
236727
236728










236729


236730
236731
236732
236733
236734
236735
236736
    if( pLeaf==0 ) break;

    /* Check that the leaf contains at least one term, and that it is equal
    ** to or larger than the split-key in zIdxTerm.  Also check that if there
    ** is also a rowid pointer within the leaf page header, it points to a
    ** location before the term.  */
    if( pLeaf->nn<=pLeaf->szLeaf ){










      p->rc = FTS5_CORRUPT;


    }else{
      int iOff;                   /* Offset of first term on leaf */
      int iRowidOff;              /* Offset of first rowid on leaf */
      int nTerm;                  /* Size of term on leaf in bytes */
      int res;                    /* Comparison of term and split-key */

      iOff = fts5LeafFirstTermOff(pLeaf);







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







239094
239095
239096
239097
239098
239099
239100
239101
239102
239103
239104
239105
239106
239107
239108
239109
239110
239111
239112
239113
239114
239115
239116
239117
239118
239119
239120
    if( pLeaf==0 ) break;

    /* Check that the leaf contains at least one term, and that it is equal
    ** to or larger than the split-key in zIdxTerm.  Also check that if there
    ** is also a rowid pointer within the leaf page header, it points to a
    ** location before the term.  */
    if( pLeaf->nn<=pLeaf->szLeaf ){

      if( nIdxTerm==0
       && pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE
       && pLeaf->nn==pLeaf->szLeaf
       && pLeaf->nn==4
      ){
        /* special case - the very first page in a segment keeps its %_idx
        ** entry even if all the terms are removed from it by secure-delete
        ** operations. */
      }else{
        p->rc = FTS5_CORRUPT;
      }

    }else{
      int iOff;                   /* Offset of first term on leaf */
      int iRowidOff;              /* Offset of first rowid on leaf */
      int nTerm;                  /* Size of term on leaf in bytes */
      int res;                    /* Comparison of term and split-key */

      iOff = fts5LeafFirstTermOff(pLeaf);
236786
236787
236788
236789
236790
236791
236792
236793

236794

236795

236796
236797
236798
236799
236800
236801
236802
        pLeaf = fts5DataRead(p, iKey);
        if( pLeaf ){
          i64 iRowid;
          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
          ASSERT_SZLEAF_OK(pLeaf);
          if( iRowidOff>=pLeaf->szLeaf ){
            p->rc = FTS5_CORRUPT;
          }else{

            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);

            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;

          }
          fts5DataRelease(pLeaf);
        }
      }

      iDlidxPrevLeaf = iPg;
      fts5DlidxIterFree(pDlidx);







|
>

>
|
>







239170
239171
239172
239173
239174
239175
239176
239177
239178
239179
239180
239181
239182
239183
239184
239185
239186
239187
239188
239189
        pLeaf = fts5DataRead(p, iKey);
        if( pLeaf ){
          i64 iRowid;
          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
          ASSERT_SZLEAF_OK(pLeaf);
          if( iRowidOff>=pLeaf->szLeaf ){
            p->rc = FTS5_CORRUPT;
          }else if( bSecureDelete==0 || iRowidOff>0 ){
            i64 iDlRowid = fts5DlidxIterRowid(pDlidx);
            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
            if( iRowid<iDlRowid || (bSecureDelete==0 && iRowid!=iDlRowid) ){
              p->rc = FTS5_CORRUPT;
            }
          }
          fts5DataRelease(pLeaf);
        }
      }

      iDlidxPrevLeaf = iPg;
      fts5DlidxIterFree(pDlidx);
239050
239051
239052
239053
239054
239055
239056


239057
239058
239059
239060
239061
239062
239063
239064
239065
239066





239067
239068
239069
239070
239071
239072
239073
  sqlite3_value **apVal,          /* Array of arguments */
  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
){
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  Fts5Config *pConfig = pTab->p.pConfig;
  int eType0;                     /* value_type() of apVal[0] */
  int rc = SQLITE_OK;             /* Return code */



  /* A transaction must be open when this is called. */
  assert( pTab->ts.eState==1 || pTab->ts.eState==2 );

  assert( pVtab->zErrMsg==0 );
  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
       || sqlite3_value_type(apVal[0])==SQLITE_NULL
  );
  assert( pTab->p.pConfig->pzErrmsg==0 );





  pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;

  /* Put any active cursors into REQUIRE_SEEK state. */
  fts5TripCursors(pTab);

  eType0 = sqlite3_value_type(apVal[0]);
  if( eType0==SQLITE_NULL







>
>










>
>
>
>
>







241437
241438
241439
241440
241441
241442
241443
241444
241445
241446
241447
241448
241449
241450
241451
241452
241453
241454
241455
241456
241457
241458
241459
241460
241461
241462
241463
241464
241465
241466
241467
  sqlite3_value **apVal,          /* Array of arguments */
  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
){
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  Fts5Config *pConfig = pTab->p.pConfig;
  int eType0;                     /* value_type() of apVal[0] */
  int rc = SQLITE_OK;             /* Return code */
  int bUpdateOrDelete = 0;


  /* A transaction must be open when this is called. */
  assert( pTab->ts.eState==1 || pTab->ts.eState==2 );

  assert( pVtab->zErrMsg==0 );
  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
       || sqlite3_value_type(apVal[0])==SQLITE_NULL
  );
  assert( pTab->p.pConfig->pzErrmsg==0 );
  if( pConfig->pgsz==0 ){
    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
    if( rc!=SQLITE_OK ) return rc;
  }

  pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;

  /* Put any active cursors into REQUIRE_SEEK state. */
  fts5TripCursors(pTab);

  eType0 = sqlite3_value_type(apVal[0]);
  if( eType0==SQLITE_NULL
239112
239113
239114
239115
239116
239117
239118

239119
239120
239121
239122
239123
239124
239125
239126
239127
239128
239129
239130
239131
239132
239133

239134
239135
239136
239137
239138
239139
239140
      rc = SQLITE_ERROR;
    }

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

    }

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

      if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
        rc = SQLITE_MISMATCH;
      }

      else if( eType0!=SQLITE_INTEGER ){
        /* If this is a REPLACE, first remove the current entry (if any) */
        if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
          i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);

        }
        fts5StorageInsert(&rc, pTab, apVal, pRowid);
      }

      /* UPDATE */
      else{
        i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */







>















>







241506
241507
241508
241509
241510
241511
241512
241513
241514
241515
241516
241517
241518
241519
241520
241521
241522
241523
241524
241525
241526
241527
241528
241529
241530
241531
241532
241533
241534
241535
241536
      rc = SQLITE_ERROR;
    }

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

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

      if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
        rc = SQLITE_MISMATCH;
      }

      else if( eType0!=SQLITE_INTEGER ){
        /* If this is a REPLACE, first remove the current entry (if any) */
        if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
          i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
          bUpdateOrDelete = 1;
        }
        fts5StorageInsert(&rc, pTab, apVal, pRowid);
      }

      /* UPDATE */
      else{
        i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
239155
239156
239157
239158
239159
239160
239161

239162
239163
239164













239165
239166
239167
239168
239169
239170
239171
              rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
            }
          }
        }else{
          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
          fts5StorageInsert(&rc, pTab, apVal, pRowid);
        }

      }
    }
  }














  pTab->p.pConfig->pzErrmsg = 0;
  return rc;
}

/*
** Implementation of xSync() method.







>



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







241551
241552
241553
241554
241555
241556
241557
241558
241559
241560
241561
241562
241563
241564
241565
241566
241567
241568
241569
241570
241571
241572
241573
241574
241575
241576
241577
241578
241579
241580
241581
              rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
            }
          }
        }else{
          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
          fts5StorageInsert(&rc, pTab, apVal, pRowid);
        }
        bUpdateOrDelete = 1;
      }
    }
  }

  if( rc==SQLITE_OK
   && bUpdateOrDelete
   && pConfig->bSecureDelete
   && pConfig->iVersion==FTS5_CURRENT_VERSION
  ){
    rc = sqlite3Fts5StorageConfigValue(
        pTab->pStorage, "version", 0, FTS5_CURRENT_VERSION_SECUREDELETE
    );
    if( rc==SQLITE_OK ){
      pConfig->iVersion = FTS5_CURRENT_VERSION_SECUREDELETE;
    }
  }

  pTab->p.pConfig->pzErrmsg = 0;
  return rc;
}

/*
** Implementation of xSync() method.
240018
240019
240020
240021
240022
240023
240024

240025
240026
240027
240028
240029
240030
240031
** Discard the contents of the pending terms table.
*/
static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  fts5TripCursors(pTab);

  return sqlite3Fts5StorageRollback(pTab->pStorage);
}

/*
** Register a new auxiliary function with global context pGlobal.
*/
static int fts5CreateAux(







>







242428
242429
242430
242431
242432
242433
242434
242435
242436
242437
242438
242439
242440
242441
242442
** Discard the contents of the pending terms table.
*/
static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  fts5TripCursors(pTab);
  pTab->p.pConfig->pgsz = 0;
  return sqlite3Fts5StorageRollback(pTab->pStorage);
}

/*
** Register a new auxiliary function with global context pGlobal.
*/
static int fts5CreateAux(
240220
240221
240222
240223
240224
240225
240226
240227
240228
240229
240230
240231
240232
240233
240234
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: 2023-03-10 12:13:52 20399f3eda5ec249d147ba9e48da6e87f969d7966a9a896764ca437ff7e737ff", -1, SQLITE_TRANSIENT);
}

/*
** Return true if zName is the extension on one of the shadow tables used
** by this module.
*/
static int fts5ShadowName(const char *zName){







|







242631
242632
242633
242634
242635
242636
242637
242638
242639
242640
242641
242642
242643
242644
242645
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: 2023-05-16 12:36:15 831d0fb2836b71c9bc51067c49fee4b8f18047814f2ff22d817d25195cf350b0", -1, SQLITE_TRANSIENT);
}

/*
** Return true if zName is the extension on one of the shadow tables used
** by this module.
*/
static int fts5ShadowName(const char *zName){
Changes to sqlite3/src/main/jni/sqlite/sqlite3.h.
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.41.1"
#define SQLITE_VERSION_NUMBER 3041001
#define SQLITE_SOURCE_ID      "2023-03-10 12:13:52 20399f3eda5ec249d147ba9e48da6e87f969d7966a9a896764ca437ff7e737ff"

/*
** 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







|
|
|







142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.42.0"
#define SQLITE_VERSION_NUMBER 3042000
#define SQLITE_SOURCE_ID      "2023-05-16 12:36:15 831d0fb2836b71c9bc51067c49fee4b8f18047814f2ff22d817d25195cf350b0"

/*
** 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
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670











1671
1672
1673
1674
1675
1676
1677
** applications and so this routine is usually not necessary.  It is
** provided to support rare applications with unusual needs.
**
** <b>The sqlite3_config() interface is not threadsafe. The application
** must ensure that no other SQLite interfaces are invoked by other
** threads while sqlite3_config() is running.</b>
**
** The sqlite3_config() interface
** may only be invoked prior to library initialization using
** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
** Note, however, that ^sqlite3_config() can be called as part of the
** implementation of an application-defined [sqlite3_os_init()].
**
** The first argument to sqlite3_config() is an integer
** [configuration option] that determines
** what property of SQLite is to be configured.  Subsequent arguments
** vary depending on the [configuration option]
** in the first argument.











**
** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
** ^If the option is unknown or SQLite is unable to set the option
** then this routine returns a non-zero [error code].
*/
SQLITE_API int sqlite3_config(int, ...);








<
<
<
<
<
<
<
<





>
>
>
>
>
>
>
>
>
>
>







1651
1652
1653
1654
1655
1656
1657








1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
** applications and so this routine is usually not necessary.  It is
** provided to support rare applications with unusual needs.
**
** <b>The sqlite3_config() interface is not threadsafe. The application
** must ensure that no other SQLite interfaces are invoked by other
** threads while sqlite3_config() is running.</b>
**








** The first argument to sqlite3_config() is an integer
** [configuration option] that determines
** what property of SQLite is to be configured.  Subsequent arguments
** vary depending on the [configuration option]
** in the first argument.
**
** For most configuration options, the sqlite3_config() interface
** may only be invoked prior to library initialization using
** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
** The exceptional configuration options that may be invoked at any time
** are called "anytime configuration options".
** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
** [sqlite3_shutdown()] with a first argument that is not an anytime
** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE.
** Note, however, that ^sqlite3_config() can be called as part of the
** implementation of an application-defined [sqlite3_os_init()].
**
** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
** ^If the option is unknown or SQLite is unable to set the option
** then this routine returns a non-zero [error code].
*/
SQLITE_API int sqlite3_config(int, ...);

1771
1772
1773
1774
1775
1776
1777

















1778
1779
1780
1781
1782
1783
1784

/*
** CAPI3REF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
** can be passed as the first argument to the [sqlite3_config()] interface.

















**
** New configuration options may be added in future releases of SQLite.
** Existing configuration options might be discontinued.  Applications
** should check the return code from [sqlite3_config()] to make sure that
** the call worked.  The [sqlite3_config()] interface will return a
** non-zero [error code] if a discontinued or unsupported configuration option
** is invoked.







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







1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804

/*
** CAPI3REF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
** can be passed as the first argument to the [sqlite3_config()] interface.
**
** Most of the configuration options for sqlite3_config()
** will only work if invoked prior to [sqlite3_initialize()] or after
** [sqlite3_shutdown()].  The few exceptions to this rule are called
** "anytime configuration options".
** ^Calling [sqlite3_config()] with a first argument that is not an
** anytime configuration option in between calls to [sqlite3_initialize()] and
** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE.
**
** The set of anytime configuration options can change (by insertions
** and/or deletions) from one release of SQLite to the next.
** As of SQLite version 3.42.0, the complete set of anytime configuration
** options is:
** <ul>
** <li> SQLITE_CONFIG_LOG
** <li> SQLITE_CONFIG_PCACHE_HDRSZ
** </ul>
**
** New configuration options may be added in future releases of SQLite.
** Existing configuration options might be discontinued.  Applications
** should check the return code from [sqlite3_config()] to make sure that
** the call worked.  The [sqlite3_config()] interface will return a
** non-zero [error code] if a discontinued or unsupported configuration option
** is invoked.
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
** size can be adjusted up or down for individual databases using the
** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this
** configuration setting is never used, then the default maximum is determined
** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that
** compile-time option is not set, then the default maximum is 1073741824.
** </dl>
*/
#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_SCRATCH       6  /* No longer used */
#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
#define SQLITE_CONFIG_PCACHE       14  /* no-op */
#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
#define SQLITE_CONFIG_URI          17  /* int */
#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */
#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|







2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
** size can be adjusted up or down for individual databases using the
** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this
** configuration setting is never used, then the default maximum is determined
** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that
** compile-time option is not set, then the default maximum is 1073741824.
** </dl>
*/
#define SQLITE_CONFIG_SINGLETHREAD         1  /* nil */
#define SQLITE_CONFIG_MULTITHREAD          2  /* nil */
#define SQLITE_CONFIG_SERIALIZED           3  /* nil */
#define SQLITE_CONFIG_MALLOC               4  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_GETMALLOC            5  /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_SCRATCH              6  /* No longer used */
#define SQLITE_CONFIG_PAGECACHE            7  /* void*, int sz, int N */
#define SQLITE_CONFIG_HEAP                 8  /* void*, int nByte, int min */
#define SQLITE_CONFIG_MEMSTATUS            9  /* boolean */
#define SQLITE_CONFIG_MUTEX               10  /* sqlite3_mutex_methods* */
#define SQLITE_CONFIG_GETMUTEX            11  /* sqlite3_mutex_methods* */
/* previously SQLITE_CONFIG_CHUNKALLOC    12 which is now unused. */
#define SQLITE_CONFIG_LOOKASIDE           13  /* int int */
#define SQLITE_CONFIG_PCACHE              14  /* no-op */
#define SQLITE_CONFIG_GETPCACHE           15  /* no-op */
#define SQLITE_CONFIG_LOG                 16  /* xFunc, void* */
#define SQLITE_CONFIG_URI                 17  /* int */
#define SQLITE_CONFIG_PCACHE2             18  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_GETPCACHE2          19  /* sqlite3_pcache_methods2* */
#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
#define SQLITE_CONFIG_SQLLOG              21  /* xSqllog, void* */
#define SQLITE_CONFIG_MMAP_SIZE           22  /* sqlite3_int64, sqlite3_int64 */
#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
#define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
#define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */
#define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
































2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458


2459
2460
2461
2462
2463
2464
2465
2466
** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the
** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
** additional information. This feature can also be turned on and off
** using the [PRAGMA legacy_alter_table] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DML]]
** <dt>SQLITE_DBCONFIG_DQS_DML</td>
** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DML statements
** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DDL]]
** <dt>SQLITE_DBCONFIG_DQS_DDL</td>
** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DDL statements,
** such as CREATE TABLE and CREATE INDEX. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
** assume that database schemas are untainted by malicious content.
** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
** takes additional defensive steps to protect the application from harm
** including:
** <ul>
** <li> Prohibit the use of SQL functions inside triggers, views,
** CHECK constraints, DEFAULT clauses, expression indexes,
** partial indexes, or generated columns
** unless those functions are tagged with [SQLITE_INNOCUOUS].
** <li> Prohibit the use of virtual tables inside of triggers or views
** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
** </ul>
** This setting defaults to "on" for legacy compatibility, however
** all applications are advised to turn it off if possible. This setting
** can also be controlled using the [PRAGMA trusted_schema] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
** the legacy file format flag.  When activated, this flag causes all newly
** created database file to have a schema format version number (the 4-byte
** integer found at offset 44 into the database header) of 1.  This in turn
** means that the resulting database file will be readable and writable by
** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,
** newly created databases are generally not understandable by SQLite versions
** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there
** is now scarcely any need to generated database files that are compatible
** all the way back to version 3.0.0, and so this setting is of little
** practical use, but is provided so that SQLite can continue to claim the
** ability to generate new database files that are compatible with  version
** 3.0.0.
** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
** the [VACUUM] command will fail with an obscure error when attempting to
** process a table with generated columns and a descending index.  This is
** not considered a bug since SQLite versions 3.3.0 and earlier do not support
** either generated columns or decending indexes.
** </dd>
































** </dl>
*/
#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */
#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */
#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */
#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */
#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */


#define SQLITE_DBCONFIG_MAX                   1017 /* Largest DBCONFIG */

/*
** CAPI3REF: Enable Or Disable Extended Result Codes
** METHOD: sqlite3
**
** ^The sqlite3_extended_result_codes() routine enables or disables the
** [extended result codes] feature of SQLite. ^The extended result







|








|








|



















|








|










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




















>
>
|







2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
** behaves as it did prior to [version 3.24.0] (2018-06-04).  See the
** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
** additional information. This feature can also be turned on and off
** using the [PRAGMA legacy_alter_table] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DML]]
** <dt>SQLITE_DBCONFIG_DQS_DML</dt>
** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DML statements
** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_DQS_DDL]]
** <dt>SQLITE_DBCONFIG_DQS_DDL</dt>
** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
** the legacy [double-quoted string literal] misfeature for DDL statements,
** such as CREATE TABLE and CREATE INDEX. The
** default value of this setting is determined by the [-DSQLITE_DQS]
** compile-time option.
** </dd>
**
** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</dt>
** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
** assume that database schemas are untainted by malicious content.
** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
** takes additional defensive steps to protect the application from harm
** including:
** <ul>
** <li> Prohibit the use of SQL functions inside triggers, views,
** CHECK constraints, DEFAULT clauses, expression indexes,
** partial indexes, or generated columns
** unless those functions are tagged with [SQLITE_INNOCUOUS].
** <li> Prohibit the use of virtual tables inside of triggers or views
** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
** </ul>
** This setting defaults to "on" for legacy compatibility, however
** all applications are advised to turn it off if possible. This setting
** can also be controlled using the [PRAGMA trusted_schema] statement.
** </dd>
**
** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt>
** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
** the legacy file format flag.  When activated, this flag causes all newly
** created database file to have a schema format version number (the 4-byte
** integer found at offset 44 into the database header) of 1.  This in turn
** means that the resulting database file will be readable and writable by
** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,
** newly created databases are generally not understandable by SQLite versions
** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there
** is now scarcely any need to generate database files that are compatible
** all the way back to version 3.0.0, and so this setting is of little
** practical use, but is provided so that SQLite can continue to claim the
** ability to generate new database files that are compatible with  version
** 3.0.0.
** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
** the [VACUUM] command will fail with an obscure error when attempting to
** process a table with generated columns and a descending index.  This is
** not considered a bug since SQLite versions 3.3.0 and earlier do not support
** either generated columns or decending indexes.
** </dd>
**
** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]]
** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt>
** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in
** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears
** a flag that enables collection of the sqlite3_stmt_scanstatus_v2()
** statistics. For statistics to be collected, the flag must be set on
** the database handle both when the SQL statement is prepared and when it
** is stepped. The flag is set (collection of statistics is enabled)
** by default.  This option takes two arguments: an integer and a pointer to
** an integer..  The first argument is 1, 0, or -1 to enable, disable, or
** leave unchanged the statement scanstatus option.  If the second argument
** is not NULL, then the value of the statement scanstatus setting after
** processing the first argument is written into the integer that the second
** argument points to.
** </dd>
**
** [[SQLITE_DBCONFIG_REVERSE_SCANORDER]]
** <dt>SQLITE_DBCONFIG_REVERSE_SCANORDER</dt>
** <dd>The SQLITE_DBCONFIG_REVERSE_SCANORDER option changes the default order
** in which tables and indexes are scanned so that the scans start at the end
** and work toward the beginning rather than starting at the beginning and
** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the
** same as setting [PRAGMA reverse_unordered_selects].  This option takes
** two arguments which are an integer and a pointer to an integer.  The first
** argument is 1, 0, or -1 to enable, disable, or leave unchanged the
** reverse scan order flag, respectively.  If the second argument is not NULL,
** then 0 or 1 is written into the integer that the second argument points to
** depending on if the reverse scan order flag is set after processing the
** first argument.
** </dd>
**
** </dl>
*/
#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
#define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */
#define SQLITE_DBCONFIG_WRITABLE_SCHEMA       1011 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    1012 /* int int* */
#define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */
#define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */
#define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */
#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */
#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */
#define SQLITE_DBCONFIG_STMT_SCANSTATUS       1018 /* int int* */
#define SQLITE_DBCONFIG_REVERSE_SCANORDER     1019 /* int int* */
#define SQLITE_DBCONFIG_MAX                   1019 /* Largest DBCONFIG */

/*
** CAPI3REF: Enable Or Disable Extended Result Codes
** METHOD: sqlite3
**
** ^The sqlite3_extended_result_codes() routine enables or disables the
** [extended result codes] feature of SQLite. ^The extended result
6197
6198
6199
6200
6201
6202
6203







6204
6205
6206
6207
6208
6209
6210
** requested from the operating system is returned.
**
** ^SQLite implements this interface by calling the xSleep()
** method of the default [sqlite3_vfs] object.  If the xSleep() method
** of the default VFS is not implemented correctly, or not implemented at
** all, then the behavior of sqlite3_sleep() may deviate from the description
** in the previous paragraphs.







*/
SQLITE_API int sqlite3_sleep(int);

/*
** CAPI3REF: Name Of The Folder Holding Temporary Files
**
** ^(If this global variable is made to point to a string which is







>
>
>
>
>
>
>







6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
** requested from the operating system is returned.
**
** ^SQLite implements this interface by calling the xSleep()
** method of the default [sqlite3_vfs] object.  If the xSleep() method
** of the default VFS is not implemented correctly, or not implemented at
** all, then the behavior of sqlite3_sleep() may deviate from the description
** in the previous paragraphs.
**
** If a negative argument is passed to sqlite3_sleep() the results vary by
** VFS and operating system.  Some system treat a negative argument as an
** instruction to sleep forever.  Others understand it to mean do not sleep
** at all. ^In SQLite version 3.42.0 and later, a negative
** argument passed into sqlite3_sleep() is changed to zero before it is relayed
** down into the xSleep method of the VFS.
*/
SQLITE_API int sqlite3_sleep(int);

/*
** CAPI3REF: Name Of The Folder Holding Temporary Files
**
** ^(If this global variable is made to point to a string which is
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
** behavior.)^
**
** ^The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.   The behavior
** is undefined if the mutex is not currently entered by the
** calling thread or is not currently allocated.
**
** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
** sqlite3_mutex_leave() is a NULL pointer, then all three routines
** behave as no-ops.
**
** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
*/
SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);







|
|
|







7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
** behavior.)^
**
** ^The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.   The behavior
** is undefined if the mutex is not currently entered by the
** calling thread or is not currently allocated.
**
** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(),
** sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer,
** then any of the four routines behaves as a no-op.
**
** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
*/
SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573









9574
9575
9576
9577
9578

9579
9580
9581
9582
9583
9584
9585
** prohibits that virtual table from being used from within triggers and
** views.
** </dd>
**
** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
** <dd>Calls of the form
** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
** identify that virtual table as being safe to use from within triggers
** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
** virtual table can do no serious harm even if it is controlled by a
** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
** flag unless absolutely necessary.
** </dd>









** </dl>
*/
#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
#define SQLITE_VTAB_INNOCUOUS          2
#define SQLITE_VTAB_DIRECTONLY         3


/*
** CAPI3REF: Determine The Virtual Table Conflict Policy
**
** This function may only be called from within a call to the [xUpdate] method
** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],







|






>
>
>
>
>
>
>
>
>





>







9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
** prohibits that virtual table from being used from within triggers and
** views.
** </dd>
**
** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
** <dd>Calls of the form
** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
** the [xConnect] or [xCreate] methods of a [virtual table] implementation
** identify that virtual table as being safe to use from within triggers
** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
** virtual table can do no serious harm even if it is controlled by a
** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
** flag unless absolutely necessary.
** </dd>
**
** [[SQLITE_VTAB_USES_ALL_SCHEMAS]]<dt>SQLITE_VTAB_USES_ALL_SCHEMAS</dt>
** <dd>Calls of the form
** [sqlite3_vtab_config](db,SQLITE_VTAB_USES_ALL_SCHEMA) from within the
** the [xConnect] or [xCreate] methods of a [virtual table] implementation
** instruct the query planner to begin at least a read transaction on
** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the
** virtual table is used.
** </dd>
** </dl>
*/
#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
#define SQLITE_VTAB_INNOCUOUS          2
#define SQLITE_VTAB_DIRECTONLY         3
#define SQLITE_VTAB_USES_ALL_SCHEMAS   4

/*
** CAPI3REF: Determine The Virtual Table Conflict Policy
**
** This function may only be called from within a call to the [xUpdate] method
** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759




10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780

10781







10782
10783

10784
10785
10786
10787
10788
10789
10790
** Session objects must be deleted before the database handle to which they
** are attached is closed. Refer to the documentation for
** [sqlite3session_create()] for details.
*/
SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);

/*
** CAPIREF: Conigure a Session Object
** METHOD: sqlite3_session
**
** This method is used to configure a session object after it has been
** created. At present the only valid value for the second parameter is
** [SQLITE_SESSION_OBJCONFIG_SIZE].
**




** Arguments for sqlite3session_object_config()
**
** The following values may passed as the the 4th parameter to
** sqlite3session_object_config().
**
** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
**   This option is used to set, clear or query the flag that enables
**   the [sqlite3session_changeset_size()] API. Because it imposes some
**   computational overhead, this API is disabled by default. Argument
**   pArg must point to a value of type (int). If the value is initially
**   0, then the sqlite3session_changeset_size() API is disabled. If it
**   is greater than 0, then the same API is enabled. Or, if the initial
**   value is less than zero, no change is made. In all cases the (int)
**   variable is set to 1 if the sqlite3session_changeset_size() API is
**   enabled following the current call, or 0 otherwise.
**
**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
**   the first table has been attached to the session object.
*/
SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);


/*







*/
#define SQLITE_SESSION_OBJCONFIG_SIZE 1


/*
** CAPI3REF: Enable Or Disable A Session Object
** METHOD: sqlite3_session
**
** Enable or disable the recording of changes by a session object. When
** enabled, a session object records changes made to the database. When







|



|
|

>
>
>
>
|

|















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

|
>







10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
** Session objects must be deleted before the database handle to which they
** are attached is closed. Refer to the documentation for
** [sqlite3session_create()] for details.
*/
SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);

/*
** CAPI3REF: Configure a Session Object
** METHOD: sqlite3_session
**
** This method is used to configure a session object after it has been
** created. At present the only valid values for the second parameter are
** [SQLITE_SESSION_OBJCONFIG_SIZE] and [SQLITE_SESSION_OBJCONFIG_ROWID].
**
*/
SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);

/*
** CAPI3REF: Options for sqlite3session_object_config
**
** The following values may passed as the the 2nd parameter to
** sqlite3session_object_config().
**
** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
**   This option is used to set, clear or query the flag that enables
**   the [sqlite3session_changeset_size()] API. Because it imposes some
**   computational overhead, this API is disabled by default. Argument
**   pArg must point to a value of type (int). If the value is initially
**   0, then the sqlite3session_changeset_size() API is disabled. If it
**   is greater than 0, then the same API is enabled. Or, if the initial
**   value is less than zero, no change is made. In all cases the (int)
**   variable is set to 1 if the sqlite3session_changeset_size() API is
**   enabled following the current call, or 0 otherwise.
**
**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
**   the first table has been attached to the session object.
**
** <dt>SQLITE_SESSION_OBJCONFIG_ROWID <dd>
**   This option is used to set, clear or query the flag that enables
**   collection of data for tables with no explicit PRIMARY KEY.
**
**   Normally, tables with no explicit PRIMARY KEY are simply ignored
**   by the sessions module. However, if this flag is set, it behaves
**   as if such tables have a column "_rowid_ INTEGER PRIMARY KEY" inserted
**   as their leftmost columns.
**
**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
**   the first table has been attached to the session object.
*/
#define SQLITE_SESSION_OBJCONFIG_SIZE  1
#define SQLITE_SESSION_OBJCONFIG_ROWID 2

/*
** CAPI3REF: Enable Or Disable A Session Object
** METHOD: sqlite3_session
**
** Enable or disable the recording of changes by a session object. When
** enabled, a session object records changes made to the database. When
11909
11910
11911
11912
11913
11914
11915













11916
11917
11918

11919
11920
11921
11922
11923
11924
11925
**   caller has an open transaction or savepoint when apply_v2() is called,
**   it may revert the partially applied changeset by rolling it back.
**
** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
**   Invert the changeset before applying it. This is equivalent to inverting
**   a changeset using sqlite3changeset_invert() before applying it. It is
**   an error to specify this flag with a patchset.













*/
#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
#define SQLITE_CHANGESETAPPLY_INVERT        0x0002


/*
** CAPI3REF: Constants Passed To The Conflict Handler
**
** Values that may be passed as the second argument to a conflict-handler.
**
** <dl>







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



>







11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
**   caller has an open transaction or savepoint when apply_v2() is called,
**   it may revert the partially applied changeset by rolling it back.
**
** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
**   Invert the changeset before applying it. This is equivalent to inverting
**   a changeset using sqlite3changeset_invert() before applying it. It is
**   an error to specify this flag with a patchset.
**
** <dt>SQLITE_CHANGESETAPPLY_IGNORENOOP <dd>
**   Do not invoke the conflict handler callback for any changes that
**   would not actually modify the database even if they were applied.
**   Specifically, this means that the conflict handler is not invoked
**   for:
**    <ul>
**    <li>a delete change if the row being deleted cannot be found,
**    <li>an update change if the modified fields are already set to
**        their new values in the conflicting row, or
**    <li>an insert change if all fields of the conflicting row match
**        the row being inserted.
**    </ul>
*/
#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
#define SQLITE_CHANGESETAPPLY_INVERT        0x0002
#define SQLITE_CHANGESETAPPLY_IGNORENOOP    0x0004

/*
** CAPI3REF: Constants Passed To The Conflict Handler
**
** Values that may be passed as the second argument to a conflict-handler.
**
** <dl>