sqlite: upgrade to 3.35.4 default tip @

Fri, 16 Apr 2021 18:42:21 +0200

author
David Demelier <markand@malikania.fr>
date
Fri, 16 Apr 2021 18:42:21 +0200
changeset 91
66eb00c3c225
parent 90
90346f702984

sqlite: upgrade to 3.35.4

VERSION.libsqlite.txt file | annotate | diff | comparison | revisions
libsqlite/sqlite3.c file | annotate | diff | comparison | revisions
libsqlite/sqlite3.h file | annotate | diff | comparison | revisions
--- a/VERSION.libsqlite.txt	Mon Dec 21 23:44:59 2020 +0100
+++ b/VERSION.libsqlite.txt	Fri Apr 16 18:42:21 2021 +0200
@@ -1,1 +1,1 @@
-3.34.0
+3.35.4
--- a/libsqlite/sqlite3.c	Mon Dec 21 23:44:59 2020 +0100
+++ b/libsqlite/sqlite3.c	Fri Apr 16 18:42:21 2021 +0200
@@ -1,6 +1,6 @@
 /******************************************************************************
 ** This file is an amalgamation of many separate C source files from SQLite
-** version 3.34.0.  By combining all the individual C code files into this
+** version 3.35.4.  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
@@ -284,6 +284,9 @@
 #ifdef SQLITE_ENABLE_LOCKING_STYLE
   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
 #endif
+#if SQLITE_ENABLE_MATH_FUNCTIONS
+  "ENABLE_MATH_FUNCTIONS",
+#endif
 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
   "ENABLE_MEMORY_MANAGEMENT",
 #endif
@@ -990,6 +993,18 @@
 # define MSVC_VERSION 0
 #endif
 
+/*
+** Some C99 functions in "math.h" are only present for MSVC when its version
+** is associated with Visual Studio 2013 or higher.
+*/
+#ifndef SQLITE_HAVE_C99_MATH_FUNCS
+# if MSVC_VERSION==0 || MSVC_VERSION>=1800
+#  define SQLITE_HAVE_C99_MATH_FUNCS (1)
+# else
+#  define SQLITE_HAVE_C99_MATH_FUNCS (0)
+# endif
+#endif
+
 /* Needed for various definitions... */
 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
 # define _GNU_SOURCE
@@ -1171,9 +1186,9 @@
 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
 ** [sqlite_version()] and [sqlite_source_id()].
 */
-#define SQLITE_VERSION        "3.34.0"
-#define SQLITE_VERSION_NUMBER 3034000
-#define SQLITE_SOURCE_ID      "2020-12-01 16:14:00 a26b6597e3ae272231b96f9982c3bcc17ddec2f2b6eb4df06a224b91089fed5b"
+#define SQLITE_VERSION        "3.35.4"
+#define SQLITE_VERSION_NUMBER 3035004
+#define SQLITE_SOURCE_ID      "2021-04-02 15:20:15 5d4c65779dab868b285519b19e4cf9d451d50c6048f06f653aa701ec212df45e"
 
 /*
 ** CAPI3REF: Run-Time Library Version Numbers
@@ -3163,7 +3178,13 @@
 ** The second parameter is a pointer to an integer into which
 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
 ** following this call.  The second parameter may be a NULL pointer, in
-** which case the trigger setting is not reported back. </dd>
+** which case the trigger setting is not reported back.
+**
+** <p>Originally this option disabled all triggers.  ^(However, since
+** SQLite version 3.35.0, TEMP triggers are still allowed even if
+** this option is off.  So, in other words, this option now only disables
+** triggers in the main database schema or in the schemas of ATTACH-ed
+** databases.)^ </dd>
 **
 ** [[SQLITE_DBCONFIG_ENABLE_VIEW]]
 ** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>
@@ -3174,7 +3195,13 @@
 ** The second parameter is a pointer to an integer into which
 ** is written 0 or 1 to indicate whether views are disabled or enabled
 ** following this call.  The second parameter may be a NULL pointer, in
-** which case the view setting is not reported back. </dd>
+** which case the view setting is not reported back.
+**
+** <p>Originally this option disabled all views.  ^(However, since
+** SQLite version 3.35.0, TEMP views are still allowed even if
+** this option is off.  So, in other words, this option now only disables
+** views in the main database schema or in the schemas of ATTACH-ed
+** databases.)^ </dd>
 **
 ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
 ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
@@ -4547,6 +4574,7 @@
 **          that uses dot-files in place of posix advisory locking.
 ** <tr><td> file:data.db?mode=readonly <td>
 **          An error. "readonly" is not a valid option for the "mode" parameter.
+**          Use "ro" instead:  "file:data.db?mode=ro".
 ** </table>
 **
 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
@@ -4745,7 +4773,7 @@
 ** If the Y parameter to sqlite3_free_filename(Y) is anything other
 ** than a NULL pointer or a pointer previously acquired from
 ** sqlite3_create_filename(), then bad things such as heap
-** corruption or segfaults may occur. The value Y should be
+** corruption or segfaults may occur. The value Y should not be
 ** used again after sqlite3_free_filename(Y) has been called.  This means
 ** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
 ** then the corresponding [sqlite3_module.xClose() method should also be
@@ -8813,7 +8841,8 @@
 #define SQLITE_TESTCTRL_PRNG_SEED               28
 #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
 #define SQLITE_TESTCTRL_SEEK_COUNT              30
-#define SQLITE_TESTCTRL_LAST                    30  /* Largest TESTCTRL */
+#define SQLITE_TESTCTRL_TRACEFLAGS              31
+#define SQLITE_TESTCTRL_LAST                    31  /* Largest TESTCTRL */
 
 /*
 ** CAPI3REF: SQL Keyword Checking
@@ -11487,6 +11516,14 @@
 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 
 /*
+** CAPI3REF: Query for the amount of heap memory used by a session object.
+**
+** This API returns the total amount of heap memory in bytes currently
+** used by the session object passed as the only argument.
+*/
+SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession);
+
+/*
 ** CAPI3REF: Create An Iterator To Traverse A Changeset
 ** CONSTRUCTOR: sqlite3_changeset_iter
 **
@@ -11588,18 +11625,23 @@
 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
 ** is not the case, this function returns [SQLITE_MISUSE].
 **
-** If argument pzTab is not NULL, then *pzTab is set to point to a
-** nul-terminated utf-8 encoded string containing the name of the table
-** affected by the current change. The buffer remains valid until either
-** sqlite3changeset_next() is called on the iterator or until the
-** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
-** set to the number of columns in the table affected by the change. If
-** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
+** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three
+** outputs are set through these pointers:
+**
+** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
+** depending on the type of change that the iterator currently points to;
+**
+** *pnCol is set to the number of columns in the table affected by the change; and
+**
+** *pzTab is set to point to a nul-terminated utf-8 encoded string containing
+** the name of the table affected by the current change. The buffer remains
+** valid until either sqlite3changeset_next() is called on the iterator
+** or until the conflict-handler function returns.
+**
+** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
 ** is an indirect change, or false (0) otherwise. See the documentation for
 ** [sqlite3session_indirect()] for a description of direct and indirect
-** changes. Finally, if pOp is not NULL, then *pOp is set to one of
-** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
-** type of change that the iterator currently points to.
+** changes.
 **
 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
 ** SQLite error code is returned. The values of the output variables may not
@@ -13528,7 +13570,8 @@
 #ifndef __has_extension
 # define __has_extension(x) 0     /* compatibility with non-clang compilers */
 #endif
-#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
+#if GCC_VERSION>=4007000 || \
+    (__has_extension(c_atomic) && __has_extension(c_atomic_store_n))
 # define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
 # define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
 #else
@@ -14095,90 +14138,92 @@
 #define TK_TIES                            94
 #define TK_GENERATED                       95
 #define TK_ALWAYS                          96
-#define TK_REINDEX                         97
-#define TK_RENAME                          98
-#define TK_CTIME_KW                        99
-#define TK_ANY                            100
-#define TK_BITAND                         101
-#define TK_BITOR                          102
-#define TK_LSHIFT                         103
-#define TK_RSHIFT                         104
-#define TK_PLUS                           105
-#define TK_MINUS                          106
-#define TK_STAR                           107
-#define TK_SLASH                          108
-#define TK_REM                            109
-#define TK_CONCAT                         110
-#define TK_COLLATE                        111
-#define TK_BITNOT                         112
-#define TK_ON                             113
-#define TK_INDEXED                        114
-#define TK_STRING                         115
-#define TK_JOIN_KW                        116
-#define TK_CONSTRAINT                     117
-#define TK_DEFAULT                        118
-#define TK_NULL                           119
-#define TK_PRIMARY                        120
-#define TK_UNIQUE                         121
-#define TK_CHECK                          122
-#define TK_REFERENCES                     123
-#define TK_AUTOINCR                       124
-#define TK_INSERT                         125
-#define TK_DELETE                         126
-#define TK_UPDATE                         127
-#define TK_SET                            128
-#define TK_DEFERRABLE                     129
-#define TK_FOREIGN                        130
-#define TK_DROP                           131
-#define TK_UNION                          132
-#define TK_ALL                            133
-#define TK_EXCEPT                         134
-#define TK_INTERSECT                      135
-#define TK_SELECT                         136
-#define TK_VALUES                         137
-#define TK_DISTINCT                       138
-#define TK_DOT                            139
-#define TK_FROM                           140
-#define TK_JOIN                           141
-#define TK_USING                          142
-#define TK_ORDER                          143
-#define TK_GROUP                          144
-#define TK_HAVING                         145
-#define TK_LIMIT                          146
-#define TK_WHERE                          147
-#define TK_INTO                           148
-#define TK_NOTHING                        149
-#define TK_FLOAT                          150
-#define TK_BLOB                           151
-#define TK_INTEGER                        152
-#define TK_VARIABLE                       153
-#define TK_CASE                           154
-#define TK_WHEN                           155
-#define TK_THEN                           156
-#define TK_ELSE                           157
-#define TK_INDEX                          158
-#define TK_ALTER                          159
-#define TK_ADD                            160
-#define TK_WINDOW                         161
-#define TK_OVER                           162
-#define TK_FILTER                         163
-#define TK_COLUMN                         164
-#define TK_AGG_FUNCTION                   165
-#define TK_AGG_COLUMN                     166
-#define TK_TRUEFALSE                      167
-#define TK_ISNOT                          168
-#define TK_FUNCTION                       169
-#define TK_UMINUS                         170
-#define TK_UPLUS                          171
-#define TK_TRUTH                          172
-#define TK_REGISTER                       173
-#define TK_VECTOR                         174
-#define TK_SELECT_COLUMN                  175
-#define TK_IF_NULL_ROW                    176
-#define TK_ASTERISK                       177
-#define TK_SPAN                           178
-#define TK_SPACE                          179
-#define TK_ILLEGAL                        180
+#define TK_MATERIALIZED                    97
+#define TK_REINDEX                         98
+#define TK_RENAME                          99
+#define TK_CTIME_KW                       100
+#define TK_ANY                            101
+#define TK_BITAND                         102
+#define TK_BITOR                          103
+#define TK_LSHIFT                         104
+#define TK_RSHIFT                         105
+#define TK_PLUS                           106
+#define TK_MINUS                          107
+#define TK_STAR                           108
+#define TK_SLASH                          109
+#define TK_REM                            110
+#define TK_CONCAT                         111
+#define TK_COLLATE                        112
+#define TK_BITNOT                         113
+#define TK_ON                             114
+#define TK_INDEXED                        115
+#define TK_STRING                         116
+#define TK_JOIN_KW                        117
+#define TK_CONSTRAINT                     118
+#define TK_DEFAULT                        119
+#define TK_NULL                           120
+#define TK_PRIMARY                        121
+#define TK_UNIQUE                         122
+#define TK_CHECK                          123
+#define TK_REFERENCES                     124
+#define TK_AUTOINCR                       125
+#define TK_INSERT                         126
+#define TK_DELETE                         127
+#define TK_UPDATE                         128
+#define TK_SET                            129
+#define TK_DEFERRABLE                     130
+#define TK_FOREIGN                        131
+#define TK_DROP                           132
+#define TK_UNION                          133
+#define TK_ALL                            134
+#define TK_EXCEPT                         135
+#define TK_INTERSECT                      136
+#define TK_SELECT                         137
+#define TK_VALUES                         138
+#define TK_DISTINCT                       139
+#define TK_DOT                            140
+#define TK_FROM                           141
+#define TK_JOIN                           142
+#define TK_USING                          143
+#define TK_ORDER                          144
+#define TK_GROUP                          145
+#define TK_HAVING                         146
+#define TK_LIMIT                          147
+#define TK_WHERE                          148
+#define TK_RETURNING                      149
+#define TK_INTO                           150
+#define TK_NOTHING                        151
+#define TK_FLOAT                          152
+#define TK_BLOB                           153
+#define TK_INTEGER                        154
+#define TK_VARIABLE                       155
+#define TK_CASE                           156
+#define TK_WHEN                           157
+#define TK_THEN                           158
+#define TK_ELSE                           159
+#define TK_INDEX                          160
+#define TK_ALTER                          161
+#define TK_ADD                            162
+#define TK_WINDOW                         163
+#define TK_OVER                           164
+#define TK_FILTER                         165
+#define TK_COLUMN                         166
+#define TK_AGG_FUNCTION                   167
+#define TK_AGG_COLUMN                     168
+#define TK_TRUEFALSE                      169
+#define TK_ISNOT                          170
+#define TK_FUNCTION                       171
+#define TK_UMINUS                         172
+#define TK_UPLUS                          173
+#define TK_TRUTH                          174
+#define TK_REGISTER                       175
+#define TK_VECTOR                         176
+#define TK_SELECT_COLUMN                  177
+#define TK_IF_NULL_ROW                    178
+#define TK_ASTERISK                       179
+#define TK_SPAN                           180
+#define TK_SPACE                          181
+#define TK_ILLEGAL                        182
 
 /************** End of parse.h ***********************************************/
 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -14594,15 +14639,14 @@
 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
 ** the Select query generator tracing logic is turned on.
 */
-#if defined(SQLITE_ENABLE_SELECTTRACE)
-# define SELECTTRACE_ENABLED 1
-#else
-# define SELECTTRACE_ENABLED 0
-#endif
-#if defined(SQLITE_ENABLE_SELECTTRACE)
+#if !defined(SQLITE_AMALGAMATION)
+SQLITE_PRIVATE u32 sqlite3SelectTrace;
+#endif
+#if defined(SQLITE_DEBUG) \
+    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE))
 # define SELECTTRACE_ENABLED 1
 # define SELECTTRACE(K,P,S,X)  \
-  if(sqlite3_unsupported_selecttrace&(K))   \
+  if(sqlite3SelectTrace&(K))   \
     sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
     sqlite3DebugPrintf X
 #else
@@ -14611,6 +14655,19 @@
 #endif
 
 /*
+** Macros for "wheretrace"
+*/
+SQLITE_PRIVATE u32 sqlite3WhereTrace;
+#if defined(SQLITE_DEBUG) \
+    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
+# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
+# define WHERETRACE_ENABLED 1
+#else
+# define WHERETRACE(K,X)
+#endif
+
+
+/*
 ** An instance of the following structure is used to store the busy-handler
 ** callback for a given sqlite handle.
 **
@@ -14721,7 +14778,10 @@
 typedef struct Bitvec Bitvec;
 typedef struct CollSeq CollSeq;
 typedef struct Column Column;
+typedef struct Cte Cte;
+typedef struct CteUse CteUse;
 typedef struct Db Db;
+typedef struct DbFixer DbFixer;
 typedef struct Schema Schema;
 typedef struct Expr Expr;
 typedef struct ExprList ExprList;
@@ -14739,14 +14799,17 @@
 typedef struct Module Module;
 typedef struct NameContext NameContext;
 typedef struct Parse Parse;
+typedef struct ParseCleanup ParseCleanup;
 typedef struct PreUpdate PreUpdate;
 typedef struct PrintfArguments PrintfArguments;
 typedef struct RenameToken RenameToken;
+typedef struct Returning Returning;
 typedef struct RowSet RowSet;
 typedef struct Savepoint Savepoint;
 typedef struct Select Select;
 typedef struct SQLiteThread SQLiteThread;
 typedef struct SelectDest SelectDest;
+typedef struct SrcItem SrcItem;
 typedef struct SrcList SrcList;
 typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
 typedef struct Table Table;
@@ -15318,6 +15381,7 @@
 #define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
 #define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
 #define BTREE_APPEND       0x08  /* Insert is likely an append */
+#define BTREE_PREFORMAT    0x80  /* Inserted data is a preformated cell */
 
 /* An instance of the BtreePayload object describes the content of a single
 ** entry in either an index or table btree.
@@ -15417,6 +15481,8 @@
 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
 #endif
 
+SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor*, BtCursor*, i64);
+
 /*
 ** If we are not using shared cache, then there is no need to
 ** use mutexes to access the BtShared structures.  So make the
@@ -15716,103 +15782,105 @@
 #define OP_Copy           77 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
 #define OP_SCopy          78 /* synopsis: r[P2]=r[P1]                      */
 #define OP_IntCopy        79 /* synopsis: r[P2]=r[P1]                      */
-#define OP_ResultRow      80 /* synopsis: output=r[P1@P2]                  */
-#define OP_CollSeq        81
-#define OP_AddImm         82 /* synopsis: r[P1]=r[P1]+P2                   */
-#define OP_RealAffinity   83
-#define OP_Cast           84 /* synopsis: affinity(r[P1])                  */
-#define OP_Permutation    85
-#define OP_Compare        86 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
-#define OP_IsTrue         87 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
-#define OP_Offset         88 /* synopsis: r[P3] = sqlite_offset(P1)        */
-#define OP_Column         89 /* synopsis: r[P3]=PX                         */
-#define OP_Affinity       90 /* synopsis: affinity(r[P1@P2])               */
-#define OP_MakeRecord     91 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
-#define OP_Count          92 /* synopsis: r[P2]=count()                    */
-#define OP_ReadCookie     93
-#define OP_SetCookie      94
-#define OP_ReopenIdx      95 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenRead       96 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenWrite      97 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenDup        98
-#define OP_OpenAutoindex  99 /* synopsis: nColumn=P2                       */
-#define OP_OpenEphemeral 100 /* synopsis: nColumn=P2                       */
-#define OP_BitAnd        101 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
-#define OP_BitOr         102 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
-#define OP_ShiftLeft     103 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
-#define OP_ShiftRight    104 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
-#define OP_Add           105 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
-#define OP_Subtract      106 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
-#define OP_Multiply      107 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
-#define OP_Divide        108 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
-#define OP_Remainder     109 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
-#define OP_Concat        110 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
-#define OP_SorterOpen    111
-#define OP_BitNot        112 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
-#define OP_SequenceTest  113 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
-#define OP_OpenPseudo    114 /* synopsis: P3 columns in r[P2]              */
-#define OP_String8       115 /* same as TK_STRING, synopsis: r[P2]='P4'    */
-#define OP_Close         116
-#define OP_ColumnsUsed   117
-#define OP_SeekScan      118 /* synopsis: Scan-ahead up to P1 rows         */
-#define OP_SeekHit       119 /* synopsis: set P2<=seekHit<=P3              */
-#define OP_Sequence      120 /* synopsis: r[P2]=cursor[P1].ctr++           */
-#define OP_NewRowid      121 /* synopsis: r[P2]=rowid                      */
-#define OP_Insert        122 /* synopsis: intkey=r[P3] data=r[P2]          */
-#define OP_Delete        123
-#define OP_ResetCount    124
-#define OP_SorterCompare 125 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
-#define OP_SorterData    126 /* synopsis: r[P2]=data                       */
-#define OP_RowData       127 /* synopsis: r[P2]=data                       */
-#define OP_Rowid         128 /* synopsis: r[P2]=rowid                      */
-#define OP_NullRow       129
-#define OP_SeekEnd       130
-#define OP_IdxInsert     131 /* synopsis: key=r[P2]                        */
-#define OP_SorterInsert  132 /* synopsis: key=r[P2]                        */
-#define OP_IdxDelete     133 /* synopsis: key=r[P2@P3]                     */
-#define OP_DeferredSeek  134 /* synopsis: Move P3 to P1.rowid if needed    */
-#define OP_IdxRowid      135 /* synopsis: r[P2]=rowid                      */
-#define OP_FinishSeek    136
-#define OP_Destroy       137
-#define OP_Clear         138
-#define OP_ResetSorter   139
-#define OP_CreateBtree   140 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
-#define OP_SqlExec       141
-#define OP_ParseSchema   142
-#define OP_LoadAnalysis  143
-#define OP_DropTable     144
-#define OP_DropIndex     145
-#define OP_DropTrigger   146
-#define OP_IntegrityCk   147
-#define OP_RowSetAdd     148 /* synopsis: rowset(P1)=r[P2]                 */
-#define OP_Param         149
-#define OP_Real          150 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
-#define OP_FkCounter     151 /* synopsis: fkctr[P1]+=P2                    */
-#define OP_MemMax        152 /* synopsis: r[P1]=max(r[P1],r[P2])           */
-#define OP_OffsetLimit   153 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
-#define OP_AggInverse    154 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
-#define OP_AggStep       155 /* synopsis: accum=r[P3] step(r[P2@P5])       */
-#define OP_AggStep1      156 /* synopsis: accum=r[P3] step(r[P2@P5])       */
-#define OP_AggValue      157 /* synopsis: r[P3]=value N=P2                 */
-#define OP_AggFinal      158 /* synopsis: accum=r[P1] N=P2                 */
-#define OP_Expire        159
-#define OP_CursorLock    160
-#define OP_CursorUnlock  161
-#define OP_TableLock     162 /* synopsis: iDb=P1 root=P2 write=P3          */
-#define OP_VBegin        163
-#define OP_VCreate       164
-#define OP_VDestroy      165
-#define OP_VOpen         166
-#define OP_VColumn       167 /* synopsis: r[P3]=vcolumn(P2)                */
-#define OP_VRename       168
-#define OP_Pagecount     169
-#define OP_MaxPgcnt      170
-#define OP_Trace         171
-#define OP_CursorHint    172
-#define OP_ReleaseReg    173 /* synopsis: release r[P1@P2] mask P3         */
-#define OP_Noop          174
-#define OP_Explain       175
-#define OP_Abortable     176
+#define OP_ChngCntRow     80 /* synopsis: output=r[P1]                     */
+#define OP_ResultRow      81 /* synopsis: output=r[P1@P2]                  */
+#define OP_CollSeq        82
+#define OP_AddImm         83 /* synopsis: r[P1]=r[P1]+P2                   */
+#define OP_RealAffinity   84
+#define OP_Cast           85 /* synopsis: affinity(r[P1])                  */
+#define OP_Permutation    86
+#define OP_Compare        87 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
+#define OP_IsTrue         88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
+#define OP_Offset         89 /* synopsis: r[P3] = sqlite_offset(P1)        */
+#define OP_Column         90 /* synopsis: r[P3]=PX                         */
+#define OP_Affinity       91 /* synopsis: affinity(r[P1@P2])               */
+#define OP_MakeRecord     92 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
+#define OP_Count          93 /* synopsis: r[P2]=count()                    */
+#define OP_ReadCookie     94
+#define OP_SetCookie      95
+#define OP_ReopenIdx      96 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenRead       97 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenWrite      98 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenDup        99
+#define OP_OpenAutoindex 100 /* synopsis: nColumn=P2                       */
+#define OP_OpenEphemeral 101 /* synopsis: nColumn=P2                       */
+#define OP_BitAnd        102 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
+#define OP_BitOr         103 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
+#define OP_ShiftLeft     104 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
+#define OP_ShiftRight    105 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
+#define OP_Add           106 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
+#define OP_Subtract      107 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
+#define OP_Multiply      108 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
+#define OP_Divide        109 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
+#define OP_Remainder     110 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
+#define OP_Concat        111 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
+#define OP_SorterOpen    112
+#define OP_BitNot        113 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
+#define OP_SequenceTest  114 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
+#define OP_OpenPseudo    115 /* synopsis: P3 columns in r[P2]              */
+#define OP_String8       116 /* same as TK_STRING, synopsis: r[P2]='P4'    */
+#define OP_Close         117
+#define OP_ColumnsUsed   118
+#define OP_SeekScan      119 /* synopsis: Scan-ahead up to P1 rows         */
+#define OP_SeekHit       120 /* synopsis: set P2<=seekHit<=P3              */
+#define OP_Sequence      121 /* synopsis: r[P2]=cursor[P1].ctr++           */
+#define OP_NewRowid      122 /* synopsis: r[P2]=rowid                      */
+#define OP_Insert        123 /* synopsis: intkey=r[P3] data=r[P2]          */
+#define OP_RowCell       124
+#define OP_Delete        125
+#define OP_ResetCount    126
+#define OP_SorterCompare 127 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
+#define OP_SorterData    128 /* synopsis: r[P2]=data                       */
+#define OP_RowData       129 /* synopsis: r[P2]=data                       */
+#define OP_Rowid         130 /* synopsis: r[P2]=rowid                      */
+#define OP_NullRow       131
+#define OP_SeekEnd       132
+#define OP_IdxInsert     133 /* synopsis: key=r[P2]                        */
+#define OP_SorterInsert  134 /* synopsis: key=r[P2]                        */
+#define OP_IdxDelete     135 /* synopsis: key=r[P2@P3]                     */
+#define OP_DeferredSeek  136 /* synopsis: Move P3 to P1.rowid if needed    */
+#define OP_IdxRowid      137 /* synopsis: r[P2]=rowid                      */
+#define OP_FinishSeek    138
+#define OP_Destroy       139
+#define OP_Clear         140
+#define OP_ResetSorter   141
+#define OP_CreateBtree   142 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
+#define OP_SqlExec       143
+#define OP_ParseSchema   144
+#define OP_LoadAnalysis  145
+#define OP_DropTable     146
+#define OP_DropIndex     147
+#define OP_DropTrigger   148
+#define OP_IntegrityCk   149
+#define OP_RowSetAdd     150 /* synopsis: rowset(P1)=r[P2]                 */
+#define OP_Param         151
+#define OP_Real          152 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
+#define OP_FkCounter     153 /* synopsis: fkctr[P1]+=P2                    */
+#define OP_MemMax        154 /* synopsis: r[P1]=max(r[P1],r[P2])           */
+#define OP_OffsetLimit   155 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
+#define OP_AggInverse    156 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
+#define OP_AggStep       157 /* synopsis: accum=r[P3] step(r[P2@P5])       */
+#define OP_AggStep1      158 /* synopsis: accum=r[P3] step(r[P2@P5])       */
+#define OP_AggValue      159 /* synopsis: r[P3]=value N=P2                 */
+#define OP_AggFinal      160 /* synopsis: accum=r[P1] N=P2                 */
+#define OP_Expire        161
+#define OP_CursorLock    162
+#define OP_CursorUnlock  163
+#define OP_TableLock     164 /* synopsis: iDb=P1 root=P2 write=P3          */
+#define OP_VBegin        165
+#define OP_VCreate       166
+#define OP_VDestroy      167
+#define OP_VOpen         168
+#define OP_VColumn       169 /* synopsis: r[P3]=vcolumn(P2)                */
+#define OP_VRename       170
+#define OP_Pagecount     171
+#define OP_MaxPgcnt      172
+#define OP_Trace         173
+#define OP_CursorHint    174
+#define OP_ReleaseReg    175 /* synopsis: release r[P1@P2] mask P3         */
+#define OP_Noop          176
+#define OP_Explain       177
+#define OP_Abortable     178
 
 /* Properties such as "out2" or "jump" that are specified in
 ** comments following the "case" for each opcode in the vdbe.c
@@ -15835,19 +15903,19 @@
 /*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00,\
 /*  64 */ 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\
 /*  72 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\
-/*  80 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12,\
-/*  88 */ 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
-/*  96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26, 0x26,\
-/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
-/* 112 */ 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
-/* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 128 */ 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
-/* 136 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\
-/* 144 */ 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x10, 0x00,\
-/* 152 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/*  80 */ 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
+/*  88 */ 0x12, 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
+/*  96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26,\
+/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
+/* 112 */ 0x00, 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\
+/* 120 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 128 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x04, 0x04, 0x00,\
+/* 136 */ 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x00,\
+/* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10,\
+/* 152 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
 /* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 168 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 176 */ 0x00,}
+/* 168 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
+/* 176 */ 0x00, 0x00, 0x00,}
 
 /* The sqlite3P2Values() routine is able to run faster if it knows
 ** the value of the largest JUMP opcode.  The smaller the maximum
@@ -15915,7 +15983,7 @@
 #else
 # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
 #endif
-SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
+SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*, int, char*, u16);
 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);
 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
@@ -16887,6 +16955,11 @@
 #endif /* SQLITE_OMIT_DEPRECATED */
 #define SQLITE_TRACE_NONLEGACY_MASK  0x0f     /* Normal flags */
 
+/*
+** Maximum number of sqlite3.aDb[] entries.  This is the number of attached
+** databases plus 2 for "main" and "temp".
+*/
+#define SQLITE_MAX_DB (SQLITE_MAX_ATTACHED+2)
 
 /*
 ** Each database connection is an instance of the following structure.
@@ -16907,7 +16980,7 @@
   int errCode;                  /* Most recent error code (SQLITE_*) */
   int errMask;                  /* & result codes with this before returning */
   int iSysErrno;                /* Errno value from last system error */
-  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
+  u32 dbOptFlags;               /* Flags to enable/disable optimizations */
   u8 enc;                       /* Text encoding */
   u8 autoCommit;                /* The auto-commit flag. */
   u8 temp_store;                /* 1: file 2: memory 0: default */
@@ -16934,7 +17007,10 @@
     unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
     unsigned imposterTable : 1; /* Building an imposter table */
     unsigned reopenMemdb : 1;   /* ATTACH is really a reopen using MemDB */
+    unsigned bDropColumn : 1;   /* Doing schema check after DROP COLUMN */
     char **azInit;              /* "type", "name", and "tbl_name" columns */
+                                /*   or if bDropColumn, then azInit[0] is the */
+                                /*   name of the column being dropped */
   } init;
   int nVdbeActive;              /* Number of VDBEs currently running */
   int nVdbeRead;                /* Number of active VDBEs that read or write */
@@ -17114,24 +17190,26 @@
 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
 ** selectively disable various optimizations.
 */
-#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
-#define SQLITE_WindowFunc     0x0002   /* Use xInverse for window functions */
-#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
-#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
-#define SQLITE_DistinctOpt    0x0010   /* DISTINCT using indexes */
-#define SQLITE_CoverIdxScan   0x0020   /* Covering index scans */
-#define SQLITE_OrderByIdxJoin 0x0040   /* ORDER BY of joins via index */
-#define SQLITE_Transitive     0x0080   /* Transitive constraints */
-#define SQLITE_OmitNoopJoin   0x0100   /* Omit unused tables in joins */
-#define SQLITE_CountOfView    0x0200   /* The count-of-view optimization */
-#define SQLITE_CursorHints    0x0400   /* Add OP_CursorHint opcodes */
-#define SQLITE_Stat4          0x0800   /* Use STAT4 data */
-   /* TH3 expects the Stat4   ^^^^^^ value to be 0x0800.  Don't change it */
-#define SQLITE_PushDown       0x1000   /* The push-down optimization */
-#define SQLITE_SimplifyJoin   0x2000   /* Convert LEFT JOIN to JOIN */
-#define SQLITE_SkipScan       0x4000   /* Skip-scans */
-#define SQLITE_PropagateConst 0x8000   /* The constant propagation opt */
-#define SQLITE_AllOpts        0xffff   /* All optimizations */
+#define SQLITE_QueryFlattener 0x00000001 /* Query flattening */
+#define SQLITE_WindowFunc     0x00000002 /* Use xInverse for window functions */
+#define SQLITE_GroupByOrder   0x00000004 /* GROUPBY cover of ORDERBY */
+#define SQLITE_FactorOutConst 0x00000008 /* Constant factoring */
+#define SQLITE_DistinctOpt    0x00000010 /* DISTINCT using indexes */
+#define SQLITE_CoverIdxScan   0x00000020 /* Covering index scans */
+#define SQLITE_OrderByIdxJoin 0x00000040 /* ORDER BY of joins via index */
+#define SQLITE_Transitive     0x00000080 /* Transitive constraints */
+#define SQLITE_OmitNoopJoin   0x00000100 /* Omit unused tables in joins */
+#define SQLITE_CountOfView    0x00000200 /* The count-of-view optimization */
+#define SQLITE_CursorHints    0x00000400 /* Add OP_CursorHint opcodes */
+#define SQLITE_Stat4          0x00000800 /* Use STAT4 data */
+   /* TH3 expects this value  ^^^^^^^^^^ to be 0x0000800. Don't change it */
+#define SQLITE_PushDown       0x00001000 /* The push-down optimization */
+#define SQLITE_SimplifyJoin   0x00002000 /* Convert LEFT JOIN to JOIN */
+#define SQLITE_SkipScan       0x00004000 /* Skip-scans */
+#define SQLITE_PropagateConst 0x00008000 /* The constant propagation opt */
+#define SQLITE_MinMaxOpt      0x00010000 /* The min/max optimization */
+#define SQLITE_ExistsToIN     0x00020000 /* The EXISTS-to-IN optimization */
+#define SQLITE_AllOpts        0xffffffff /* All optimizations */
 
 /*
 ** Macros for testing whether or not optimizations are enabled or disabled.
@@ -17287,6 +17365,9 @@
 **     a single query.  The iArg is ignored.  The user-data is always set
 **     to a NULL pointer.  The bNC parameter is not used.
 **
+**   MFUNCTION(zName, nArg, xPtr, xFunc)
+**     For math-library functions.  xPtr is an arbitrary pointer.
+**
 **   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
 **     Used for "pure" date/time functions, this macro is like DFUNCTION
 **     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
@@ -17322,6 +17403,9 @@
 #define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
   {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
+#define MFUNCTION(zName, nArg, xPtr, xFunc) \
+  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
+   xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
 #define INLINE_FUNC(zName, nArg, iArg, mFlags) \
   {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
    SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
@@ -17416,7 +17500,12 @@
   u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
 };
 
-/* Allowed values for Column.colFlags:
+/* Allowed values for Column.colFlags.
+**
+** Constraints:
+**         TF_HasVirtual == COLFLAG_VIRTUAL
+**         TF_HasStored  == COLFLAG_STORED
+**         TF_HasHidden  == COLFLAG_HIDDEN
 */
 #define COLFLAG_PRIMKEY   0x0001   /* Column is part of the primary key */
 #define COLFLAG_HIDDEN    0x0002   /* A hidden column in a virtual table */
@@ -17592,7 +17681,6 @@
 #endif
   Trigger *pTrigger;   /* List of triggers stored in pSchema */
   Schema *pSchema;     /* Schema that contains this table */
-  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
 };
 
 /*
@@ -17606,11 +17694,12 @@
 **
 ** Constraints:
 **
-**         TF_HasVirtual == COLFLAG_Virtual
-**         TF_HasStored  == COLFLAG_Stored
+**         TF_HasVirtual == COLFLAG_VIRTUAL
+**         TF_HasStored  == COLFLAG_STORED
+**         TF_HasHidden  == COLFLAG_HIDDEN
 */
 #define TF_Readonly        0x0001    /* Read-only system table */
-#define TF_Ephemeral       0x0002    /* An ephemeral table */
+#define TF_HasHidden       0x0002    /* Has one or more hidden columns */
 #define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
 #define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
 #define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
@@ -17625,6 +17714,7 @@
 #define TF_HasNotNull      0x0800    /* Contains NOT NULL constraints */
 #define TF_Shadow          0x1000    /* True for a shadow table */
 #define TF_HasStat4        0x2000    /* STAT4 info available for this table */
+#define TF_Ephemeral       0x4000    /* An ephemeral table */
 
 /*
 ** Test to see whether or not a table is a virtual table.  This is
@@ -17721,16 +17811,22 @@
 ** is returned.  REPLACE means that preexisting database rows that caused
 ** a UNIQUE constraint violation are removed so that the new insert or
 ** update can proceed.  Processing continues and no error is reported.
-**
-** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
+** UPDATE applies to insert operations only and means that the insert
+** is omitted and the DO UPDATE clause of an upsert is run instead.
+**
+** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys.
 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
-** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
+** key is set to NULL.  SETDFLT means that the foreign key is set
+** to its default value.  CASCADE means that a DELETE or UPDATE of the
 ** referenced table row is propagated into the row that holds the
 ** foreign key.
 **
+** The OE_Default value is a place holder that means to use whatever
+** conflict resolution algorthm is required from context.
+**
 ** The following symbolic values are used to record which type
-** of action to take.
+** of conflict resolution action to take.
 */
 #define OE_None     0   /* There is no constraint to check */
 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
@@ -17987,7 +18083,6 @@
   } *aFunc;
   int nFunc;              /* Number of entries in aFunc[] */
   u32 selId;              /* Select to which this AggInfo belongs */
-  AggInfo *pNext;         /* Next in list of them all */
 };
 
 /*
@@ -18116,7 +18211,7 @@
                          ** TK_VARIABLE: variable number (always >= 1).
                          ** TK_SELECT_COLUMN: column of the result vector */
   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
-  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
+  int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   union {
     Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL
@@ -18158,7 +18253,7 @@
 #define EP_ConstFunc  0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
 #define EP_CanBeNull  0x100000 /* Can be null despite NOT NULL constraint */
 #define EP_Subquery   0x200000 /* Tree contains a TK_SELECT operator */
-#define EP_Alias      0x400000 /* Is an alias for a result set column */
+                 /*   0x400000 // Available */
 #define EP_Leaf       0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
 #define EP_WinFunc   0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
 #define EP_Subrtn    0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
@@ -18307,6 +18402,45 @@
 };
 
 /*
+** The SrcItem object represents a single term in the FROM clause of a query.
+** The SrcList object is mostly an array of SrcItems.
+*/
+struct SrcItem {
+  Schema *pSchema;  /* Schema to which this item is fixed */
+  char *zDatabase;  /* Name of database holding this table */
+  char *zName;      /* Name of the table */
+  char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
+  Table *pTab;      /* An SQL table corresponding to zName */
+  Select *pSelect;  /* A SELECT statement used in place of a table name */
+  int addrFillSub;  /* Address of subroutine to manifest a subquery */
+  int regReturn;    /* Register holding return address of addrFillSub */
+  int regResult;    /* Registers holding results of a co-routine */
+  struct {
+    u8 jointype;      /* Type of join between this table and the previous */
+    unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
+    unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
+    unsigned isTabFunc :1;     /* True if table-valued-function syntax */
+    unsigned isCorrelated :1;  /* True if sub-query is correlated */
+    unsigned viaCoroutine :1;  /* Implemented as a co-routine */
+    unsigned isRecursive :1;   /* True for recursive reference in WITH */
+    unsigned fromDDL :1;       /* Comes from sqlite_schema */
+    unsigned isCte :1;         /* This is a CTE */
+  } fg;
+  int iCursor;      /* The VDBE cursor number used to access this table */
+  Expr *pOn;        /* The ON clause of a join */
+  IdList *pUsing;   /* The USING clause of a join */
+  Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
+  union {
+    char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
+    ExprList *pFuncArg;  /* Arguments to table-valued-function */
+  } u1;
+  union {
+    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
+    CteUse *pCteUse;  /* CTE Usage info info fg.isCte is true */
+  } u2;
+};
+
+/*
 ** The following structure describes the FROM clause of a SELECT statement.
 ** Each table or subquery in the FROM clause is a separate element of
 ** the SrcList.a[] array.
@@ -18328,36 +18462,7 @@
 struct SrcList {
   int nSrc;        /* Number of tables or subqueries in the FROM clause */
   u32 nAlloc;      /* Number of entries allocated in a[] below */
-  struct SrcList_item {
-    Schema *pSchema;  /* Schema to which this item is fixed */
-    char *zDatabase;  /* Name of database holding this table */
-    char *zName;      /* Name of the table */
-    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
-    Table *pTab;      /* An SQL table corresponding to zName */
-    Select *pSelect;  /* A SELECT statement used in place of a table name */
-    int addrFillSub;  /* Address of subroutine to manifest a subquery */
-    int regReturn;    /* Register holding return address of addrFillSub */
-    int regResult;    /* Registers holding results of a co-routine */
-    struct {
-      u8 jointype;      /* Type of join between this table and the previous */
-      unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
-      unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
-      unsigned isTabFunc :1;     /* True if table-valued-function syntax */
-      unsigned isCorrelated :1;  /* True if sub-query is correlated */
-      unsigned viaCoroutine :1;  /* Implemented as a co-routine */
-      unsigned isRecursive :1;   /* True for recursive reference in WITH */
-      unsigned fromDDL :1;       /* Comes from sqlite_schema */
-    } fg;
-    int iCursor;      /* The VDBE cursor number used to access this table */
-    Expr *pOn;        /* The ON clause of a join */
-    IdList *pUsing;   /* The USING clause of a join */
-    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
-    union {
-      char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
-      ExprList *pFuncArg;  /* Arguments to table-valued-function */
-    } u1;
-    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
-  } a[1];             /* One entry for each identifier on the list */
+  SrcItem a[1];    /* One entry for each identifier on the list */
 };
 
 /*
@@ -18433,6 +18538,7 @@
     ExprList *pEList;    /* Optional list of result-set columns */
     AggInfo *pAggInfo;   /* Information about aggregates at this level */
     Upsert *pUpsert;     /* ON CONFLICT clause information from an upsert */
+    int iBaseReg;        /* For TK_REGISTER when parsing RETURNING */
   } uNC;
   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   int nRef;            /* Number of names resolved by this context */
@@ -18461,6 +18567,7 @@
 #define NC_UEList    0x00080  /* True if uNC.pEList is used */
 #define NC_UAggInfo  0x00100  /* True if uNC.pAggInfo is used */
 #define NC_UUpsert   0x00200  /* True if uNC.pUpsert is used */
+#define NC_UBaseReg  0x00400  /* True if uNC.iBaseReg is used */
 #define NC_MinMaxAgg 0x01000  /* min/max aggregates seen.  See note above */
 #define NC_Complex   0x02000  /* True if a function or subquery seen */
 #define NC_AllowWin  0x04000  /* Window functions are allowed here */
@@ -18484,15 +18591,21 @@
 ** WHERE clause is omitted.
 */
 struct Upsert {
-  ExprList *pUpsertTarget;  /* Optional description of conflicting index */
+  ExprList *pUpsertTarget;  /* Optional description of conflict target */
   Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
   ExprList *pUpsertSet;     /* The SET clause from an ON CONFLICT UPDATE */
   Expr *pUpsertWhere;       /* WHERE clause for the ON CONFLICT UPDATE */
-  /* The fields above comprise the parse tree for the upsert clause.
-  ** The fields below are used to transfer information from the INSERT
-  ** processing down into the UPDATE processing while generating code.
-  ** Upsert owns the memory allocated above, but not the memory below. */
-  Index *pUpsertIdx;        /* Constraint that pUpsertTarget identifies */
+  Upsert *pNextUpsert;      /* Next ON CONFLICT clause in the list */
+  u8 isDoUpdate;            /* True for DO UPDATE.  False for DO NOTHING */
+  /* Above this point is the parse tree for the ON CONFLICT clauses.
+  ** The next group of fields stores intermediate data. */
+  void *pToFree;            /* Free memory when deleting the Upsert object */
+  /* All fields above are owned by the Upsert object and must be freed
+  ** when the Upsert is destroyed.  The fields below are used to transfer
+  ** information from the INSERT processing down into the UPDATE processing
+  ** while generating code.  The fields below are owned by the INSERT
+  ** statement and will be freed by INSERT processing. */
+  Index *pUpsertIdx;        /* UNIQUE constraint specified by pUpsertTarget */
   SrcList *pUpsertSrc;      /* Table to be updated */
   int regData;              /* First register holding array of VALUES */
   int iDataCur;             /* Index of the data cursor */
@@ -18572,6 +18685,8 @@
 #define SF_View          0x0200000 /* SELECT statement is a view */
 #define SF_NoopOrderBy   0x0400000 /* ORDER BY is ignored for this query */
 #define SF_UpdateFrom    0x0800000 /* Statement is an UPDATE...FROM */
+#define SF_PushDown      0x1000000 /* SELECT has be modified by push-down opt */
+#define SF_MultiPart     0x2000000 /* Has multiple incompatible PARTITIONs */
 
 /*
 ** The results of a SELECT can be distributed in several ways, as defined
@@ -18743,6 +18858,17 @@
 #endif
 
 /*
+** An instance of the ParseCleanup object specifies an operation that
+** should be performed after parsing to deallocation resources obtained
+** during the parse and which are no longer needed.
+*/
+struct ParseCleanup {
+  ParseCleanup *pNext;               /* Next cleanup task */
+  void *pPtr;                        /* Pointer to object to deallocate */
+  void (*xCleanup)(sqlite3*,void*);  /* Deallocation routine */
+};
+
+/*
 ** An SQL parser context.  A copy of this structure is passed through
 ** the parser and down into all the parser action routine in order to
 ** carry around information that is global to the entire parse.
@@ -18773,6 +18899,9 @@
   u8 okConstFactor;    /* OK to factor out constants */
   u8 disableLookaside; /* Number of times lookaside has been disabled */
   u8 disableVtab;      /* Disable all virtual tables for this parse */
+#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 */
@@ -18800,12 +18929,15 @@
   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   Table *pTriggerTab;  /* Table triggers are being coded for */
   Parse *pParentParse; /* Parent parser if this parser is nested */
-  AggInfo *pAggList;   /* List of all AggInfo objects */
-  int addrCrTab;       /* Address of OP_CreateBtree opcode on CREATE TABLE */
+  union {
+    int addrCrTab;         /* Address of OP_CreateBtree on CREATE TABLE */
+    Returning *pReturning; /* The RETURNING clause */
+  } u1;
   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
   u32 oldmask;         /* Mask of old.* columns referenced */
   u32 newmask;         /* Mask of new.* columns referenced */
   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
+  u8 bReturning;       /* Coding a RETURNING trigger */
   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
   u8 disableTriggers;  /* True to disable triggers */
 
@@ -18851,10 +18983,9 @@
   Token sArg;               /* Complete text of a module argument */
   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
 #endif
-  Table *pZombieTab;        /* List of Table objects to delete after code gen */
   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
   With *pWith;              /* Current WITH clause, or NULL */
-  With *pWithToFree;        /* Free this WITH object at the end of the parse */
+  ParseCleanup *pCleanup;   /* List of cleanup operations to run after parse */
 #ifndef SQLITE_OMIT_ALTERTABLE
   RenameToken *pRename;     /* Tokens subject to renaming by ALTER TABLE */
 #endif
@@ -18934,6 +19065,7 @@
 #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
 #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
 #define OPFLAG_NOCHNG_MAGIC  0x6d    /* OP_MakeRecord: serialtype 10 is ok */
+#define OPFLAG_PREFORMAT     0x80    /* OP_Insert uses preformatted cell */
 
 /*
  * Each trigger present in the database schema is stored as an instance of
@@ -18955,6 +19087,7 @@
   char *table;            /* The table or view to which the trigger applies */
   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
+  u8 bReturning;          /* This trigger implements a RETURNING clause */
   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
                              the <column-list> is stored here */
@@ -19013,14 +19146,15 @@
  *
  */
 struct TriggerStep {
-  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
+  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT,
+                       ** or TK_RETURNING */
   u8 orconf;           /* OE_Rollback etc. */
   Trigger *pTrig;      /* The trigger that this step is a part of */
   Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
   char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
   SrcList *pFrom;      /* FROM clause for UPDATE statement (if any) */
   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
-  ExprList *pExprList; /* SET clause for UPDATE */
+  ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */
   IdList *pIdList;     /* Column names for INSERT */
   Upsert *pUpsert;     /* Upsert clauses on an INSERT */
   char *zSpan;         /* Original SQL text of this command */
@@ -19029,18 +19163,16 @@
 };
 
 /*
-** The following structure contains information used by the sqliteFix...
-** routines as they walk the parse tree to make database references
-** explicit.
-*/
-typedef struct DbFixer DbFixer;
-struct DbFixer {
-  Parse *pParse;      /* The parsing context.  Error messages written here */
-  Schema *pSchema;    /* Fix items to this schema */
-  u8 bTemp;           /* True for TEMP schema entries */
-  const char *zDb;    /* Make sure all objects are contained in this database */
-  const char *zType;  /* Type of the container - used for error messages */
-  const Token *pName; /* Name of the container - used for error messages */
+** Information about a RETURNING clause
+*/
+struct Returning {
+  Parse *pParse;        /* The parse that includes the RETURNING clause */
+  ExprList *pReturnEL;  /* List of expressions to return */
+  Trigger retTrig;      /* The transient trigger that implements RETURNING */
+  TriggerStep retTStep; /* The trigger step */
+  int iRetCur;          /* Transient table holding RETURNING results */
+  int nRetCol;          /* Number of in pReturnEL after expansion */
+  int iRetReg;          /* Register array for holding a row of RETURNING */
 };
 
 /*
@@ -19080,7 +19212,8 @@
 /*
 ** Allowed values for mInitFlags
 */
-#define INITFLAG_AlterTable   0x0001  /* This is a reparse after ALTER TABLE */
+#define INITFLAG_AlterRename   0x0001  /* Reparse after a RENAME */
+#define INITFLAG_AlterDrop     0x0002  /* Reparse after a DROP COLUMN */
 
 /*
 ** Structure containing global configuration data for the SQLite library.
@@ -19192,10 +19325,26 @@
     struct WhereConst *pConst;                /* WHERE clause constants */
     struct RenameCtx *pRename;                /* RENAME COLUMN context */
     struct Table *pTab;                       /* Table of generated column */
-    struct SrcList_item *pSrcItem;            /* A single FROM clause item */
+    SrcItem *pSrcItem;                        /* A single FROM clause item */
+    DbFixer *pFix;
   } u;
 };
 
+/*
+** The following structure contains information used by the sqliteFix...
+** routines as they walk the parse tree to make database references
+** explicit.
+*/
+struct DbFixer {
+  Parse *pParse;      /* The parsing context.  Error messages written here */
+  Walker w;           /* Walker object */
+  Schema *pSchema;    /* Fix items to this schema */
+  u8 bTemp;           /* True for TEMP schema entries */
+  const char *zDb;    /* Make sure all objects are contained in this database */
+  const char *zType;  /* Type of the container - used for error messages */
+  const Token *pName; /* Name of the container - used for error messages */
+};
+
 /* Forward declarations */
 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
@@ -19221,19 +19370,54 @@
 #define WRC_Abort       2   /* Abandon the tree walk */
 
 /*
-** An instance of this structure represents a set of one or more CTEs
-** (common table expressions) created by a single WITH clause.
+** A single common table expression
+*/
+struct Cte {
+  char *zName;            /* Name of this CTE */
+  ExprList *pCols;        /* List of explicit column names, or NULL */
+  Select *pSelect;        /* The definition of this CTE */
+  const char *zCteErr;    /* Error message for circular references */
+  CteUse *pUse;           /* Usage information for this CTE */
+  u8 eM10d;               /* The MATERIALIZED flag */
+};
+
+/*
+** Allowed values for the materialized flag (eM10d):
+*/
+#define M10d_Yes       0  /* AS MATERIALIZED */
+#define M10d_Any       1  /* Not specified.  Query planner's choice */
+#define M10d_No        2  /* AS NOT MATERIALIZED */
+
+/*
+** An instance of the With object represents a WITH clause containing
+** one or more CTEs (common table expressions).
 */
 struct With {
-  int nCte;                       /* Number of CTEs in the WITH clause */
-  With *pOuter;                   /* Containing WITH clause, or NULL */
-  struct Cte {                    /* For each CTE in the WITH clause.... */
-    char *zName;                    /* Name of this CTE */
-    ExprList *pCols;                /* List of explicit column names, or NULL */
-    Select *pSelect;                /* The definition of this CTE */
-    const char *zCteErr;            /* Error message for circular references */
-  } a[1];
-};
+  int nCte;               /* Number of CTEs in the WITH clause */
+  With *pOuter;           /* Containing WITH clause, or NULL */
+  Cte a[1];               /* For each CTE in the WITH clause.... */
+};
+
+/*
+** The Cte object is not guaranteed to persist for the entire duration
+** of code generation.  (The query flattener or other parser tree
+** edits might delete it.)  The following object records information
+** about each Common Table Expression that must be preserved for the
+** duration of the parse.
+**
+** The CteUse objects are freed using sqlite3ParserAddCleanup() rather
+** than sqlite3SelectDelete(), which is what enables them to persist
+** until the end of code generation.
+*/
+struct CteUse {
+  int nUse;              /* Number of users of this CTE */
+  int addrM9e;           /* Start of subroutine to compute materialization */
+  int regRtn;            /* Return address register for addrM9e subroutine */
+  int iCur;              /* Ephemeral table holding the materialization */
+  LogEst nRowEst;        /* Estimated number of rows in the table */
+  u8 eM10d;              /* The MATERIALIZED flag */
+};
+
 
 #ifdef SQLITE_DEBUG
 /*
@@ -19312,7 +19496,6 @@
 SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);
 SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
 SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
-SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
 SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
 SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
 SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
@@ -19581,6 +19764,7 @@
 SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*);
 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
+SQLITE_PRIVATE void sqlite3ExprDeferredDelete(Parse*, Expr*);
 SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
 SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
@@ -19629,6 +19813,7 @@
 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
 SQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);
 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
+SQLITE_PRIVATE void sqlite3AddReturning(Parse*,ExprList*);
 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
                     sqlite3_vfs**,char**,char **);
 #define sqlite3CodecQueryParameters(A,B,C) 0
@@ -19694,7 +19879,7 @@
                                       Token*, Select*, Expr*, IdList*);
 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
-SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
+SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, SrcItem *);
 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
@@ -19722,6 +19907,7 @@
 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
 SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
+SQLITE_PRIVATE void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*);
 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
@@ -19755,7 +19941,7 @@
 #define LOCATE_VIEW    0x01
 #define LOCATE_NOERR   0x02
 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
-SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
+SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *);
 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
@@ -19883,6 +20069,7 @@
 #endif
 
 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
+SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol);
 SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int);
 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
@@ -19905,7 +20092,6 @@
 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
-SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
 SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
 SQLITE_PRIVATE void sqlite3Int64ToText(i64,char*);
@@ -19968,6 +20154,7 @@
 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
+SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3*);
 SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
@@ -20031,7 +20218,6 @@
 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
-SQLITE_API extern u32 sqlite3_unsupported_selecttrace;
 #ifndef SQLITE_OMIT_WSD
 SQLITE_PRIVATE int sqlite3PendingByte;
 #endif
@@ -20050,6 +20236,7 @@
 SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
+SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*);
 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
 SQLITE_PRIVATE int sqlite3MatchEName(
   const struct ExprList_item*,
@@ -20067,6 +20254,7 @@
 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
+SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse*, SrcList*, Token*);
 SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
 SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
 SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
@@ -20090,6 +20278,7 @@
 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
+SQLITE_PRIVATE const char *sqlite3SelectOpName(int);
 SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*);
 
 #ifdef SQLITE_DEBUG
@@ -20220,6 +20409,7 @@
 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
+SQLITE_PRIVATE void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
 #ifdef SQLITE_ENABLE_NORMALIZE
 SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
 #endif
@@ -20234,23 +20424,32 @@
 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
 #endif
 #ifndef SQLITE_OMIT_CTE
-SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
+SQLITE_PRIVATE   Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);
+SQLITE_PRIVATE   void sqlite3CteDelete(sqlite3*,Cte*);
+SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Cte*);
 SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
 SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
 #else
-#define sqlite3WithPush(x,y,z)
-#define sqlite3WithDelete(x,y)
+# define sqlite3CteNew(P,T,E,S)   ((void*)0)
+# define sqlite3CteDelete(D,C)
+# define sqlite3CteWithAdd(P,W,C) ((void*)0)
+# define sqlite3WithDelete(x,y)
+# define sqlite3WithPush(x,y,z)
 #endif
 #ifndef SQLITE_OMIT_UPSERT
-SQLITE_PRIVATE   Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
+SQLITE_PRIVATE   Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);
 SQLITE_PRIVATE   void sqlite3UpsertDelete(sqlite3*,Upsert*);
 SQLITE_PRIVATE   Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
 SQLITE_PRIVATE   int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
 SQLITE_PRIVATE   void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
-#else
-#define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
+SQLITE_PRIVATE   Upsert *sqlite3UpsertOfIndex(Upsert*,Index*);
+SQLITE_PRIVATE   int sqlite3UpsertNextIsIPK(Upsert*);
+#else
+#define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0)
 #define sqlite3UpsertDelete(x,y)
-#define sqlite3UpsertDup(x,y)       ((Upsert*)0)
+#define sqlite3UpsertDup(x,y)         ((Upsert*)0)
+#define sqlite3UpsertOfIndex(x,y)     ((Upsert*)0)
+#define sqlite3UpsertNextIsIPK(x)     0
 #endif
 
 
@@ -20746,9 +20945,10 @@
 #endif
 
 /*
-** Flags for select tracing and the ".selecttrace" macro of the CLI
-*/
-SQLITE_API u32 sqlite3_unsupported_selecttrace = 0;
+** Tracing flags set by SQLITE_TESTCTRL_TRACEFLAGS.
+*/
+SQLITE_PRIVATE u32 sqlite3SelectTrace = 0;
+SQLITE_PRIVATE u32 sqlite3WhereTrace = 0;
 
 /* #include "opcodes.h" */
 /*
@@ -20872,6 +21072,7 @@
   Bool isEphemeral:1;     /* True for an ephemeral table */
   Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
   Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
+  Bool hasBeenDuped:1;    /* This cursor was source or target of OP_OpenDup */
   u16 seekHit;            /* See the OP_SeekHit and OP_IfNoHope opcodes */
   Btree *pBtx;            /* Separate file holding temporary table */
   i64 seqCount;           /* Sequence counter */
@@ -21167,7 +21368,7 @@
   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
   Parse *pParse;          /* Parsing context used to create this Vdbe */
   ynVar nVar;             /* Number of entries in aVar[] */
-  u32 magic;              /* Magic number for sanity checking */
+  u32 iVdbeMagic;         /* Magic number defining state of the SQL statement */
   int nMem;               /* Number of memory locations currently allocated */
   int nCursor;            /* Number of slots in apCsr[] */
   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
@@ -22672,6 +22873,7 @@
   int eType;
   memset(p, 0, sizeof(*p));
   if( argc==0 ){
+    if( !sqlite3NotPureFunc(context) ) return 1;
     return setDateTimeToCurrent(context, p);
   }
   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
@@ -23172,6 +23374,8 @@
 #ifdef SQLITE_TEST
   if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
    && op!=SQLITE_FCNTL_LOCK_TIMEOUT
+   && op!=SQLITE_FCNTL_CKPT_DONE
+   && op!=SQLITE_FCNTL_CKPT_START
   ){
     /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
     ** is using a regular VFS, it is called after the corresponding
@@ -23182,7 +23386,12 @@
     ** The core must call OsFileControl() though, not OsFileControlHint(),
     ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
     ** means the commit really has failed and an error should be returned
-    ** to the user.  */
+    ** to the user.
+    **
+    ** The CKPT_DONE and CKPT_START file-controls are write-only signals
+    ** to the cksumvfs.  Their return code is meaningless and is ignored
+    ** by the SQLite core, so there is no point in simulating OOMs for them.
+    */
     DO_OS_MALLOC_TEST(id);
   }
 #endif
@@ -29081,7 +29290,7 @@
       case etSRCLIST: {
         SrcList *pSrc;
         int k;
-        struct SrcList_item *pItem;
+        SrcItem *pItem;
         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
         pSrc = va_arg(ap, SrcList*);
         k = va_arg(ap, int);
@@ -29146,7 +29355,7 @@
   }else{
     char *zOld = isMalloced(p) ? p->zText : 0;
     i64 szNew = p->nChar;
-    szNew += N + 1;
+    szNew += (sqlite3_int64)N + 1;
     if( szNew+p->nChar<=p->mxAlloc ){
       /* Force exponential buffer size growth as long as it does not overflow,
       ** to avoid having to call this routine too often */
@@ -29649,7 +29858,10 @@
         }
         sqlite3_str_appendf(&x, ")");
       }
-      sqlite3_str_appendf(&x, " AS");
+      if( pCte->pUse ){
+        sqlite3_str_appendf(&x, " (pUse=0x%p, nUse=%d)", pCte->pUse,
+                 pCte->pUse->nUse);
+      }
       sqlite3StrAccumFinish(&x);
       sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
       sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
@@ -29665,7 +29877,7 @@
 SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
   int i;
   for(i=0; i<pSrc->nSrc; i++){
-    const struct SrcList_item *pItem = &pSrc->a[i];
+    const SrcItem *pItem = &pSrc->a[i];
     StrAccum x;
     char zLine[100];
     sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
@@ -29688,6 +29900,9 @@
     if( pItem->fg.fromDDL ){
       sqlite3_str_appendf(&x, " DDL");
     }
+    if( pItem->fg.isCte ){
+      sqlite3_str_appendf(&x, " CteUse=0x%p", pItem->u2.pCteUse);
+    }
     sqlite3StrAccumFinish(&x);
     sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
     if( pItem->pSelect ){
@@ -31385,6 +31600,16 @@
 }
 
 /*
+** The equivalent of sqlite3Error(db, SQLITE_OK).  Clear the error state
+** and error message.
+*/
+SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3 *db){
+  assert( db!=0 );
+  db->errCode = SQLITE_OK;
+  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
+}
+
+/*
 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
 ** to do based on the SQLite error code in rc.
 */
@@ -33330,103 +33555,105 @@
     /*  77 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
     /*  78 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
     /*  79 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
-    /*  80 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
-    /*  81 */ "CollSeq"          OpHelp(""),
-    /*  82 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
-    /*  83 */ "RealAffinity"     OpHelp(""),
-    /*  84 */ "Cast"             OpHelp("affinity(r[P1])"),
-    /*  85 */ "Permutation"      OpHelp(""),
-    /*  86 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
-    /*  87 */ "IsTrue"           OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
-    /*  88 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
-    /*  89 */ "Column"           OpHelp("r[P3]=PX"),
-    /*  90 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
-    /*  91 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
-    /*  92 */ "Count"            OpHelp("r[P2]=count()"),
-    /*  93 */ "ReadCookie"       OpHelp(""),
-    /*  94 */ "SetCookie"        OpHelp(""),
-    /*  95 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
-    /*  96 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
-    /*  97 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
-    /*  98 */ "OpenDup"          OpHelp(""),
-    /*  99 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
-    /* 100 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
-    /* 101 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
-    /* 102 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
-    /* 103 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
-    /* 104 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
-    /* 105 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
-    /* 106 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
-    /* 107 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
-    /* 108 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
-    /* 109 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
-    /* 110 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
-    /* 111 */ "SorterOpen"       OpHelp(""),
-    /* 112 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
-    /* 113 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
-    /* 114 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
-    /* 115 */ "String8"          OpHelp("r[P2]='P4'"),
-    /* 116 */ "Close"            OpHelp(""),
-    /* 117 */ "ColumnsUsed"      OpHelp(""),
-    /* 118 */ "SeekScan"         OpHelp("Scan-ahead up to P1 rows"),
-    /* 119 */ "SeekHit"          OpHelp("set P2<=seekHit<=P3"),
-    /* 120 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
-    /* 121 */ "NewRowid"         OpHelp("r[P2]=rowid"),
-    /* 122 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
-    /* 123 */ "Delete"           OpHelp(""),
-    /* 124 */ "ResetCount"       OpHelp(""),
-    /* 125 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
-    /* 126 */ "SorterData"       OpHelp("r[P2]=data"),
-    /* 127 */ "RowData"          OpHelp("r[P2]=data"),
-    /* 128 */ "Rowid"            OpHelp("r[P2]=rowid"),
-    /* 129 */ "NullRow"          OpHelp(""),
-    /* 130 */ "SeekEnd"          OpHelp(""),
-    /* 131 */ "IdxInsert"        OpHelp("key=r[P2]"),
-    /* 132 */ "SorterInsert"     OpHelp("key=r[P2]"),
-    /* 133 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
-    /* 134 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
-    /* 135 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
-    /* 136 */ "FinishSeek"       OpHelp(""),
-    /* 137 */ "Destroy"          OpHelp(""),
-    /* 138 */ "Clear"            OpHelp(""),
-    /* 139 */ "ResetSorter"      OpHelp(""),
-    /* 140 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
-    /* 141 */ "SqlExec"          OpHelp(""),
-    /* 142 */ "ParseSchema"      OpHelp(""),
-    /* 143 */ "LoadAnalysis"     OpHelp(""),
-    /* 144 */ "DropTable"        OpHelp(""),
-    /* 145 */ "DropIndex"        OpHelp(""),
-    /* 146 */ "DropTrigger"      OpHelp(""),
-    /* 147 */ "IntegrityCk"      OpHelp(""),
-    /* 148 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
-    /* 149 */ "Param"            OpHelp(""),
-    /* 150 */ "Real"             OpHelp("r[P2]=P4"),
-    /* 151 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
-    /* 152 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
-    /* 153 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
-    /* 154 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
-    /* 155 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
-    /* 156 */ "AggStep1"         OpHelp("accum=r[P3] step(r[P2@P5])"),
-    /* 157 */ "AggValue"         OpHelp("r[P3]=value N=P2"),
-    /* 158 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
-    /* 159 */ "Expire"           OpHelp(""),
-    /* 160 */ "CursorLock"       OpHelp(""),
-    /* 161 */ "CursorUnlock"     OpHelp(""),
-    /* 162 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
-    /* 163 */ "VBegin"           OpHelp(""),
-    /* 164 */ "VCreate"          OpHelp(""),
-    /* 165 */ "VDestroy"         OpHelp(""),
-    /* 166 */ "VOpen"            OpHelp(""),
-    /* 167 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
-    /* 168 */ "VRename"          OpHelp(""),
-    /* 169 */ "Pagecount"        OpHelp(""),
-    /* 170 */ "MaxPgcnt"         OpHelp(""),
-    /* 171 */ "Trace"            OpHelp(""),
-    /* 172 */ "CursorHint"       OpHelp(""),
-    /* 173 */ "ReleaseReg"       OpHelp("release r[P1@P2] mask P3"),
-    /* 174 */ "Noop"             OpHelp(""),
-    /* 175 */ "Explain"          OpHelp(""),
-    /* 176 */ "Abortable"        OpHelp(""),
+    /*  80 */ "ChngCntRow"       OpHelp("output=r[P1]"),
+    /*  81 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
+    /*  82 */ "CollSeq"          OpHelp(""),
+    /*  83 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
+    /*  84 */ "RealAffinity"     OpHelp(""),
+    /*  85 */ "Cast"             OpHelp("affinity(r[P1])"),
+    /*  86 */ "Permutation"      OpHelp(""),
+    /*  87 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
+    /*  88 */ "IsTrue"           OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
+    /*  89 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
+    /*  90 */ "Column"           OpHelp("r[P3]=PX"),
+    /*  91 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
+    /*  92 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
+    /*  93 */ "Count"            OpHelp("r[P2]=count()"),
+    /*  94 */ "ReadCookie"       OpHelp(""),
+    /*  95 */ "SetCookie"        OpHelp(""),
+    /*  96 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
+    /*  97 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
+    /*  98 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
+    /*  99 */ "OpenDup"          OpHelp(""),
+    /* 100 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
+    /* 101 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
+    /* 102 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
+    /* 103 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
+    /* 104 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
+    /* 105 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
+    /* 106 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
+    /* 107 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
+    /* 108 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
+    /* 109 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
+    /* 110 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
+    /* 111 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
+    /* 112 */ "SorterOpen"       OpHelp(""),
+    /* 113 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
+    /* 114 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
+    /* 115 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
+    /* 116 */ "String8"          OpHelp("r[P2]='P4'"),
+    /* 117 */ "Close"            OpHelp(""),
+    /* 118 */ "ColumnsUsed"      OpHelp(""),
+    /* 119 */ "SeekScan"         OpHelp("Scan-ahead up to P1 rows"),
+    /* 120 */ "SeekHit"          OpHelp("set P2<=seekHit<=P3"),
+    /* 121 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
+    /* 122 */ "NewRowid"         OpHelp("r[P2]=rowid"),
+    /* 123 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
+    /* 124 */ "RowCell"          OpHelp(""),
+    /* 125 */ "Delete"           OpHelp(""),
+    /* 126 */ "ResetCount"       OpHelp(""),
+    /* 127 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
+    /* 128 */ "SorterData"       OpHelp("r[P2]=data"),
+    /* 129 */ "RowData"          OpHelp("r[P2]=data"),
+    /* 130 */ "Rowid"            OpHelp("r[P2]=rowid"),
+    /* 131 */ "NullRow"          OpHelp(""),
+    /* 132 */ "SeekEnd"          OpHelp(""),
+    /* 133 */ "IdxInsert"        OpHelp("key=r[P2]"),
+    /* 134 */ "SorterInsert"     OpHelp("key=r[P2]"),
+    /* 135 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
+    /* 136 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
+    /* 137 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
+    /* 138 */ "FinishSeek"       OpHelp(""),
+    /* 139 */ "Destroy"          OpHelp(""),
+    /* 140 */ "Clear"            OpHelp(""),
+    /* 141 */ "ResetSorter"      OpHelp(""),
+    /* 142 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
+    /* 143 */ "SqlExec"          OpHelp(""),
+    /* 144 */ "ParseSchema"      OpHelp(""),
+    /* 145 */ "LoadAnalysis"     OpHelp(""),
+    /* 146 */ "DropTable"        OpHelp(""),
+    /* 147 */ "DropIndex"        OpHelp(""),
+    /* 148 */ "DropTrigger"      OpHelp(""),
+    /* 149 */ "IntegrityCk"      OpHelp(""),
+    /* 150 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
+    /* 151 */ "Param"            OpHelp(""),
+    /* 152 */ "Real"             OpHelp("r[P2]=P4"),
+    /* 153 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
+    /* 154 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
+    /* 155 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
+    /* 156 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
+    /* 157 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
+    /* 158 */ "AggStep1"         OpHelp("accum=r[P3] step(r[P2@P5])"),
+    /* 159 */ "AggValue"         OpHelp("r[P3]=value N=P2"),
+    /* 160 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
+    /* 161 */ "Expire"           OpHelp(""),
+    /* 162 */ "CursorLock"       OpHelp(""),
+    /* 163 */ "CursorUnlock"     OpHelp(""),
+    /* 164 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
+    /* 165 */ "VBegin"           OpHelp(""),
+    /* 166 */ "VCreate"          OpHelp(""),
+    /* 167 */ "VDestroy"         OpHelp(""),
+    /* 168 */ "VOpen"            OpHelp(""),
+    /* 169 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
+    /* 170 */ "VRename"          OpHelp(""),
+    /* 171 */ "Pagecount"        OpHelp(""),
+    /* 172 */ "MaxPgcnt"         OpHelp(""),
+    /* 173 */ "Trace"            OpHelp(""),
+    /* 174 */ "CursorHint"       OpHelp(""),
+    /* 175 */ "ReleaseReg"       OpHelp("release r[P1@P2] mask P3"),
+    /* 176 */ "Noop"             OpHelp(""),
+    /* 177 */ "Explain"          OpHelp(""),
+    /* 178 */ "Abortable"        OpHelp(""),
   };
   return azName[i];
 }
@@ -39995,7 +40222,8 @@
   int j = *pJ;
   int i;
   if( j<=0 ) return 0;
-  for(i=j-1; ALWAYS(i>0) && z[i-1]!='/'; i--){}
+  for(i=j-1; i>0 && z[i-1]!='/'; i--){}
+  if( i==0 ) return 0;
   if( z[i]=='.' && i==j-2 && z[i+1]=='.' ) return 0;
   *pJ = i-1;
   return 1;
@@ -50435,6 +50663,7 @@
     p->page.pExtra = &p[1];
     p->isBulkLocal = 0;
     p->isAnchor = 0;
+    p->pLruPrev = 0;           /* Initializing this saves a valgrind error */
   }
   (*pCache->pnPurgeable)++;
   return p;
@@ -52353,6 +52582,7 @@
   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   Pgno nOrig;                  /* Original number of pages in file */
   Pgno iSubRec;                /* Index of first record in sub-journal */
+  int bTruncateOnRelease;      /* If stmt journal may be truncated on RELEASE */
 #ifndef SQLITE_OMIT_WAL
   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
 #endif
@@ -52988,6 +53218,9 @@
   for(i=0; i<pPager->nSavepoint; i++){
     p = &pPager->aSavepoint[i];
     if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
+      for(i=i+1; i<pPager->nSavepoint; i++){
+        pPager->aSavepoint[i].bTruncateOnRelease = 0;
+      }
       return 1;
     }
   }
@@ -58766,6 +58999,7 @@
     }
     aNew[ii].iSubRec = pPager->nSubRec;
     aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
+    aNew[ii].bTruncateOnRelease = 1;
     if( !aNew[ii].pInSavepoint ){
       return SQLITE_NOMEM_BKPT;
     }
@@ -58847,13 +59081,15 @@
     /* If this is a release of the outermost savepoint, truncate
     ** the sub-journal to zero bytes in size. */
     if( op==SAVEPOINT_RELEASE ){
-      if( nNew==0 && isOpen(pPager->sjfd) ){
+      PagerSavepoint *pRel = &pPager->aSavepoint[nNew];
+      if( pRel->bTruncateOnRelease && isOpen(pPager->sjfd) ){
         /* Only truncate if it is an in-memory sub-journal. */
         if( sqlite3JournalIsInMemory(pPager->sjfd) ){
-          rc = sqlite3OsTruncate(pPager->sjfd, 0);
+          i64 sz = (pPager->pageSize+4)*pRel->iSubRec;
+          rc = sqlite3OsTruncate(pPager->sjfd, sz);
           assert( rc==SQLITE_OK );
         }
-        pPager->nSubRec = 0;
+        pPager->nSubRec = pRel->iSubRec;
       }
     }
     /* Else this is a rollback operation, playback the specified savepoint.
@@ -64044,7 +64280,7 @@
   u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   int nBackup;       /* Number of backup operations reading this btree */
-  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
+  u32 iBDataVersion; /* Combines with pBt->pPager->iDataVersion */
   Btree *pNext;      /* List of other sharable Btrees from the same db */
   Btree *pPrev;      /* Back pointer of the same list */
 #ifdef SQLITE_DEBUG
@@ -64149,6 +64385,7 @@
   Btree *pWriter;       /* Btree with currently open write transaction */
 #endif
   u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
+  int nPreformatSize;   /* Size of last cell written by TransferRow() */
 };
 
 /*
@@ -65863,6 +66100,24 @@
 }
 
 /*
+** Given a record with nPayload bytes of payload stored within btree
+** page pPage, return the number of bytes of payload stored locally.
+*/
+static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
+  int maxLocal;  /* Maximum amount of payload held locally */
+  maxLocal = pPage->maxLocal;
+  if( nPayload<=maxLocal ){
+    return nPayload;
+  }else{
+    int minLocal;  /* Minimum amount of payload held locally */
+    int surplus;   /* Overflow payload available for local storage */
+    minLocal = pPage->minLocal;
+    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
+    return ( surplus <= maxLocal ) ? surplus : minLocal;
+  }
+}
+
+/*
 ** The following routines are implementations of the MemPage.xParseCell()
 ** method.
 **
@@ -67438,19 +67693,23 @@
 */
 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   BtShared *pBt = p->pBt;
-  BtCursor *pCur;
 
   /* Close all cursors opened via this handle.  */
   assert( sqlite3_mutex_held(p->db->mutex) );
   sqlite3BtreeEnter(p);
-  pCur = pBt->pCursor;
-  while( pCur ){
-    BtCursor *pTmp = pCur;
-    pCur = pCur->pNext;
-    if( pTmp->pBtree==p ){
-      sqlite3BtreeCloseCursor(pTmp);
-    }
-  }
+
+  /* Verify that no other cursors have this Btree open */
+#ifdef SQLITE_DEBUG
+  {
+    BtCursor *pCur = pBt->pCursor;
+    while( pCur ){
+      BtCursor *pTmp = pCur;
+      pCur = pCur->pNext;
+      assert( pTmp->pBtree!=p );
+
+    }
+  }
+#endif
 
   /* Rollback any active transaction and free the handle structure.
   ** The call to sqlite3BtreeRollback() drops any table-locks held by
@@ -67602,6 +67861,7 @@
         ((pageSize-1)&pageSize)==0 ){
     assert( (pageSize & 7)==0 );
     assert( !pBt->pCursor );
+    if( nReserve>32 && pageSize==512 ) pageSize = 1024;
     pBt->pageSize = (u32)pageSize;
     freeTempSpace(pBt);
   }
@@ -68831,7 +69091,7 @@
       sqlite3BtreeLeave(p);
       return rc;
     }
-    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
+    p->iBDataVersion--;  /* Compensate for pPager->iDataVersion++; */
     pBt->inTransaction = TRANS_READ;
     btreeClearHasContent(pBt);
   }
@@ -69241,7 +69501,14 @@
     unlockBtreeIfUnused(pBt);
     sqlite3_free(pCur->aOverflow);
     sqlite3_free(pCur->pKey);
-    sqlite3BtreeLeave(pBtree);
+    if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
+      /* Since the BtShared is not sharable, there is no need to
+      ** worry about the missing sqlite3BtreeLeave() call here.  */
+      assert( pBtree->sharable==0 );
+      sqlite3BtreeClose(pBtree);
+    }else{
+      sqlite3BtreeLeave(pBtree);
+    }
     pCur->pBtree = 0;
   }
   return SQLITE_OK;
@@ -72337,7 +72604,9 @@
   }
   pgno = get4byte(pRight);
   while( 1 ){
-    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
+    if( rc==SQLITE_OK ){
+      rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
+    }
     if( rc ){
       memset(apOld, 0, (i+1)*sizeof(MemPage*));
       goto balance_cleanup;
@@ -72376,12 +72645,10 @@
       if( pBt->btsFlags & BTS_FAST_SECURE ){
         int iOff;
 
+        /* If the following if() condition is not true, the db is corrupted.
+        ** The call to dropCell() below will detect this.  */
         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
-        if( (iOff+szNew[i])>(int)pBt->usableSize ){
-          rc = SQLITE_CORRUPT_BKPT;
-          memset(apOld, 0, (i+1)*sizeof(MemPage*));
-          goto balance_cleanup;
-        }else{
+        if( (iOff+szNew[i])<=(int)pBt->usableSize ){
           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
         }
@@ -72675,6 +72942,9 @@
       apOld[i] = 0;
       rc = sqlite3PagerWrite(pNew->pDbPage);
       nNew++;
+      if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv)) ){
+        rc = SQLITE_CORRUPT_BKPT;
+      }
       if( rc ) goto balance_cleanup;
     }else{
       assert( i>0 );
@@ -72711,7 +72981,7 @@
     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
     aPgFlags[i] = apNew[i]->pDbPage->flags;
     for(j=0; j<i; j++){
-      if( aPgno[j]==aPgno[i] ){
+      if( NEVER(aPgno[j]==aPgno[i]) ){
         /* This branch is taken if the set of sibling pages somehow contains
         ** duplicate entries. This can happen if the database is corrupt.
         ** It would be simpler to detect this as part of the loop below, but
@@ -73379,7 +73649,8 @@
   unsigned char *oldCell;
   unsigned char *newCell = 0;
 
-  assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
+  assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
+  assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
 
   if( pCur->eState==CURSOR_FAULT ){
     assert( pCur->skipNext!=SQLITE_OK );
@@ -73397,7 +73668,7 @@
   ** keys with no associated data. If the cursor was opened expecting an
   ** intkey table, the caller should be inserting integer keys with a
   ** blob of associated data.  */
-  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
+  assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
 
   /* Save the positions of any other cursors open on this table.
   **
@@ -73507,7 +73778,7 @@
        || CORRUPT_DB );
 
   pPage = pCur->pPage;
-  assert( pPage->intKey || pX->nKey>=0 );
+  assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
   assert( pPage->leaf || !pPage->intKey );
   if( pPage->nFree<0 ){
     if( pCur->eState>CURSOR_INVALID ){
@@ -73524,7 +73795,21 @@
   assert( pPage->isInit );
   newCell = pBt->pTmpSpace;
   assert( newCell!=0 );
-  rc = fillInCell(pPage, newCell, pX, &szNew);
+  if( flags & BTREE_PREFORMAT ){
+    rc = SQLITE_OK;
+    szNew = pBt->nPreformatSize;
+    if( szNew<4 ) szNew = 4;
+    if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
+      CellInfo info;
+      pPage->xParseCell(pPage, newCell, &info);
+      if( info.nPayload!=info.nLocal ){
+        Pgno ovfl = get4byte(&newCell[szNew-4]);
+        ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
+      }
+    }
+  }else{
+    rc = fillInCell(pPage, newCell, pX, &szNew);
+  }
   if( rc ) goto end_insert;
   assert( szNew==pPage->xCellSize(pPage, newCell) );
   assert( szNew <= MX_CELL_SIZE(pBt) );
@@ -73632,6 +73917,114 @@
 }
 
 /*
+** This function is used as part of copying the current row from cursor
+** pSrc into cursor pDest. If the cursors are open on intkey tables, then
+** parameter iKey is used as the rowid value when the record is copied
+** into pDest. Otherwise, the record is copied verbatim.
+**
+** This function does not actually write the new value to cursor pDest.
+** Instead, it creates and populates any required overflow pages and
+** writes the data for the new cell into the BtShared.pTmpSpace buffer
+** for the destination database. The size of the cell, in bytes, is left
+** in BtShared.nPreformatSize. The caller completes the insertion by
+** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
+**
+** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
+*/
+SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
+  int rc = SQLITE_OK;
+  BtShared *pBt = pDest->pBt;
+  u8 *aOut = pBt->pTmpSpace;    /* Pointer to next output buffer */
+  const u8 *aIn;                /* Pointer to next input buffer */
+  u32 nIn;                      /* Size of input buffer aIn[] */
+  u32 nRem;                     /* Bytes of data still to copy */
+
+  getCellInfo(pSrc);
+  aOut += putVarint32(aOut, pSrc->info.nPayload);
+  if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
+  nIn = pSrc->info.nLocal;
+  aIn = pSrc->info.pPayload;
+  if( aIn+nIn>pSrc->pPage->aDataEnd ){
+    return SQLITE_CORRUPT_BKPT;
+  }
+  nRem = pSrc->info.nPayload;
+  if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
+    memcpy(aOut, aIn, nIn);
+    pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
+  }else{
+    Pager *pSrcPager = pSrc->pBt->pPager;
+    u8 *pPgnoOut = 0;
+    Pgno ovflIn = 0;
+    DbPage *pPageIn = 0;
+    MemPage *pPageOut = 0;
+    u32 nOut;                     /* Size of output buffer aOut[] */
+
+    nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
+    pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
+    if( nOut<pSrc->info.nPayload ){
+      pPgnoOut = &aOut[nOut];
+      pBt->nPreformatSize += 4;
+    }
+
+    if( nRem>nIn ){
+      if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
+        return SQLITE_CORRUPT_BKPT;
+      }
+      ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
+    }
+
+    do {
+      nRem -= nOut;
+      do{
+        assert( nOut>0 );
+        if( nIn>0 ){
+          int nCopy = MIN(nOut, nIn);
+          memcpy(aOut, aIn, nCopy);
+          nOut -= nCopy;
+          nIn -= nCopy;
+          aOut += nCopy;
+          aIn += nCopy;
+        }
+        if( nOut>0 ){
+          sqlite3PagerUnref(pPageIn);
+          pPageIn = 0;
+          rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
+          if( rc==SQLITE_OK ){
+            aIn = (const u8*)sqlite3PagerGetData(pPageIn);
+            ovflIn = get4byte(aIn);
+            aIn += 4;
+            nIn = pSrc->pBt->usableSize - 4;
+          }
+        }
+      }while( rc==SQLITE_OK && nOut>0 );
+
+      if( rc==SQLITE_OK && nRem>0 ){
+        Pgno pgnoNew;
+        MemPage *pNew = 0;
+        rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
+        put4byte(pPgnoOut, pgnoNew);
+        if( ISAUTOVACUUM && pPageOut ){
+          ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
+        }
+        releasePage(pPageOut);
+        pPageOut = pNew;
+        if( pPageOut ){
+          pPgnoOut = pPageOut->aData;
+          put4byte(pPgnoOut, 0);
+          aOut = &pPgnoOut[4];
+          nOut = MIN(pBt->usableSize - 4, nRem);
+        }
+      }
+    }while( nRem>0 && rc==SQLITE_OK );
+
+    releasePage(pPageOut);
+    sqlite3PagerUnref(pPageIn);
+  }
+
+  return rc;
+}
+
+/*
 ** Delete the entry that the cursor is pointing to.
 **
 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
@@ -74228,7 +74621,7 @@
   assert( idx>=0 && idx<=15 );
 
   if( idx==BTREE_DATA_VERSION ){
-    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
+    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
   }else{
     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   }
@@ -78019,7 +78412,7 @@
   p->pNext = db->pVdbe;
   p->pPrev = 0;
   db->pVdbe = p;
-  p->magic = VDBE_MAGIC_INIT;
+  p->iVdbeMagic = VDBE_MAGIC_INIT;
   p->pParse = pParse;
   pParse->pVdbe = p;
   assert( pParse->aLabel==0 );
@@ -78220,7 +78613,7 @@
   VdbeOp *pOp;
 
   i = p->nOp;
-  assert( p->magic==VDBE_MAGIC_INIT );
+  assert( p->iVdbeMagic==VDBE_MAGIC_INIT );
   assert( op>=0 && op<0xff );
   if( p->nOpAlloc<=i ){
     return growOp3(p, op, p1, p2, p3);
@@ -78455,9 +78848,10 @@
 ** The zWhere string must have been obtained from sqlite3_malloc().
 ** This routine will take ownership of the allocated memory.
 */
-SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
+SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere, u16 p5){
   int j;
   sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
+  sqlite3VdbeChangeP5(p, p5);
   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
   sqlite3MayAbort(p->pParse);
 }
@@ -78549,7 +78943,7 @@
 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
   Parse *p = v->pParse;
   int j = ADDR(x);
-  assert( v->magic==VDBE_MAGIC_INIT );
+  assert( v->iVdbeMagic==VDBE_MAGIC_INIT );
   assert( j<-p->nLabel );
   assert( j>=0 );
 #ifdef SQLITE_DEBUG
@@ -78874,7 +79268,7 @@
 ** Return the address of the next instruction to be inserted.
 */
 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
-  assert( p->magic==VDBE_MAGIC_INIT );
+  assert( p->iVdbeMagic==VDBE_MAGIC_INIT );
   return p->nOp;
 }
 
@@ -78959,7 +79353,7 @@
   int i;
   VdbeOp *pOut, *pFirst;
   assert( nOp>0 );
-  assert( p->magic==VDBE_MAGIC_INIT );
+  assert( p->iVdbeMagic==VDBE_MAGIC_INIT );
   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
     return 0;
   }
@@ -79283,7 +79677,7 @@
   sqlite3 *db;
   assert( p!=0 );
   db = p->db;
-  assert( p->magic==VDBE_MAGIC_INIT );
+  assert( p->iVdbeMagic==VDBE_MAGIC_INIT );
   assert( p->aOp!=0 || db->mallocFailed );
   if( db->mallocFailed ){
     if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
@@ -79412,7 +79806,7 @@
   /* C89 specifies that the constant "dummy" will be initialized to all
   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
-  assert( p->magic==VDBE_MAGIC_INIT );
+  assert( p->iVdbeMagic==VDBE_MAGIC_INIT );
   if( addr<0 ){
     addr = p->nOp - 1;
   }
@@ -80097,7 +80491,7 @@
   Op *pOp;                             /* Current opcode */
 
   assert( p->explain );
-  assert( p->magic==VDBE_MAGIC_RUN );
+  assert( p->iVdbeMagic==VDBE_MAGIC_RUN );
   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
 
   /* Even though this opcode does not use dynamic strings for
@@ -80277,14 +80671,14 @@
   int i;
 #endif
   assert( p!=0 );
-  assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
+  assert( p->iVdbeMagic==VDBE_MAGIC_INIT || p->iVdbeMagic==VDBE_MAGIC_RESET );
 
   /* There should be at least one opcode.
   */
   assert( p->nOp>0 );
 
   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
-  p->magic = VDBE_MAGIC_RUN;
+  p->iVdbeMagic = VDBE_MAGIC_RUN;
 
 #ifdef SQLITE_DEBUG
   for(i=0; i<p->nMem; i++){
@@ -80340,8 +80734,10 @@
   assert( p!=0 );
   assert( p->nOp>0 );
   assert( pParse!=0 );
-  assert( p->magic==VDBE_MAGIC_INIT );
+  assert( p->iVdbeMagic==VDBE_MAGIC_INIT );
   assert( pParse==p->pParse );
+  p->pVList = pParse->pVList;
+  pParse->pVList =  0;
   db = p->db;
   assert( db->mallocFailed==0 );
   nVar = pParse->nVar;
@@ -80426,8 +80822,6 @@
     }
   }
 
-  p->pVList = pParse->pVList;
-  pParse->pVList =  0;
   if( db->mallocFailed ){
     p->nVar = 0;
     p->nCursor = 0;
@@ -80455,20 +80849,15 @@
     return;
   }
   assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
+  assert( pCx->pBtx==0 || pCx->isEphemeral );
   switch( pCx->eCurType ){
     case CURTYPE_SORTER: {
       sqlite3VdbeSorterClose(p->db, pCx);
       break;
     }
     case CURTYPE_BTREE: {
-      if( pCx->isEphemeral ){
-        if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
-        /* The pCx->pCursor will be close automatically, if it exists, by
-        ** the call above. */
-      }else{
-        assert( pCx->uc.pCursor!=0 );
-        sqlite3BtreeCloseCursor(pCx->uc.pCursor);
-      }
+      assert( pCx->uc.pCursor!=0 );
+      sqlite3BtreeCloseCursor(pCx->uc.pCursor);
       break;
     }
 #ifndef SQLITE_OMIT_VIRTUALTABLE
@@ -81025,7 +81414,7 @@
   ** one, or the complete transaction if there is no statement transaction.
   */
 
-  if( p->magic!=VDBE_MAGIC_RUN ){
+  if( p->iVdbeMagic!=VDBE_MAGIC_RUN ){
     return SQLITE_OK;
   }
   if( db->mallocFailed ){
@@ -81183,7 +81572,7 @@
     assert( db->nVdbeRead>=db->nVdbeWrite );
     assert( db->nVdbeWrite>=0 );
   }
-  p->magic = VDBE_MAGIC_HALT;
+  p->iVdbeMagic = VDBE_MAGIC_HALT;
   checkActiveVdbeCnt(db);
   if( db->mallocFailed ){
     p->rc = SQLITE_NOMEM_BKPT;
@@ -81356,7 +81745,7 @@
     }
   }
 #endif
-  p->magic = VDBE_MAGIC_RESET;
+  p->iVdbeMagic = VDBE_MAGIC_RESET;
   return p->rc & db->errMask;
 }
 
@@ -81366,7 +81755,7 @@
 */
 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   int rc = SQLITE_OK;
-  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
+  if( p->iVdbeMagic==VDBE_MAGIC_RUN || p->iVdbeMagic==VDBE_MAGIC_HALT ){
     rc = sqlite3VdbeReset(p);
     assert( (rc & p->db->errMask)==rc );
   }
@@ -81427,7 +81816,7 @@
     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
     sqlite3DbFree(db, pSub);
   }
-  if( p->magic!=VDBE_MAGIC_INIT ){
+  if( p->iVdbeMagic!=VDBE_MAGIC_INIT ){
     releaseMemArray(p->aVar, p->nVar);
     sqlite3DbFree(db, p->pVList);
     sqlite3DbFree(db, p->pFree);
@@ -81475,7 +81864,7 @@
   if( p->pNext ){
     p->pNext->pPrev = p->pPrev;
   }
-  p->magic = VDBE_MAGIC_DEAD;
+  p->iVdbeMagic = VDBE_MAGIC_DEAD;
   p->db = 0;
   sqlite3DbFreeNN(db, p);
 }
@@ -81552,6 +81941,7 @@
   assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
   if( p->deferredMoveto ){
     u32 iMap;
+    assert( !p->isEphemeral );
     if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 && !p->nullRow ){
       *pp = p->pAltCursor;
       *piCol = iMap - 1;
@@ -83854,7 +84244,7 @@
   int rc;
 
   assert(p);
-  if( p->magic!=VDBE_MAGIC_RUN ){
+  if( p->iVdbeMagic!=VDBE_MAGIC_RUN ){
     /* We used to require that sqlite3_reset() be called before retrying
     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
     ** with version 3.7.0, we changed this so that sqlite3_reset() would
@@ -84570,7 +84960,7 @@
     return SQLITE_MISUSE_BKPT;
   }
   sqlite3_mutex_enter(p->db->mutex);
-  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
+  if( p->iVdbeMagic!=VDBE_MAGIC_RUN || p->pc>=0 ){
     sqlite3Error(p->db, SQLITE_MISUSE);
     sqlite3_mutex_leave(p->db->mutex);
     sqlite3_log(SQLITE_MISUSE,
@@ -84924,7 +85314,7 @@
 */
 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
   Vdbe *v = (Vdbe*)pStmt;
-  return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
+  return v!=0 && v->iVdbeMagic==VDBE_MAGIC_RUN && v->pc>=0;
 }
 
 /*
@@ -85416,7 +85806,7 @@
         assert( idx>0 );
       }
       zRawSql += nToken;
-      nextIndex = idx + 1;
+      nextIndex = MAX(idx + 1, nextIndex);
       assert( idx>0 && idx<=p->nVar );
       pVar = &p->aVar[idx-1];
       if( pVar->flags & MEM_Null ){
@@ -85760,11 +86150,6 @@
 
   assert( iCur>=0 && iCur<p->nCursor );
   if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
-    /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag
-    ** is clear. Otherwise, if this is an ephemeral cursor created by
-    ** OP_OpenDup, the cursor will not be closed and will still be part
-    ** of a BtShared.pCursor list.  */
-    if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0;
     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
     p->apCsr[iCur] = 0;
   }
@@ -86262,7 +86647,7 @@
 #endif
   /*** INSERT STACK UNION HERE ***/
 
-  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
+  assert( p->iVdbeMagic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   sqlite3VdbeEnter(p);
 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   if( db->xProgress ){
@@ -87022,6 +87407,26 @@
   break;
 }
 
+/* Opcode: ChngCntRow P1 P2 * * *
+** Synopsis: output=r[P1]
+**
+** Output value in register P1 as the chance count for a DML statement,
+** due to the "PRAGMA count_changes=ON" setting.  Or, if there was a
+** foreign key error in the statement, trigger the error now.
+**
+** This opcode is a variant of OP_ResultRow that checks the foreign key
+** immediate constraint count and throws an error if the count is
+** non-zero.  The P2 opcode must be 1.
+*/
+case OP_ChngCntRow: {
+  assert( pOp->p2==1 );
+  if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){
+    goto abort_due_to_error;
+  }
+  /* Fall through to the next case, OP_ResultRow */
+  /* no break */ deliberate_fall_through
+}
+
 /* Opcode: ResultRow P1 P2 * * *
 ** Synopsis: output=r[P1@P2]
 **
@@ -87038,34 +87443,6 @@
   assert( pOp->p1>0 );
   assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
 
-  /* If this statement has violated immediate foreign key constraints, do
-  ** not return the number of rows modified. And do not RELEASE the statement
-  ** transaction. It needs to be rolled back.  */
-  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
-    assert( db->flags&SQLITE_CountRows );
-    assert( p->usesStmtJournal );
-    goto abort_due_to_error;
-  }
-
-  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
-  ** DML statements invoke this opcode to return the number of rows
-  ** modified to the user. This is the only way that a VM that
-  ** opens a statement transaction may invoke this opcode.
-  **
-  ** In case this is such a statement, close any statement transaction
-  ** opened by this VM before returning control to the user. This is to
-  ** ensure that statement-transactions are always nested, not overlapping.
-  ** If the open statement-transaction is not closed here, then the user
-  ** may step another VM that opens its own statement transaction. This
-  ** may lead to overlapping statement transactions.
-  **
-  ** The statement transaction is never a top-level transaction.  Hence
-  ** the RELEASE call below can never fail.
-  */
-  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
-  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
-  assert( rc==SQLITE_OK );
-
   /* Invalidate all ephemeral cursor row caches */
   p->cacheCtr = (p->cacheCtr + 2)|1;
 
@@ -89458,7 +89835,7 @@
 
   pOrig = p->apCsr[pOp->p2];
   assert( pOrig );
-  assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */
+  assert( pOrig->isEphemeral );  /* Only ephemeral cursors can be duplicated */
 
   pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
   if( pCx==0 ) goto no_mem;
@@ -89468,7 +89845,10 @@
   pCx->isTable = pOrig->isTable;
   pCx->pgnoRoot = pOrig->pgnoRoot;
   pCx->isOrdered = pOrig->isOrdered;
-  rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
+  pCx->pBtx = pOrig->pBtx;
+  pCx->hasBeenDuped = 1;
+  pOrig->hasBeenDuped = 1;
+  rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
                           pCx->pKeyInfo, pCx->uc.pCursor);
   /* The sqlite3BtreeCursor() routine can only fail for the first cursor
   ** opened for a database.  Since there is already an open cursor when this
@@ -89534,9 +89914,10 @@
     aMem[pOp->p3].z = "";
   }
   pCx = p->apCsr[pOp->p1];
-  if( pCx && pCx->pBtx ){
-    /* If the ephermeral table is already open, erase all existing content
-    ** so that the table is empty again, rather than creating a new table. */
+  if( pCx && !pCx->hasBeenDuped ){
+    /* If the ephermeral table is already open and has no duplicates from
+    ** OP_OpenDup, then erase all existing content so that the table is
+    ** empty again, rather than creating a new table. */
     assert( pCx->isEphemeral );
     pCx->seqCount = 0;
     pCx->cacheStatus = CACHE_STALE;
@@ -89550,33 +89931,36 @@
                           vfsFlags);
     if( rc==SQLITE_OK ){
       rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
-    }
-    if( rc==SQLITE_OK ){
-      /* If a transient index is required, create it by calling
-      ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
-      ** opening it. If a transient table is required, just use the
-      ** automatically created table with root-page 1 (an BLOB_INTKEY table).
-      */
-      if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
-        assert( pOp->p4type==P4_KEYINFO );
-        rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
-                                     BTREE_BLOBKEY | pOp->p5);
-        if( rc==SQLITE_OK ){
-          assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
-          assert( pKeyInfo->db==db );
-          assert( pKeyInfo->enc==ENC(db) );
-          rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
-                                  pKeyInfo, pCx->uc.pCursor);
-        }
-        pCx->isTable = 0;
-      }else{
-        pCx->pgnoRoot = SCHEMA_ROOT;
-        rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR,
-                                0, pCx->uc.pCursor);
-        pCx->isTable = 1;
-      }
-    }
-    pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
+      if( rc==SQLITE_OK ){
+        /* If a transient index is required, create it by calling
+        ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
+        ** opening it. If a transient table is required, just use the
+        ** automatically created table with root-page 1 (an BLOB_INTKEY table).
+        */
+        if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
+          assert( pOp->p4type==P4_KEYINFO );
+          rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
+              BTREE_BLOBKEY | pOp->p5);
+          if( rc==SQLITE_OK ){
+            assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
+            assert( pKeyInfo->db==db );
+            assert( pKeyInfo->enc==ENC(db) );
+            rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
+                pKeyInfo, pCx->uc.pCursor);
+          }
+          pCx->isTable = 0;
+        }else{
+          pCx->pgnoRoot = SCHEMA_ROOT;
+          rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR,
+              0, pCx->uc.pCursor);
+          pCx->isTable = 1;
+        }
+      }
+      pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
+      if( rc ){
+        sqlite3BtreeClose(pCx->pBtx);
+      }
+    }
   }
   if( rc ) goto abort_due_to_error;
   pCx->nullRow = 1;
@@ -90010,13 +90394,13 @@
 **
 ** There are three possible outcomes from this opcode:<ol>
 **
-** <li> If after This.P1 steps, the cursor is still point to a place that
-**      is earlier in the btree than the target row,
-**      then fall through into the subsquence OP_SeekGE opcode.
+** <li> If after This.P1 steps, the cursor is still pointing to a place that
+**      is earlier in the btree than the target row, then fall through
+**      into the subsquence OP_SeekGE opcode.
 **
 ** <li> If the cursor is successfully moved to the target row by 0 or more
 **      sqlite3BtreeNext() calls, then jump to This.P2, which will land just
-**      past the OP_IdxGT opcode that follows the OP_SeekGE.
+**      past the OP_IdxGT or OP_IdxGE opcode that follows the OP_SeekGE.
 **
 ** <li> If the cursor ends up past the target row (indicating the the target
 **      row does not exist in the btree) then jump to SeekOP.P2.
@@ -90033,7 +90417,8 @@
   /* pOp->p2 points to the first instruction past the OP_IdxGT that
   ** follows the OP_SeekGE.  */
   assert( pOp->p2>=(int)(pOp-aOp)+2 );
-  assert( aOp[pOp->p2-1].opcode==OP_IdxGT );
+  assert( aOp[pOp->p2-1].opcode==OP_IdxGT || aOp[pOp->p2-1].opcode==OP_IdxGE );
+  testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
   assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
   assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
   assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
@@ -90486,8 +90871,10 @@
   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   int res;               /* Result of an sqlite3BtreeLast() */
   int cnt;               /* Counter to limit the number of searches */
+#ifndef SQLITE_OMIT_AUTOINCREMENT
   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   VdbeFrame *pFrame;     /* Root frame of VDBE */
+#endif
 
   v = 0;
   res = 0;
@@ -90703,7 +91090,8 @@
   }
   x.pKey = 0;
   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
-      (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
+      (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
+      seekResult
   );
   pC->deferredMoveto = 0;
   pC->cacheStatus = CACHE_STALE;
@@ -90720,6 +91108,33 @@
   break;
 }
 
+/* Opcode: RowCell P1 P2 P3 * *
+**
+** P1 and P2 are both open cursors. Both must be opened on the same type
+** of table - intkey or index. This opcode is used as part of copying
+** the current row from P2 into P1. If the cursors are opened on intkey
+** tables, register P3 contains the rowid to use with the new record in
+** P1. If they are opened on index tables, P3 is not used.
+**
+** This opcode must be followed by either an Insert or InsertIdx opcode
+** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
+*/
+case OP_RowCell: {
+  VdbeCursor *pDest;              /* Cursor to write to */
+  VdbeCursor *pSrc;               /* Cursor to read from */
+  i64 iKey;                       /* Rowid value to insert with */
+  assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
+  assert( pOp[1].opcode==OP_Insert    || pOp->p3==0 );
+  assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
+  assert( pOp[1].p5 & OPFLAG_PREFORMAT );
+  pDest = p->apCsr[pOp->p1];
+  pSrc = p->apCsr[pOp->p2];
+  iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
+  rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
+  if( rc!=SQLITE_OK ) goto abort_due_to_error;
+  break;
+};
+
 /* Opcode: Delete P1 P2 P3 P4 P5
 **
 ** Delete the record at which the P1 cursor is currently pointing.
@@ -91375,7 +91790,7 @@
   assert( pC!=0 );
   assert( !isSorter(pC) );
   pIn2 = &aMem[pOp->p2];
-  assert( pIn2->flags & MEM_Blob );
+  assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   assert( pC->eCurType==CURTYPE_BTREE );
   assert( pC->isTable==0 );
@@ -91386,7 +91801,7 @@
   x.aMem = aMem + pOp->p3;
   x.nMem = (u16)pOp->p4.i;
   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
-       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
+       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
       ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
       );
   assert( pC->deferredMoveto==0 );
@@ -91459,7 +91874,7 @@
     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
     if( rc ) goto abort_due_to_error;
   }else if( pOp->p5 ){
-    rc = SQLITE_CORRUPT_INDEX;
+    rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
     goto abort_due_to_error;
   }
   assert( pC->deferredMoveto==0 );
@@ -91538,6 +91953,8 @@
       pTabCur->deferredMoveto = 1;
       assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
       pTabCur->aAltMap = pOp->p4.ai;
+      assert( !pC->isEphemeral );
+      assert( !pTabCur->isEphemeral );
       pTabCur->pAltCursor = pC;
     }else{
       pOut = out2Prerelease(p, pOp);
@@ -91885,7 +92302,7 @@
   if( pOp->p4.z==0 ){
     sqlite3SchemaClear(db->aDb[iDb].pSchema);
     db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
-    rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
+    rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
     db->mDbFlags |= DBFLAG_SchemaChange;
     p->expired = 0;
   }else
@@ -97593,7 +98010,6 @@
   int nChunkSize;                 /* In-memory chunk-size */
 
   int nSpill;                     /* Bytes of data before flushing */
-  int nSize;                      /* Bytes of data currently in memory */
   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   FilePoint endpoint;             /* Pointer to the end of the file */
   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
@@ -97654,14 +98070,13 @@
 /*
 ** Free the list of FileChunk structures headed at MemJournal.pFirst.
 */
-static void memjrnlFreeChunks(MemJournal *p){
+static void memjrnlFreeChunks(FileChunk *pFirst){
   FileChunk *pIter;
   FileChunk *pNext;
-  for(pIter=p->pFirst; pIter; pIter=pNext){
+  for(pIter=pFirst; pIter; pIter=pNext){
     pNext = pIter->pNext;
     sqlite3_free(pIter);
   }
-  p->pFirst = 0;
 }
 
 /*
@@ -97688,7 +98103,7 @@
     }
     if( rc==SQLITE_OK ){
       /* No error has occurred. Free the in-memory buffers. */
-      memjrnlFreeChunks(&copy);
+      memjrnlFreeChunks(copy.pFirst);
     }
   }
   if( rc!=SQLITE_OK ){
@@ -97771,30 +98186,37 @@
         nWrite -= iSpace;
         p->endpoint.iOffset += iSpace;
       }
-      p->nSize = iAmt + iOfst;
-    }
-  }
-
-  return SQLITE_OK;
-}
-
-/*
-** Truncate the file.
-**
-** If the journal file is already on disk, truncate it there. Or, if it
-** is still in main memory but is being truncated to zero bytes in size,
-** ignore
+    }
+  }
+
+  return SQLITE_OK;
+}
+
+/*
+** Truncate the in-memory file.
 */
 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   MemJournal *p = (MemJournal *)pJfd;
-  if( ALWAYS(size==0) ){
-    memjrnlFreeChunks(p);
-    p->nSize = 0;
-    p->endpoint.pChunk = 0;
-    p->endpoint.iOffset = 0;
-    p->readpoint.pChunk = 0;
-    p->readpoint.iOffset = 0;
-  }
+  FileChunk *pIter = 0;
+
+  if( size==0 ){
+    memjrnlFreeChunks(p->pFirst);
+    p->pFirst = 0;
+  }else{
+    i64 iOff = p->nChunkSize;
+    for(pIter=p->pFirst; ALWAYS(pIter) && iOff<=size; pIter=pIter->pNext){
+      iOff += p->nChunkSize;
+    }
+    if( ALWAYS(pIter) ){
+      memjrnlFreeChunks(pIter->pNext);
+      pIter->pNext = 0;
+    }
+  }
+
+  p->endpoint.pChunk = pIter;
+  p->endpoint.iOffset = size;
+  p->readpoint.pChunk = 0;
+  p->readpoint.iOffset = 0;
   return SQLITE_OK;
 }
 
@@ -97803,7 +98225,7 @@
 */
 static int memjrnlClose(sqlite3_file *pJfd){
   MemJournal *p = (MemJournal *)pJfd;
-  memjrnlFreeChunks(p);
+  memjrnlFreeChunks(p->pFirst);
   return SQLITE_OK;
 }
 
@@ -97977,7 +98399,7 @@
 ** Walk all expressions linked into the list of Window objects passed
 ** as the second argument.
 */
-static int walkWindowList(Walker *pWalker, Window *pList){
+static int walkWindowList(Walker *pWalker, Window *pList, int bOneOnly){
   Window *pWin;
   for(pWin=pList; pWin; pWin=pWin->pNextWin){
     int rc;
@@ -97996,6 +98418,7 @@
     if( NEVER(rc) ) return WRC_Abort;
     rc = sqlite3WalkExpr(pWalker, pWin->pEnd);
     if( NEVER(rc) ) return WRC_Abort;
+    if( bOneOnly ) break;
   }
   return WRC_Continue;
 }
@@ -98043,7 +98466,7 @@
         }
 #ifndef SQLITE_OMIT_WINDOWFUNC
         if( ExprHasProperty(pExpr, EP_WinFunc) ){
-          if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort;
+          if( walkWindowList(pWalker, pExpr->y.pWin, 1) ) return WRC_Abort;
         }
 #endif
       }
@@ -98090,7 +98513,7 @@
     if( pParse && IN_RENAME_OBJECT ){
       /* The following may return WRC_Abort if there are unresolvable
       ** symbols (e.g. a table that does not exist) in a window definition. */
-      int rc = walkWindowList(pWalker, p->pWinDefn);
+      int rc = walkWindowList(pWalker, p->pWinDefn, 0);
       return rc;
     }
   }
@@ -98108,7 +98531,7 @@
 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   SrcList *pSrc;
   int i;
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
 
   pSrc = p->pSrc;
   if( pSrc ){
@@ -98274,7 +98697,6 @@
   ExprList *pEList,      /* A result set */
   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   Expr *pExpr,           /* Transform this into an alias to the result set */
-  const char *zType,     /* "GROUP" or "ORDER" or "" */
   int nSubquery          /* Number of subqueries that the label is moving */
 ){
   Expr *pOrig;           /* The iCol-th column of the result set */
@@ -98287,7 +98709,7 @@
   db = pParse->db;
   pDup = sqlite3ExprDup(db, pOrig, 0);
   if( pDup!=0 ){
-    if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
+    incrAggFunctionDepth(pDup, nSubquery);
     if( pExpr->op==TK_COLLATE ){
       pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
     }
@@ -98316,7 +98738,6 @@
     }
     sqlite3DbFree(db, pDup);
   }
-  ExprSetProperty(pExpr, EP_Alias);
 }
 
 
@@ -98451,8 +98872,8 @@
   int cntTab = 0;                   /* Number of matching table names */
   int nSubquery = 0;                /* How many levels of subquery */
   sqlite3 *db = pParse->db;         /* The database connection */
-  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
-  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
+  SrcItem *pItem;                   /* Use for looping over pSrcList items */
+  SrcItem *pMatch = 0;              /* The matching pSrcList item */
   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   Schema *pSchema = 0;              /* Schema of the expression */
   int eNewExprOp = TK_COLUMN;       /* New value for pExpr->op on success */
@@ -98573,25 +98994,33 @@
 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
     /* If we have not already resolved the name, then maybe
     ** it is a new.* or old.* trigger argument reference.  Or
-    ** maybe it is an excluded.* from an upsert.
-    */
-    if( zDb==0 && zTab!=0 && cntTab==0 ){
+    ** maybe it is an excluded.* from an upsert.  Or maybe it is
+    ** a reference in the RETURNING clause to a table being modified.
+    */
+    if( cnt==0 && zDb==0 ){
       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( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
+        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;
-        }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
+        }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
           pExpr->iTable = 0;
           pTab = pParse->pTriggerTab;
         }
       }
 #endif /* SQLITE_OMIT_TRIGGER */
 #ifndef SQLITE_OMIT_UPSERT
-      if( (pNC->ncFlags & NC_UUpsert)!=0 ){
+      if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
         Upsert *pUpsert = pNC->uNC.pUpsert;
         if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
           pTab = pUpsert->pUpsertSrc->a[0].pTab;
@@ -98619,6 +99048,7 @@
         }
         if( iCol<pTab->nCol ){
           cnt++;
+          pMatch = 0;
 #ifndef SQLITE_OMIT_UPSERT
           if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
             testcase( iCol==(-1) );
@@ -98630,27 +99060,32 @@
               pExpr->iTable = pNC->uNC.pUpsert->regData +
                  sqlite3TableColumnToStorage(pTab, iCol);
               eNewExprOp = TK_REGISTER;
-              ExprSetProperty(pExpr, EP_Alias);
             }
           }else
 #endif /* SQLITE_OMIT_UPSERT */
           {
-#ifndef SQLITE_OMIT_TRIGGER
-            if( iCol<0 ){
-              pExpr->affExpr = SQLITE_AFF_INTEGER;
-            }else if( pExpr->iTable==0 ){
-              testcase( iCol==31 );
-              testcase( iCol==32 );
-              pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
+            pExpr->y.pTab = pTab;
+            if( pParse->bReturning ){
+              eNewExprOp = TK_REGISTER;
+              pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
+                 sqlite3TableColumnToStorage(pTab, iCol) + 1;
             }else{
-              testcase( iCol==31 );
-              testcase( iCol==32 );
-              pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
+              pExpr->iColumn = (i16)iCol;
+              eNewExprOp = TK_TRIGGER;
+#ifndef SQLITE_OMIT_TRIGGER
+              if( iCol<0 ){
+                pExpr->affExpr = SQLITE_AFF_INTEGER;
+              }else if( pExpr->iTable==0 ){
+                testcase( iCol==31 );
+                testcase( iCol==32 );
+                pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
+              }else{
+                testcase( iCol==31 );
+                testcase( iCol==32 );
+                pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
+              }
+#endif /* SQLITE_OMIT_TRIGGER */
             }
-            pExpr->y.pTab = pTab;
-            pExpr->iColumn = (i16)iCol;
-            eNewExprOp = TK_TRIGGER;
-#endif /* SQLITE_OMIT_TRIGGER */
           }
         }
       }
@@ -98720,7 +99155,7 @@
             sqlite3ErrorMsg(pParse, "row value misused");
             return WRC_Abort;
           }
-          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
+          resolveAlias(pParse, pEList, j, pExpr, nSubquery);
           cnt = 1;
           pMatch = 0;
           assert( zTab==0 && zDb==0 );
@@ -98755,6 +99190,7 @@
     assert( pExpr->op==TK_ID );
     if( ExprHasProperty(pExpr,EP_DblQuoted)
      && areDoubleQuotedStringsEnabled(db, pTopNC)
+     && (db->init.bDropColumn==0 || sqlite3StrICmp(zCol, db->init.azInit[0])!=0)
     ){
       /* If a double-quoted identifier does not match any known column name,
       ** then treat it as a string.
@@ -98769,6 +99205,11 @@
       ** Someday, I hope to get rid of this hack. Unfortunately there is
       ** a huge amount of legacy SQL that uses it. So for now, we just
       ** issue a warning.
+      **
+      ** 2021-03-15: ticket 1c24a659e6d7f3a1
+      ** Do not do the ID-to-STRING conversion when doing the schema
+      ** sanity check following a DROP COLUMN if the identifer name matches
+      ** the name of the column being dropped.
       */
       sqlite3_log(SQLITE_WARNING,
         "double-quoted string literal: \"%w\"", zCol);
@@ -98822,18 +99263,24 @@
 
   /* Clean up and return
   */
-  sqlite3ExprDelete(db, pExpr->pLeft);
-  pExpr->pLeft = 0;
-  sqlite3ExprDelete(db, pExpr->pRight);
-  pExpr->pRight = 0;
+  if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
+    sqlite3ExprDelete(db, pExpr->pLeft);
+    pExpr->pLeft = 0;
+    sqlite3ExprDelete(db, pExpr->pRight);
+    pExpr->pRight = 0;
+  }
   pExpr->op = eNewExprOp;
   ExprSetProperty(pExpr, EP_Leaf);
 lookupname_end:
   if( cnt==1 ){
     assert( pNC!=0 );
-    if( !ExprHasProperty(pExpr, EP_Alias) ){
+#ifndef SQLITE_OMIT_AUTHORIZATION
+    if( pParse->db->xAuth
+     && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
+    ){
       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
     }
+#endif
     /* Increment the nRef value on all name contexts from TopNC up to
     ** the point where the name matched. */
     for(;;){
@@ -98855,7 +99302,7 @@
 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   if( p ){
-    struct SrcList_item *pItem = &pSrc->a[iSrc];
+    SrcItem *pItem = &pSrc->a[iSrc];
     Table *pTab = p->y.pTab = pItem->pTab;
     p->iTable = pItem->iCursor;
     if( p->y.pTab->iPKey==iCol ){
@@ -98967,7 +99414,7 @@
     */
     case TK_ROW: {
       SrcList *pSrcList = pNC->pSrcList;
-      struct SrcList_item *pItem;
+      SrcItem *pItem;
       assert( pSrcList && pSrcList->nSrc>=1 );
       pItem = pSrcList->a;
       pExpr->op = TK_COLUMN;
@@ -98978,6 +99425,47 @@
       break;
     }
 
+    /* An optimization:  Attempt to convert
+    **
+    **      "expr IS NOT NULL"  -->  "TRUE"
+    **      "expr IS NULL"      -->  "FALSE"
+    **
+    ** if we can prove that "expr" is never NULL.  Call this the
+    ** "NOT NULL strength reduction optimization".
+    **
+    ** If this optimization occurs, also restore the NameContext ref-counts
+    ** to the state they where in before the "column" LHS expression was
+    ** resolved.  This prevents "column" from being counted as having been
+    ** referenced, which might prevent a SELECT from being erroneously
+    ** marked as correlated.
+    */
+    case TK_NOTNULL:
+    case TK_ISNULL: {
+      int anRef[8];
+      NameContext *p;
+      int i;
+      for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
+        anRef[i] = p->nRef;
+      }
+      sqlite3WalkExpr(pWalker, pExpr->pLeft);
+      if( 0==sqlite3ExprCanBeNull(pExpr->pLeft) && !IN_RENAME_OBJECT ){
+        if( pExpr->op==TK_NOTNULL ){
+          pExpr->u.zToken = "true";
+          ExprSetProperty(pExpr, EP_IsTrue);
+        }else{
+          pExpr->u.zToken = "false";
+          ExprSetProperty(pExpr, EP_IsFalse);
+        }
+        pExpr->op = TK_TRUEFALSE;
+        for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
+          p->nRef = anRef[i];
+        }
+        sqlite3ExprDelete(pParse->db, pExpr->pLeft);
+        pExpr->pLeft = 0;
+      }
+      return WRC_Prune;
+    }
+
     /* A column name:                    ID
     ** Or table name and column name:    ID.ID
     ** Or a database, table and column:  ID.ID.ID
@@ -99205,6 +99693,7 @@
           assert( pWin==pExpr->y.pWin );
           if( IN_RENAME_OBJECT==0 ){
             sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
+            if( pParse->db->mallocFailed ) break;
           }
           sqlite3WalkExprList(pWalker, pWin->pPartition);
           sqlite3WalkExprList(pWalker, pWin->pOrderBy);
@@ -99279,7 +99768,7 @@
       assert( !ExprHasProperty(pExpr, EP_Reduced) );
       /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
       ** and "x IS NOT FALSE". */
-      if( pRight && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
+      if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
         int rc = resolveExprStep(pWalker, pRight);
         if( rc==WRC_Abort ) return WRC_Abort;
         if( pRight->op==TK_TRUEFALSE ){
@@ -99595,8 +100084,7 @@
         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
         return 1;
       }
-      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
-                   zType,0);
+      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
     }
   }
   return 0;
@@ -99781,27 +100269,26 @@
     /* Recursively resolve names in all subqueries
     */
     for(i=0; i<p->pSrc->nSrc; i++){
-      struct SrcList_item *pItem = &p->pSrc->a[i];
+      SrcItem *pItem = &p->pSrc->a[i];
       if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
-        NameContext *pNC;         /* Used to iterate name contexts */
-        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
+        int nRef = pOuterNC ? pOuterNC->nRef : 0;
         const char *zSavedContext = pParse->zAuthContext;
 
-        /* Count the total number of references to pOuterNC and all of its
-        ** parent contexts. After resolving references to expressions in
-        ** pItem->pSelect, check if this value has changed. If so, then
-        ** SELECT statement pItem->pSelect must be correlated. Set the
-        ** pItem->fg.isCorrelated flag if this is the case. */
-        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
-
         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
         pParse->zAuthContext = zSavedContext;
         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
 
-        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
-        assert( pItem->fg.isCorrelated==0 && nRef<=0 );
-        pItem->fg.isCorrelated = (nRef!=0);
+        /* If the number of references to the outer context changed when
+        ** expressions in the sub-select were resolved, the sub-select
+        ** is correlated. It is not required to check the refcount on any
+        ** but the innermost outer context object, as lookupName() increments
+        ** the refcount on all contexts between the current one and the
+        ** context containing the column when it resolves a name. */
+        if( pOuterNC ){
+          assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
+          pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
+        }
       }
     }
 
@@ -99843,7 +100330,7 @@
     ** Minor point: If this is the case, then the expression will be
     ** re-evaluated for each reference to it.
     */
-    assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
+    assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
     sNC.uNC.pEList = p->pEList;
     sNC.ncFlags |= NC_UEList;
     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
@@ -99851,7 +100338,7 @@
 
     /* Resolve names in table-valued-function arguments */
     for(i=0; i<p->pSrc->nSrc; i++){
-      struct SrcList_item *pItem = &p->pSrc->a[i];
+      SrcItem *pItem = &p->pSrc->a[i];
       if( pItem->fg.isTabFunc
        && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
       ){
@@ -100260,7 +100747,18 @@
   const Token *pCollName,  /* Name of collating sequence */
   int dequote              /* True to dequote pCollName */
 ){
-  if( pCollName->n>0 ){
+  assert( pExpr!=0 || pParse->db->mallocFailed );
+  if( pExpr==0 ) return 0;
+  if( pExpr->op==TK_VECTOR ){
+    ExprList *pList = pExpr->x.pList;
+    if( ALWAYS(pList!=0) ){
+      int i;
+      for(i=0; i<pList->nExpr; i++){
+        pList->a[i].pExpr = sqlite3ExprAddCollateToken(pParse,pList->a[i].pExpr,
+                                                       pCollName, dequote);
+      }
+    }
+  }else if( pCollName->n>0 ){
     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
     if( pNew ){
       pNew->pLeft = pExpr;
@@ -101112,8 +101610,8 @@
   }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))
          && !IN_RENAME_OBJECT
   ){
-    sqlite3ExprDelete(db, pLeft);
-    sqlite3ExprDelete(db, pRight);
+    sqlite3ExprDeferredDelete(pParse, pLeft);
+    sqlite3ExprDeferredDelete(pParse, pRight);
     return sqlite3Expr(db, TK_INTEGER, "0");
   }else{
     return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
@@ -101310,6 +101808,22 @@
   if( p ) sqlite3ExprDeleteNN(db, p);
 }
 
+
+/*
+** Arrange to cause pExpr to be deleted when the pParse is deleted.
+** This is similar to sqlite3ExprDelete() except that the delete is
+** deferred untilthe pParse is deleted.
+**
+** The pExpr might be deleted immediately on an OOM error.
+**
+** The deferred delete is (currently) implemented by adding the
+** pExpr to the pParse->pConstExpr list with a register number of 0.
+*/
+SQLITE_PRIVATE void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
+  pParse->pConstExpr =
+      sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
+}
+
 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
 ** expression.
 */
@@ -101684,8 +102198,8 @@
   if( pNew==0 ) return 0;
   pNew->nSrc = pNew->nAlloc = p->nSrc;
   for(i=0; i<p->nSrc; i++){
-    struct SrcList_item *pNewItem = &pNew->a[i];
-    struct SrcList_item *pOldItem = &p->a[i];
+    SrcItem *pNewItem = &pNew->a[i];
+    SrcItem *pOldItem = &p->a[i];
     Table *pTab;
     pNewItem->pSchema = pOldItem->pSchema;
     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
@@ -101698,7 +102212,10 @@
     if( pNewItem->fg.isIndexedBy ){
       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
     }
-    pNewItem->pIBIndex = pOldItem->pIBIndex;
+    pNewItem->u2 = pOldItem->u2;
+    if( pNewItem->fg.isCte ){
+      pNewItem->u2.pCteUse->nUse++;
+    }
     if( pNewItem->fg.isTabFunc ){
       pNewItem->u1.pFuncArg =
           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
@@ -102736,7 +103253,7 @@
 
     /* Code an OP_Transaction and OP_TableLock for <table>. */
     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
-    assert( iDb>=0 && iDb<SQLITE_MAX_ATTACHED );
+    assert( iDb>=0 && iDb<SQLITE_MAX_DB );
     sqlite3CodeVerifySchema(pParse, iDb);
     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
 
@@ -105932,8 +106449,7 @@
         pExpr = sqlite3ExprDup(db, pExpr, 0);
         if( pExpr ){
           pAggInfo->aCol[iAgg].pCExpr = pExpr;
-          pParse->pConstExpr =
-             sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
+          sqlite3ExprDeferredDelete(pParse, pExpr);
         }
       }
     }else{
@@ -105942,8 +106458,7 @@
         pExpr = sqlite3ExprDup(db, pExpr, 0);
         if( pExpr ){
           pAggInfo->aFunc[iAgg].pFExpr = pExpr;
-          pParse->pConstExpr =
-             sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
+          sqlite3ExprDeferredDelete(pParse, pExpr);
         }
       }
     }
@@ -106015,7 +106530,7 @@
       /* Check to see if the column is in one of the tables in the FROM
       ** clause of the aggregate query */
       if( ALWAYS(pSrcList!=0) ){
-        struct SrcList_item *pItem = pSrcList->a;
+        SrcItem *pItem = pSrcList->a;
         for(i=0; i<pSrcList->nSrc; i++, pItem++){
           struct AggInfo_col *pCol;
           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
@@ -106304,15 +106819,22 @@
 ** statement to ensure that the operation has not rendered any schema
 ** objects unusable.
 */
-static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
+static void renameTestSchema(
+  Parse *pParse,                  /* Parse context */
+  const char *zDb,                /* Name of db to verify schema of */
+  int bTemp,                      /* True if this is the temp db */
+  const char *zWhen,              /* "when" part of error message */
+  const char *zDropColumn         /* Name of column being dropped */
+){
+  pParse->colNamesSet = 1;
   sqlite3NestedParse(pParse,
       "SELECT 1 "
       "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
       " AND sql NOT LIKE 'create virtual%%'"
-      " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
+      " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %Q)=NULL ",
       zDb,
-      zDb, bTemp
+      zDb, bTemp, zWhen, zDropColumn
   );
 
   if( bTemp==0 ){
@@ -106321,8 +106843,8 @@
         "FROM temp." DFLT_SCHEMA_TABLE " "
         "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
         " AND sql NOT LIKE 'create virtual%%'"
-        " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
-        zDb
+        " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %Q)=NULL ",
+        zDb, zWhen, zDropColumn
     );
   }
 }
@@ -106331,12 +106853,12 @@
 ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
 ** the temp database as well.
 */
-static void renameReloadSchema(Parse *pParse, int iDb){
+static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
   Vdbe *v = pParse->pVdbe;
   if( v ){
     sqlite3ChangeCookie(pParse, iDb);
-    sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
-    if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
+    sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
+    if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
   }
 }
 
@@ -106485,7 +107007,7 @@
             "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
             "tbl_name = "
               "CASE WHEN tbl_name=%Q COLLATE nocase AND "
-              "          sqlite_rename_test(%Q, sql, type, name, 1) "
+              "  sqlite_rename_test(%Q, sql, type, name, 1, 'after rename',0) "
               "THEN %Q ELSE tbl_name END "
             "WHERE type IN ('view', 'trigger')"
         , zDb, zTabName, zName, zTabName, zDb, zName);
@@ -106504,8 +107026,8 @@
   }
 #endif
 
-  renameReloadSchema(pParse, iDb);
-  renameTestSchema(pParse, zDb, iDb==1);
+  renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
+  renameTestSchema(pParse, zDb, iDb==1, "after rename", 0);
 
 exit_rename_table:
   sqlite3SrcListDelete(db, pSrc);
@@ -106636,11 +107158,14 @@
       *zEnd-- = '\0';
     }
     db->mDbFlags |= DBFLAG_PreferBuiltin;
+    /* substr() operations on characters, but addColOffset is in bytes. So we
+    ** have to use printf() to translate between these units: */
     sqlite3NestedParse(pParse,
         "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
-          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
+          "sql = printf('%%.%ds, ',sql) || %Q"
+          " || substr(sql,1+length(printf('%%.%ds',sql))) "
         "WHERE type = 'table' AND name = %Q",
-      zDb, pNew->addColOffset, zCol, pNew->addColOffset+1,
+      zDb, pNew->addColOffset, zCol, pNew->addColOffset,
       zTab
     );
     sqlite3DbFree(db, zCol);
@@ -106664,7 +107189,7 @@
   }
 
   /* Reload the table definition */
-  renameReloadSchema(pParse, iDb);
+  renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
 }
 
 /*
@@ -106764,7 +107289,7 @@
 ** Or, if pTab is not a view or virtual table, zero is returned.
 */
 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
-static int isRealTable(Parse *pParse, Table *pTab){
+static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
   const char *zType = 0;
 #ifndef SQLITE_OMIT_VIEW
   if( pTab->pSelect ){
@@ -106777,15 +107302,16 @@
   }
 #endif
   if( zType ){
-    sqlite3ErrorMsg(
-        pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
+    sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
+        (bDrop ? "drop column from" : "rename columns of"),
+        zType, pTab->zName
     );
     return 1;
   }
   return 0;
 }
 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
-# define isRealTable(x,y) (0)
+# define isRealTable(x,y,z) (0)
 #endif
 
 /*
@@ -106814,7 +107340,7 @@
 
   /* Cannot alter a system table */
   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
-  if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
+  if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
 
   /* Which schema holds the table to be altered */
   iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
@@ -106868,8 +107394,8 @@
   );
 
   /* Drop and reload the database schema. */
-  renameReloadSchema(pParse, iSchema);
-  renameTestSchema(pParse, zDb, iSchema==1);
+  renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
+  renameTestSchema(pParse, zDb, iSchema==1, "after rename", 0);
 
  exit_rename_column:
   sqlite3SrcListDelete(db, pSrc);
@@ -107121,23 +107647,33 @@
 
 /*
 ** Search the Parse object passed as the first argument for a RenameToken
-** object associated with parse tree element pPtr. If found, remove it
-** from the Parse object and add it to the list maintained by the
-** RenameCtx object passed as the second argument.
-*/
-static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
+** object associated with parse tree element pPtr. If found, return a pointer
+** to it. Otherwise, return NULL.
+**
+** If the second argument passed to this function is not NULL and a matching
+** RenameToken object is found, remove it from the Parse object and add it to
+** the list maintained by the RenameCtx object.
+*/
+static RenameToken *renameTokenFind(
+  Parse *pParse,
+  struct RenameCtx *pCtx,
+  void *pPtr
+){
   RenameToken **pp;
   assert( pPtr!=0 );
   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
     if( (*pp)->p==pPtr ){
       RenameToken *pToken = *pp;
-      *pp = pToken->pNext;
-      pToken->pNext = pCtx->pList;
-      pCtx->pList = pToken;
-      pCtx->nList++;
-      break;
-    }
-  }
+      if( pCtx ){
+        *pp = pToken->pNext;
+        pToken->pNext = pCtx->pList;
+        pCtx->pList = pToken;
+        pCtx->nList++;
+      }
+      return pToken;
+    }
+  }
+  return 0;
 }
 
 /*
@@ -107208,7 +107744,7 @@
 */
 static void renameColumnParseError(
   sqlite3_context *pCtx,
-  int bPost,
+  const char *zWhen,
   sqlite3_value *pType,
   sqlite3_value *pObject,
   Parse *pParse
@@ -107217,8 +107753,8 @@
   const char *zN = (const char*)sqlite3_value_text(pObject);
   char *zErr;
 
-  zErr = sqlite3_mprintf("error in %s %s%s: %s",
-      zT, zN, (bPost ? " after rename" : ""),
+  zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
+      zT, zN, (zWhen[0] ? " " : ""), zWhen,
       pParse->zErrMsg
   );
   sqlite3_result_error(pCtx, zErr, -1);
@@ -107283,12 +107819,17 @@
   const char *zDb,                /* Name of schema SQL belongs to */
   sqlite3 *db,                    /* Database handle */
   const char *zSql,               /* SQL to parse */
-  int bTemp                       /* True if SQL is from temp schema */
+  int bTemp,                      /* True if SQL is from temp schema */
+  const char *zDropColumn         /* Name of column being dropped */
 ){
   int rc;
   char *zErr = 0;
 
   db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
+  if( zDropColumn ){
+    db->init.bDropColumn = 1;
+    db->init.azInit = (char**)&zDropColumn;
+  }
 
   /* Parse the SQL statement passed as the first argument. If no error
   ** occurs and the parse does not result in a new table, index or
@@ -107297,7 +107838,7 @@
   p->eParseMode = PARSE_MODE_RENAME;
   p->db = db;
   p->nQueryLoop = 1;
-  rc = sqlite3RunParser(p, zSql, &zErr);
+  rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
   assert( p->zErrMsg==0 );
   assert( rc!=SQLITE_OK || zErr==0 );
   p->zErrMsg = zErr;
@@ -107321,6 +107862,7 @@
 #endif
 
   db->init.iDb = 0;
+  db->init.bDropColumn = 0;
   return rc;
 }
 
@@ -107450,7 +107992,7 @@
       if( pSrc ){
         int i;
         for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
-          struct SrcList_item *p = &pSrc->a[i];
+          SrcItem *p = &pSrc->a[i];
           p->iCursor = pParse->nTab++;
           if( p->pSelect ){
             sqlite3SelectPrep(pParse, p->pSelect, 0);
@@ -107476,9 +108018,8 @@
           rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
         }
         assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
-        if( pStep->pUpsert ){
+        if( pStep->pUpsert && rc==SQLITE_OK ){
           Upsert *pUpsert = pStep->pUpsert;
-          assert( rc==SQLITE_OK );
           pUpsert->pUpsertSrc = pSrc;
           sNC.uNC.pUpsert = pUpsert;
           sNC.ncFlags = NC_UUpsert;
@@ -107623,7 +108164,7 @@
 #ifndef SQLITE_OMIT_AUTHORIZATION
   db->xAuth = 0;
 #endif
-  rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
+  rc = renameParseSql(&sParse, zDb, db, zSql, bTemp, 0);
 
   /* Find tokens that need to be replaced. */
   memset(&sWalker, 0, sizeof(Walker));
@@ -107665,12 +108206,12 @@
         for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
         }
-      }
 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
-      for(i=0; i<sParse.pNewTable->nCol; i++){
-        sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
-      }
-#endif
+        for(i=0; i<sParse.pNewTable->nCol; i++){
+          sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
+        }
+#endif
+      }
 
       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
         for(i=0; i<pFKey->nCol; i++){
@@ -107724,7 +108265,7 @@
 renameColumnFunc_done:
   if( rc!=SQLITE_OK ){
     if( sParse.zErrMsg ){
-      renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
+      renameColumnParseError(context, "", argv[1], argv[2], &sParse);
     }else{
       sqlite3_result_error_code(context, rc);
     }
@@ -107762,7 +108303,7 @@
     return WRC_Abort;
   }
   for(i=0; i<pSrc->nSrc; i++){
-    struct SrcList_item *pItem = &pSrc->a[i];
+    SrcItem *pItem = &pSrc->a[i];
     if( pItem->pTab==p->pTab ){
       renameTokenFind(pWalker->pParse, p, pItem->zName);
     }
@@ -107827,7 +108368,7 @@
     sWalker.xSelectCallback = renameTableSelectCb;
     sWalker.u.pRename = &sCtx;
 
-    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
+    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp, 0);
 
     if( rc==SQLITE_OK ){
       int isLegacy = (db->flags & SQLITE_LegacyAlter);
@@ -107913,7 +108454,7 @@
     }
     if( rc!=SQLITE_OK ){
       if( sParse.zErrMsg ){
-        renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
+        renameColumnParseError(context, "", argv[1], argv[2], &sParse);
       }else{
         sqlite3_result_error_code(context, rc);
       }
@@ -107942,6 +108483,8 @@
 **   2: Object type ("view", "table", "trigger" or "index").
 **   3: Object name.
 **   4: True if object is from temp schema.
+**   5: "when" part of error message.
+**   6: Name of column being dropped, or NULL.
 **
 ** Unless it finds an error, this function normally returns NULL. However, it
 ** returns integer value 1 if:
@@ -107959,6 +108502,8 @@
   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
   int bTemp = sqlite3_value_int(argv[4]);
   int isLegacy = (db->flags & SQLITE_LegacyAlter);
+  char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
+  char const *zDropColumn = (const char*)sqlite3_value_text(argv[6]);
 
 #ifndef SQLITE_OMIT_AUTHORIZATION
   sqlite3_xauth xAuth = db->xAuth;
@@ -107969,7 +108514,7 @@
   if( zDb && zInput ){
     int rc;
     Parse sParse;
-    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
+    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp, zDropColumn);
     if( rc==SQLITE_OK ){
       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
         NameContext sNC;
@@ -107991,8 +108536,8 @@
       }
     }
 
-    if( rc!=SQLITE_OK ){
-      renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
+    if( rc!=SQLITE_OK && zWhen ){
+      renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
     }
     renameParseCleanup(&sParse);
   }
@@ -108003,13 +108548,205 @@
 }
 
 /*
+** The implementation of internal UDF sqlite_drop_column().
+**
+** Arguments:
+**
+**  argv[0]: An integer - the index of the schema containing the table
+**  argv[1]: CREATE TABLE statement to modify.
+**  argv[2]: An integer - the index of the column to remove.
+**
+** The value returned is a string containing the CREATE TABLE statement
+** with column argv[2] removed.
+*/
+static void dropColumnFunc(
+  sqlite3_context *context,
+  int NotUsed,
+  sqlite3_value **argv
+){
+  sqlite3 *db = sqlite3_context_db_handle(context);
+  int iSchema = sqlite3_value_int(argv[0]);
+  const char *zSql = (const char*)sqlite3_value_text(argv[1]);
+  int iCol = sqlite3_value_int(argv[2]);
+  const char *zDb = db->aDb[iSchema].zDbSName;
+  int rc;
+  Parse sParse;
+  RenameToken *pCol;
+  Table *pTab;
+  const char *zEnd;
+  char *zNew = 0;
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  sqlite3_xauth xAuth = db->xAuth;
+  db->xAuth = 0;
+#endif
+
+  UNUSED_PARAMETER(NotUsed);
+  rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1, 0);
+  if( rc!=SQLITE_OK ) goto drop_column_done;
+  pTab = sParse.pNewTable;
+  if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
+    /* This can happen if the sqlite_schema table is corrupt */
+    rc = SQLITE_CORRUPT_BKPT;
+    goto drop_column_done;
+  }
+
+  pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
+  if( iCol<pTab->nCol-1 ){
+    RenameToken *pEnd;
+    pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
+    zEnd = (const char*)pEnd->t.z;
+  }else{
+    zEnd = (const char*)&zSql[pTab->addColOffset];
+    while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
+  }
+
+  zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
+  sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
+  sqlite3_free(zNew);
+
+drop_column_done:
+  renameParseCleanup(&sParse);
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  db->xAuth = xAuth;
+#endif
+  if( rc!=SQLITE_OK ){
+    sqlite3_result_error_code(context, rc);
+  }
+}
+
+/*
+** This function is called by the parser upon parsing an
+**
+**     ALTER TABLE pSrc DROP COLUMN pName
+**
+** statement. Argument pSrc contains the possibly qualified name of the
+** table being edited, and token pName the name of the column to drop.
+*/
+SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
+  sqlite3 *db = pParse->db;       /* Database handle */
+  Table *pTab;                    /* Table to modify */
+  int iDb;                        /* Index of db containing pTab in aDb[] */
+  const char *zDb;                /* Database containing pTab ("main" etc.) */
+  char *zCol = 0;                 /* Name of column to drop */
+  int iCol;                       /* Index of column zCol in pTab->aCol[] */
+
+  /* Look up the table being altered. */
+  assert( pParse->pNewTable==0 );
+  assert( sqlite3BtreeHoldsAllMutexes(db) );
+  if( NEVER(db->mallocFailed) ) goto exit_drop_column;
+  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
+  if( !pTab ) goto exit_drop_column;
+
+  /* Make sure this is not an attempt to ALTER a view, virtual table or
+  ** system table. */
+  if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
+  if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
+
+  /* Find the index of the column being dropped. */
+  zCol = sqlite3NameFromToken(db, pName);
+  if( zCol==0 ){
+    assert( db->mallocFailed );
+    goto exit_drop_column;
+  }
+  iCol = sqlite3ColumnIndex(pTab, zCol);
+  if( iCol<0 ){
+    sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
+    goto exit_drop_column;
+  }
+
+  /* Do not allow the user to drop a PRIMARY KEY column or a column
+  ** constrained by a UNIQUE constraint.  */
+  if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
+    sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
+        (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
+        zCol
+    );
+    goto exit_drop_column;
+  }
+
+  /* Do not allow the number of columns to go to zero */
+  if( pTab->nCol<=1 ){
+    sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
+    goto exit_drop_column;
+  }
+
+  /* Edit the sqlite_schema table */
+  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+  assert( iDb>=0 );
+  zDb = db->aDb[iDb].zDbSName;
+  renameTestSchema(pParse, zDb, iDb==1, "", 0);
+  sqlite3NestedParse(pParse,
+      "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+      "sql = sqlite_drop_column(%d, sql, %d) "
+      "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
+      , zDb, iDb, iCol, pTab->zName
+  );
+
+  /* Drop and reload the database schema. */
+  renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
+  renameTestSchema(pParse, zDb, iDb==1, "after drop column", zCol);
+
+  /* Edit rows of table on disk */
+  if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
+    int i;
+    int addr;
+    int reg;
+    int regRec;
+    Index *pPk = 0;
+    int nField = 0;               /* Number of non-virtual columns after drop */
+    int iCur;
+    Vdbe *v = sqlite3GetVdbe(pParse);
+    iCur = pParse->nTab++;
+    sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
+    addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
+    reg = ++pParse->nMem;
+    pParse->nMem += pTab->nCol;
+    if( HasRowid(pTab) ){
+      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
+    }else{
+      pPk = sqlite3PrimaryKeyIndex(pTab);
+    }
+    for(i=0; i<pTab->nCol; i++){
+      if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
+        int regOut;
+        if( pPk ){
+          int iPos = sqlite3TableColumnToIndex(pPk, i);
+          int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
+          regOut = reg+1+iPos-(iPos>iColPos);
+        }else{
+          regOut = reg+1+nField;
+        }
+        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
+        nField++;
+      }
+    }
+    regRec = reg + pTab->nCol;
+    sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
+    if( pPk ){
+      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
+    }else{
+      sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
+    }
+
+    sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
+    sqlite3VdbeJumpHere(v, addr);
+  }
+
+exit_drop_column:
+  sqlite3DbFree(db, zCol);
+  sqlite3SrcListDelete(db, pSrc);
+}
+
+/*
 ** Register built-in functions used to help implement ALTER TABLE
 */
 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
   static FuncDef aAlterTableFuncs[] = {
-    INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
-    INTERNAL_FUNCTION(sqlite_rename_table,  7, renameTableFunc),
-    INTERNAL_FUNCTION(sqlite_rename_test,   5, renameTableTest),
+    INTERNAL_FUNCTION(sqlite_rename_column,  9, renameColumnFunc),
+    INTERNAL_FUNCTION(sqlite_rename_table,   7, renameTableFunc),
+    INTERNAL_FUNCTION(sqlite_rename_test,    7, renameTableTest),
+    INTERNAL_FUNCTION(sqlite_drop_column,    3, dropColumnFunc),
   };
   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
 }
@@ -110399,6 +111136,62 @@
 #endif /* SQLITE_OMIT_ATTACH */
 
 /*
+** Expression callback used by sqlite3FixAAAA() routines.
+*/
+static int fixExprCb(Walker *p, Expr *pExpr){
+  DbFixer *pFix = p->u.pFix;
+  if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
+  if( pExpr->op==TK_VARIABLE ){
+    if( pFix->pParse->db->init.busy ){
+      pExpr->op = TK_NULL;
+    }else{
+      sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
+      return WRC_Abort;
+    }
+  }
+  return WRC_Continue;
+}
+
+/*
+** Select callback used by sqlite3FixAAAA() routines.
+*/
+static int fixSelectCb(Walker *p, Select *pSelect){
+  DbFixer *pFix = p->u.pFix;
+  int i;
+  SrcItem *pItem;
+  sqlite3 *db = pFix->pParse->db;
+  int iDb = sqlite3FindDbName(db, pFix->zDb);
+  SrcList *pList = pSelect->pSrc;
+
+  if( NEVER(pList==0) ) return WRC_Continue;
+  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
+    if( pFix->bTemp==0 ){
+      if( pItem->zDatabase && iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){
+        sqlite3ErrorMsg(pFix->pParse,
+            "%s %T cannot reference objects in database %s",
+            pFix->zType, pFix->pName, pItem->zDatabase);
+        return WRC_Abort;
+      }
+      sqlite3DbFree(db, pItem->zDatabase);
+      pItem->zDatabase = 0;
+      pItem->pSchema = pFix->pSchema;
+      pItem->fg.fromDDL = 1;
+    }
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
+    if( sqlite3WalkExpr(&pFix->w, pList->a[i].pOn) ) return WRC_Abort;
+#endif
+  }
+  if( pSelect->pWith ){
+    for(i=0; i<pSelect->pWith->nCte; i++){
+      if( sqlite3WalkSelect(p, pSelect->pWith->a[i].pSelect) ){
+        return WRC_Abort;
+      }
+    }
+  }
+  return WRC_Continue;
+}
+
+/*
 ** Initialize a DbFixer structure.  This routine must be called prior
 ** to passing the structure to one of the sqliteFixAAAA() routines below.
 */
@@ -110409,9 +111202,7 @@
   const char *zType,  /* "view", "trigger", or "index" */
   const Token *pName  /* Name of the view, trigger, or index */
 ){
-  sqlite3 *db;
-
-  db = pParse->db;
+  sqlite3 *db = pParse->db;
   assert( db->nDb>iDb );
   pFix->pParse = pParse;
   pFix->zDb = db->aDb[iDb].zDbSName;
@@ -110419,6 +111210,13 @@
   pFix->zType = zType;
   pFix->pName = pName;
   pFix->bTemp = (iDb==1);
+  pFix->w.pParse = pParse;
+  pFix->w.xExprCallback = fixExprCb;
+  pFix->w.xSelectCallback = fixSelectCb;
+  pFix->w.xSelectCallback2 = 0;
+  pFix->w.walkerDepth = 0;
+  pFix->w.eCode = 0;
+  pFix->w.u.pFix = pFix;
 }
 
 /*
@@ -110439,115 +111237,27 @@
   DbFixer *pFix,       /* Context of the fixation */
   SrcList *pList       /* The Source list to check and modify */
 ){
-  int i;
-  struct SrcList_item *pItem;
-  sqlite3 *db = pFix->pParse->db;
-  int iDb = sqlite3FindDbName(db, pFix->zDb);
-
-  if( NEVER(pList==0) ) return 0;
-
-  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
-    if( pFix->bTemp==0 ){
-      if( pItem->zDatabase && iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){
-        sqlite3ErrorMsg(pFix->pParse,
-            "%s %T cannot reference objects in database %s",
-            pFix->zType, pFix->pName, pItem->zDatabase);
-        return 1;
-      }
-      sqlite3DbFree(db, pItem->zDatabase);
-      pItem->zDatabase = 0;
-      pItem->pSchema = pFix->pSchema;
-      pItem->fg.fromDDL = 1;
-    }
-#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
-    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
-    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
-#endif
-    if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
-      return 1;
-    }
-  }
-  return 0;
+  int res = 0;
+  if( pList ){
+    Select s;
+    memset(&s, 0, sizeof(s));
+    s.pSrc = pList;
+    res = sqlite3WalkSelect(&pFix->w, &s);
+  }
+  return res;
 }
 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
 SQLITE_PRIVATE int sqlite3FixSelect(
   DbFixer *pFix,       /* Context of the fixation */
   Select *pSelect      /* The SELECT statement to be fixed to one database */
 ){
-  while( pSelect ){
-    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
-      return 1;
-    }
-    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
-      return 1;
-    }
-    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
-      return 1;
-    }
-    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
-      return 1;
-    }
-    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
-      return 1;
-    }
-    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
-      return 1;
-    }
-    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
-      return 1;
-    }
-    if( pSelect->pWith ){
-      int i;
-      for(i=0; i<pSelect->pWith->nCte; i++){
-        if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
-          return 1;
-        }
-      }
-    }
-    pSelect = pSelect->pPrior;
-  }
-  return 0;
+  return sqlite3WalkSelect(&pFix->w, pSelect);
 }
 SQLITE_PRIVATE int sqlite3FixExpr(
   DbFixer *pFix,     /* Context of the fixation */
   Expr *pExpr        /* The expression to be fixed to one database */
 ){
-  while( pExpr ){
-    if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
-    if( pExpr->op==TK_VARIABLE ){
-      if( pFix->pParse->db->init.busy ){
-        pExpr->op = TK_NULL;
-      }else{
-        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
-        return 1;
-      }
-    }
-    if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
-    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
-      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
-    }else{
-      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
-    }
-    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
-      return 1;
-    }
-    pExpr = pExpr->pLeft;
-  }
-  return 0;
-}
-SQLITE_PRIVATE int sqlite3FixExprList(
-  DbFixer *pFix,     /* Context of the fixation */
-  ExprList *pList    /* The expression to be fixed to one database */
-){
-  int i;
-  struct ExprList_item *pItem;
-  if( pList==0 ) return 0;
-  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
-    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
-      return 1;
-    }
-  }
-  return 0;
+  return sqlite3WalkExpr(&pFix->w, pExpr);
 }
 #endif
 
@@ -110557,25 +111267,20 @@
   TriggerStep *pStep /* The trigger step be fixed to one database */
 ){
   while( pStep ){
-    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
-      return 1;
-    }
-    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
-      return 1;
-    }
-    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
-      return 1;
-    }
-    if( pStep->pFrom && sqlite3FixSrcList(pFix, pStep->pFrom) ){
+    if( sqlite3WalkSelect(&pFix->w, pStep->pSelect)
+     || sqlite3WalkExpr(&pFix->w, pStep->pWhere)
+     || sqlite3WalkExprList(&pFix->w, pStep->pExprList)
+     || sqlite3FixSrcList(pFix, pStep->pFrom)
+    ){
       return 1;
     }
 #ifndef SQLITE_OMIT_UPSERT
     if( pStep->pUpsert ){
       Upsert *pUp = pStep->pUpsert;
-      if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
-       || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
-       || sqlite3FixExprList(pFix, pUp->pUpsertSet)
-       || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
+      if( sqlite3WalkExprList(&pFix->w, pUp->pUpsertTarget)
+       || sqlite3WalkExpr(&pFix->w, pUp->pUpsertTargetWhere)
+       || sqlite3WalkExprList(&pFix->w, pUp->pUpsertSet)
+       || sqlite3WalkExpr(&pFix->w, pUp->pUpsertWhere)
       ){
         return 1;
       }
@@ -110583,6 +111288,7 @@
 #endif
     pStep = pStep->pNext;
   }
+
   return 0;
 }
 #endif
@@ -110734,7 +111440,6 @@
   Schema *pSchema,      /* The schema of the expression */
   SrcList *pTabList     /* All table that pExpr might refer to */
 ){
-  sqlite3 *db = pParse->db;
   Table *pTab = 0;      /* The table being read */
   const char *zCol;     /* Name of the column of the table */
   int iSrc;             /* Index in pTabList->a[] of table being read */
@@ -110742,8 +111447,8 @@
   int iCol;             /* Index of column in table */
 
   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
-  assert( !IN_RENAME_OBJECT || db->xAuth==0 );
-  if( db->xAuth==0 ) return;
+  assert( !IN_RENAME_OBJECT );
+  assert( pParse->db->xAuth!=0 );
   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   if( iDb<0 ){
     /* An attempt to read a column out of a subquery or other
@@ -110755,7 +111460,7 @@
     pTab = pParse->pTriggerTab;
   }else{
     assert( pTabList );
-    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
+    for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
         pTab = pTabList->a[iSrc].pTab;
         break;
@@ -110763,7 +111468,7 @@
     }
   }
   iCol = pExpr->iColumn;
-  if( NEVER(pTab==0) ) return;
+  if( pTab==0 ) return;
 
   if( iCol>=0 ){
     assert( iCol<pTab->nCol );
@@ -110774,7 +111479,7 @@
   }else{
     zCol = "ROWID";
   }
-  assert( iDb>=0 && iDb<db->nDb );
+  assert( iDb>=0 && iDb<pParse->db->nDb );
   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
     pExpr->op = TK_NULL;
   }
@@ -110800,11 +111505,7 @@
   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   */
   assert( !IN_RENAME_OBJECT || db->xAuth==0 );
-  if( db->init.busy || IN_SPECIAL_PARSE ){
-    return SQLITE_OK;
-  }
-
-  if( db->xAuth==0 ){
+  if( db->xAuth==0 || db->init.busy || IN_SPECIAL_PARSE ){
     return SQLITE_OK;
   }
 
@@ -111010,10 +111711,36 @@
   /* Begin by generating some termination code at the end of the
   ** vdbe program
   */
-  v = sqlite3GetVdbe(pParse);
+  v = pParse->pVdbe;
+  if( v==0 ){
+    if( db->init.busy ){
+      pParse->rc = SQLITE_DONE;
+      return;
+    }
+    v = sqlite3GetVdbe(pParse);
+    if( v==0 ) pParse->rc = SQLITE_ERROR;
+  }
   assert( !pParse->isMultiWrite
        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   if( v ){
+    if( pParse->bReturning ){
+      Returning *pReturning = pParse->u1.pReturning;
+      int addrRewind;
+      int i;
+      int reg;
+
+      addrRewind =
+         sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
+      VdbeCoverage(v);
+      reg = pReturning->iRetReg;
+      for(i=0; i<pReturning->nRetCol; i++){
+        sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
+      }
+      sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
+      sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
+      VdbeCoverage(v);
+      sqlite3VdbeJumpHere(v, addrRewind);
+    }
     sqlite3VdbeAddOp0(v, OP_Halt);
 
 #if SQLITE_USER_AUTHENTICATION
@@ -111091,12 +111818,16 @@
         }
       }
 
+      if( pParse->bReturning ){
+        Returning *pRet = pParse->u1.pReturning;
+        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
+      }
+
       /* Finally, jump back to the beginning of the executable code. */
       sqlite3VdbeGoto(v, 1);
     }
   }
 
-
   /* Get the VDBE program ready for execution
   */
   if( v && pParse->nErr==0 && !db->mallocFailed ){
@@ -111315,7 +112046,7 @@
 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
   Parse *pParse,
   u32 flags,
-  struct SrcList_item *p
+  SrcItem *p
 ){
   const char *zDb;
   assert( p->pSchema==0 || p->zDatabase==0 );
@@ -112073,7 +112804,8 @@
     }else
 #endif
     {
-      pParse->addrCrTab =
+      assert( !pParse->bReturning );
+      pParse->u1.addrCrTab =
          sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
     }
     sqlite3OpenSchemaTable(pParse, iDb);
@@ -112100,12 +112832,85 @@
 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
   if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
     pCol->colFlags |= COLFLAG_HIDDEN;
+    if( pTab ) pTab->tabFlags |= TF_HasHidden;
   }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
     pTab->tabFlags |= TF_OOOHidden;
   }
 }
 #endif
 
+/*
+** Name of the special TEMP trigger used to implement RETURNING.  The
+** name begins with "sqlite_" so that it is guaranteed not to collide
+** with any application-generated triggers.
+*/
+#define RETURNING_TRIGGER_NAME  "sqlite_returning"
+
+/*
+** Clean up the data structures associated with the RETURNING clause.
+*/
+static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){
+  Hash *pHash;
+  pHash = &(db->aDb[1].pSchema->trigHash);
+  sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, 0);
+  sqlite3ExprListDelete(db, pRet->pReturnEL);
+  sqlite3DbFree(db, pRet);
+}
+
+/*
+** Add the RETURNING clause to the parse currently underway.
+**
+** This routine creates a special TEMP trigger that will fire for each row
+** of the DML statement.  That TEMP trigger contains a single SELECT
+** statement with a result set that is the argument of the RETURNING clause.
+** The trigger has the Trigger.bReturning flag and an opcode of
+** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
+** knows to handle it specially.  The TEMP trigger is automatically
+** removed at the end of the parse.
+**
+** When this routine is called, we do not yet know if the RETURNING clause
+** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
+** RETURNING trigger instead.  It will then be converted into the appropriate
+** type on the first call to sqlite3TriggersExist().
+*/
+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;
+  }
+  pParse->u1.pReturning = pRet;
+  pRet->pParse = pParse;
+  pRet->pReturnEL = pList;
+  sqlite3ParserAddCleanup(pParse,
+     (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet);
+  testcase( pParse->earlyCleanup );
+  if( db->mallocFailed ) return;
+  pRet->retTrig.zName = RETURNING_TRIGGER_NAME;
+  pRet->retTrig.op = TK_RETURNING;
+  pRet->retTrig.tr_tm = TRIGGER_AFTER;
+  pRet->retTrig.bReturning = 1;
+  pRet->retTrig.pSchema = 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);
+  }
+}
 
 /*
 ** Add a new column to the table currently being constructed.
@@ -112122,6 +112927,8 @@
   char *zType;
   Column *pCol;
   sqlite3 *db = pParse->db;
+  u8 hName;
+
   if( (p = pParse->pNewTable)==0 ) return;
   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
@@ -112133,8 +112940,9 @@
   memcpy(z, pName->z, pName->n);
   z[pName->n] = 0;
   sqlite3Dequote(z);
+  hName = sqlite3StrIHash(z);
   for(i=0; i<p->nCol; i++){
-    if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
+    if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zName)==0 ){
       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
       sqlite3DbFree(db, z);
       return;
@@ -112152,7 +112960,7 @@
   pCol = &p->aCol[p->nCol];
   memset(pCol, 0, sizeof(p->aCol[0]));
   pCol->zName = z;
-  pCol->hName = sqlite3StrIHash(z);
+  pCol->hName = hName;
   sqlite3ColumnPropertiesFromName(p, pCol);
 
   if( pType->n==0 ){
@@ -112935,9 +113743,10 @@
   /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
   ** into BTREE_BLOBKEY.
   */
-  if( pParse->addrCrTab ){
+  assert( !pParse->bReturning );
+  if( pParse->u1.addrCrTab ){
     assert( v );
-    sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
+    sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
   }
 
   /* Locate the PRIMARY KEY index.  Or, if this table was originally
@@ -113401,7 +114210,7 @@
 
     /* Reparse everything to update our internal data structures */
     sqlite3VdbeAddParseSchemaOp(v, iDb,
-           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
+           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
   }
 
   /* Add the table to the in-memory representation of the database.
@@ -113418,20 +114227,17 @@
     }
     pParse->pNewTable = 0;
     db->mDbFlags |= DBFLAG_SchemaChange;
+  }
 
 #ifndef SQLITE_OMIT_ALTERTABLE
-    if( !p->pSelect ){
-      const char *zName = (const char *)pParse->sNameToken.z;
-      int nName;
-      assert( !pSelect && pCons && pEnd );
-      if( pCons->z==0 ){
-        pCons = pEnd;
-      }
-      nName = (int)((const char *)pCons->z - zName);
-      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
-    }
-#endif
-  }
+  if( !pSelect && !p->pSelect ){
+    assert( pCons && pEnd );
+    if( pCons->z==0 ){
+      pCons = pEnd;
+    }
+    p->addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
+  }
+#endif
 }
 
 #ifndef SQLITE_OMIT_VIEW
@@ -113622,6 +114428,7 @@
       assert( pTable->aCol==0 );
       pTable->nCol = pSelTab->nCol;
       pTable->aCol = pSelTab->aCol;
+      pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
       pSelTab->nCol = 0;
       pSelTab->aCol = 0;
       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
@@ -114889,7 +115696,7 @@
         sqlite3RefillIndex(pParse, pIndex, iMem);
         sqlite3ChangeCookie(pParse, iDb);
         sqlite3VdbeAddParseSchemaOp(v, iDb,
-            sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
+            sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
         sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
       }
 
@@ -114910,7 +115717,11 @@
   /* Clean up before exiting */
 exit_create_index:
   if( pIndex ) sqlite3FreeIndex(db, pIndex);
-  if( pTab ){  /* Ensure all REPLACE indexes are at the end of the list */
+  if( pTab ){
+    /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
+    ** The list was already ordered when this routine was entered, so at this
+    ** point at most a single index (the newly added index) will be out of
+    ** order.  So we have to reorder at most one index. */
     Index **ppFrom = &pTab->pIndex;
     Index *pThis;
     for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
@@ -114924,6 +115735,16 @@
       }
       break;
     }
+#ifdef SQLITE_DEBUG
+    /* Verify that all REPLACE indexes really are now at the end
+    ** of the index list.  In other words, no other index type ever
+    ** comes after a REPLACE index on the list. */
+    for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
+      assert( pThis->onError!=OE_Replace
+           || pThis->pNext==0
+           || pThis->pNext->onError==OE_Replace );
+    }
+#endif
   }
   sqlite3ExprDelete(db, pPIWhere);
   sqlite3ExprListDelete(db, pList);
@@ -115282,7 +116103,7 @@
   Token *pTable,      /* Table to append */
   Token *pDatabase    /* Database of the table */
 ){
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
   sqlite3 *db;
   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   assert( pParse!=0 );
@@ -115323,7 +116144,7 @@
 */
 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   int i;
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
   assert(pList || pParse->db->mallocFailed );
   if( pList ){
     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
@@ -115341,7 +116162,7 @@
 */
 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   int i;
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
   if( pList==0 ) return;
   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
     if( pItem->zDatabase ) sqlite3DbFreeNN(db, pItem->zDatabase);
@@ -115383,7 +116204,7 @@
   Expr *pOn,              /* The ON clause of a join */
   IdList *pUsing          /* The USING clause of a join */
 ){
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
   sqlite3 *db = pParse->db;
   if( !p && (pOn || pUsing) ){
     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
@@ -115427,7 +116248,7 @@
 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   assert( pIndexedBy!=0 );
   if( p && pIndexedBy->n>0 ){
-    struct SrcList_item *pItem;
+    SrcItem *pItem;
     assert( p->nSrc>0 );
     pItem = &p->a[p->nSrc-1];
     assert( pItem->fg.notIndexed==0 );
@@ -115457,7 +116278,7 @@
       sqlite3SrcListDelete(pParse->db, p2);
     }else{
       p1 = pNew;
-      memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(struct SrcList_item));
+      memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
       sqlite3DbFree(pParse->db, p2);
     }
   }
@@ -115470,7 +116291,7 @@
 */
 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
   if( p ){
-    struct SrcList_item *pItem = &p->a[p->nSrc-1];
+    SrcItem *pItem = &p->a[p->nSrc-1];
     assert( pItem->fg.notIndexed==0 );
     assert( pItem->fg.isIndexedBy==0 );
     assert( pItem->fg.isTabFunc==0 );
@@ -115625,7 +116446,7 @@
 static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
   assert( iDb>=0 && iDb<pToplevel->db->nDb );
   assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
-  assert( iDb<SQLITE_MAX_ATTACHED+2 );
+  assert( iDb<SQLITE_MAX_DB );
   assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
     DbMaskSet(pToplevel->cookieMask, iDb);
@@ -115968,23 +116789,75 @@
 
 #ifndef SQLITE_OMIT_CTE
 /*
+** Create a new CTE object
+*/
+SQLITE_PRIVATE Cte *sqlite3CteNew(
+  Parse *pParse,          /* Parsing context */
+  Token *pName,           /* Name of the common-table */
+  ExprList *pArglist,     /* Optional column name list for the table */
+  Select *pQuery,         /* Query used to initialize the table */
+  u8 eM10d                /* The MATERIALIZED flag */
+){
+  Cte *pNew;
+  sqlite3 *db = pParse->db;
+
+  pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
+  assert( pNew!=0 || db->mallocFailed );
+
+  if( db->mallocFailed ){
+    sqlite3ExprListDelete(db, pArglist);
+    sqlite3SelectDelete(db, pQuery);
+  }else{
+    pNew->pSelect = pQuery;
+    pNew->pCols = pArglist;
+    pNew->zName = sqlite3NameFromToken(pParse->db, pName);
+    pNew->eM10d = eM10d;
+  }
+  return pNew;
+}
+
+/*
+** Clear information from a Cte object, but do not deallocate storage
+** for the object itself.
+*/
+static void cteClear(sqlite3 *db, Cte *pCte){
+  assert( pCte!=0 );
+  sqlite3ExprListDelete(db, pCte->pCols);
+  sqlite3SelectDelete(db, pCte->pSelect);
+  sqlite3DbFree(db, pCte->zName);
+}
+
+/*
+** Free the contents of the CTE object passed as the second argument.
+*/
+SQLITE_PRIVATE void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
+  assert( pCte!=0 );
+  cteClear(db, pCte);
+  sqlite3DbFree(db, pCte);
+}
+
+/*
 ** This routine is invoked once per CTE by the parser while parsing a
-** WITH clause.
+** WITH clause.  The CTE described by teh third argument is added to
+** the WITH clause of the second argument.  If the second argument is
+** NULL, then a new WITH argument is created.
 */
 SQLITE_PRIVATE With *sqlite3WithAdd(
   Parse *pParse,          /* Parsing context */
   With *pWith,            /* Existing WITH clause, or NULL */
-  Token *pName,           /* Name of the common-table */
-  ExprList *pArglist,     /* Optional column name list for the table */
-  Select *pQuery          /* Query used to initialize the table */
+  Cte *pCte               /* CTE to add to the WITH clause */
 ){
   sqlite3 *db = pParse->db;
   With *pNew;
   char *zName;
 
+  if( pCte==0 ){
+    return pWith;
+  }
+
   /* Check that the CTE name is unique within this WITH clause. If
   ** not, store an error in the Parse structure. */
-  zName = sqlite3NameFromToken(pParse->db, pName);
+  zName = pCte->zName;
   if( zName && pWith ){
     int i;
     for(i=0; i<pWith->nCte; i++){
@@ -116003,16 +116876,11 @@
   assert( (pNew!=0 && zName!=0) || db->mallocFailed );
 
   if( db->mallocFailed ){
-    sqlite3ExprListDelete(db, pArglist);
-    sqlite3SelectDelete(db, pQuery);
-    sqlite3DbFree(db, zName);
+    sqlite3CteDelete(db, pCte);
     pNew = pWith;
   }else{
-    pNew->a[pNew->nCte].pSelect = pQuery;
-    pNew->a[pNew->nCte].pCols = pArglist;
-    pNew->a[pNew->nCte].zName = zName;
-    pNew->a[pNew->nCte].zCteErr = 0;
-    pNew->nCte++;
+    pNew->a[pNew->nCte++] = *pCte;
+    sqlite3DbFree(db, pCte);
   }
 
   return pNew;
@@ -116025,10 +116893,7 @@
   if( pWith ){
     int i;
     for(i=0; i<pWith->nCte; i++){
-      struct Cte *pCte = &pWith->a[i];
-      sqlite3ExprListDelete(db, pCte->pCols);
-      sqlite3SelectDelete(db, pCte->pSelect);
-      sqlite3DbFree(db, pCte->zName);
+      cteClear(db, &pWith->a[i]);
     }
     sqlite3DbFree(db, pWith);
   }
@@ -116607,7 +117472,7 @@
 **
 */
 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
-  struct SrcList_item *pItem = pSrc->a;
+  SrcItem *pItem = pSrc->a;
   Table *pTab;
   assert( pItem && pSrc->nSrc>=1 );
   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
@@ -116615,9 +117480,9 @@
   pItem->pTab = pTab;
   if( pTab ){
     pTab->nTabRef++;
-  }
-  if( sqlite3IndexedByLookup(pParse, pItem) ){
-    pTab = 0;
+    if( pItem->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pItem) ){
+      pTab = 0;
+    }
   }
   return pTab;
 }
@@ -116785,9 +117650,15 @@
   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   ** and the SELECT subtree. */
   pSrc->a[0].pTab = 0;
-  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
+  pSelectSrc = sqlite3SrcListDup(db, pSrc, 0);
   pSrc->a[0].pTab = pTab;
-  pSrc->a[0].pIBIndex = 0;
+  if( pSrc->a[0].fg.isIndexedBy ){
+    pSrc->a[0].u2.pIBIndex = 0;
+    pSrc->a[0].fg.isIndexedBy = 0;
+    sqlite3DbFree(db, pSrc->a[0].u1.zIndexedBy);
+  }else if( pSrc->a[0].fg.isCte ){
+    pSrc->a[0].u2.pCteUse->nUse++;
+  }
 
   /* generate the SELECT expression tree. */
   pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
@@ -116965,6 +117836,7 @@
   if( (db->flags & SQLITE_CountRows)!=0
    && !pParse->nested
    && !pParse->pTriggerTab
+   && !pParse->bReturning
   ){
     memCnt = ++pParse->nMem;
     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
@@ -117186,7 +118058,7 @@
   ** invoke the callback function.
   */
   if( memCnt ){
-    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
+    sqlite3VdbeAddOp2(v, OP_ChngCntRow, memCnt, 1);
     sqlite3VdbeSetNumCols(v, 1);
     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   }
@@ -118234,7 +119106,8 @@
       /* Skip over multiple "*" characters in the pattern.  If there
       ** are also "?" characters, skip those as well, but consume a
       ** single character of the input string for each "?" skipped */
-      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
+      while( (c=Utf8Read(zPattern)) == matchAll
+             || (c == matchOne && matchOne!=0) ){
         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
           return SQLITE_NOWILDCARDMATCH;
         }
@@ -119405,7 +120278,9 @@
 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   FuncDef *pDef;
   int nExpr;
-  if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
+  assert( pExpr!=0 );
+  assert( pExpr->op==TK_FUNCTION );
+  if( !pExpr->x.pList ){
     return 0;
   }
   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
@@ -119444,6 +120319,203 @@
   return 1;
 }
 
+/* Mathematical Constants */
+#ifndef M_PI
+# define M_PI   3.141592653589793238462643383279502884
+#endif
+#ifndef M_LN10
+# define M_LN10 2.302585092994045684017991454684364208
+#endif
+#ifndef M_LN2
+# define M_LN2  0.693147180559945309417232121458176568
+#endif
+
+
+/* Extra math functions that require linking with -lm
+*/
+#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
+/*
+** Implementation SQL functions:
+**
+**   ceil(X)
+**   ceiling(X)
+**   floor(X)
+**
+** The sqlite3_user_data() pointer is a pointer to the libm implementation
+** of the underlying C function.
+*/
+static void ceilingFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  assert( argc==1 );
+  switch( sqlite3_value_numeric_type(argv[0]) ){
+    case SQLITE_INTEGER: {
+       sqlite3_result_int64(context, sqlite3_value_int64(argv[0]));
+       break;
+    }
+    case SQLITE_FLOAT: {
+       double (*x)(double) = (double(*)(double))sqlite3_user_data(context);
+       sqlite3_result_double(context, x(sqlite3_value_double(argv[0])));
+       break;
+    }
+    default: {
+       break;
+    }
+  }
+}
+
+/*
+** On some systems, ceil() and floor() are intrinsic function.  You are
+** unable to take a pointer to these functions.  Hence, we here wrap them
+** in our own actual functions.
+*/
+static double xCeil(double x){ return ceil(x); }
+static double xFloor(double x){ return floor(x); }
+
+/*
+** Implementation of SQL functions:
+**
+**   ln(X)       - natural logarithm
+**   log(X)      - log X base 10
+**   log10(X)    - log X base 10
+**   log(B,X)    - log X base B
+*/
+static void logFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  double x, b, ans;
+  assert( argc==1 || argc==2 );
+  switch( sqlite3_value_numeric_type(argv[0]) ){
+    case SQLITE_INTEGER:
+    case SQLITE_FLOAT:
+      x = sqlite3_value_double(argv[0]);
+      if( x<=0.0 ) return;
+      break;
+    default:
+      return;
+  }
+  if( argc==2 ){
+    switch( sqlite3_value_numeric_type(argv[0]) ){
+      case SQLITE_INTEGER:
+      case SQLITE_FLOAT:
+        b = log(x);
+        if( b<=0.0 ) return;
+        x = sqlite3_value_double(argv[1]);
+        if( x<=0.0 ) return;
+        break;
+     default:
+        return;
+    }
+    ans = log(x)/b;
+  }else{
+    ans = log(x);
+    switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context)) ){
+      case 1:
+        /* Convert from natural logarithm to log base 10 */
+        ans *= 1.0/M_LN10;
+        break;
+      case 2:
+        /* Convert from natural logarithm to log base 2 */
+        ans *= 1.0/M_LN2;
+        break;
+      default:
+        break;
+    }
+  }
+  sqlite3_result_double(context, ans);
+}
+
+/*
+** Functions to converts degrees to radians and radians to degrees.
+*/
+static double degToRad(double x){ return x*(M_PI/180.0); }
+static double radToDeg(double x){ return x*(180.0/M_PI); }
+
+/*
+** Implementation of 1-argument SQL math functions:
+**
+**   exp(X)  - Compute e to the X-th power
+*/
+static void math1Func(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  int type0;
+  double v0, ans;
+  double (*x)(double);
+  assert( argc==1 );
+  type0 = sqlite3_value_numeric_type(argv[0]);
+  if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
+  v0 = sqlite3_value_double(argv[0]);
+  x = (double(*)(double))sqlite3_user_data(context);
+  ans = x(v0);
+  sqlite3_result_double(context, ans);
+}
+
+/*
+** Implementation of 2-argument SQL math functions:
+**
+**   power(X,Y)  - Compute X to the Y-th power
+*/
+static void math2Func(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  int type0, type1;
+  double v0, v1, ans;
+  double (*x)(double,double);
+  assert( argc==2 );
+  type0 = sqlite3_value_numeric_type(argv[0]);
+  if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
+  type1 = sqlite3_value_numeric_type(argv[1]);
+  if( type1!=SQLITE_INTEGER && type1!=SQLITE_FLOAT ) return;
+  v0 = sqlite3_value_double(argv[0]);
+  v1 = sqlite3_value_double(argv[1]);
+  x = (double(*)(double,double))sqlite3_user_data(context);
+  ans = x(v0, v1);
+  sqlite3_result_double(context, ans);
+}
+
+/*
+** Implementation of 2-argument SQL math functions:
+**
+**   power(X,Y)  - Compute X to the Y-th power
+*/
+static void piFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  assert( argc==0 );
+  sqlite3_result_double(context, M_PI);
+}
+
+#endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
+
+/*
+** Implementation of sign(X) function.
+*/
+static void signFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  int type0;
+  double x;
+  UNUSED_PARAMETER(argc);
+  assert( argc==1 );
+  type0 = sqlite3_value_numeric_type(argv[0]);
+  if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
+  x = sqlite3_value_double(argv[0]);
+  sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0);
+}
+
 /*
 ** All of the FuncDef structures in the aBuiltinFunc[] array above
 ** to the global function hash table.  This occurs at start-time (as
@@ -119562,6 +120634,43 @@
 #endif
     FUNCTION(coalesce,           1, 0, 0, 0                ),
     FUNCTION(coalesce,           0, 0, 0, 0                ),
+#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
+    MFUNCTION(ceil,              1, xCeil,     ceilingFunc ),
+    MFUNCTION(ceiling,           1, xCeil,     ceilingFunc ),
+    MFUNCTION(floor,             1, xFloor,    ceilingFunc ),
+#if SQLITE_HAVE_C99_MATH_FUNCS
+    MFUNCTION(trunc,             1, trunc,     ceilingFunc ),
+#endif
+    FUNCTION(ln,                 1, 0, 0,      logFunc     ),
+    FUNCTION(log,                1, 1, 0,      logFunc     ),
+    FUNCTION(log10,              1, 1, 0,      logFunc     ),
+    FUNCTION(log2,               1, 2, 0,      logFunc     ),
+    FUNCTION(log,                2, 0, 0,      logFunc     ),
+    MFUNCTION(exp,               1, exp,       math1Func   ),
+    MFUNCTION(pow,               2, pow,       math2Func   ),
+    MFUNCTION(power,             2, pow,       math2Func   ),
+    MFUNCTION(mod,               2, fmod,      math2Func   ),
+    MFUNCTION(acos,              1, acos,      math1Func   ),
+    MFUNCTION(asin,              1, asin,      math1Func   ),
+    MFUNCTION(atan,              1, atan,      math1Func   ),
+    MFUNCTION(atan2,             2, atan2,     math2Func   ),
+    MFUNCTION(cos,               1, cos,       math1Func   ),
+    MFUNCTION(sin,               1, sin,       math1Func   ),
+    MFUNCTION(tan,               1, tan,       math1Func   ),
+    MFUNCTION(cosh,              1, cosh,      math1Func   ),
+    MFUNCTION(sinh,              1, sinh,      math1Func   ),
+    MFUNCTION(tanh,              1, tanh,      math1Func   ),
+#if SQLITE_HAVE_C99_MATH_FUNCS
+    MFUNCTION(acosh,             1, acosh,     math1Func   ),
+    MFUNCTION(asinh,             1, asinh,     math1Func   ),
+    MFUNCTION(atanh,             1, atanh,     math1Func   ),
+#endif
+    MFUNCTION(sqrt,              1, sqrt,      math1Func   ),
+    MFUNCTION(radians,           1, degToRad,  math1Func   ),
+    MFUNCTION(degrees,           1, radToDeg,  math1Func   ),
+    FUNCTION(pi,                 0, 0, 0,      piFunc      ),
+#endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
+    FUNCTION(sign,               1, 0, 0,      signFunc    ),
     INLINE_FUNC(coalesce,       -1, INLINEFUNC_coalesce, 0 ),
     INLINE_FUNC(iif,             3, INLINEFUNC_iif,      0 ),
   };
@@ -120617,7 +121726,7 @@
     ** child table as a SrcList for sqlite3WhereBegin() */
     pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
     if( pSrc ){
-      struct SrcList_item *pItem = pSrc->a;
+      SrcItem *pItem = pSrc->a;
       pItem->pTab = pFKey->pFrom;
       pItem->zName = pFKey->pFrom->zName;
       pItem->pTab->nTabRef++;
@@ -120705,7 +121814,9 @@
 **
 ** For an UPDATE, this function returns 2 if:
 **
-**   * There are any FKs for which pTab is the child and the parent table, or
+**   * There are any FKs for which pTab is the child and the parent table
+**     and any FK processing at all is required (even of a different FK), or
+**
 **   * the UPDATE modifies one or more parent keys for which the action is
 **     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
 **
@@ -120717,13 +121828,14 @@
   int *aChange,                   /* Non-NULL for UPDATE operations */
   int chngRowid                   /* True for UPDATE that affects rowid */
 ){
-  int eRet = 0;
+  int eRet = 1;                   /* Value to return if bHaveFK is true */
+  int bHaveFK = 0;                /* If FK processing is required */
   if( pParse->db->flags&SQLITE_ForeignKeys ){
     if( !aChange ){
       /* A DELETE operation. Foreign key processing is required if the
       ** table in question is either the child or parent table for any
       ** foreign key constraint.  */
-      eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
+      bHaveFK = (sqlite3FkReferences(pTab) || pTab->pFKey);
     }else{
       /* This is an UPDATE. Foreign key processing is only required if the
       ** operation modifies one or more child or parent key columns. */
@@ -120731,9 +121843,9 @@
 
       /* Check if any child key columns are being modified. */
       for(p=pTab->pFKey; p; p=p->pNextFrom){
-        if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
         if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
-          eRet = 1;
+          if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) eRet = 2;
+          bHaveFK = 1;
         }
       }
 
@@ -120741,12 +121853,12 @@
       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
         if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
           if( p->aAction[1]!=OE_None ) return 2;
-          eRet = 1;
-        }
-      }
-    }
-  }
-  return eRet;
+          bHaveFK = 1;
+        }
+      }
+    }
+  }
+  return bHaveFK ? eRet : 0;
 }
 
 /*
@@ -121415,7 +122527,9 @@
     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
     if( pInfo==0 ){
       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
-      if( pInfo==0 ) return 0;
+      sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
+      testcase( pParse->earlyCleanup );
+      if( pParse->db->mallocFailed ) return 0;
       pInfo->pNext = pToplevel->pAinc;
       pToplevel->pAinc = pInfo;
       pInfo->pTab = pTab;
@@ -121973,19 +123087,24 @@
       }
     }
 #endif
-  }
-
-  /* Make sure the number of columns in the source data matches the number
-  ** of columns to be inserted into the table.
-  */
-  for(i=0; i<pTab->nCol; i++){
-    if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
-  }
-  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
-    sqlite3ErrorMsg(pParse,
-       "table %S has %d columns but %d values were supplied",
-       pTabList, 0, pTab->nCol-nHidden, nColumn);
-    goto insert_cleanup;
+
+    /* Make sure the number of columns in the source data matches the number
+    ** of columns to be inserted into the table.
+    */
+    assert( TF_HasHidden==COLFLAG_HIDDEN );
+    assert( TF_HasGenerated==COLFLAG_GENERATED );
+    assert( COLFLAG_NOINSERT==(COLFLAG_GENERATED|COLFLAG_HIDDEN) );
+    if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
+      for(i=0; i<pTab->nCol; i++){
+        if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
+      }
+    }
+    if( nColumn!=(pTab->nCol-nHidden) ){
+      sqlite3ErrorMsg(pParse,
+         "table %S has %d columns but %d values were supplied",
+         pTabList, 0, pTab->nCol-nHidden, nColumn);
+     goto insert_cleanup;
+    }
   }
   if( pColumn!=0 && nColumn!=pColumn->nId ){
     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
@@ -121997,6 +123116,7 @@
   if( (db->flags & SQLITE_CountRows)!=0
    && !pParse->nested
    && !pParse->pTriggerTab
+   && !pParse->bReturning
   ){
     regRowCount = ++pParse->nMem;
     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
@@ -122020,6 +123140,7 @@
   }
 #ifndef SQLITE_OMIT_UPSERT
   if( pUpsert ){
+    Upsert *pNx;
     if( IsVirtual(pTab) ){
       sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
               pTab->zName);
@@ -122033,13 +123154,19 @@
       goto insert_cleanup;
     }
     pTabList->a[0].iCursor = iDataCur;
-    pUpsert->pUpsertSrc = pTabList;
-    pUpsert->regData = regData;
-    pUpsert->iDataCur = iDataCur;
-    pUpsert->iIdxCur = iIdxCur;
-    if( pUpsert->pUpsertTarget ){
-      sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
-    }
+    pNx = pUpsert;
+    do{
+      pNx->pUpsertSrc = pTabList;
+      pNx->regData = regData;
+      pNx->iDataCur = iDataCur;
+      pNx->iIdxCur = iIdxCur;
+      if( pNx->pUpsertTarget ){
+        if( sqlite3UpsertAnalyzeTarget(pParse, pTabList, pNx) ){
+          goto insert_cleanup;
+        }
+      }
+      pNx = pNx->pNextUpsert;
+    }while( pNx!=0 );
   }
 #endif
 
@@ -122180,11 +123307,6 @@
       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
     }
 
-    /* Cannot have triggers on a virtual table. If it were possible,
-    ** this block would have to account for hidden column.
-    */
-    assert( !IsVirtual(pTab) );
-
     /* Copy the new data already generated. */
     assert( pTab->nNVCol>0 );
     sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
@@ -122339,7 +123461,9 @@
     sqlite3VdbeJumpHere(v, addrInsTop);
   }
 
+#ifndef SQLITE_OMIT_XFER_OPT
 insert_end:
+#endif /* SQLITE_OMIT_XFER_OPT */
   /* Update the sqlite_sequence table by storing the content of the
   ** maximum rowid counter values recorded while inserting into
   ** autoincrement tables.
@@ -122354,7 +123478,7 @@
   ** invoke the callback function.
   */
   if( regRowCount ){
-    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
+    sqlite3VdbeAddOp2(v, OP_ChngCntRow, regRowCount, 1);
     sqlite3VdbeSetNumCols(v, 1);
     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   }
@@ -122445,6 +123569,70 @@
 }
 
 /*
+** The sqlite3GenerateConstraintChecks() routine usually wants to visit
+** the indexes of a table in the order provided in the Table->pIndex list.
+** However, sometimes (rarely - when there is an upsert) it wants to visit
+** the indexes in a different order.  The following data structures accomplish
+** this.
+**
+** The IndexIterator object is used to walk through all of the indexes
+** of a table in either Index.pNext order, or in some other order established
+** by an array of IndexListTerm objects.
+*/
+typedef struct IndexListTerm IndexListTerm;
+typedef struct IndexIterator IndexIterator;
+struct IndexIterator {
+  int eType;    /* 0 for Index.pNext list.  1 for an array of IndexListTerm */
+  int i;        /* Index of the current item from the list */
+  union {
+    struct {    /* Use this object for eType==0: A Index.pNext list */
+      Index *pIdx;   /* The current Index */
+    } lx;
+    struct {    /* Use this object for eType==1; Array of IndexListTerm */
+      int nIdx;               /* Size of the array */
+      IndexListTerm *aIdx;    /* Array of IndexListTerms */
+    } ax;
+  } u;
+};
+
+/* When IndexIterator.eType==1, then each index is an array of instances
+** of the following object
+*/
+struct IndexListTerm {
+  Index *p;  /* The index */
+  int ix;    /* Which entry in the original Table.pIndex list is this index*/
+};
+
+/* Return the first index on the list */
+static Index *indexIteratorFirst(IndexIterator *pIter, int *pIx){
+  assert( pIter->i==0 );
+  if( pIter->eType ){
+    *pIx = pIter->u.ax.aIdx[0].ix;
+    return pIter->u.ax.aIdx[0].p;
+  }else{
+    *pIx = 0;
+    return pIter->u.lx.pIdx;
+  }
+}
+
+/* Return the next index from the list.  Return NULL when out of indexes */
+static Index *indexIteratorNext(IndexIterator *pIter, int *pIx){
+  if( pIter->eType ){
+    int i = ++pIter->i;
+    if( i>=pIter->u.ax.nIdx ){
+      *pIx = i;
+      return 0;
+    }
+    *pIx = pIter->u.ax.aIdx[i].ix;
+    return pIter->u.ax.aIdx[i].p;
+  }else{
+    ++(*pIx);
+    pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
+    return pIter->u.lx.pIdx;
+  }
+}
+
+/*
 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
 ** on table pTab.
 **
@@ -122552,7 +123740,7 @@
 ){
   Vdbe *v;             /* VDBE under constrution */
   Index *pIdx;         /* Pointer to one of the indices */
-  Index *pPk = 0;      /* The PRIMARY KEY index */
+  Index *pPk = 0;      /* The PRIMARY KEY index for WITHOUT ROWID tables */
   sqlite3 *db;         /* Database connection */
   int i;               /* loop counter */
   int ix;              /* Index loop counter */
@@ -122560,11 +123748,11 @@
   int onError;         /* Conflict resolution strategy */
   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
-  Index *pUpIdx = 0;   /* Index to which to apply the upsert */
-  u8 isUpdate;         /* True if this is an UPDATE operation */
+  Upsert *pUpsertClause = 0;  /* The specific ON CONFLICT clause for pIdx */
+  u8 isUpdate;           /* True if this is an UPDATE operation */
   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
-  int upsertBypass = 0;  /* Address of Goto to bypass upsert subroutine */
-  int upsertJump = 0;    /* Address of Goto that jumps into upsert subroutine */
+  int upsertIpkReturn = 0; /* Address of Goto at end of IPK uniqueness check */
+  int upsertIpkDelay = 0;  /* Address of Goto to bypass initial IPK check */
   int ipkTop = 0;        /* Top of the IPK uniqueness check */
   int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
   /* Variables associated with retesting uniqueness constraints after
@@ -122574,6 +123762,7 @@
   int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
   Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */
   int nReplaceTrig = 0; /* Number of replace triggers coded */
+  IndexIterator sIdxIter;  /* Index iterator */
 
   isUpdate = regOldData!=0;
   db = pParse->db;
@@ -122771,19 +123960,63 @@
   ** list of indexes attached to a table puts all OE_Replace indexes last
   ** in the list.  See sqlite3CreateIndex() for where that happens.
   */
-
+  sIdxIter.eType = 0;
+  sIdxIter.i = 0;
+  sIdxIter.u.ax.aIdx = 0;  /* Silence harmless compiler warning */
+  sIdxIter.u.lx.pIdx = pTab->pIndex;
   if( pUpsert ){
     if( pUpsert->pUpsertTarget==0 ){
-      /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
-      ** Make all unique constraint resolution be OE_Ignore */
-      assert( pUpsert->pUpsertSet==0 );
-      overrideError = OE_Ignore;
-      pUpsert = 0;
-    }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
-      /* If the constraint-target uniqueness check must be run first.
-      ** Jump to that uniqueness check now */
-      upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
-      VdbeComment((v, "UPSERT constraint goes first"));
+      /* There is just on ON CONFLICT clause and it has no constraint-target */
+      assert( pUpsert->pNextUpsert==0 );
+      if( pUpsert->isDoUpdate==0 ){
+        /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
+        ** Make all unique constraint resolution be OE_Ignore */
+        overrideError = OE_Ignore;
+        pUpsert = 0;
+      }else{
+        /* A single ON CONFLICT DO UPDATE.  Make all resolutions OE_Update */
+        overrideError = OE_Update;
+      }
+    }else if( pTab->pIndex!=0 ){
+      /* Otherwise, we'll need to run the IndexListTerm array version of the
+      ** iterator to ensure that all of the ON CONFLICT conditions are
+      ** checked first and in order. */
+      int nIdx, jj;
+      u64 nByte;
+      Upsert *pTerm;
+      u8 *bUsed;
+      for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
+         assert( aRegIdx[nIdx]>0 );
+      }
+      sIdxIter.eType = 1;
+      sIdxIter.u.ax.nIdx = nIdx;
+      nByte = (sizeof(IndexListTerm)+1)*nIdx + nIdx;
+      sIdxIter.u.ax.aIdx = sqlite3DbMallocZero(db, nByte);
+      if( sIdxIter.u.ax.aIdx==0 ) return; /* OOM */
+      bUsed = (u8*)&sIdxIter.u.ax.aIdx[nIdx];
+      pUpsert->pToFree = sIdxIter.u.ax.aIdx;
+      for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
+        if( pTerm->pUpsertTarget==0 ) break;
+        if( pTerm->pUpsertIdx==0 ) continue;  /* Skip ON CONFLICT for the IPK */
+        jj = 0;
+        pIdx = pTab->pIndex;
+        while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
+           pIdx = pIdx->pNext;
+           jj++;
+        }
+        if( bUsed[jj] ) continue; /* Duplicate ON CONFLICT clause ignored */
+        bUsed[jj] = 1;
+        sIdxIter.u.ax.aIdx[i].p = pIdx;
+        sIdxIter.u.ax.aIdx[i].ix = jj;
+        i++;
+      }
+      for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
+        if( bUsed[jj] ) continue;
+        sIdxIter.u.ax.aIdx[i].p = pIdx;
+        sIdxIter.u.ax.aIdx[i].ix = jj;
+        i++;
+      }
+      assert( i==nIdx );
     }
   }
 
@@ -122846,11 +124079,20 @@
     }
 
     /* figure out whether or not upsert applies in this case */
-    if( pUpsert && pUpsert->pUpsertIdx==0 ){
-      if( pUpsert->pUpsertSet==0 ){
-        onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
-      }else{
-        onError = OE_Update;  /* DO UPDATE */
+    if( pUpsert ){
+      pUpsertClause = sqlite3UpsertOfIndex(pUpsert,0);
+      if( pUpsertClause!=0 ){
+        if( pUpsertClause->isDoUpdate==0 ){
+          onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
+        }else{
+          onError = OE_Update;  /* DO UPDATE */
+        }
+      }
+      if( pUpsertClause!=pUpsert ){
+        /* The first ON CONFLICT clause has a conflict target other than
+        ** the IPK.  We have to jump ahead to that first ON CONFLICT clause
+        ** and then come back here and deal with the IPK afterwards */
+        upsertIpkDelay = sqlite3VdbeAddOp0(v, OP_Goto);
       }
     }
 
@@ -122860,7 +124102,7 @@
     ** the UNIQUE constraints have run.
     */
     if( onError==OE_Replace      /* IPK rule is REPLACE */
-     && onError!=overrideError   /* Rules for other contraints are different */
+     && onError!=overrideError   /* Rules for other constraints are different */
      && pTab->pIndex             /* There exist other constraints */
     ){
       ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
@@ -122957,7 +124199,9 @@
       }
     }
     sqlite3VdbeResolveLabel(v, addrRowidOk);
-    if( ipkTop ){
+    if( pUpsert && pUpsertClause!=pUpsert ){
+      upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
+    }else if( ipkTop ){
       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
       sqlite3VdbeJumpHere(v, ipkTop-1);
     }
@@ -122970,7 +124214,10 @@
   ** This loop also handles the case of the PRIMARY KEY index for a
   ** WITHOUT ROWID table.
   */
-  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
+  for(pIdx = indexIteratorFirst(&sIdxIter, &ix);
+      pIdx;
+      pIdx = indexIteratorNext(&sIdxIter, &ix)
+  ){
     int regIdx;          /* Range of registers hold conent for pIdx */
     int regR;            /* Range of registers holding conflicting PK */
     int iThisCur;        /* Cursor for this UNIQUE index */
@@ -122978,15 +124225,14 @@
     int addrConflictCk;  /* First opcode in the conflict check logic */
 
     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
-    if( pUpIdx==pIdx ){
-      addrUniqueOk = upsertJump+1;
-      upsertBypass = sqlite3VdbeGoto(v, 0);
-      VdbeComment((v, "Skip upsert subroutine"));
-      sqlite3VdbeJumpHere(v, upsertJump);
-    }else{
-      addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
-    }
-    if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
+    if( pUpsert ){
+      pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
+      if( upsertIpkDelay && pUpsertClause==pUpsert ){
+        sqlite3VdbeJumpHere(v, upsertIpkDelay);
+      }
+    }
+    addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
+    if( bAffinityDone==0 ){
       sqlite3TableAffinity(v, pTab, regNewData+1);
       bAffinityDone = 1;
     }
@@ -123057,8 +124303,8 @@
     }
 
     /* Figure out if the upsert clause applies to this index */
-    if( pUpIdx==pIdx ){
-      if( pUpsert->pUpsertSet==0 ){
+    if( pUpsertClause ){
+      if( pUpsertClause->isDoUpdate==0 ){
         onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
       }else{
         onError = OE_Update;  /* DO UPDATE */
@@ -123096,7 +124342,7 @@
                            regIdx, pIdx->nKeyCol); VdbeCoverage(v);
 
     /* Generate code to handle collisions */
-    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
+    regR = pIdx==pPk ? regIdx : sqlite3GetTempRange(pParse, nPkField);
     if( isUpdate || onError==OE_Replace ){
       if( HasRowid(pTab) ){
         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
@@ -123248,13 +124494,16 @@
         break;
       }
     }
-    if( pUpIdx==pIdx ){
-      sqlite3VdbeGoto(v, upsertJump+1);
-      sqlite3VdbeJumpHere(v, upsertBypass);
-    }else{
-      sqlite3VdbeResolveLabel(v, addrUniqueOk);
-    }
+    sqlite3VdbeResolveLabel(v, addrUniqueOk);
     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
+    if( pUpsertClause
+     && upsertIpkReturn
+     && sqlite3UpsertNextIsIPK(pUpsertClause)
+    ){
+      sqlite3VdbeGoto(v, upsertIpkDelay+1);
+      sqlite3VdbeJumpHere(v, upsertIpkReturn);
+      upsertIpkReturn = 0;
+    }
   }
 
   /* If the IPK constraint is a REPLACE, run it last */
@@ -123321,6 +124570,32 @@
 #endif
 
 /*
+** Table pTab is a WITHOUT ROWID table that is being written to. The cursor
+** number is iCur, and register regData contains the new record for the
+** PK index. This function adds code to invoke the pre-update hook,
+** if one is registered.
+*/
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+static void codeWithoutRowidPreupdate(
+  Parse *pParse,                  /* Parse context */
+  Table *pTab,                    /* Table being updated */
+  int iCur,                       /* Cursor number for table */
+  int regData                     /* Data containing new record */
+){
+  Vdbe *v = pParse->pVdbe;
+  int r = sqlite3GetTempReg(pParse);
+  assert( !HasRowid(pTab) );
+  assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
+  sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
+  sqlite3VdbeAddOp4(v, OP_Insert, iCur, regData, r, (char*)pTab, P4_TABLE);
+  sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
+  sqlite3ReleaseTempReg(pParse, r);
+}
+#else
+# define codeWithoutRowidPreupdate(a,b,c,d)
+#endif
+
+/*
 ** This routine generates code to finish the INSERT or UPDATE operation
 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
 ** A consecutive range of registers starting at regNewData contains the
@@ -123368,17 +124643,9 @@
       assert( pParse->nested==0 );
       pik_flags |= OPFLAG_NCHANGE;
       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
-#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
       if( update_flags==0 ){
-        int r = sqlite3GetTempReg(pParse);
-        sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
-        sqlite3VdbeAddOp4(v, OP_Insert,
-            iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
-        );
-        sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
-        sqlite3ReleaseTempReg(pParse, r);
-      }
-#endif
+        codeWithoutRowidPreupdate(pParse, pTab, iIdxCur+i, aRegIdx[i]);
+      }
     }
     sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
                          aRegIdx[i]+1,
@@ -123576,7 +124843,7 @@
   ExprList *pEList;                /* The result set of the SELECT */
   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
-  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
+  SrcItem *pItem;                  /* An element of pSelect->pSrc */
   int i;                           /* Loop counter */
   int iDbSrc;                      /* The database of pSrc */
   int iSrc, iDest;                 /* Cursors from source and destination */
@@ -123793,6 +125060,7 @@
   iDest = pParse->nTab++;
   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   regData = sqlite3GetTempReg(pParse);
+  sqlite3VdbeAddOp2(v, OP_Null, 0, regData);
   regRowid = sqlite3GetTempReg(pParse);
   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   assert( HasRowid(pDest) || destHasUniqueIdx );
@@ -123828,11 +125096,13 @@
     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
     if( pDest->iPKey>=0 ){
       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
-      sqlite3VdbeVerifyAbortable(v, onError);
-      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
-      VdbeCoverage(v);
-      sqlite3RowidConstraint(pParse, onError, pDest);
-      sqlite3VdbeJumpHere(v, addr2);
+      if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
+        sqlite3VdbeVerifyAbortable(v, onError);
+        addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
+        VdbeCoverage(v);
+        sqlite3RowidConstraint(pParse, onError, pDest);
+        sqlite3VdbeJumpHere(v, addr2);
+      }
       autoIncStep(pParse, regAutoinc, regRowid);
     }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
@@ -123840,16 +125110,28 @@
       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
     }
+
     if( db->mDbFlags & DBFLAG_Vacuum ){
       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
-      insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
-    }else{
-      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
-    }
-    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
-    sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
-                      (char*)pDest, P4_TABLE);
+      insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
+    }else{
+      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND|OPFLAG_PREFORMAT;
+    }
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+    if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
+      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
+      insFlags &= ~OPFLAG_PREFORMAT;
+    }else
+#endif
+    {
+      sqlite3VdbeAddOp3(v, OP_RowCell, iDest, iSrc, regRowid);
+    }
+    sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
+    if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
+      sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
+    }
     sqlite3VdbeChangeP5(v, insFlags);
+
     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
@@ -123891,13 +125173,22 @@
         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
       }
       if( i==pSrcIdx->nColumn ){
-        idxInsFlags = OPFLAG_USESEEKRESULT;
+        idxInsFlags = OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT;
         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
+        sqlite3VdbeAddOp2(v, OP_RowCell, iDest, iSrc);
       }
     }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
       idxInsFlags |= OPFLAG_NCHANGE;
     }
-    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
+    if( idxInsFlags!=(OPFLAG_USESEEKRESULT|OPFLAG_PREFORMAT) ){
+      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
+      if( (db->mDbFlags & DBFLAG_Vacuum)==0
+       && !HasRowid(pDest)
+       && IsPrimaryKeyIndex(pDestIdx)
+      ){
+        codeWithoutRowidPreupdate(pParse, pDest, iDest, regData);
+      }
+    }
     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
@@ -128213,7 +129504,7 @@
   ** Checkpoint the database.
   */
   case PragTyp_WAL_CHECKPOINT: {
-    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
+    int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
     int eMode = SQLITE_CHECKPOINT_PASSIVE;
     if( zRight ){
       if( sqlite3StrICmp(zRight, "full")==0 ){
@@ -128861,7 +130152,7 @@
 */
 static void corruptSchema(
   InitData *pData,     /* Initialization context */
-  const char *zObj,    /* Object being parsed at the point of error */
+  char **azObj,        /* Type and name of object being parsed */
   const char *zExtra   /* Error information */
 ){
   sqlite3 *db = pData->db;
@@ -128869,14 +130160,18 @@
     pData->rc = SQLITE_NOMEM_BKPT;
   }else if( pData->pzErrMsg[0]!=0 ){
     /* A error message has already been generated.  Do not overwrite it */
-  }else if( pData->mInitFlags & INITFLAG_AlterTable ){
-    *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
+  }else if( pData->mInitFlags & (INITFLAG_AlterRename|INITFLAG_AlterDrop) ){
+    *pData->pzErrMsg = sqlite3MPrintf(db,
+        "error in %s %s after %s: %s", azObj[0], azObj[1],
+        (pData->mInitFlags & INITFLAG_AlterRename) ? "rename" : "drop column",
+        zExtra
+    );
     pData->rc = SQLITE_ERROR;
   }else if( db->flags & SQLITE_WriteSchema ){
     pData->rc = SQLITE_CORRUPT_BKPT;
   }else{
     char *z;
-    if( zObj==0 ) zObj = "?";
+    const char *zObj = azObj[1] ? azObj[1] : "?";
     z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
     if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
     *pData->pzErrMsg = z;
@@ -128934,19 +130229,26 @@
   db->mDbFlags |= DBFLAG_EncodingFixed;
   pData->nInitRow++;
   if( db->mallocFailed ){
-    corruptSchema(pData, argv[1], 0);
+    corruptSchema(pData, argv, 0);
     return 1;
   }
 
   assert( iDb>=0 && iDb<db->nDb );
   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   if( argv[3]==0 ){
-    corruptSchema(pData, argv[1], 0);
-  }else if( sqlite3_strnicmp(argv[4],"create ",7)==0 ){
+    corruptSchema(pData, argv, 0);
+  }else if( argv[4]
+         && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
+         && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
     ** But because db->init.busy is set to 1, no VDBE code is generated
     ** or executed.  All the parser does is build the internal data
     ** structures that describe the table, index, or view.
+    **
+    ** No other valid SQL statement, other than the variable CREATE statements,
+    ** can begin with the letters "C" and "R".  Thus, it is not possible run
+    ** any other kind of statement while parsing the schema, even a corrupt
+    ** schema.
     */
     int rc;
     u8 saved_iDb = db->init.iDb;
@@ -128959,7 +130261,7 @@
      || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
     ){
       if( sqlite3Config.bExtraSchemaChecks ){
-        corruptSchema(pData, argv[1], "invalid rootpage");
+        corruptSchema(pData, argv, "invalid rootpage");
       }
     }
     db->init.orphanTrigger = 0;
@@ -128978,13 +130280,13 @@
         if( rc==SQLITE_NOMEM ){
           sqlite3OomFault(db);
         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
-          corruptSchema(pData, argv[1], sqlite3_errmsg(db));
+          corruptSchema(pData, argv, sqlite3_errmsg(db));
         }
       }
     }
     sqlite3_finalize(pStmt);
   }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
-    corruptSchema(pData, argv[1], 0);
+    corruptSchema(pData, argv, 0);
   }else{
     /* If the SQL column is blank it means this is an index that
     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
@@ -128995,7 +130297,7 @@
     Index *pIndex;
     pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
     if( pIndex==0 ){
-      corruptSchema(pData, argv[1], "orphan index");
+      corruptSchema(pData, argv, "orphan index");
     }else
     if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
      || pIndex->tnum<2
@@ -129003,7 +130305,7 @@
      || sqlite3IndexHasDuplicateRootPage(pIndex)
     ){
       if( sqlite3Config.bExtraSchemaChecks ){
-        corruptSchema(pData, argv[1], "invalid rootpage");
+        corruptSchema(pData, argv, "invalid rootpage");
       }
     }
   }
@@ -129384,27 +130686,20 @@
 }
 
 /*
-** Deallocate a single AggInfo object
-*/
-static void agginfoFree(sqlite3 *db, AggInfo *p){
-  sqlite3DbFree(db, p->aCol);
-  sqlite3DbFree(db, p->aFunc);
-  sqlite3DbFree(db, p);
-}
-
-/*
 ** Free all memory allocations in the pParse object
 */
 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
   sqlite3 *db = pParse->db;
-  AggInfo *pThis = pParse->pAggList;
-  while( pThis ){
-    AggInfo *pNext = pThis->pNext;
-    agginfoFree(db, pThis);
-    pThis = pNext;
+  while( pParse->pCleanup ){
+    ParseCleanup *pCleanup = pParse->pCleanup;
+    pParse->pCleanup = pCleanup->pNext;
+    pCleanup->xCleanup(db, pCleanup->pPtr);
+    sqlite3DbFreeNN(db, pCleanup);
   }
   sqlite3DbFree(db, pParse->aLabel);
-  sqlite3ExprListDelete(db, pParse->pConstExpr);
+  if( pParse->pConstExpr ){
+    sqlite3ExprListDelete(db, pParse->pConstExpr);
+  }
   if( db ){
     assert( db->lookaside.bDisable >= pParse->disableLookaside );
     db->lookaside.bDisable -= pParse->disableLookaside;
@@ -129414,6 +130709,55 @@
 }
 
 /*
+** Add a new cleanup operation to a Parser.  The cleanup should happen when
+** the parser object is destroyed.  But, beware: the cleanup might happen
+** immediately.
+**
+** Use this mechanism for uncommon cleanups.  There is a higher setup
+** cost for this mechansim (an extra malloc), so it should not be used
+** for common cleanups that happen on most calls.  But for less
+** common cleanups, we save a single NULL-pointer comparison in
+** sqlite3ParserReset(), which reduces the total CPU cycle count.
+**
+** If a memory allocation error occurs, then the cleanup happens immediately.
+** When either SQLITE_DEBUG or SQLITE_COVERAGE_TEST are defined, the
+** pParse->earlyCleanup flag is set in that case.  Calling code show verify
+** that test cases exist for which this happens, to guard against possible
+** use-after-free errors following an OOM.  The preferred way to do this is
+** to immediately follow the call to this routine with:
+**
+**       testcase( pParse->earlyCleanup );
+**
+** This routine returns a copy of its pPtr input (the third parameter)
+** except if an early cleanup occurs, in which case it returns NULL.  So
+** another way to check for early cleanup is to check the return value.
+** Or, stop using the pPtr parameter with this call and use only its
+** return value thereafter.  Something like this:
+**
+**       pObj = sqlite3ParserAddCleanup(pParse, destructor, pObj);
+*/
+SQLITE_PRIVATE void *sqlite3ParserAddCleanup(
+  Parse *pParse,                      /* Destroy when this Parser finishes */
+  void (*xCleanup)(sqlite3*,void*),   /* The cleanup routine */
+  void *pPtr                          /* Pointer to object to be cleaned up */
+){
+  ParseCleanup *pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
+  if( pCleanup ){
+    pCleanup->pNext = pParse->pCleanup;
+    pParse->pCleanup = pCleanup;
+    pCleanup->pPtr = pPtr;
+    pCleanup->xCleanup = xCleanup;
+  }else{
+    xCleanup(pParse->db, pPtr);
+    pPtr = 0;
+#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
+    pParse->earlyCleanup = 1;
+#endif
+  }
+  return pPtr;
+}
+
+/*
 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
 */
 static int sqlite3Prepare(
@@ -129511,12 +130855,6 @@
   }
   assert( 0==sParse.nQueryLoop );
 
-  if( sParse.rc==SQLITE_DONE ){
-    sParse.rc = SQLITE_OK;
-  }
-  if( sParse.checkSchema ){
-    schemaIsValid(&sParse);
-  }
   if( pzTail ){
     *pzTail = sParse.zTail;
   }
@@ -129527,20 +130865,28 @@
   if( db->mallocFailed ){
     sParse.rc = SQLITE_NOMEM_BKPT;
   }
-  rc = sParse.rc;
-  if( rc!=SQLITE_OK ){
-    if( sParse.pVdbe ) sqlite3VdbeFinalize(sParse.pVdbe);
-    assert(!(*ppStmt));
-  }else{
+  if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){
+    if( sParse.checkSchema ){
+      schemaIsValid(&sParse);
+    }
+    if( sParse.pVdbe ){
+      sqlite3VdbeFinalize(sParse.pVdbe);
+    }
+    assert( 0==(*ppStmt) );
+    rc = sParse.rc;
+    if( zErrMsg ){
+      sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
+      sqlite3DbFree(db, zErrMsg);
+    }else{
+      sqlite3Error(db, rc);
+    }
+  }else{
+    assert( zErrMsg==0 );
     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
-  }
-
-  if( zErrMsg ){
-    sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
-    sqlite3DbFree(db, zErrMsg);
-  }else{
-    sqlite3Error(db, rc);
-  }
+    rc = SQLITE_OK;
+    sqlite3ErrorClear(db);
+  }
+
 
   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   while( sParse.pTriggerPrg ){
@@ -129886,12 +131232,16 @@
     sqlite3ExprDelete(db, p->pHaving);
     sqlite3ExprListDelete(db, p->pOrderBy);
     sqlite3ExprDelete(db, p->pLimit);
+    if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
 #ifndef SQLITE_OMIT_WINDOWFUNC
     if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
       sqlite3WindowListDelete(db, p->pWinDefn);
     }
-#endif
-    if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
+    while( p->pWin ){
+      assert( p->pWin->ppThis==&p->pWin );
+      sqlite3WindowUnlinkFromSelect(p->pWin);
+    }
+#endif
     if( bFree ) sqlite3DbFreeNN(db, p);
     p = pPrior;
     bFree = 1;
@@ -130063,7 +131413,7 @@
 ** Return the index of a column in a table.  Return -1 if the column
 ** is not contained in the table.
 */
-static int columnIndex(Table *pTab, const char *zCol){
+SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol){
   int i;
   u8 h = sqlite3StrIHash(zCol);
   Column *pCol;
@@ -130095,7 +131445,7 @@
 
   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   for(i=0; i<N; i++){
-    iCol = columnIndex(pSrc->a[i].pTab, zCol);
+    iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol);
     if( iCol>=0
      && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
     ){
@@ -130148,7 +131498,7 @@
     ExprSetProperty(pEq, EP_FromJoin);
     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
     ExprSetVVAProperty(pEq, EP_NoReduce);
-    pEq->iRightJoinTable = (i16)pE2->iTable;
+    pEq->iRightJoinTable = pE2->iTable;
   }
   *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
 }
@@ -130184,7 +131534,7 @@
     ExprSetProperty(p, EP_FromJoin);
     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
     ExprSetVVAProperty(p, EP_NoReduce);
-    p->iRightJoinTable = (i16)iTable;
+    p->iRightJoinTable = iTable;
     if( p->op==TK_FUNCTION && p->x.pList ){
       int i;
       for(i=0; i<p->x.pList->nExpr; i++){
@@ -130208,6 +131558,9 @@
      && (iTable<0 || p->iRightJoinTable==iTable) ){
       ExprClearProperty(p, EP_FromJoin);
     }
+    if( p->op==TK_COLUMN && p->iTable==iTable ){
+      ExprClearProperty(p, EP_CanBeNull);
+    }
     if( p->op==TK_FUNCTION && p->x.pList ){
       int i;
       for(i=0; i<p->x.pList->nExpr; i++){
@@ -130236,8 +131589,8 @@
 static int sqliteProcessJoin(Parse *pParse, Select *p){
   SrcList *pSrc;                  /* All tables in the FROM clause */
   int i, j;                       /* Loop counters */
-  struct SrcList_item *pLeft;     /* Left table being joined */
-  struct SrcList_item *pRight;    /* Right table being joined */
+  SrcItem *pLeft;                 /* Left table being joined */
+  SrcItem *pRight;                /* Right table being joined */
 
   pSrc = p->pSrc;
   pLeft = &pSrc->a[0];
@@ -130305,7 +131658,7 @@
         int iRightCol;   /* Column number of matching column on the right */
 
         zName = pList->a[j].zName;
-        iRightCol = columnIndex(pRightTab, zName);
+        iRightCol = sqlite3ColumnIndex(pRightTab, zName);
         if( iRightCol<0
          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0)
         ){
@@ -131184,7 +132537,7 @@
 /*
 ** Name of the connection operator, used for error messages.
 */
-static const char *selectOpName(int id){
+SQLITE_PRIVATE const char *sqlite3SelectOpName(int id){
   char *z;
   switch( id ){
     case TK_ALL:       z = "UNION ALL";   break;
@@ -131780,7 +133133,7 @@
     nCol = pEList->nExpr;
     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
     testcase( aCol==0 );
-    if( nCol>32767 ) nCol = 32767;
+    if( NEVER(nCol>32767) ) nCol = 32767;
   }else{
     nCol = 0;
     aCol = 0;
@@ -131887,6 +133240,7 @@
   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
     const char *zType;
     int n, m;
+    pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
     p = a[i].pExpr;
     zType = columnType(&sNC, p, 0, 0, 0);
     /* pCol->szEst = ... // Column size est for SELECT tables never used */
@@ -132402,12 +133756,8 @@
   db = pParse->db;
   pPrior = p->pPrior;
   dest = *pDest;
-  if( pPrior->pOrderBy || pPrior->pLimit ){
-    sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
-      pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
-    rc = 1;
-    goto multi_select_end;
-  }
+  assert( pPrior->pOrderBy==0 );
+  assert( pPrior->pLimit==0 );
 
   v = sqlite3GetVdbe(pParse);
   assert( v!=0 );  /* The VDBE already created by calling function */
@@ -132464,7 +133814,7 @@
         pPrior->iOffset = p->iOffset;
         pPrior->pLimit = p->pLimit;
         rc = sqlite3Select(pParse, pPrior, &dest);
-        p->pLimit = 0;
+        pPrior->pLimit = 0;
         if( rc ){
           goto multi_select_end;
         }
@@ -132485,8 +133835,8 @@
         pDelete = p->pPrior;
         p->pPrior = pPrior;
         p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
-        if( pPrior->pLimit
-         && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
+        if( p->pLimit
+         && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
          && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
         ){
           p->nSelectRow = sqlite3LogEst((u64)nLimit);
@@ -132550,7 +133900,7 @@
         p->pLimit = 0;
         uniondest.eDest = op;
         ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
-                          selectOpName(p->op)));
+                          sqlite3SelectOpName(p->op)));
         rc = sqlite3Select(pParse, p, &uniondest);
         testcase( rc!=SQLITE_OK );
         assert( p->pOrderBy==0 );
@@ -132626,7 +133976,7 @@
         p->pLimit = 0;
         intersectdest.iSDParm = tab2;
         ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
-                          selectOpName(p->op)));
+                          sqlite3SelectOpName(p->op)));
         rc = sqlite3Select(pParse, p, &intersectdest);
         testcase( rc!=SQLITE_OK );
         pDelete = p->pPrior;
@@ -132735,7 +134085,8 @@
     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
   }else{
     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
-      " do not have the same number of result columns", selectOpName(p->op));
+      " do not have the same number of result columns",
+      sqlite3SelectOpName(p->op));
   }
 }
 
@@ -132832,10 +134183,8 @@
     ** if it is the RHS of a row-value IN operator.
     */
     case SRT_Mem: {
-      if( pParse->nErr==0 ){
-        testcase( pIn->nSdst>1 );
-        sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
-      }
+      testcase( pIn->nSdst>1 );
+      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
       /* The LIMIT clause will jump out of the loop for us */
       break;
     }
@@ -133127,7 +134476,7 @@
   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
 
-  ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
+  ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
 
   /* Generate a coroutine to evaluate the SELECT statement to the
   ** left of the compound operator - the "A" select.
@@ -133397,7 +134746,7 @@
   int doPrior           /* Do substitutes on p->pPrior too */
 ){
   SrcList *pSrc;
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
   int i;
   if( !p ) return;
   do{
@@ -133427,7 +134776,7 @@
 ** pSrcItem->colUsed mask.
 */
 static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
   if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
   pItem = pWalker->u.pSrcItem;
   if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
@@ -133437,7 +134786,7 @@
 }
 static void recomputeColumnsUsed(
   Select *pSelect,                 /* The complete SELECT statement */
-  struct SrcList_item *pSrcItem    /* Which FROM clause item to recompute */
+  SrcItem *pSrcItem                /* Which FROM clause item to recompute */
 ){
   Walker w;
   if( NEVER(pSrcItem->pTab==0) ) return;
@@ -133452,6 +134801,89 @@
 
 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
 /*
+** Assign new cursor numbers to each of the items in pSrc. For each
+** new cursor number assigned, set an entry in the aCsrMap[] array
+** to map the old cursor number to the new:
+**
+**     aCsrMap[iOld] = iNew;
+**
+** The array is guaranteed by the caller to be large enough for all
+** existing cursor numbers in pSrc.
+**
+** If pSrc contains any sub-selects, call this routine recursively
+** on the FROM clause of each such sub-select, with iExcept set to -1.
+*/
+static void srclistRenumberCursors(
+  Parse *pParse,                  /* Parse context */
+  int *aCsrMap,                   /* Array to store cursor mappings in */
+  SrcList *pSrc,                  /* FROM clause to renumber */
+  int iExcept                     /* FROM clause item to skip */
+){
+  int i;
+  SrcItem *pItem;
+  for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
+    if( i!=iExcept ){
+      Select *p;
+      pItem->iCursor = aCsrMap[pItem->iCursor] = pParse->nTab++;
+      for(p=pItem->pSelect; p; p=p->pPrior){
+        srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
+      }
+    }
+  }
+}
+
+/*
+** Expression walker callback used by renumberCursors() to update
+** Expr objects to match newly assigned cursor numbers.
+*/
+static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){
+  int *aCsrMap = pWalker->u.aiCol;
+  int op = pExpr->op;
+  if( (op==TK_COLUMN || op==TK_IF_NULL_ROW) && aCsrMap[pExpr->iTable] ){
+    pExpr->iTable = aCsrMap[pExpr->iTable];
+  }
+  if( ExprHasProperty(pExpr, EP_FromJoin) && aCsrMap[pExpr->iRightJoinTable] ){
+    pExpr->iRightJoinTable = aCsrMap[pExpr->iRightJoinTable];
+  }
+  return WRC_Continue;
+}
+
+/*
+** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc)
+** of the SELECT statement passed as the second argument, and to each
+** cursor in the FROM clause of any FROM clause sub-selects, recursively.
+** Except, do not assign a new cursor number to the iExcept'th element in
+** the FROM clause of (*p). Update all expressions and other references
+** to refer to the new cursor numbers.
+**
+** Argument aCsrMap is an array that may be used for temporary working
+** space. Two guarantees are made by the caller:
+**
+**   * the array is larger than the largest cursor number used within the
+**     select statement passed as an argument, and
+**
+**   * the array entries for all cursor numbers that do *not* appear in
+**     FROM clauses of the select statement as described above are
+**     initialized to zero.
+*/
+static void renumberCursors(
+  Parse *pParse,                  /* Parse context */
+  Select *p,                      /* Select to renumber cursors within */
+  int iExcept,                    /* FROM clause item to skip */
+  int *aCsrMap                    /* Working space */
+){
+  Walker w;
+  srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
+  memset(&w, 0, sizeof(w));
+  w.u.aiCol = aCsrMap;
+  w.xExprCallback = renumberCursorsCb;
+  w.xSelectCallback = sqlite3SelectWalkNoop;
+  sqlite3WalkSelect(&w, p);
+}
+#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+/*
 ** This routine attempts to flatten subqueries as a performance optimization.
 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
 **
@@ -133544,9 +134976,9 @@
 **        (17c) every term within the subquery compound must have a FROM clause
 **        (17d) the outer query may not be
 **              (17d1) aggregate, or
-**              (17d2) DISTINCT, or
-**              (17d3) a join.
-**        (17e) the subquery may not contain window functions
+**              (17d2) DISTINCT
+**        (17e) the subquery may not contain window functions, and
+**        (17f) the subquery must not be the RHS of a LEFT JOIN.
 **
 **        The parent and sub-query may contain WHERE clauses. Subject to
 **        rules (11), (13) and (14), they may also contain ORDER BY,
@@ -133562,8 +134994,8 @@
 **        syntax error and return a detailed message.
 **
 **  (18)  If the sub-query is a compound select, then all terms of the
-**        ORDER BY clause of the parent must be simple references to
-**        columns of the sub-query.
+**        ORDER BY clause of the parent must be copies of a term returned
+**        by the parent query.
 **
 **  (19)  If the subquery uses LIMIT then the outer query may not
 **        have a WHERE clause.
@@ -133579,9 +135011,8 @@
 **
 **  (22)  The subquery may not be a recursive CTE.
 **
-**  (**)  Subsumed into restriction (17d3).  Was: If the outer query is
-**        a recursive CTE, then the sub-query may not be a compound query.
-**        This restriction is because transforming the
+**  (23)  If the outer query is a recursive CTE, then the sub-query may not be
+**        a compound query.  This restriction is because transforming the
 **        parent to a compound query confuses the code that handles
 **        recursive queries in multiSelect().
 **
@@ -133623,9 +135054,10 @@
   int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
   int i;              /* Loop counter */
   Expr *pWhere;                    /* The WHERE clause */
-  struct SrcList_item *pSubitem;   /* The subquery */
+  SrcItem *pSubitem;               /* The subquery */
   sqlite3 *db = pParse->db;
   Walker w;                        /* Walker to persist agginfo data */
+  int *aCsrMap = 0;
 
   /* Check to see if flattening is permitted.  Return 0 if not.
   */
@@ -133721,13 +135153,14 @@
     if( pSub->pOrderBy ){
       return 0;  /* Restriction (20) */
     }
-    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
-      return 0; /* (17d1), (17d2), or (17d3) */
+    if( isAgg || (p->selFlags & SF_Distinct)!=0 || isLeftJoin>0 ){
+      return 0; /* (17d1), (17d2), or (17f) */
     }
     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
       assert( pSub->pSrc!=0 );
+      assert( (pSub->selFlags & SF_Recursive)==0 );
       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
        || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
@@ -133748,15 +135181,15 @@
         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
       }
     }
-  }
-
-  /* Ex-restriction (23):
-  ** The only way that the recursive part of a CTE can contain a compound
-  ** subquery is for the subquery to be one term of a join.  But if the
-  ** subquery is a join, then the flattening has already been stopped by
-  ** restriction (17d3)
-  */
-  assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
+
+    /* Restriction (23) */
+    if( (p->selFlags & SF_Recursive) ) return 0;
+
+    if( pSrc->nSrc>1 ){
+      if( pParse->nSelect>500 ) return 0;
+      aCsrMap = sqlite3DbMallocZero(db, pParse->nTab*sizeof(int));
+    }
+  }
 
   /***** If we reach this point, flattening is permitted. *****/
   SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
@@ -133768,6 +135201,17 @@
   testcase( i==SQLITE_DENY );
   pParse->zAuthContext = zSavedAuthContext;
 
+  /* Delete the transient structures associated with thesubquery */
+  pSub1 = pSubitem->pSelect;
+  sqlite3DbFree(db, pSubitem->zDatabase);
+  sqlite3DbFree(db, pSubitem->zName);
+  sqlite3DbFree(db, pSubitem->zAlias);
+  pSubitem->zDatabase = 0;
+  pSubitem->zName = 0;
+  pSubitem->zAlias = 0;
+  pSubitem->pSelect = 0;
+  assert( pSubitem->pOn==0 );
+
   /* If the sub-query is a compound SELECT statement, then (by restrictions
   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   ** be of the form:
@@ -133806,18 +135250,23 @@
     ExprList *pOrderBy = p->pOrderBy;
     Expr *pLimit = p->pLimit;
     Select *pPrior = p->pPrior;
+    Table *pItemTab = pSubitem->pTab;
+    pSubitem->pTab = 0;
     p->pOrderBy = 0;
-    p->pSrc = 0;
     p->pPrior = 0;
     p->pLimit = 0;
     pNew = sqlite3SelectDup(db, p, 0);
     p->pLimit = pLimit;
     p->pOrderBy = pOrderBy;
-    p->pSrc = pSrc;
     p->op = TK_ALL;
+    pSubitem->pTab = pItemTab;
     if( pNew==0 ){
       p->pPrior = pPrior;
     }else{
+      pNew->selId = ++pParse->nSelect;
+      if( aCsrMap && db->mallocFailed==0 ){
+        renumberCursors(pParse, pNew, iFrom, aCsrMap);
+      }
       pNew->pPrior = pPrior;
       if( pPrior ) pPrior->pNext = pNew;
       pNew->pNext = p;
@@ -133825,24 +135274,13 @@
       SELECTTRACE(2,pParse,p,("compound-subquery flattener"
                               " creates %u as peer\n",pNew->selId));
     }
-    if( db->mallocFailed ) return 1;
-  }
-
-  /* Begin flattening the iFrom-th entry of the FROM clause
-  ** in the outer query.
-  */
-  pSub = pSub1 = pSubitem->pSelect;
-
-  /* Delete the transient table structure associated with the
-  ** subquery
-  */
-  sqlite3DbFree(db, pSubitem->zDatabase);
-  sqlite3DbFree(db, pSubitem->zName);
-  sqlite3DbFree(db, pSubitem->zAlias);
-  pSubitem->zDatabase = 0;
-  pSubitem->zName = 0;
-  pSubitem->zAlias = 0;
-  pSubitem->pSelect = 0;
+    assert( pSubitem->pSelect==0 );
+  }
+  sqlite3DbFree(db, aCsrMap);
+  if( db->mallocFailed ){
+    pSubitem->pSelect = pSub1;
+    return 1;
+  }
 
   /* Defer deleting the Table object associated with the
   ** subquery until code generation is
@@ -133855,8 +135293,10 @@
     Table *pTabToDel = pSubitem->pTab;
     if( pTabToDel->nTabRef==1 ){
       Parse *pToplevel = sqlite3ParseToplevel(pParse);
-      pTabToDel->pNextZombie = pToplevel->pZombieTab;
-      pToplevel->pZombieTab = pTabToDel;
+      sqlite3ParserAddCleanup(pToplevel,
+         (void(*)(sqlite3*,void*))sqlite3DeleteTable,
+         pTabToDel);
+      testcase( pToplevel->earlyCleanup );
     }else{
       pTabToDel->nTabRef--;
     }
@@ -133876,6 +135316,7 @@
   ** those references with expressions that resolve to the subquery FROM
   ** elements we are now copying in.
   */
+  pSub = pSub1;
   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
     int nSubSrc;
     u8 jointype = 0;
@@ -133884,14 +135325,8 @@
     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
 
-    if( pSrc ){
-      assert( pParent==p );  /* First time through the loop */
-      jointype = pSubitem->fg.jointype;
-    }else{
-      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
-      pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
-      if( pSrc==0 ) break;
-      pParent->pSrc = pSrc;
+    if( pParent==p ){
+      jointype = pSubitem->fg.jointype;     /* First time through the loop */
     }
 
     /* The subquery uses a single slot of the FROM clause of the outer
@@ -134011,7 +135446,7 @@
   sqlite3SelectDelete(db, pSub1);
 
 #if SELECTTRACE_ENABLED
-  if( sqlite3_unsupported_selecttrace & 0x100 ){
+  if( sqlite3SelectTrace & 0x100 ){
     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
     sqlite3TreeViewSelect(0, p, 0);
   }
@@ -134206,6 +135641,35 @@
 }
 
 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+# if !defined(SQLITE_OMIT_WINDOWFUNC)
+/*
+** This function is called to determine whether or not it is safe to
+** push WHERE clause expression pExpr down to FROM clause sub-query
+** pSubq, which contains at least one window function. Return 1
+** if it is safe and the expression should be pushed down, or 0
+** otherwise.
+**
+** It is only safe to push the expression down if it consists only
+** of constants and copies of expressions that appear in the PARTITION
+** BY clause of all window function used by the sub-query. It is safe
+** to filter out entire partitions, but not rows within partitions, as
+** this may change the results of the window functions.
+**
+** At the time this function is called it is guaranteed that
+**
+**   * the sub-query uses only one distinct window frame, and
+**   * that the window frame has a PARTITION BY clase.
+*/
+static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
+  assert( pSubq->pWin->pPartition );
+  assert( (pSubq->selFlags & SF_MultiPart)==0 );
+  assert( pSubq->pPrior==0 );
+  return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
+}
+# endif /* SQLITE_OMIT_WINDOWFUNC */
+#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
 /*
 ** Make copies of relevant WHERE clause terms of the outer query into
 ** the WHERE clause of subquery.  Example:
@@ -134252,9 +135716,24 @@
 **       But if the (b2=2) term were to be pushed down into the bb subquery,
 **       then the (1,1,NULL) row would be suppressed.
 **
-**   (6) The inner query features one or more window-functions (since
-**       changes to the WHERE clause of the inner query could change the
-**       window over which window functions are calculated).
+**   (6) Window functions make things tricky as changes to the WHERE clause
+**       of the inner query could change the window over which window
+**       functions are calculated. Therefore, do not attempt the optimization
+**       if:
+**
+**     (6a) The inner query uses multiple incompatible window partitions.
+**
+**     (6b) The inner query is a compound and uses window-functions.
+**
+**     (6c) The WHERE clause does not consist entirely of constants and
+**          copies of expressions found in the PARTITION BY clause of
+**          all window-functions used by the sub-query. It is safe to
+**          filter out entire partitions, as this does not change the
+**          window over which any window-function is calculated.
+**
+**   (7) The inner query is a Common Table Expression (CTE) that should
+**       be materialized.  (This restriction is implemented in the calling
+**       routine.)
 **
 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
 ** terms are duplicated into the subquery.
@@ -134268,13 +135747,17 @@
 ){
   Expr *pNew;
   int nChng = 0;
-  Select *pSel;
   if( pWhere==0 ) return 0;
-  if( pSubq->selFlags & SF_Recursive ) return 0;  /* restriction (2) */
+  if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ) return 0;
 
 #ifndef SQLITE_OMIT_WINDOWFUNC
-  for(pSel=pSubq; pSel; pSel=pSel->pPrior){
-    if( pSel->pWin ) return 0;    /* restriction (6) */
+  if( pSubq->pPrior ){
+    Select *pSel;
+    for(pSel=pSubq; pSel; pSel=pSel->pPrior){
+      if( pSel->pWin ) return 0;    /* restriction (6b) */
+    }
+  }else{
+    if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
   }
 #endif
 
@@ -134310,6 +135793,7 @@
   }
   if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
     nChng++;
+    pSubq->selFlags |= SF_PushDown;
     while( pSubq ){
       SubstContext x;
       pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
@@ -134320,6 +135804,14 @@
       x.isLeftJoin = 0;
       x.pEList = pSubq->pEList;
       pNew = substExpr(&x, pNew);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+      if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
+        /* Restriction 6c has prevented push-down in this case */
+        sqlite3ExprDelete(pParse->db, pNew);
+        nChng--;
+        break;
+      }
+#endif
       if( pSubq->selFlags & SF_Aggregate ){
         pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
       }else{
@@ -134358,7 +135850,11 @@
   assert( *ppMinMax==0 );
   assert( pFunc->op==TK_AGG_FUNCTION );
   assert( !IsWindowFunc(pFunc) );
-  if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){
+  if( pEList==0
+   || pEList->nExpr!=1
+   || ExprHasProperty(pFunc, EP_WinFunc)
+   || OptimizationDisabled(db, SQLITE_MinMaxOpt)
+  ){
     return eRet;
   }
   zFunc = pFunc->u.zToken;
@@ -134421,24 +135917,26 @@
 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
 ** pFrom->pIndex and return SQLITE_OK.
 */
-SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
-  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
-    Table *pTab = pFrom->pTab;
-    char *zIndexedBy = pFrom->u1.zIndexedBy;
-    Index *pIdx;
-    for(pIdx=pTab->pIndex;
-        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
-        pIdx=pIdx->pNext
-    );
-    if( !pIdx ){
-      sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
-      pParse->checkSchema = 1;
-      return SQLITE_ERROR;
-    }
-    pFrom->pIBIndex = pIdx;
-  }
-  return SQLITE_OK;
-}
+SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
+  Table *pTab = pFrom->pTab;
+  char *zIndexedBy = pFrom->u1.zIndexedBy;
+  Index *pIdx;
+  assert( pTab!=0 );
+  assert( pFrom->fg.isIndexedBy!=0 );
+
+  for(pIdx=pTab->pIndex;
+      pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
+      pIdx=pIdx->pNext
+  );
+  if( !pIdx ){
+    sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
+    pParse->checkSchema = 1;
+    return SQLITE_ERROR;
+  }
+  pFrom->u2.pIBIndex = pIdx;
+  return SQLITE_OK;
+}
+
 /*
 ** Detect compound SELECT statements that use an ORDER BY clause with
 ** an alternative collating sequence.
@@ -134525,7 +136023,7 @@
 ** arguments.  If it does, leave an error message in pParse and return
 ** non-zero, since pFrom is not allowed to be a table-valued function.
 */
-static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
+static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
   if( pFrom->fg.isTabFunc ){
     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
     return 1;
@@ -134546,19 +136044,19 @@
 */
 static struct Cte *searchWith(
   With *pWith,                    /* Current innermost WITH clause */
-  struct SrcList_item *pItem,     /* FROM clause element to resolve */
+  SrcItem *pItem,                 /* FROM clause element to resolve */
   With **ppContext                /* OUT: WITH clause return value belongs to */
 ){
-  const char *zName;
-  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
-    With *p;
-    for(p=pWith; p; p=p->pOuter){
-      int i;
-      for(i=0; i<p->nCte; i++){
-        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
-          *ppContext = p;
-          return &p->a[i];
-        }
+  const char *zName = pItem->zName;
+  With *p;
+  assert( pItem->zDatabase==0 );
+  assert( zName!=0 );
+  for(p=pWith; p; p=p->pOuter){
+    int i;
+    for(i=0; i<p->nCte; i++){
+      if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
+        *ppContext = p;
+        return &p->a[i];
       }
     }
   }
@@ -134576,46 +136074,54 @@
 ** statement with which it is associated.
 */
 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
-  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
   if( pWith ){
     assert( pParse->pWith!=pWith );
     pWith->pOuter = pParse->pWith;
     pParse->pWith = pWith;
-    if( bFree ) pParse->pWithToFree = pWith;
+    if( bFree ){
+      sqlite3ParserAddCleanup(pParse,
+         (void(*)(sqlite3*,void*))sqlite3WithDelete,
+         pWith);
+      testcase( pParse->earlyCleanup );
+    }
   }
 }
 
 /*
 ** This function checks if argument pFrom refers to a CTE declared by
-** a WITH clause on the stack currently maintained by the parser. And,
-** if currently processing a CTE expression, if it is a recursive
-** reference to the current CTE.
-**
-** If pFrom falls into either of the two categories above, pFrom->pTab
-** and other fields are populated accordingly. The caller should check
-** (pFrom->pTab!=0) to determine whether or not a successful match
-** was found.
-**
-** Whether or not a match is found, SQLITE_OK is returned if no error
-** occurs. If an error does occur, an error message is stored in the
-** parser and some error code other than SQLITE_OK returned.
-*/
-static int withExpand(
-  Walker *pWalker,
-  struct SrcList_item *pFrom
-){
-  Parse *pParse = pWalker->pParse;
-  sqlite3 *db = pParse->db;
-  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
-  With *pWith;                    /* WITH clause that pCte belongs to */
+** a WITH clause on the stack currently maintained by the parser (on the
+** pParse->pWith linked list).  And if currently processing a CTE
+** CTE expression, through routine checks to see if the reference is
+** a recursive reference to the CTE.
+**
+** If pFrom matches a CTE according to either of these two above, pFrom->pTab
+** and other fields are populated accordingly.
+**
+** Return 0 if no match is found.
+** Return 1 if a match is found.
+** Return 2 if an error condition is detected.
+*/
+static int resolveFromTermToCte(
+  Parse *pParse,                  /* The parsing context */
+  Walker *pWalker,                /* Current tree walker */
+  SrcItem *pFrom                  /* The FROM clause term to check */
+){
+  Cte *pCte;               /* Matched CTE (or NULL if no match) */
+  With *pWith;             /* The matching WITH */
 
   assert( pFrom->pTab==0 );
-  if( pParse->nErr ){
-    return SQLITE_ERROR;
-  }
-
+  if( pParse->pWith==0 ){
+    /* There are no WITH clauses in the stack.  No match is possible */
+    return 0;
+  }
+  if( pFrom->zDatabase!=0 ){
+    /* The FROM term contains a schema qualifier (ex: main.t1) and so
+    ** it cannot possibly be a CTE reference. */
+    return 0;
+  }
   pCte = searchWith(pParse->pWith, pFrom, &pWith);
   if( pCte ){
+    sqlite3 *db = pParse->db;
     Table *pTab;
     ExprList *pEList;
     Select *pSel;
@@ -134624,6 +136130,7 @@
     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
     With *pSavedWith;             /* Initial value of pParse->pWith */
     int iRecTab = -1;             /* Cursor for recursive table */
+    CteUse *pCteUse;
 
     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
     ** recursive reference to CTE pCte. Leave an error in pParse and return
@@ -134631,21 +136138,39 @@
     ** In this case, proceed.  */
     if( pCte->zCteErr ){
       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
-      return SQLITE_ERROR;
-    }
-    if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
+      return 2;
+    }
+    if( cannotBeFunction(pParse, pFrom) ) return 2;
 
     assert( pFrom->pTab==0 );
-    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
-    if( pTab==0 ) return WRC_Abort;
+    pTab = sqlite3DbMallocZero(db, sizeof(Table));
+    if( pTab==0 ) return 2;
+    pCteUse = pCte->pUse;
+    if( pCteUse==0 ){
+      pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
+      if( pCteUse==0
+       || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
+      ){
+        sqlite3DbFree(db, pTab);
+        return 2;
+      }
+      pCteUse->eM10d = pCte->eM10d;
+    }
+    pFrom->pTab = pTab;
     pTab->nTabRef = 1;
     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
     pTab->iPKey = -1;
     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
-    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
+    if( db->mallocFailed ) return 2;
     assert( pFrom->pSelect );
+    pFrom->fg.isCte = 1;
+    pFrom->u2.pCteUse = pCteUse;
+    pCteUse->nUse++;
+    if( pCteUse->nUse>=2 && pCteUse->eM10d==M10d_Any ){
+      pCteUse->eM10d = M10d_Yes;
+    }
 
     /* Check if this is a recursive CTE. */
     pRecTerm = pSel = pFrom->pSelect;
@@ -134655,7 +136180,7 @@
       SrcList *pSrc = pRecTerm->pSrc;
       assert( pRecTerm->pPrior!=0 );
       for(i=0; i<pSrc->nSrc; i++){
-        struct SrcList_item *pItem = &pSrc->a[i];
+        SrcItem *pItem = &pSrc->a[i];
         if( pItem->zDatabase==0
          && pItem->zName!=0
          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
@@ -134667,7 +136192,7 @@
             sqlite3ErrorMsg(pParse,
                "multiple references to recursive table: %s", pCte->zName
             );
-            return SQLITE_ERROR;
+            return 2;
           }
           pRecTerm->selFlags |= SF_Recursive;
           if( iRecTab<0 ) iRecTab = pParse->nTab++;
@@ -134682,16 +136207,24 @@
     pSavedWith = pParse->pWith;
     pParse->pWith = pWith;
     if( pSel->selFlags & SF_Recursive ){
+      int rc;
       assert( pRecTerm!=0 );
       assert( (pRecTerm->selFlags & SF_Recursive)==0 );
       assert( pRecTerm->pNext!=0 );
       assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
       assert( pRecTerm->pWith==0 );
       pRecTerm->pWith = pSel->pWith;
-      sqlite3WalkSelect(pWalker, pRecTerm);
+      rc = sqlite3WalkSelect(pWalker, pRecTerm);
       pRecTerm->pWith = 0;
-    }else{
-      sqlite3WalkSelect(pWalker, pSel);
+      if( rc ){
+        pParse->pWith = pSavedWith;
+        return 2;
+      }
+    }else{
+      if( sqlite3WalkSelect(pWalker, pSel) ){
+        pParse->pWith = pSavedWith;
+        return 2;
+      }
     }
     pParse->pWith = pWith;
 
@@ -134703,7 +136236,7 @@
             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
         );
         pParse->pWith = pSavedWith;
-        return SQLITE_ERROR;
+        return 2;
       }
       pEList = pCte->pCols;
     }
@@ -134719,9 +136252,9 @@
     }
     pCte->zCteErr = 0;
     pParse->pWith = pSavedWith;
-  }
-
-  return SQLITE_OK;
+    return 1;  /* Success */
+  }
+  return 0;  /* No match */
 }
 #endif
 
@@ -134755,7 +136288,7 @@
 ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
 ** SQLITE_NOMEM.
 */
-SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
+SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
   Select *pSel = pFrom->pSelect;
   Table *pTab;
 
@@ -134803,10 +136336,10 @@
 */
 static int selectExpander(Walker *pWalker, Select *p){
   Parse *pParse = pWalker->pParse;
-  int i, j, k;
+  int i, j, k, rc;
   SrcList *pTabList;
   ExprList *pEList;
-  struct SrcList_item *pFrom;
+  SrcItem *pFrom;
   sqlite3 *db = pParse->db;
   Expr *pE, *pRight, *pExpr;
   u16 selFlags = p->selFlags;
@@ -134842,10 +136375,6 @@
     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
     if( pFrom->pTab ) continue;
     assert( pFrom->fg.isRecursive==0 );
-#ifndef SQLITE_OMIT_CTE
-    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
-    if( pFrom->pTab ) {} else
-#endif
     if( pFrom->zName==0 ){
 #ifndef SQLITE_OMIT_SUBQUERY
       Select *pSel = pFrom->pSelect;
@@ -134855,6 +136384,12 @@
       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
       if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
 #endif
+#ifndef SQLITE_OMIT_CTE
+    }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
+      if( rc>1 ) return WRC_Abort;
+      pTab = pFrom->pTab;
+      assert( pTab!=0 );
+#endif
     }else{
       /* An ordinary table or view name in the FROM clause */
       assert( pFrom->pTab==0 );
@@ -134876,7 +136411,10 @@
         u8 eCodeOrig = pWalker->eCode;
         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
         assert( pFrom->pSelect==0 );
-        if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){
+        if( pTab->pSelect
+         && (db->flags & SQLITE_EnableView)==0
+         && pTab->pSchema!=db->aDb[1].pSchema
+        ){
           sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
             pTab->zName);
         }
@@ -134902,7 +136440,7 @@
     }
 
     /* Locate the index named by the INDEXED BY clause, if any. */
-    if( sqlite3IndexedByLookup(pParse, pFrom) ){
+    if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
       return WRC_Abort;
     }
   }
@@ -135145,7 +136683,7 @@
   Parse *pParse;
   int i;
   SrcList *pTabList;
-  struct SrcList_item *pFrom;
+  SrcItem *pFrom;
 
   assert( p->selFlags & SF_Resolved );
   if( p->selFlags & SF_HasTypeInfo ) return;
@@ -135416,7 +136954,9 @@
 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
   if( pExpr->op!=TK_AND ){
     Select *pS = pWalker->u.pSelect;
-    if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
+    if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
+     && ExprAlwaysFalse(pExpr)==0
+    ){
       sqlite3 *db = pWalker->pParse->db;
       Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
       if( pNew ){
@@ -135455,7 +136995,7 @@
   sWalker.u.pSelect = p;
   sqlite3WalkExpr(&sWalker, p->pHaving);
 #if SELECTTRACE_ENABLED
-  if( sWalker.eCode && (sqlite3_unsupported_selecttrace & 0x100)!=0 ){
+  if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
     SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
     sqlite3TreeViewSelect(0, p, 0);
   }
@@ -135467,11 +137007,13 @@
 ** If it is, then return the SrcList_item for the prior view.  If it is not,
 ** then return 0.
 */
-static struct SrcList_item *isSelfJoinView(
+static SrcItem *isSelfJoinView(
   SrcList *pTabList,           /* Search for self-joins in this FROM clause */
-  struct SrcList_item *pThis   /* Search for prior reference to this subquery */
-){
-  struct SrcList_item *pItem;
+  SrcItem *pThis               /* Search for prior reference to this subquery */
+){
+  SrcItem *pItem;
+  assert( pThis->pSelect!=0 );
+  if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
   for(pItem = pTabList->a; pItem<pThis; pItem++){
     Select *pS1;
     if( pItem->pSelect==0 ) continue;
@@ -135487,9 +137029,7 @@
       ** names in the same FROM clause. */
       continue;
     }
-    if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
-     || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
-    ){
+    if( pItem->pSelect->selFlags & SF_PushDown ){
       /* The view was modified by some other optimization such as
       ** pushDownWhereTerms() */
       continue;
@@ -135499,6 +137039,15 @@
   return 0;
 }
 
+/*
+** Deallocate a single AggInfo object
+*/
+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
@@ -135577,7 +137126,7 @@
   p->selFlags &= ~SF_Aggregate;
 
 #if SELECTTRACE_ENABLED
-  if( sqlite3_unsupported_selecttrace & 0x400 ){
+  if( sqlite3SelectTrace & 0x400 ){
     SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
     sqlite3TreeViewSelect(0, p, 0);
   }
@@ -135630,7 +137179,7 @@
   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
 #if SELECTTRACE_ENABLED
   SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
-  if( sqlite3_unsupported_selecttrace & 0x100 ){
+  if( sqlite3SelectTrace & 0x100 ){
     sqlite3TreeViewSelect(0, p, 0);
   }
 #endif
@@ -135644,8 +137193,19 @@
            pDest->eDest==SRT_Except     || pDest->eDest==SRT_Discard ||
            pDest->eDest==SRT_DistQueue  || pDest->eDest==SRT_DistFifo );
     /* All of these destinations are also able to ignore the ORDER BY clause */
-    sqlite3ExprListDelete(db, p->pOrderBy);
-    p->pOrderBy = 0;
+    if( p->pOrderBy ){
+#if SELECTTRACE_ENABLED
+      SELECTTRACE(1,pParse,p, ("dropping superfluous ORDER BY:\n"));
+      if( sqlite3SelectTrace & 0x100 ){
+        sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
+      }
+#endif
+      sqlite3ParserAddCleanup(pParse,
+        (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
+        p->pOrderBy);
+      testcase( pParse->earlyCleanup );
+      p->pOrderBy = 0;
+    }
     p->selFlags &= ~SF_Distinct;
     p->selFlags |= SF_NoopOrderBy;
   }
@@ -135655,7 +137215,7 @@
   }
   assert( p->pEList!=0 );
 #if SELECTTRACE_ENABLED
-  if( sqlite3_unsupported_selecttrace & 0x104 ){
+  if( sqlite3SelectTrace & 0x104 ){
     SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
     sqlite3TreeViewSelect(0, p, 0);
   }
@@ -135666,9 +137226,9 @@
   ** In this case, it is an error if the target object (pSrc->a[0]) name
   ** or alias is duplicated within FROM clause (pSrc->a[1..n]).  */
   if( p->selFlags & SF_UpdateFrom ){
-    struct SrcList_item *p0 = &p->pSrc->a[0];
+    SrcItem *p0 = &p->pSrc->a[0];
     for(i=1; i<p->pSrc->nSrc; i++){
-      struct SrcList_item *p1 = &p->pSrc->a[i];
+      SrcItem *p1 = &p->pSrc->a[i];
       if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
         sqlite3ErrorMsg(pParse,
             "target object/alias may not appear in FROM clause: %s",
@@ -135690,7 +137250,7 @@
     goto select_end;
   }
 #if SELECTTRACE_ENABLED
-  if( p->pWin && (sqlite3_unsupported_selecttrace & 0x108)!=0 ){
+  if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){
     SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
     sqlite3TreeViewSelect(0, p, 0);
   }
@@ -135706,7 +137266,7 @@
   */
 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
-    struct SrcList_item *pItem = &pTabList->a[i];
+    SrcItem *pItem = &pTabList->a[i];
     Select *pSub = pItem->pSelect;
     Table *pTab = pItem->pTab;
 
@@ -135797,7 +137357,7 @@
     rc = multiSelect(pParse, p, pDest);
 #if SELECTTRACE_ENABLED
     SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
-    if( (sqlite3_unsupported_selecttrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
+    if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
       sqlite3TreeViewSelect(0, p, 0);
     }
 #endif
@@ -135816,7 +137376,7 @@
    && propagateConstants(pParse, p)
   ){
 #if SELECTTRACE_ENABLED
-    if( sqlite3_unsupported_selecttrace & 0x100 ){
+    if( sqlite3SelectTrace & 0x100 ){
       SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
       sqlite3TreeViewSelect(0, p, 0);
     }
@@ -135840,7 +137400,8 @@
   ** (2) Generate code for all sub-queries
   */
   for(i=0; i<pTabList->nSrc; i++){
-    struct SrcList_item *pItem = &pTabList->a[i];
+    SrcItem *pItem = &pTabList->a[i];
+    SrcItem *pPrior;
     SelectDest dest;
     Select *pSub;
 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
@@ -135900,16 +137461,18 @@
     ** 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)
      && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
                            (pItem->fg.jointype & JT_OUTER)!=0)
     ){
 #if SELECTTRACE_ENABLED
-      if( sqlite3_unsupported_selecttrace & 0x100 ){
+      if( sqlite3SelectTrace & 0x100 ){
         SELECTTRACE(0x100,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{
       SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
     }
@@ -135919,16 +137482,18 @@
 
     /* Generate code to implement the subquery
     **
-    ** The subquery is implemented as a co-routine if the subquery is
-    ** guaranteed to be the outer loop (so that it does not need to be
-    ** computed more than once)
-    **
-    ** TODO: Are there other reasons beside (1) to use a co-routine
+    ** The subquery is implemented as a co-routine if:
+    **    (1)  the subquery is guaranteed to be the outer loop (so that
+    **         it does not need to be computed more than once), and
+    **    (2)  the subquery is not a CTE that should be materialized
+    **
+    ** TODO: Are there other reasons beside (1) and (2) to use a co-routine
     ** implementation?
     */
     if( i==0
      && (pTabList->nSrc==1
             || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
+     && (pItem->fg.isCte==0 || pItem->u2.pCteUse->eM10d!=M10d_Yes)  /* (2) */
     ){
       /* Implement a co-routine that will return a single row of the result
       ** set on each invocation.
@@ -135948,16 +137513,32 @@
       sqlite3VdbeEndCoroutine(v, pItem->regReturn);
       sqlite3VdbeJumpHere(v, addrTop-1);
       sqlite3ClearTempRegCache(pParse);
-    }else{
-      /* Generate a subroutine that will fill an ephemeral table with
-      ** the content of this subquery.  pItem->addrFillSub will point
-      ** to the address of the generated subroutine.  pItem->regReturn
-      ** is a register allocated to hold the subroutine return address
-      */
+    }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
+      /* This is a CTE for which materialization code has already been
+      ** generated.  Invoke the subroutine to compute the materialization,
+      ** the make the pItem->iCursor be a copy of the ephemerial table that
+      ** holds the result of the materialization. */
+      CteUse *pCteUse = pItem->u2.pCteUse;
+      sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
+      if( pItem->iCursor!=pCteUse->iCur ){
+        sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
+      }
+      pSub->nSelectRow = pCteUse->nRowEst;
+    }else if( (pPrior = isSelfJoinView(pTabList, pItem))!=0 ){
+      /* This view has already been materialized by a prior entry in
+      ** this same FROM clause.  Reuse it. */
+      if( pPrior->addrFillSub ){
+        sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
+      }
+      sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
+      pSub->nSelectRow = pPrior->pSelect->nSelectRow;
+    }else{
+      /* Materalize the view.  If the view is not correlated, generate a
+      ** subroutine to do the materialization so that subsequent uses of
+      ** the same view can reuse the materialization. */
       int topAddr;
       int onceAddr = 0;
       int retAddr;
-      struct SrcList_item *pPrior;
 
       testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */
       pItem->regReturn = ++pParse->nMem;
@@ -135972,22 +137553,22 @@
       }else{
         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
       }
-      pPrior = isSelfJoinView(pTabList, pItem);
-      if( pPrior ){
-        sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
-        assert( pPrior->pSelect!=0 );
-        pSub->nSelectRow = pPrior->pSelect->nSelectRow;
-      }else{
-        sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
-        ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
-        sqlite3Select(pParse, pSub, &dest);
-      }
+      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
+      ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
+      sqlite3Select(pParse, pSub, &dest);
       pItem->pTab->nRowLogEst = pSub->nSelectRow;
       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
       VdbeComment((v, "end %s", pItem->pTab->zName));
       sqlite3VdbeChangeP1(v, topAddr, retAddr);
       sqlite3ClearTempRegCache(pParse);
+      if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
+        CteUse *pCteUse = pItem->u2.pCteUse;
+        pCteUse->addrM9e = pItem->addrFillSub;
+        pCteUse->regRtn = pItem->regReturn;
+        pCteUse->iCur = pItem->iCursor;
+        pCteUse->nRowEst = pSub->nSelectRow;
+      }
     }
     if( db->mallocFailed ) goto select_end;
     pParse->nHeight -= sqlite3SelectExprHeight(p);
@@ -136004,7 +137585,7 @@
   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
 
 #if SELECTTRACE_ENABLED
-  if( sqlite3_unsupported_selecttrace & 0x400 ){
+  if( sqlite3SelectTrace & 0x400 ){
     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
     sqlite3TreeViewSelect(0, p, 0);
   }
@@ -136040,7 +137621,7 @@
     assert( sDistinct.isTnct );
 
 #if SELECTTRACE_ENABLED
-    if( sqlite3_unsupported_selecttrace & 0x400 ){
+    if( sqlite3SelectTrace & 0x400 ){
       SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
       sqlite3TreeViewSelect(0, p, 0);
     }
@@ -136132,6 +137713,7 @@
         sSort.pOrderBy = 0;
       }
     }
+    SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
 
     /* If sorting index that was created by a prior OP_OpenEphemeral
     ** instruction ended up not being needed, then change the OP_OpenEphemeral
@@ -136170,6 +137752,7 @@
 
       /* End the database scan loop.
       */
+      SELECTTRACE(1,pParse,p,("WhereEnd\n"));
       sqlite3WhereEnd(pWInfo);
     }
   }else{
@@ -136240,11 +137823,14 @@
     ** SELECT statement.
     */
     pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
-    if( pAggInfo==0 ){
+    if( pAggInfo ){
+      sqlite3ParserAddCleanup(pParse,
+          (void(*)(sqlite3*,void*))agginfoFree, pAggInfo);
+      testcase( pParse->earlyCleanup );
+    }
+    if( db->mallocFailed ){
       goto select_end;
     }
-    pAggInfo->pNext = pParse->pAggList;
-    pParse->pAggList = pAggInfo;
     pAggInfo->selId = p->selId;
     memset(&sNC, 0, sizeof(sNC));
     sNC.pParse = pParse;
@@ -136288,10 +137874,14 @@
     pAggInfo->mxReg = pParse->nMem;
     if( db->mallocFailed ) goto select_end;
 #if SELECTTRACE_ENABLED
-    if( sqlite3_unsupported_selecttrace & 0x400 ){
+    if( sqlite3SelectTrace & 0x400 ){
       int ii;
       SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
       sqlite3TreeViewSelect(0, p, 0);
+      if( minMaxFlag ){
+        sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
+        sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
+      }
       for(ii=0; ii<pAggInfo->nColumn; ii++){
         sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
             ii, pAggInfo->aCol[ii].iMem);
@@ -136359,6 +137949,7 @@
           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
       );
       if( pWInfo==0 ) goto select_end;
+      SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
         /* The optimizer is able to deliver rows in group by order so
         ** we do not have to sort.  The OP_OpenEphemeral table will be
@@ -136407,6 +137998,7 @@
         sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
         sqlite3ReleaseTempReg(pParse, regRecord);
         sqlite3ReleaseTempRange(pParse, regBase, nCol);
+        SELECTTRACE(1,pParse,p,("WhereEnd\n"));
         sqlite3WhereEnd(pWInfo);
         pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
         sortOut = sqlite3GetTempReg(pParse);
@@ -136481,9 +138073,10 @@
       /* End of the loop
       */
       if( groupBySort ){
-        sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx, addrTopOfLoop);
+        sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
         VdbeCoverage(v);
       }else{
+        SELECTTRACE(1,pParse,p,("WhereEnd\n"));
         sqlite3WhereEnd(pWInfo);
         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
       }
@@ -136593,7 +138186,6 @@
         explainSimpleCount(pParse, pTab, pBest);
       }else{
         int regAcc = 0;           /* "populate accumulators" flag */
-        int addrSkip;
 
         /* If there are accumulator registers but no min() or max() functions
         ** without FILTER clauses, allocate register regAcc. Register regAcc
@@ -136640,12 +138232,13 @@
         if( pWInfo==0 ){
           goto select_end;
         }
+        SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
         updateAccumulator(pParse, regAcc, pAggInfo);
         if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
-        addrSkip = sqlite3WhereOrderByLimitOptLabel(pWInfo);
-        if( addrSkip!=sqlite3WhereContinueLabel(pWInfo) ){
-          sqlite3VdbeGoto(v, addrSkip);
-        }
+        if( minMaxFlag ){
+          sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
+        }
+        SELECTTRACE(1,pParse,p,("WhereEnd\n"));
         sqlite3WhereEnd(pWInfo);
         finalizeAggFunctions(pParse, pAggInfo);
       }
@@ -136690,15 +138283,13 @@
   if( pAggInfo && !db->mallocFailed ){
     for(i=0; i<pAggInfo->nColumn; i++){
       Expr *pExpr = pAggInfo->aCol[i].pCExpr;
-      assert( pExpr!=0 || db->mallocFailed );
-      if( pExpr==0 ) continue;
+      assert( pExpr!=0 );
       assert( pExpr->pAggInfo==pAggInfo );
       assert( pExpr->iAgg==i );
     }
     for(i=0; i<pAggInfo->nFunc; i++){
       Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
-      assert( pExpr!=0 || db->mallocFailed );
-      if( pExpr==0 ) continue;
+      assert( pExpr!=0 );
       assert( pExpr->pAggInfo==pAggInfo );
       assert( pExpr->iAgg==i );
     }
@@ -136707,7 +138298,7 @@
 
 #if SELECTTRACE_ENABLED
   SELECTTRACE(0x1,pParse,p,("end processing\n"));
-  if( (sqlite3_unsupported_selecttrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
+  if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
     sqlite3TreeViewSelect(0, p, 0);
   }
 #endif
@@ -136968,28 +138559,39 @@
 ** pTab as well as the triggers lised in pTab->pTrigger.
 */
 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
-  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
-  Trigger *pList = 0;                  /* List of triggers to return */
+  Schema *pTmpSchema;       /* Schema of the pTab table */
+  Trigger *pList;           /* List of triggers to return */
+  HashElem *p;              /* Loop variable for TEMP triggers */
 
   if( pParse->disableTriggers ){
     return 0;
   }
-
+  pTmpSchema = pParse->db->aDb[1].pSchema;
+  p = sqliteHashFirst(&pTmpSchema->trigHash);
+  if( p==0 ){
+    return pTab->pTrigger;
+  }
+  pList = pTab->pTrigger;
   if( pTmpSchema!=pTab->pSchema ){
-    HashElem *p;
-    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
-    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
+    while( p ){
       Trigger *pTrig = (Trigger *)sqliteHashData(p);
       if( pTrig->pTabSchema==pTab->pSchema
        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
       ){
-        pTrig->pNext = (pList ? pList : pTab->pTrigger);
+        pTrig->pNext = pList;
         pList = pTrig;
-      }
-    }
-  }
-
-  return (pList ? pList : pTab->pTrigger);
+      }else if( pTrig->op==TK_RETURNING ){
+        assert( pParse->bReturning );
+        assert( &(pParse->u1.pReturning->retTrig) == pTrig );
+        pTrig->table = pTab->zName;
+        pTrig->pTabSchema = pTab->pSchema;
+        pTrig->pNext = pList;
+        pList = pTrig;
+      }
+      p = sqliteHashNext(p);
+    }
+  }
+  return pList;
 }
 
 /*
@@ -137265,7 +138867,7 @@
     sqlite3DbFree(db, z);
     sqlite3ChangeCookie(pParse, iDb);
     sqlite3VdbeAddParseSchemaOp(v, iDb,
-        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
+        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName), 0);
   }
 
   if( db->init.busy ){
@@ -137478,7 +139080,7 @@
 ** Recursively delete a Trigger structure
 */
 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
-  if( pTrigger==0 ) return;
+  if( pTrigger==0 || pTrigger->bReturning ) return;
   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   sqlite3DbFree(db, pTrigger->zName);
   sqlite3DbFree(db, pTrigger->table);
@@ -137643,15 +139245,53 @@
   Trigger *pList = 0;
   Trigger *p;
 
-  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
-    pList = sqlite3TriggerList(pParse, pTab);
-  }
-  assert( pList==0 || IsVirtual(pTab)==0 );
-  for(p=pList; p; p=p->pNext){
-    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
-      mask |= p->tr_tm;
-    }
-  }
+  pList = sqlite3TriggerList(pParse, pTab);
+  assert( pList==0 || IsVirtual(pTab)==0
+           || (pList->bReturning && pList->pNext==0) );
+  if( pList!=0 ){
+    p = pList;
+    if( (pParse->db->flags & SQLITE_EnableTrigger)==0
+     && pTab->pTrigger!=0
+    ){
+      /* The SQLITE_DBCONFIG_ENABLE_TRIGGER setting is off.  That means that
+      ** only TEMP triggers are allowed.  Truncate the pList so that it
+      ** includes only TEMP triggers */
+      if( pList==pTab->pTrigger ){
+        pList = 0;
+        goto exit_triggers_exist;
+      }
+      while( ALWAYS(p->pNext) && p->pNext!=pTab->pTrigger ) p = p->pNext;
+      p->pNext = 0;
+      p = pList;
+    }
+    do{
+      if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
+        mask |= p->tr_tm;
+      }else if( p->op==TK_RETURNING ){
+        /* The first time a RETURNING trigger is seen, the "op" value tells
+        ** us what time of trigger it should be. */
+        assert( sqlite3IsToplevel(pParse) );
+        p->op = op;
+        if( IsVirtual(pTab) ){
+          if( op!=TK_INSERT ){
+            sqlite3ErrorMsg(pParse,
+              "%s RETURNING is not available on virtual tables",
+              op==TK_DELETE ? "DELETE" : "UPDATE");
+          }
+          p->tr_tm = TRIGGER_BEFORE;
+        }else{
+          p->tr_tm = TRIGGER_AFTER;
+        }
+        mask |= p->tr_tm;
+      }else if( p->bReturning && p->op==TK_INSERT && op==TK_UPDATE
+                && sqlite3IsToplevel(pParse) ){
+        /* Also fire a RETURNING trigger for an UPSERT */
+        mask |= p->tr_tm;
+      }
+      p = p->pNext;
+    }while( p );
+  }
+exit_triggers_exist:
   if( pMask ){
     *pMask = mask;
   }
@@ -137695,6 +139335,131 @@
 }
 
 /*
+** Return true if the pExpr term from the RETURNING clause argument
+** list is of the form "*".  Raise an error if the terms if of the
+** form "table.*".
+*/
+static int isAsteriskTerm(
+  Parse *pParse,      /* Parsing context */
+  Expr *pTerm         /* A term in the RETURNING clause */
+){
+  assert( pTerm!=0 );
+  if( pTerm->op==TK_ASTERISK ) return 1;
+  if( pTerm->op!=TK_DOT ) return 0;
+  assert( pTerm->pRight!=0 );
+  assert( pTerm->pLeft!=0 );
+  if( pTerm->pRight->op!=TK_ASTERISK ) return 0;
+  sqlite3ErrorMsg(pParse, "RETURNING may not use \"TABLE.*\" wildcards");
+  return 1;
+}
+
+/* The input list pList is the list of result set terms from a RETURNING
+** clause.  The table that we are returning from is pTab.
+**
+** This routine makes a copy of the pList, and at the same time expands
+** any "*" wildcards to be the complete set of columns from pTab.
+*/
+static ExprList *sqlite3ExpandReturning(
+  Parse *pParse,        /* Parsing context */
+  ExprList *pList,      /* The arguments to RETURNING */
+  Table *pTab           /* The table being updated */
+){
+  ExprList *pNew = 0;
+  sqlite3 *db = pParse->db;
+  int i;
+
+  for(i=0; i<pList->nExpr; i++){
+    Expr *pOldExpr = pList->a[i].pExpr;
+    if( NEVER(pOldExpr==0) ) continue;
+    if( isAsteriskTerm(pParse, pOldExpr) ){
+      int jj;
+      for(jj=0; jj<pTab->nCol; jj++){
+        Expr *pNewExpr;
+        if( IsHiddenColumn(pTab->aCol+jj) ) continue;
+        pNewExpr = sqlite3Expr(db, TK_ID, pTab->aCol[jj].zName);
+        pNew = sqlite3ExprListAppend(pParse, pNew, pNewExpr);
+        if( !db->mallocFailed ){
+          struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
+          pItem->zEName = sqlite3DbStrDup(db, pTab->aCol[jj].zName);
+          pItem->eEName = ENAME_NAME;
+        }
+      }
+    }else{
+      Expr *pNewExpr = sqlite3ExprDup(db, pOldExpr, 0);
+      pNew = sqlite3ExprListAppend(pParse, pNew, pNewExpr);
+      if( !db->mallocFailed && ALWAYS(pList->a[i].zEName!=0) ){
+        struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
+        pItem->zEName = sqlite3DbStrDup(db, pList->a[i].zEName);
+        pItem->eEName = pList->a[i].eEName;
+      }
+    }
+  }
+  if( !db->mallocFailed ){
+    Vdbe *v = pParse->pVdbe;
+    assert( v!=0 );
+    sqlite3VdbeSetNumCols(v, pNew->nExpr);
+    for(i=0; i<pNew->nExpr; i++){
+      sqlite3VdbeSetColName(v, i, COLNAME_NAME, pNew->a[i].zEName,
+                            SQLITE_TRANSIENT);
+    }
+  }
+  return pNew;
+}
+
+/*
+** Generate code for the RETURNING trigger.  Unlike other triggers
+** that invoke a subprogram in the bytecode, the code for RETURNING
+** is generated in-line.
+*/
+static void codeReturningTrigger(
+  Parse *pParse,       /* Parse context */
+  Trigger *pTrigger,   /* The trigger step that defines the RETURNING */
+  Table *pTab,         /* The table to code triggers from */
+  int regIn            /* The first in an array of registers */
+){
+  Vdbe *v = pParse->pVdbe;
+  ExprList *pNew;
+  Returning *pReturning;
+
+  assert( v!=0 );
+  assert( pParse->bReturning );
+  pReturning = pParse->u1.pReturning;
+  assert( pTrigger == &(pReturning->retTrig) );
+  pNew = sqlite3ExpandReturning(pParse, pReturning->pReturnEL, pTab);
+  if( pNew ){
+    NameContext sNC;
+    memset(&sNC, 0, sizeof(sNC));
+    if( pReturning->nRetCol==0 ){
+      pReturning->nRetCol = pNew->nExpr;
+      pReturning->iRetCur = pParse->nTab++;
+    }
+    sNC.pParse = pParse;
+    sNC.uNC.iBaseReg = regIn;
+    sNC.ncFlags = NC_UBaseReg;
+    pParse->eTriggerOp = pTrigger->op;
+    pParse->pTriggerTab = pTab;
+    if( sqlite3ResolveExprListNames(&sNC, pNew)==SQLITE_OK ){
+      int i;
+      int nCol = pNew->nExpr;
+      int reg = pParse->nMem+1;
+      pParse->nMem += nCol+2;
+      pReturning->iRetReg = reg;
+      for(i=0; i<nCol; i++){
+        sqlite3ExprCodeFactorable(pParse, pNew->a[i].pExpr, reg+i);
+      }
+      sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, i, reg+i);
+      sqlite3VdbeAddOp2(v, OP_NewRowid, pReturning->iRetCur, reg+i+1);
+      sqlite3VdbeAddOp3(v, OP_Insert, pReturning->iRetCur, reg+i, reg+i+1);
+    }
+    sqlite3ExprListDelete(pParse->db, pNew);
+    pParse->eTriggerOp = 0;
+    pParse->pTriggerTab = 0;
+  }
+}
+
+
+
+/*
 ** Generate VDBE code for the statements inside the body of a single
 ** trigger.
 */
@@ -137743,6 +139508,7 @@
           sqlite3ExprDup(db, pStep->pWhere, 0),
           pParse->eOrconf, 0, 0, 0
         );
+        sqlite3VdbeAddOp0(v, OP_ResetCount);
         break;
       }
       case TK_INSERT: {
@@ -137753,6 +139519,7 @@
           pParse->eOrconf,
           sqlite3UpsertDup(db, pStep->pUpsert)
         );
+        sqlite3VdbeAddOp0(v, OP_ResetCount);
         break;
       }
       case TK_DELETE: {
@@ -137760,6 +139527,7 @@
           sqlite3TriggerStepSrc(pParse, pStep),
           sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
         );
+        sqlite3VdbeAddOp0(v, OP_ResetCount);
         break;
       }
       default: assert( pStep->op==TK_SELECT ); {
@@ -137771,9 +139539,6 @@
         break;
       }
     }
-    if( pStep->op!=TK_SELECT ){
-      sqlite3VdbeAddOp0(v, OP_ResetCount);
-    }
   }
 
   return 0;
@@ -137920,7 +139685,6 @@
     sqlite3VdbeDelete(v);
   }
 
-  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   sqlite3ParserReset(pSubParse);
   sqlite3StackFree(db, pSubParse);
@@ -138022,7 +139786,7 @@
 **   ...            ...
 **   reg+N          OLD.* value of right-most column of pTab
 **   reg+N+1        NEW.rowid
-**   reg+N+2        OLD.* value of left-most column of pTab
+**   reg+N+2        NEW.* value of left-most column of pTab
 **   ...            ...
 **   reg+N+N+1      NEW.* value of right-most column of pTab
 **
@@ -138067,12 +139831,20 @@
     assert( p->pSchema==p->pTabSchema
          || p->pSchema==pParse->db->aDb[1].pSchema );
 
-    /* Determine whether we should code this trigger */
-    if( p->op==op
+    /* Determine whether we should code this trigger.  One of two choices:
+    **   1. The trigger is an exact match to the current DML statement
+    **   2. This is a RETURNING trigger for INSERT but we are currently
+    **      doing the UPDATE part of an UPSERT.
+    */
+    if( (p->op==op || (p->bReturning && p->op==TK_INSERT && op==TK_UPDATE))
      && p->tr_tm==tr_tm
      && checkColumnOverlap(p->pColumns, pChanges)
     ){
-      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
+      if( !p->bReturning ){
+        sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
+      }else if( sqlite3IsToplevel(pParse) ){
+        codeReturningTrigger(pParse, p, pTab, reg);
+      }
     }
   }
 }
@@ -138117,13 +139889,18 @@
 
   assert( isNew==1 || isNew==0 );
   for(p=pTrigger; p; p=p->pNext){
-    if( p->op==op && (tr_tm&p->tr_tm)
+    if( p->op==op
+     && (tr_tm&p->tr_tm)
      && checkColumnOverlap(p->pColumns,pChanges)
     ){
-      TriggerPrg *pPrg;
-      pPrg = getRowTrigger(pParse, p, pTab, orconf);
-      if( pPrg ){
-        mask |= pPrg->aColmask[isNew];
+      if( p->bReturning ){
+        mask = 0xffffffff;
+      }else{
+        TriggerPrg *pPrg;
+        pPrg = getRowTrigger(pParse, p, pTab, orconf);
+        if( pPrg ){
+          mask |= pPrg->aColmask[isNew];
+        }
       }
     }
   }
@@ -138780,6 +140557,7 @@
   if( (db->flags&SQLITE_CountRows)!=0
    && !pParse->pTriggerTab
    && !pParse->nested
+   && !pParse->bReturning
    && pUpsert==0
   ){
     regRowCount = ++pParse->nMem;
@@ -139243,7 +141021,7 @@
   ** that information.
   */
   if( regRowCount ){
-    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
+    sqlite3VdbeAddOp2(v, OP_ChngCntRow, regRowCount, 1);
     sqlite3VdbeSetNumCols(v, 1);
     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   }
@@ -139478,15 +141256,22 @@
 /*
 ** Free a list of Upsert objects
 */
-SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
-  if( p ){
+static void SQLITE_NOINLINE upsertDelete(sqlite3 *db, Upsert *p){
+  do{
+    Upsert *pNext = p->pNextUpsert;
     sqlite3ExprListDelete(db, p->pUpsertTarget);
     sqlite3ExprDelete(db, p->pUpsertTargetWhere);
     sqlite3ExprListDelete(db, p->pUpsertSet);
     sqlite3ExprDelete(db, p->pUpsertWhere);
+    sqlite3DbFree(db, p->pToFree);
     sqlite3DbFree(db, p);
-  }
-}
+    p = pNext;
+  }while( p );
+}
+SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
+  if( p ) upsertDelete(db, p);
+}
+
 
 /*
 ** Duplicate an Upsert object.
@@ -139497,7 +141282,8 @@
            sqlite3ExprListDup(db, p->pUpsertTarget, 0),
            sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
            sqlite3ExprListDup(db, p->pUpsertSet, 0),
-           sqlite3ExprDup(db, p->pUpsertWhere, 0)
+           sqlite3ExprDup(db, p->pUpsertWhere, 0),
+           sqlite3UpsertDup(db, p->pNextUpsert)
          );
 }
 
@@ -139509,22 +141295,25 @@
   ExprList *pTarget,     /* Target argument to ON CONFLICT, or NULL */
   Expr *pTargetWhere,    /* Optional WHERE clause on the target */
   ExprList *pSet,        /* UPDATE columns, or NULL for a DO NOTHING */
-  Expr *pWhere           /* WHERE clause for the ON CONFLICT UPDATE */
+  Expr *pWhere,          /* WHERE clause for the ON CONFLICT UPDATE */
+  Upsert *pNext          /* Next ON CONFLICT clause in the list */
 ){
   Upsert *pNew;
-  pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
+  pNew = sqlite3DbMallocZero(db, sizeof(Upsert));
   if( pNew==0 ){
     sqlite3ExprListDelete(db, pTarget);
     sqlite3ExprDelete(db, pTargetWhere);
     sqlite3ExprListDelete(db, pSet);
     sqlite3ExprDelete(db, pWhere);
+    sqlite3UpsertDelete(db, pNext);
     return 0;
   }else{
     pNew->pUpsertTarget = pTarget;
     pNew->pUpsertTargetWhere = pTargetWhere;
     pNew->pUpsertSet = pSet;
     pNew->pUpsertWhere = pWhere;
-    pNew->pUpsertIdx = 0;
+    pNew->isDoUpdate = pSet!=0;
+    pNew->pNextUpsert = pNext;
   }
   return pNew;
 }
@@ -139549,6 +141338,7 @@
   Expr *pTerm;            /* One term of the conflict-target clause */
   NameContext sNC;        /* Context for resolving symbolic names */
   Expr sCol[2];           /* Index column converted into an Expr */
+  int nClause = 0;        /* Counter of ON CONFLICT clauses */
 
   assert( pTabList->nSrc==1 );
   assert( pTabList->a[0].pTab!=0 );
@@ -139562,87 +141352,131 @@
   memset(&sNC, 0, sizeof(sNC));
   sNC.pParse = pParse;
   sNC.pSrcList = pTabList;
-  rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
-  if( rc ) return rc;
-  rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
-  if( rc ) return rc;
-
-  /* Check to see if the conflict target matches the rowid. */
-  pTab = pTabList->a[0].pTab;
-  pTarget = pUpsert->pUpsertTarget;
-  iCursor = pTabList->a[0].iCursor;
-  if( HasRowid(pTab)
-   && pTarget->nExpr==1
-   && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
-   && pTerm->iColumn==XN_ROWID
-  ){
-    /* The conflict-target is the rowid of the primary table */
-    assert( pUpsert->pUpsertIdx==0 );
-    return SQLITE_OK;
-  }
-
-  /* Initialize sCol[0..1] to be an expression parse tree for a
-  ** single column of an index.  The sCol[0] node will be the TK_COLLATE
-  ** operator and sCol[1] will be the TK_COLUMN operator.  Code below
-  ** will populate the specific collation and column number values
-  ** prior to comparing against the conflict-target expression.
-  */
-  memset(sCol, 0, sizeof(sCol));
-  sCol[0].op = TK_COLLATE;
-  sCol[0].pLeft = &sCol[1];
-  sCol[1].op = TK_COLUMN;
-  sCol[1].iTable = pTabList->a[0].iCursor;
-
-  /* Check for matches against other indexes */
-  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
-    int ii, jj, nn;
-    if( !IsUniqueIndex(pIdx) ) continue;
-    if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
-    if( pIdx->pPartIdxWhere ){
-      if( pUpsert->pUpsertTargetWhere==0 ) continue;
-      if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
-                             pIdx->pPartIdxWhere, iCursor)!=0 ){
+  for(; pUpsert && pUpsert->pUpsertTarget;
+        pUpsert=pUpsert->pNextUpsert, nClause++){
+    rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
+    if( rc ) return rc;
+    rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
+    if( rc ) return rc;
+
+    /* Check to see if the conflict target matches the rowid. */
+    pTab = pTabList->a[0].pTab;
+    pTarget = pUpsert->pUpsertTarget;
+    iCursor = pTabList->a[0].iCursor;
+    if( HasRowid(pTab)
+     && pTarget->nExpr==1
+     && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
+     && pTerm->iColumn==XN_ROWID
+    ){
+      /* The conflict-target is the rowid of the primary table */
+      assert( pUpsert->pUpsertIdx==0 );
+      continue;
+    }
+
+    /* Initialize sCol[0..1] to be an expression parse tree for a
+    ** single column of an index.  The sCol[0] node will be the TK_COLLATE
+    ** operator and sCol[1] will be the TK_COLUMN operator.  Code below
+    ** will populate the specific collation and column number values
+    ** prior to comparing against the conflict-target expression.
+    */
+    memset(sCol, 0, sizeof(sCol));
+    sCol[0].op = TK_COLLATE;
+    sCol[0].pLeft = &sCol[1];
+    sCol[1].op = TK_COLUMN;
+    sCol[1].iTable = pTabList->a[0].iCursor;
+
+    /* Check for matches against other indexes */
+    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+      int ii, jj, nn;
+      if( !IsUniqueIndex(pIdx) ) continue;
+      if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
+      if( pIdx->pPartIdxWhere ){
+        if( pUpsert->pUpsertTargetWhere==0 ) continue;
+        if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
+                               pIdx->pPartIdxWhere, iCursor)!=0 ){
+          continue;
+        }
+      }
+      nn = pIdx->nKeyCol;
+      for(ii=0; ii<nn; ii++){
+        Expr *pExpr;
+        sCol[0].u.zToken = (char*)pIdx->azColl[ii];
+        if( pIdx->aiColumn[ii]==XN_EXPR ){
+          assert( pIdx->aColExpr!=0 );
+          assert( pIdx->aColExpr->nExpr>ii );
+          pExpr = pIdx->aColExpr->a[ii].pExpr;
+          if( pExpr->op!=TK_COLLATE ){
+            sCol[0].pLeft = pExpr;
+            pExpr = &sCol[0];
+          }
+        }else{
+          sCol[0].pLeft = &sCol[1];
+          sCol[1].iColumn = pIdx->aiColumn[ii];
+          pExpr = &sCol[0];
+        }
+        for(jj=0; jj<nn; jj++){
+          if( sqlite3ExprCompare(pParse,pTarget->a[jj].pExpr,pExpr,iCursor)<2 ){
+            break;  /* Column ii of the index matches column jj of target */
+          }
+        }
+        if( jj>=nn ){
+          /* The target contains no match for column jj of the index */
+          break;
+        }
+      }
+      if( ii<nn ){
+        /* Column ii of the index did not match any term of the conflict target.
+        ** Continue the search with the next index. */
         continue;
       }
-    }
-    nn = pIdx->nKeyCol;
-    for(ii=0; ii<nn; ii++){
-      Expr *pExpr;
-      sCol[0].u.zToken = (char*)pIdx->azColl[ii];
-      if( pIdx->aiColumn[ii]==XN_EXPR ){
-        assert( pIdx->aColExpr!=0 );
-        assert( pIdx->aColExpr->nExpr>ii );
-        pExpr = pIdx->aColExpr->a[ii].pExpr;
-        if( pExpr->op!=TK_COLLATE ){
-          sCol[0].pLeft = pExpr;
-          pExpr = &sCol[0];
-        }
-      }else{
-        sCol[0].pLeft = &sCol[1];
-        sCol[1].iColumn = pIdx->aiColumn[ii];
-        pExpr = &sCol[0];
-      }
-      for(jj=0; jj<nn; jj++){
-        if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
-          break;  /* Column ii of the index matches column jj of target */
-        }
-      }
-      if( jj>=nn ){
-        /* The target contains no match for column jj of the index */
-        break;
-      }
-    }
-    if( ii<nn ){
-      /* Column ii of the index did not match any term of the conflict target.
-      ** Continue the search with the next index. */
-      continue;
-    }
-    pUpsert->pUpsertIdx = pIdx;
-    return SQLITE_OK;
-  }
-  sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
-                          "PRIMARY KEY or UNIQUE constraint");
-  return SQLITE_ERROR;
+      pUpsert->pUpsertIdx = pIdx;
+      break;
+    }
+    if( pUpsert->pUpsertIdx==0 ){
+      char zWhich[16];
+      if( nClause==0 && pUpsert->pNextUpsert==0 ){
+        zWhich[0] = 0;
+      }else{
+        sqlite3_snprintf(sizeof(zWhich),zWhich,"%r ", nClause+1);
+      }
+      sqlite3ErrorMsg(pParse, "%sON CONFLICT clause does not match any "
+                              "PRIMARY KEY or UNIQUE constraint", zWhich);
+      return SQLITE_ERROR;
+    }
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Return true if pUpsert is the last ON CONFLICT clause with a
+** conflict target, or if pUpsert is followed by another ON CONFLICT
+** clause that targets the INTEGER PRIMARY KEY.
+*/
+SQLITE_PRIVATE int sqlite3UpsertNextIsIPK(Upsert *pUpsert){
+  Upsert *pNext;
+  if( NEVER(pUpsert==0) ) return 0;
+  pNext = pUpsert->pNextUpsert;
+  if( pNext==0 ) return 1;
+  if( pNext->pUpsertTarget==0 ) return 1;
+  if( pNext->pUpsertIdx==0 ) return 1;
+  return 0;
+}
+
+/*
+** Given the list of ON CONFLICT clauses described by pUpsert, and
+** a particular index pIdx, return a pointer to the particular ON CONFLICT
+** clause that applies to the index.  Or, if the index is not subject to
+** any ON CONFLICT clause, return NULL.
+*/
+SQLITE_PRIVATE Upsert *sqlite3UpsertOfIndex(Upsert *pUpsert, Index *pIdx){
+  while(
+      pUpsert
+   && pUpsert->pUpsertTarget!=0
+   && pUpsert->pUpsertIdx!=pIdx
+  ){
+     pUpsert = pUpsert->pNextUpsert;
+  }
+  return pUpsert;
 }
 
 /*
@@ -139666,11 +141500,13 @@
   SrcList *pSrc;            /* FROM clause for the UPDATE */
   int iDataCur;
   int i;
+  Upsert *pTop = pUpsert;
 
   assert( v!=0 );
   assert( pUpsert!=0 );
+  iDataCur = pUpsert->iDataCur;
+  pUpsert = sqlite3UpsertOfIndex(pTop, pIdx);
   VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
-  iDataCur = pUpsert->iDataCur;
   if( pIdx && iCur!=iDataCur ){
     if( HasRowid(pTab) ){
       int regRowid = sqlite3GetTempReg(pParse);
@@ -139700,19 +141536,17 @@
       sqlite3VdbeJumpHere(v, i);
     }
   }
-  /* pUpsert does not own pUpsertSrc - the outer INSERT statement does.  So
-  ** we have to make a copy before passing it down into sqlite3Update() */
-  pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
+  /* pUpsert does not own pTop->pUpsertSrc - the outer INSERT statement does.
+  ** So we have to make a copy before passing it down into sqlite3Update() */
+  pSrc = sqlite3SrcListDup(db, pTop->pUpsertSrc, 0);
   /* excluded.* columns of type REAL need to be converted to a hard real */
   for(i=0; i<pTab->nCol; i++){
     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
-      sqlite3VdbeAddOp1(v, OP_RealAffinity, pUpsert->regData+i);
-    }
-  }
-  sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
-      pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
-  pUpsert->pUpsertSet = 0;    /* Will have been deleted by sqlite3Update() */
-  pUpsert->pUpsertWhere = 0;  /* Will have been deleted by sqlite3Update() */
+      sqlite3VdbeAddOp1(v, OP_RealAffinity, pTop->regData+i);
+    }
+  }
+  sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0),
+      sqlite3ExprDup(db,pUpsert->pUpsertWhere,0), OE_Abort, 0, 0, pUpsert);
   VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
 }
 
@@ -140618,7 +142452,7 @@
 
     sqlite3VdbeAddOp0(v, OP_Expire);
     zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt);
-    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
+    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere, 0);
     sqlite3DbFree(db, zStmt);
 
     iReg = ++pParse->nMem;
@@ -140789,6 +142623,7 @@
             zType[i-1] = '\0';
           }
           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
+          pTab->tabFlags |= TF_HasHidden;
           oooHidden = TF_OOOHidden;
         }else{
           pTab->tabFlags |= oooHidden;
@@ -140957,7 +142792,7 @@
       Table *pNew = sParse.pNewTable;
       Index *pIdx;
       pTab->aCol = pNew->aCol;
-      pTab->nCol = pNew->nCol;
+      pTab->nNVCol = pTab->nCol = pNew->nCol;
       pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
       pNew->nCol = 0;
       pNew->aCol = 0;
@@ -141489,19 +143324,6 @@
 #ifndef SQLITE_WHEREINT_H
 #define SQLITE_WHEREINT_H
 
-/*
-** Trace output macros
-*/
-#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
-/***/ extern int sqlite3WhereTrace;
-#endif
-#if defined(SQLITE_DEBUG) \
-    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
-# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
-# define WHERETRACE_ENABLED 1
-#else
-# define WHERETRACE(K,X)
-#endif
 
 /* Forward references
 */
@@ -141755,11 +143577,7 @@
 #define TERM_ORINFO     0x0010 /* Need to free the WhereTerm.u.pOrInfo object */
 #define TERM_ANDINFO    0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */
 #define TERM_OR_OK      0x0040 /* Used during OR-clause processing */
-#ifdef SQLITE_ENABLE_STAT4
-#  define TERM_VNULL    0x0080 /* Manufactured x>NULL or x<=NULL term */
-#else
-#  define TERM_VNULL    0x0000 /* Disabled if not using stat4 */
-#endif
+#define TERM_VNULL      0x0080 /* Manufactured x>NULL or x<=NULL term */
 #define TERM_LIKEOPT    0x0100 /* Virtual terms from the LIKE optimization */
 #define TERM_LIKECOND   0x0200 /* Conditionally this LIKE operator term */
 #define TERM_LIKE       0x0400 /* The original LIKE operator */
@@ -142029,7 +143847,7 @@
 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
-SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
+SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*);
 
 
 
@@ -142207,7 +144025,7 @@
   if( sqlite3ParseToplevel(pParse)->explain==2 )
 #endif
   {
-    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
+    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. */
@@ -143000,7 +144818,7 @@
 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
 */
 static void codeCursorHint(
-  struct SrcList_item *pTabItem,  /* FROM clause item */
+  SrcItem *pTabItem,  /* FROM clause item */
   WhereInfo *pWInfo,    /* The where clause */
   WhereLevel *pLevel,   /* Which loop to provide hints for */
   WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
@@ -143375,7 +145193,7 @@
   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   WhereTerm *pTerm;               /* A WHERE clause term */
   sqlite3 *db;                    /* Database connection */
-  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
+  SrcItem *pTabItem;              /* FROM clause term being coded */
   int addrBrk;                    /* Jump here to break out of the loop */
   int addrHalt;                   /* addrBrk for the outermost loop */
   int addrCont;                   /* Jump here to continue with next cycle */
@@ -143821,6 +145639,12 @@
       SWAP(u8, nBtm, nTop);
     }
 
+    if( iLevel>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 ){
+      /* In case OP_SeekScan is used, ensure that the index cursor does not
+      ** point to a valid row for the first iteration of this loop. */
+      sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
+    }
+
     /* Generate code to evaluate all constraint terms using == or IN
     ** and store the values of those terms in an array of registers
     ** starting at regBase.
@@ -144157,7 +145981,7 @@
     */
     if( pWInfo->nLevel>1 ){
       int nNotReady;                 /* The number of notReady tables */
-      struct SrcList_item *origSrc;     /* Original list of tables */
+      SrcItem *origSrc;              /* Original list of tables */
       nNotReady = pWInfo->nLevel - iLevel - 1;
       pOrTab = sqlite3StackAllocRaw(db,
                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
@@ -145577,6 +147401,277 @@
 }
 
 /*
+** Expression callback for exprUsesSrclist().
+*/
+static int exprUsesSrclistCb(Walker *p, Expr *pExpr){
+  if( pExpr->op==TK_COLUMN ){
+    SrcList *pSrc = p->u.pSrcList;
+    int iCsr = pExpr->iTable;
+    int ii;
+    for(ii=0; ii<pSrc->nSrc; ii++){
+      if( pSrc->a[ii].iCursor==iCsr ){
+        return p->eCode ? WRC_Abort : WRC_Continue;
+      }
+    }
+    return p->eCode ? WRC_Continue : WRC_Abort;
+  }
+  return WRC_Continue;
+}
+
+/*
+** Select callback for exprUsesSrclist().
+*/
+static int exprUsesSrclistSelectCb(Walker *NotUsed1, Select *NotUsed2){
+  UNUSED_PARAMETER(NotUsed1);
+  UNUSED_PARAMETER(NotUsed2);
+  return WRC_Abort;
+}
+
+/*
+** This function always returns true if expression pExpr contains
+** a sub-select.
+**
+** If there is no sub-select in pExpr, then return true if pExpr
+** contains a TK_COLUMN node for a table that is (bUses==1)
+** or is not (bUses==0) in pSrc.
+**
+** Said another way:
+**
+**   bUses      Return     Meaning
+**   --------   ------     ------------------------------------------------
+**
+**   bUses==1   true       pExpr contains either a sub-select or a
+**                         TK_COLUMN referencing pSrc.
+**
+**   bUses==1   false      pExpr contains no sub-selects and all TK_COLUMN
+**                         nodes reference tables not found in pSrc
+**
+**   bUses==0   true       pExpr contains either a sub-select or a TK_COLUMN
+**                         that references a table not in pSrc.
+**
+**   bUses==0   false      pExpr contains no sub-selects and all TK_COLUMN
+**                         nodes reference pSrc
+*/
+static int exprUsesSrclist(SrcList *pSrc, Expr *pExpr, int bUses){
+  Walker sWalker;
+  memset(&sWalker, 0, sizeof(Walker));
+  sWalker.eCode = bUses;
+  sWalker.u.pSrcList = pSrc;
+  sWalker.xExprCallback = exprUsesSrclistCb;
+  sWalker.xSelectCallback = exprUsesSrclistSelectCb;
+  return (sqlite3WalkExpr(&sWalker, pExpr)==WRC_Abort);
+}
+
+/*
+** Context object used by exprExistsToInIter() as it iterates through an
+** expression tree.
+*/
+struct ExistsToInCtx {
+  SrcList *pSrc;    /* The tables in an EXISTS(SELECT ... FROM <here> ...) */
+  Expr *pInLhs;     /* OUT:  Use this as the LHS of the IN operator */
+  Expr *pEq;        /* OUT:  The == term that include pInLhs */
+  Expr **ppAnd;     /* OUT:  The AND operator that includes pEq as a child */
+  Expr **ppParent;  /* The AND operator currently being examined */
+};
+
+/*
+** Iterate through all AND connected nodes in the expression tree
+** headed by (*ppExpr), populating the structure passed as the first
+** argument with the values required by exprAnalyzeExistsFindEq().
+**
+** This function returns non-zero if the expression tree does not meet
+** the two conditions described by the header comment for
+** exprAnalyzeExistsFindEq(), or zero if it does.
+*/
+static int exprExistsToInIter(struct ExistsToInCtx *p, Expr **ppExpr){
+  Expr *pExpr = *ppExpr;
+  switch( pExpr->op ){
+    case TK_AND:
+      p->ppParent = ppExpr;
+      if( exprExistsToInIter(p, &pExpr->pLeft) ) return 1;
+      p->ppParent = ppExpr;
+      if( exprExistsToInIter(p, &pExpr->pRight) ) return 1;
+      break;
+    case TK_EQ: {
+      int bLeft = exprUsesSrclist(p->pSrc, pExpr->pLeft, 0);
+      int bRight = exprUsesSrclist(p->pSrc, pExpr->pRight, 0);
+      if( bLeft || bRight ){
+        if( (bLeft && bRight) || p->pInLhs ) return 1;
+        p->pInLhs = bLeft ? pExpr->pLeft : pExpr->pRight;
+        if( exprUsesSrclist(p->pSrc, p->pInLhs, 1) ) return 1;
+        p->pEq = pExpr;
+        p->ppAnd = p->ppParent;
+      }
+      break;
+    }
+    default:
+      if( exprUsesSrclist(p->pSrc, pExpr, 0) ){
+        return 1;
+      }
+      break;
+  }
+
+  return 0;
+}
+
+/*
+** This function is used by exprAnalyzeExists() when creating virtual IN(...)
+** terms equivalent to user-supplied EXIST(...) clauses. It splits the WHERE
+** clause of the Select object passed as the first argument into one or more
+** expressions joined by AND operators, and then tests if the following are
+** true:
+**
+**   1. Exactly one of the AND separated terms refers to the outer
+**      query, and it is an == (TK_EQ) expression.
+**
+**   2. Only one side of the == expression refers to the outer query, and
+**      it does not refer to any columns from the inner query.
+**
+** If both these conditions are true, then a pointer to the side of the ==
+** expression that refers to the outer query is returned. The caller will
+** use this expression as the LHS of the IN(...) virtual term. Or, if one
+** or both of the above conditions are not true, NULL is returned.
+**
+** If non-NULL is returned and ppEq is non-NULL, *ppEq is set to point
+** to the == expression node before returning. If pppAnd is non-NULL and
+** the == node is not the root of the WHERE clause, then *pppAnd is set
+** to point to the pointer to the AND node that is the parent of the ==
+** node within the WHERE expression tree.
+*/
+static Expr *exprAnalyzeExistsFindEq(
+  Select *pSel,                   /* The SELECT of the EXISTS */
+  Expr **ppEq,                    /* OUT: == node from WHERE clause */
+  Expr ***pppAnd                  /* OUT: Pointer to parent of ==, if any */
+){
+  struct ExistsToInCtx ctx;
+  memset(&ctx, 0, sizeof(ctx));
+  ctx.pSrc = pSel->pSrc;
+  if( exprExistsToInIter(&ctx, &pSel->pWhere) ){
+    return 0;
+  }
+  if( ppEq ) *ppEq = ctx.pEq;
+  if( pppAnd ) *pppAnd = ctx.ppAnd;
+  return ctx.pInLhs;
+}
+
+/*
+** Term idxTerm of the WHERE clause passed as the second argument is an
+** EXISTS expression with a correlated SELECT statement on the RHS.
+** This function analyzes the SELECT statement, and if possible adds an
+** equivalent "? IN(SELECT...)" virtual term to the WHERE clause.
+**
+** For an EXISTS term such as the following:
+**
+**     EXISTS (SELECT ... FROM <srclist> WHERE <e1> = <e2> AND <e3>)
+**
+** The virtual IN() term added is:
+**
+**     <e1> IN (SELECT <e2> FROM <srclist> WHERE <e3>)
+**
+** The virtual term is only added if the following conditions are met:
+**
+**     1. The sub-select must not be an aggregate or use window functions,
+**
+**     2. The sub-select must not be a compound SELECT,
+**
+**     3. Expression <e1> must refer to at least one column from the outer
+**        query, and must not refer to any column from the inner query
+**        (i.e. from <srclist>).
+**
+**     4. <e2> and <e3> must not refer to any values from the outer query.
+**        In other words, once <e1> has been removed, the inner query
+**        must not be correlated.
+**
+*/
+static void exprAnalyzeExists(
+  SrcList *pSrc,            /* the FROM clause */
+  WhereClause *pWC,         /* the WHERE clause */
+  int idxTerm               /* Index of the term to be analyzed */
+){
+  Parse *pParse = pWC->pWInfo->pParse;
+  WhereTerm *pTerm = &pWC->a[idxTerm];
+  Expr *pExpr = pTerm->pExpr;
+  Select *pSel = pExpr->x.pSelect;
+  Expr *pDup = 0;
+  Expr *pEq = 0;
+  Expr *pRet = 0;
+  Expr *pInLhs = 0;
+  Expr **ppAnd = 0;
+  int idxNew;
+  sqlite3 *db = pParse->db;
+
+  assert( pExpr->op==TK_EXISTS );
+  assert( (pExpr->flags & EP_VarSelect) && (pExpr->flags & EP_xIsSelect) );
+
+  if( pSel->selFlags & SF_Aggregate ) return;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+  if( pSel->pWin ) return;
+#endif
+  if( pSel->pPrior ) return;
+  if( pSel->pWhere==0 ) return;
+  if( pSel->pLimit ) return;
+  if( 0==exprAnalyzeExistsFindEq(pSel, 0, 0) ) return;
+
+  pDup = sqlite3ExprDup(db, pExpr, 0);
+  if( db->mallocFailed ){
+    sqlite3ExprDelete(db, pDup);
+    return;
+  }
+  pSel = pDup->x.pSelect;
+  sqlite3ExprListDelete(db, pSel->pEList);
+  pSel->pEList = 0;
+
+  pInLhs = exprAnalyzeExistsFindEq(pSel, &pEq, &ppAnd);
+  assert( pInLhs && pEq );
+  assert( pEq==pSel->pWhere || ppAnd );
+  if( pInLhs==pEq->pLeft ){
+    pRet = pEq->pRight;
+  }else{
+    CollSeq *p = sqlite3ExprCompareCollSeq(pParse, pEq);
+    pInLhs = sqlite3ExprAddCollateString(pParse, pInLhs, p?p->zName:"BINARY");
+    pRet = pEq->pLeft;
+  }
+
+  assert( pDup->pLeft==0 );
+  pDup->op = TK_IN;
+  pDup->pLeft = pInLhs;
+  pDup->flags &= ~EP_VarSelect;
+  if( pRet->op==TK_VECTOR ){
+    pSel->pEList = pRet->x.pList;
+    pRet->x.pList = 0;
+    sqlite3ExprDelete(db, pRet);
+  }else{
+    pSel->pEList = sqlite3ExprListAppend(pParse, 0, pRet);
+  }
+  pEq->pLeft = 0;
+  pEq->pRight = 0;
+  if( ppAnd ){
+    Expr *pAnd = *ppAnd;
+    Expr *pOther = (pAnd->pLeft==pEq) ? pAnd->pRight : pAnd->pLeft;
+    pAnd->pLeft = pAnd->pRight = 0;
+    sqlite3ExprDelete(db, pAnd);
+    *ppAnd = pOther;
+  }else{
+    assert( pSel->pWhere==pEq );
+    pSel->pWhere = 0;
+  }
+  sqlite3ExprDelete(db, pEq);
+
+#ifdef WHERETRACE_ENABLED  /* 0x20 */
+  if( sqlite3WhereTrace & 0x20 ){
+    sqlite3DebugPrintf("Convert EXISTS:\n");
+    sqlite3TreeViewExpr(0, pExpr, 0);
+    sqlite3DebugPrintf("into IN:\n");
+    sqlite3TreeViewExpr(0, pDup, 0);
+  }
+#endif
+  idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
+  exprAnalyze(pSrc, pWC, idxNew);
+  markTermAsChild(pWC, idxNew, idxTerm);
+  pWC->a[idxTerm].wtFlags |= TERM_COPIED;
+}
+
+/*
 ** The input to this routine is an WhereTerm structure with only the
 ** "pExpr" field filled in.  The job of this routine is to analyze the
 ** subexpression and populate all the other fields of the WhereTerm
@@ -145709,6 +147804,12 @@
       pNew->prereqRight = prereqLeft | extraRight;
       pNew->prereqAll = prereqAll;
       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
+    }else if( op==TK_ISNULL && 0==sqlite3ExprCanBeNull(pLeft) ){
+      pExpr->op = TK_TRUEFALSE;
+      pExpr->u.zToken = "false";
+      ExprSetProperty(pExpr, EP_IsFalse);
+      pTerm->prereqAll = 0;
+      pTerm->eOperator = 0;
     }
   }
 
@@ -145761,6 +147862,52 @@
   }
 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
 
+  else if( pExpr->op==TK_EXISTS ){
+    /* Perhaps treat an EXISTS operator as an IN operator */
+    if( (pExpr->flags & EP_VarSelect)!=0
+     && OptimizationEnabled(db, SQLITE_ExistsToIN)
+    ){
+      exprAnalyzeExists(pSrc, pWC, idxTerm);
+    }
+  }
+
+  /* The form "x IS NOT NULL" can sometimes be evaluated more efficiently
+  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
+  ** virtual term of that form.
+  **
+  ** The virtual term must be tagged with TERM_VNULL.
+  */
+  else if( pExpr->op==TK_NOTNULL ){
+    if( pExpr->pLeft->op==TK_COLUMN
+     && pExpr->pLeft->iColumn>=0
+     && !ExprHasProperty(pExpr, EP_FromJoin)
+    ){
+      Expr *pNewExpr;
+      Expr *pLeft = pExpr->pLeft;
+      int idxNew;
+      WhereTerm *pNewTerm;
+
+      pNewExpr = sqlite3PExpr(pParse, TK_GT,
+                              sqlite3ExprDup(db, pLeft, 0),
+                              sqlite3ExprAlloc(db, TK_NULL, 0, 0));
+
+      idxNew = whereClauseInsert(pWC, pNewExpr,
+                                TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
+      if( idxNew ){
+        pNewTerm = &pWC->a[idxNew];
+        pNewTerm->prereqRight = 0;
+        pNewTerm->leftCursor = pLeft->iTable;
+        pNewTerm->u.x.leftColumn = pLeft->iColumn;
+        pNewTerm->eOperator = WO_GT;
+        markTermAsChild(pWC, idxNew, idxTerm);
+        pTerm = &pWC->a[idxTerm];
+        pTerm->wtFlags |= TERM_COPIED;
+        pNewTerm->prereqAll = pTerm->prereqAll;
+      }
+    }
+  }
+
+
 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   /* Add constraints to reduce the search space on a LIKE or GLOB
   ** operator.
@@ -145775,7 +147922,8 @@
   ** bound is made all lowercase so that the bounds also work when comparing
   ** BLOBs.
   */
-  if( pWC->op==TK_AND
+  else if( pExpr->op==TK_FUNCTION
+   && pWC->op==TK_AND
    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   ){
     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
@@ -145845,6 +147993,65 @@
   }
 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
 
+  /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
+  ** new terms for each component comparison - "a = ?" and "b = ?".  The
+  ** new terms completely replace the original vector comparison, which is
+  ** no longer used.
+  **
+  ** This is only required if at least one side of the comparison operation
+  ** is not a sub-select.  */
+  if( (pExpr->op==TK_EQ || pExpr->op==TK_IS)
+   && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
+   && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
+   && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
+     || (pExpr->pRight->flags & EP_xIsSelect)==0)
+   && pWC->op==TK_AND
+  ){
+    int i;
+    for(i=0; i<nLeft; i++){
+      int idxNew;
+      Expr *pNew;
+      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
+      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
+
+      pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
+      transferJoinMarkings(pNew, pExpr);
+      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
+      exprAnalyze(pSrc, pWC, idxNew);
+    }
+    pTerm = &pWC->a[idxTerm];
+    pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
+    pTerm->eOperator = 0;
+  }
+
+  /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
+  ** a virtual term for each vector component. The expression object
+  ** used by each such virtual term is pExpr (the full vector IN(...)
+  ** expression). The WhereTerm.u.x.iField variable identifies the index within
+  ** the vector on the LHS that the virtual term represents.
+  **
+  ** This only works if the RHS is a simple SELECT (not a compound) that does
+  ** not use window functions.
+  */
+  else if( pExpr->op==TK_IN
+   && pTerm->u.x.iField==0
+   && pExpr->pLeft->op==TK_VECTOR
+   && pExpr->x.pSelect->pPrior==0
+#ifndef SQLITE_OMIT_WINDOWFUNC
+   && pExpr->x.pSelect->pWin==0
+#endif
+   && pWC->op==TK_AND
+  ){
+    int i;
+    for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
+      int idxNew;
+      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
+      pWC->a[idxNew].u.x.iField = i+1;
+      exprAnalyze(pSrc, pWC, idxNew);
+      markTermAsChild(pWC, idxNew, idxTerm);
+    }
+  }
+
 #ifndef SQLITE_OMIT_VIRTUALTABLE
   /* Add a WO_AUX auxiliary term to the constraint set if the
   ** current expression is of the form "column OP expr" where OP
@@ -145855,7 +148062,7 @@
   ** virtual tables.  The native query optimizer does not attempt
   ** to do anything with MATCH functions.
   */
-  if( pWC->op==TK_AND ){
+  else if( pWC->op==TK_AND ){
     Expr *pRight = 0, *pLeft = 0;
     int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
     while( res-- > 0 ){
@@ -145891,102 +148098,6 @@
   }
 #endif /* SQLITE_OMIT_VIRTUALTABLE */
 
-  /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
-  ** new terms for each component comparison - "a = ?" and "b = ?".  The
-  ** new terms completely replace the original vector comparison, which is
-  ** no longer used.
-  **
-  ** This is only required if at least one side of the comparison operation
-  ** is not a sub-select.  */
-  if( pWC->op==TK_AND
-  && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
-  && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
-  && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
-  && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
-    || (pExpr->pRight->flags & EP_xIsSelect)==0)
-  ){
-    int i;
-    for(i=0; i<nLeft; i++){
-      int idxNew;
-      Expr *pNew;
-      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
-      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
-
-      pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
-      transferJoinMarkings(pNew, pExpr);
-      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
-      exprAnalyze(pSrc, pWC, idxNew);
-    }
-    pTerm = &pWC->a[idxTerm];
-    pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
-    pTerm->eOperator = 0;
-  }
-
-  /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
-  ** a virtual term for each vector component. The expression object
-  ** used by each such virtual term is pExpr (the full vector IN(...)
-  ** expression). The WhereTerm.u.x.iField variable identifies the index within
-  ** the vector on the LHS that the virtual term represents.
-  **
-  ** This only works if the RHS is a simple SELECT (not a compound) that does
-  ** not use window functions.
-  */
-  if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->u.x.iField==0
-   && pExpr->pLeft->op==TK_VECTOR
-   && pExpr->x.pSelect->pPrior==0
-#ifndef SQLITE_OMIT_WINDOWFUNC
-   && pExpr->x.pSelect->pWin==0
-#endif
-  ){
-    int i;
-    for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
-      int idxNew;
-      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
-      pWC->a[idxNew].u.x.iField = i+1;
-      exprAnalyze(pSrc, pWC, idxNew);
-      markTermAsChild(pWC, idxNew, idxTerm);
-    }
-  }
-
-#ifdef SQLITE_ENABLE_STAT4
-  /* When sqlite_stat4 histogram data is available an operator of the
-  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
-  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
-  ** virtual term of that form.
-  **
-  ** Note that the virtual term must be tagged with TERM_VNULL.
-  */
-  if( pExpr->op==TK_NOTNULL
-   && pExpr->pLeft->op==TK_COLUMN
-   && pExpr->pLeft->iColumn>=0
-   && !ExprHasProperty(pExpr, EP_FromJoin)
-   && OptimizationEnabled(db, SQLITE_Stat4)
-  ){
-    Expr *pNewExpr;
-    Expr *pLeft = pExpr->pLeft;
-    int idxNew;
-    WhereTerm *pNewTerm;
-
-    pNewExpr = sqlite3PExpr(pParse, TK_GT,
-                            sqlite3ExprDup(db, pLeft, 0),
-                            sqlite3ExprAlloc(db, TK_NULL, 0, 0));
-
-    idxNew = whereClauseInsert(pWC, pNewExpr,
-                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
-    if( idxNew ){
-      pNewTerm = &pWC->a[idxNew];
-      pNewTerm->prereqRight = 0;
-      pNewTerm->leftCursor = pLeft->iTable;
-      pNewTerm->u.x.leftColumn = pLeft->iColumn;
-      pNewTerm->eOperator = WO_GT;
-      markTermAsChild(pWC, idxNew, idxTerm);
-      pTerm = &pWC->a[idxTerm];
-      pTerm->wtFlags |= TERM_COPIED;
-      pNewTerm->prereqAll = pTerm->prereqAll;
-    }
-  }
-#endif /* SQLITE_ENABLE_STAT4 */
-
   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   ** an index for tables to the left of the join.
   */
@@ -146145,7 +148256,7 @@
 */
 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
   Parse *pParse,                    /* Parsing context */
-  struct SrcList_item *pItem,       /* The FROM clause term to process */
+  SrcItem *pItem,                   /* The FROM clause term to process */
   WhereClause *pWC                  /* Xfer function arguments to here */
 ){
   Table *pTab;
@@ -146222,12 +148333,6 @@
 /* Forward declaration of methods */
 static int whereLoopResize(sqlite3*, WhereLoop*, int);
 
-/* Test variable that can be set to enable WHERE tracing */
-#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
-/***/ int sqlite3WhereTrace = 0;
-#endif
-
-
 /*
 ** Return the estimated number of output rows from a WHERE clause
 */
@@ -146291,6 +148396,32 @@
 }
 
 /*
+** While generating code for the min/max optimization, after handling
+** the aggregate-step call to min() or max(), check to see if any
+** additional looping is required.  If the output order is such that
+** we are certain that the correct answer has already been found, then
+** code an OP_Goto to by pass subsequent processing.
+**
+** Any extra OP_Goto that is coded here is an optimization.  The
+** correct answer should be obtained regardless.  This OP_Goto just
+** makes the answer appear faster.
+*/
+SQLITE_PRIVATE void sqlite3WhereMinMaxOptEarlyOut(Vdbe *v, WhereInfo *pWInfo){
+  WhereLevel *pInner;
+  int i;
+  if( !pWInfo->bOrderedInnerLoop ) return;
+  if( pWInfo->nOBSat==0 ) return;
+  for(i=pWInfo->nLevel-1; i>=0; i--){
+    pInner = &pWInfo->a[i];
+    if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){
+      sqlite3VdbeGoto(v, pInner->addrNxt);
+      return;
+    }
+  }
+  sqlite3VdbeGoto(v, pWInfo->iBreak);
+}
+
+/*
 ** Return the VDBE address or label to jump to in order to continue
 ** immediately with the next row of a WHERE clause.
 */
@@ -146859,7 +148990,7 @@
 */
 static int termCanDriveIndex(
   WhereTerm *pTerm,              /* WHERE clause term to check */
-  struct SrcList_item *pSrc,     /* Table we are trying to access */
+  SrcItem *pSrc,                 /* Table we are trying to access */
   Bitmask notReady               /* Tables in outer loops of the join */
 ){
   char aff;
@@ -146893,7 +149024,7 @@
 static void constructAutomaticIndex(
   Parse *pParse,              /* The parsing context */
   WhereClause *pWC,           /* The WHERE clause */
-  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
+  SrcItem *pSrc,              /* The FROM clause term to get the next index */
   Bitmask notReady,           /* Mask of cursors that are not available */
   WhereLevel *pLevel          /* Write new index here */
 ){
@@ -146917,7 +149048,7 @@
   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 */
-  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
+  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 */
 
@@ -147101,7 +149232,7 @@
   Parse *pParse,                  /* The parsing context */
   WhereClause *pWC,               /* The WHERE clause being analyzed */
   Bitmask mUnusable,              /* Ignore terms with these prereqs */
-  struct SrcList_item *pSrc,      /* The FROM clause term that is the vtab */
+  SrcItem *pSrc,                  /* The FROM clause term that is the vtab */
   ExprList *pOrderBy,             /* The ORDER BY clause */
   u16 *pmNoOmit                   /* Mask of terms not to omit */
 ){
@@ -147999,7 +150130,7 @@
 SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
   WhereInfo *pWInfo = pWC->pWInfo;
   int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
-  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
+  SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
   Table *pTab = pItem->pTab;
   Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
@@ -148610,7 +150741,7 @@
 */
 static int whereLoopAddBtreeIndex(
   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
-  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
+  SrcItem *pSrc,                  /* FROM clause term being analyzed */
   Index *pProbe,                  /* An index on pSrc */
   LogEst nInMul                   /* log(Number of iterations due to IN) */
 ){
@@ -148796,7 +150927,7 @@
       pBtm = pTerm;
       pTop = 0;
       if( pTerm->wtFlags & TERM_LIKEOPT ){
-        /* Range contraints that come from the LIKE optimization are
+        /* Range constraints that come from the LIKE optimization are
         ** always used in pairs. */
         pTop = &pTerm[1];
         assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
@@ -149101,7 +151232,7 @@
   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   SrcList *pTabList;          /* The FROM clause */
-  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
+  SrcItem *pSrc;              /* The FROM clause btree term to add */
   WhereLoop *pNew;            /* Template WhereLoop object */
   int rc = SQLITE_OK;         /* Return code */
   int iSortIdx = 1;           /* Index number */
@@ -149119,9 +151250,9 @@
   pWC = pBuilder->pWC;
   assert( !IsVirtual(pSrc->pTab) );
 
-  if( pSrc->pIBIndex ){
+  if( pSrc->fg.isIndexedBy ){
     /* An INDEXED BY clause specifies a particular index to use */
-    pProbe = pSrc->pIBIndex;
+    pProbe = pSrc->u2.pIBIndex;
   }else if( !HasRowid(pTab) ){
     pProbe = pTab->pIndex;
   }else{
@@ -149157,7 +151288,7 @@
   if( !pBuilder->pOrSet      /* Not part of an OR optimization */
    && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
-   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
+   && !pSrc->fg.isIndexedBy  /* Has no INDEXED BY clause */
    && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
    && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
    && !pSrc->fg.isCorrelated /* Not a correlated subquery */
@@ -149207,7 +151338,7 @@
   /* Loop over all indices. If there was an INDEXED BY clause, then only
   ** consider index pProbe.  */
   for(; rc==SQLITE_OK && pProbe;
-      pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
+      pProbe=(pSrc->fg.isIndexedBy ? 0 : pProbe->pNext), iSortIdx++
   ){
     int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0;
     if( pProbe->pPartIdxWhere!=0
@@ -149382,7 +151513,7 @@
   int rc = SQLITE_OK;
   WhereLoop *pNew = pBuilder->pNew;
   Parse *pParse = pBuilder->pWInfo->pParse;
-  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
+  SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
   int nConstraint = pIdxInfo->nConstraint;
 
   assert( (mUsable & mPrereq)==mPrereq );
@@ -149574,7 +151705,7 @@
   WhereInfo *pWInfo;           /* WHERE analysis context */
   Parse *pParse;               /* The parsing context */
   WhereClause *pWC;            /* The WHERE clause */
-  struct SrcList_item *pSrc;   /* The FROM clause term to search */
+  SrcItem *pSrc;               /* The FROM clause term to search */
   sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
   int nConstraint;             /* Number of constraints in p */
   int bIn;                     /* True if plan uses IN(...) operator */
@@ -149702,7 +151833,7 @@
   WhereClause tempWC;
   WhereLoopBuilder sSubBuild;
   WhereOrSet sSum, sCur;
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
 
   pWC = pBuilder->pWC;
   pWCEnd = pWC->a + pWC->nTerm;
@@ -149818,8 +151949,8 @@
   Bitmask mPrior = 0;
   int iTab;
   SrcList *pTabList = pWInfo->pTabList;
-  struct SrcList_item *pItem;
-  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
+  SrcItem *pItem;
+  SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
   sqlite3 *db = pWInfo->pParse->db;
   int rc = SQLITE_OK;
   WhereLoop *pNew;
@@ -149842,7 +151973,7 @@
     }
 #ifndef SQLITE_OMIT_VIRTUALTABLE
     if( IsVirtual(pItem->pTab) ){
-      struct SrcList_item *p;
+      SrcItem *p;
       for(p=&pItem[1]; p<pEnd; p++){
         if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
           mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
@@ -150697,7 +152828,7 @@
 */
 static int whereShortCut(WhereLoopBuilder *pBuilder){
   WhereInfo *pWInfo;
-  struct SrcList_item *pItem;
+  SrcItem *pItem;
   WhereClause *pWC;
   WhereTerm *pTerm;
   WhereLoop *pLoop;
@@ -151156,7 +153287,7 @@
   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
      pWInfo->revMask = ALLBITS;
   }
-  if( pParse->nErr || NEVER(db->mallocFailed) ){
+  if( pParse->nErr || db->mallocFailed ){
     goto whereBeginError;
   }
 #ifdef WHERETRACE_ENABLED
@@ -151227,7 +153358,7 @@
     }
     for(i=pWInfo->nLevel-1; i>=1; i--){
       WhereTerm *pTerm, *pEnd;
-      struct SrcList_item *pItem;
+      SrcItem *pItem;
       pLoop = pWInfo->a[i].pWLoop;
       pItem = &pWInfo->pTabList->a[pLoop->iTab];
       if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
@@ -151317,7 +153448,7 @@
   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
     Table *pTab;     /* Table to open */
     int iDb;         /* Index of database containing table/index */
-    struct SrcList_item *pTabItem;
+    SrcItem *pTabItem;
 
     pTabItem = &pTabList->a[pLevel->iFrom];
     pTab = pTabItem->pTab;
@@ -151654,7 +153785,7 @@
     int k, last;
     VdbeOp *pOp, *pLastOp;
     Index *pIdx = 0;
-    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
+    SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
     Table *pTab = pTabItem->pTab;
     assert( pTab!=0 );
     pLoop = pLevel->pWLoop;
@@ -151730,7 +153861,7 @@
 #endif
       pOp = sqlite3VdbeGetOp(v, k);
       pLastOp = pOp + (last - k);
-      assert( pOp<pLastOp );
+      assert( pOp<pLastOp || (pParse->nErr>0 && pOp==pLastOp) );
       do{
         if( pOp->p1!=pLevel->iTabCur ){
           /* no-op */
@@ -153098,15 +155229,19 @@
 ** SELECT, or (b) the windows already linked use a compatible window frame.
 */
 SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){
-  if( pSel!=0
-   && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
-  ){
-    pWin->pNextWin = pSel->pWin;
-    if( pSel->pWin ){
-      pSel->pWin->ppThis = &pWin->pNextWin;
-    }
-    pSel->pWin = pWin;
-    pWin->ppThis = &pSel->pWin;
+  if( pSel ){
+    if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){
+      pWin->pNextWin = pSel->pWin;
+      if( pSel->pWin ){
+        pSel->pWin->ppThis = &pWin->pNextWin;
+      }
+      pSel->pWin = pWin;
+      pWin->ppThis = &pSel->pWin;
+    }else{
+      if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){
+        pSel->selFlags |= SF_MultiPart;
+      }
+    }
   }
 }
 
@@ -153259,6 +155394,7 @@
     VdbeCoverageIf(v, eCond==2);
   }
   sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
+  sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC);
   VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
   VdbeCoverageNeverNullIf(v, eCond==1); /*   the OP_MustBeInt */
   VdbeCoverageNeverNullIf(v, eCond==2);
@@ -153855,6 +155991,7 @@
   int regString = ++pParse->nMem;           /* Reg. for constant value '' */
   int arith = OP_Add;                       /* OP_Add or OP_Subtract */
   int addrGe;                               /* Jump destination */
+  CollSeq *pColl;
 
   assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
   assert( pOrderBy && pOrderBy->nExpr==1 );
@@ -153945,6 +156082,8 @@
   ** control skips over this test if the BIGNULL flag is set and either
   ** reg1 or reg2 contain a NULL value.  */
   sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
+  pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
+  sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ);
   sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
 
   assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
@@ -154951,11 +157090,21 @@
   static void parserDoubleLinkSelect(Parse *pParse, Select *p){
     assert( p!=0 );
     if( p->pPrior ){
-      Select *pNext = 0, *pLoop;
-      int mxSelect, cnt = 0;
-      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
+      Select *pNext = 0, *pLoop = p;
+      int mxSelect, cnt = 1;
+      while(1){
         pLoop->pNext = pNext;
         pLoop->selFlags |= SF_Compound;
+        pNext = pLoop;
+        pLoop = pLoop->pPrior;
+        if( pLoop==0 ) break;
+        cnt++;
+        if( pLoop->pOrderBy || pLoop->pLimit ){
+          sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
+             pLoop->pOrderBy!=0 ? "ORDER BY" : "LIMIT",
+             sqlite3SelectOpName(pNext->op));
+          break;
+        }
       }
       if( (p->selFlags & SF_MultiValue)==0 &&
         (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
@@ -154966,6 +157115,19 @@
     }
   }
 
+  /* Attach a With object describing the WITH clause to a Select
+  ** object describing the query for which the WITH clause is a prefix.
+  */
+  static Select *attachWithToSelect(Parse *pParse, Select *pSelect, With *pWith){
+    if( pSelect ){
+      pSelect->pWith = pWith;
+      parserDoubleLinkSelect(pParse, pSelect);
+    }else{
+      sqlite3WithDelete(pParse->db, pWith);
+    }
+    return pSelect;
+  }
+
 
   /* Construct a new Expr object from a single identifier.  Use the
   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
@@ -155141,90 +157303,92 @@
 #define TK_TIES                           94
 #define TK_GENERATED                      95
 #define TK_ALWAYS                         96
-#define TK_REINDEX                        97
-#define TK_RENAME                         98
-#define TK_CTIME_KW                       99
-#define TK_ANY                            100
-#define TK_BITAND                         101
-#define TK_BITOR                          102
-#define TK_LSHIFT                         103
-#define TK_RSHIFT                         104
-#define TK_PLUS                           105
-#define TK_MINUS                          106
-#define TK_STAR                           107
-#define TK_SLASH                          108
-#define TK_REM                            109
-#define TK_CONCAT                         110
-#define TK_COLLATE                        111
-#define TK_BITNOT                         112
-#define TK_ON                             113
-#define TK_INDEXED                        114
-#define TK_STRING                         115
-#define TK_JOIN_KW                        116
-#define TK_CONSTRAINT                     117
-#define TK_DEFAULT                        118
-#define TK_NULL                           119
-#define TK_PRIMARY                        120
-#define TK_UNIQUE                         121
-#define TK_CHECK                          122
-#define TK_REFERENCES                     123
-#define TK_AUTOINCR                       124
-#define TK_INSERT                         125
-#define TK_DELETE                         126
-#define TK_UPDATE                         127
-#define TK_SET                            128
-#define TK_DEFERRABLE                     129
-#define TK_FOREIGN                        130
-#define TK_DROP                           131
-#define TK_UNION                          132
-#define TK_ALL                            133
-#define TK_EXCEPT                         134
-#define TK_INTERSECT                      135
-#define TK_SELECT                         136
-#define TK_VALUES                         137
-#define TK_DISTINCT                       138
-#define TK_DOT                            139
-#define TK_FROM                           140
-#define TK_JOIN                           141
-#define TK_USING                          142
-#define TK_ORDER                          143
-#define TK_GROUP                          144
-#define TK_HAVING                         145
-#define TK_LIMIT                          146
-#define TK_WHERE                          147
-#define TK_INTO                           148
-#define TK_NOTHING                        149
-#define TK_FLOAT                          150
-#define TK_BLOB                           151
-#define TK_INTEGER                        152
-#define TK_VARIABLE                       153
-#define TK_CASE                           154
-#define TK_WHEN                           155
-#define TK_THEN                           156
-#define TK_ELSE                           157
-#define TK_INDEX                          158
-#define TK_ALTER                          159
-#define TK_ADD                            160
-#define TK_WINDOW                         161
-#define TK_OVER                           162
-#define TK_FILTER                         163
-#define TK_COLUMN                         164
-#define TK_AGG_FUNCTION                   165
-#define TK_AGG_COLUMN                     166
-#define TK_TRUEFALSE                      167
-#define TK_ISNOT                          168
-#define TK_FUNCTION                       169
-#define TK_UMINUS                         170
-#define TK_UPLUS                          171
-#define TK_TRUTH                          172
-#define TK_REGISTER                       173
-#define TK_VECTOR                         174
-#define TK_SELECT_COLUMN                  175
-#define TK_IF_NULL_ROW                    176
-#define TK_ASTERISK                       177
-#define TK_SPAN                           178
-#define TK_SPACE                          179
-#define TK_ILLEGAL                        180
+#define TK_MATERIALIZED                   97
+#define TK_REINDEX                        98
+#define TK_RENAME                         99
+#define TK_CTIME_KW                       100
+#define TK_ANY                            101
+#define TK_BITAND                         102
+#define TK_BITOR                          103
+#define TK_LSHIFT                         104
+#define TK_RSHIFT                         105
+#define TK_PLUS                           106
+#define TK_MINUS                          107
+#define TK_STAR                           108
+#define TK_SLASH                          109
+#define TK_REM                            110
+#define TK_CONCAT                         111
+#define TK_COLLATE                        112
+#define TK_BITNOT                         113
+#define TK_ON                             114
+#define TK_INDEXED                        115
+#define TK_STRING                         116
+#define TK_JOIN_KW                        117
+#define TK_CONSTRAINT                     118
+#define TK_DEFAULT                        119
+#define TK_NULL                           120
+#define TK_PRIMARY                        121
+#define TK_UNIQUE                         122
+#define TK_CHECK                          123
+#define TK_REFERENCES                     124
+#define TK_AUTOINCR                       125
+#define TK_INSERT                         126
+#define TK_DELETE                         127
+#define TK_UPDATE                         128
+#define TK_SET                            129
+#define TK_DEFERRABLE                     130
+#define TK_FOREIGN                        131
+#define TK_DROP                           132
+#define TK_UNION                          133
+#define TK_ALL                            134
+#define TK_EXCEPT                         135
+#define TK_INTERSECT                      136
+#define TK_SELECT                         137
+#define TK_VALUES                         138
+#define TK_DISTINCT                       139
+#define TK_DOT                            140
+#define TK_FROM                           141
+#define TK_JOIN                           142
+#define TK_USING                          143
+#define TK_ORDER                          144
+#define TK_GROUP                          145
+#define TK_HAVING                         146
+#define TK_LIMIT                          147
+#define TK_WHERE                          148
+#define TK_RETURNING                      149
+#define TK_INTO                           150
+#define TK_NOTHING                        151
+#define TK_FLOAT                          152
+#define TK_BLOB                           153
+#define TK_INTEGER                        154
+#define TK_VARIABLE                       155
+#define TK_CASE                           156
+#define TK_WHEN                           157
+#define TK_THEN                           158
+#define TK_ELSE                           159
+#define TK_INDEX                          160
+#define TK_ALTER                          161
+#define TK_ADD                            162
+#define TK_WINDOW                         163
+#define TK_OVER                           164
+#define TK_FILTER                         165
+#define TK_COLUMN                         166
+#define TK_AGG_FUNCTION                   167
+#define TK_AGG_COLUMN                     168
+#define TK_TRUEFALSE                      169
+#define TK_ISNOT                          170
+#define TK_FUNCTION                       171
+#define TK_UMINUS                         172
+#define TK_UPLUS                          173
+#define TK_TRUTH                          174
+#define TK_REGISTER                       175
+#define TK_VECTOR                         176
+#define TK_SELECT_COLUMN                  177
+#define TK_IF_NULL_ROW                    178
+#define TK_ASTERISK                       179
+#define TK_SPAN                           180
+#define TK_SPACE                          181
+#define TK_ILLEGAL                        182
 #endif
 /**************** End token definitions ***************************************/
 
@@ -155284,28 +157448,29 @@
 #endif
 /************* Begin control #defines *****************************************/
 #define YYCODETYPE unsigned short int
-#define YYNOCODE 310
+#define YYNOCODE 316
 #define YYACTIONTYPE unsigned short int
-#define YYWILDCARD 100
+#define YYWILDCARD 101
 #define sqlite3ParserTOKENTYPE Token
 typedef union {
   int yyinit;
   sqlite3ParserTOKENTYPE yy0;
-  SrcList* yy47;
-  u8 yy58;
-  struct FrameBound yy77;
-  With* yy131;
-  int yy192;
-  Expr* yy202;
-  struct {int value; int mask;} yy207;
-  struct TrigEvent yy230;
-  ExprList* yy242;
-  Window* yy303;
-  Upsert* yy318;
-  const char* yy436;
-  TriggerStep* yy447;
-  Select* yy539;
-  IdList* yy600;
+  Window* yy19;
+  struct TrigEvent yy50;
+  int yy60;
+  struct FrameBound yy113;
+  Upsert* yy178;
+  With* yy195;
+  IdList* yy288;
+  SrcList* yy291;
+  Select* yy307;
+  ExprList* yy338;
+  TriggerStep* yy483;
+  const char* yy528;
+  u8 yy570;
+  Expr* yy602;
+  Cte* yy607;
+  struct {int value; int mask;} yy615;
 } YYMINORTYPE;
 #ifndef YYSTACKDEPTH
 #define YYSTACKDEPTH 100
@@ -155321,18 +157486,18 @@
 #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
 #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
 #define YYFALLBACK 1
-#define YYNSTATE             553
-#define YYNRULE              385
-#define YYNRULE_WITH_ACTION  325
-#define YYNTOKEN             181
-#define YY_MAX_SHIFT         552
-#define YY_MIN_SHIFTREDUCE   803
-#define YY_MAX_SHIFTREDUCE   1187
-#define YY_ERROR_ACTION      1188
-#define YY_ACCEPT_ACTION     1189
-#define YY_NO_ACTION         1190
-#define YY_MIN_REDUCE        1191
-#define YY_MAX_REDUCE        1575
+#define YYNSTATE             570
+#define YYNRULE              398
+#define YYNRULE_WITH_ACTION  337
+#define YYNTOKEN             183
+#define YY_MAX_SHIFT         569
+#define YY_MIN_SHIFTREDUCE   825
+#define YY_MAX_SHIFTREDUCE   1222
+#define YY_ERROR_ACTION      1223
+#define YY_ACCEPT_ACTION     1224
+#define YY_NO_ACTION         1225
+#define YY_MIN_REDUCE        1226
+#define YY_MAX_REDUCE        1623
 /************* End control #defines *******************************************/
 #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
 
@@ -155399,586 +157564,600 @@
 **  yy_default[]       Default action for each state.
 **
 *********** Begin parsing tables **********************************************/
-#define YY_ACTTAB_COUNT (1962)
+#define YY_ACTTAB_COUNT (2020)
 static const YYACTIONTYPE yy_action[] = {
- /*     0 */   546, 1222,  546,  451, 1260,  546, 1239,  546,  114,  111,
- /*    10 */   211,  546, 1537,  546, 1260,  523,  114,  111,  211,  392,
- /*    20 */  1232,  344,   42,   42,   42,   42, 1225,   42,   42,   71,
- /*    30 */    71,  937, 1224,   71,   71,   71,   71, 1462, 1493,  938,
- /*    40 */   820,  453,    6,  121,  122,  112, 1165, 1165, 1006, 1009,
- /*    50 */   999,  999,  119,  119,  120,  120,  120,  120, 1543,  392,
- /*    60 */  1358, 1517,  552,    2, 1193,  194,  528,  436,  143,  291,
- /*    70 */   528,  136,  528,  371,  261,  504,  272,  385, 1273,  527,
- /*    80 */   503,  493,  164,  121,  122,  112, 1165, 1165, 1006, 1009,
- /*    90 */   999,  999,  119,  119,  120,  120,  120,  120, 1358,  442,
- /*   100 */  1514,  118,  118,  118,  118,  117,  117,  116,  116,  116,
- /*   110 */   115,  424,  266,  266,  266,  266, 1498,  358, 1500,  435,
- /*   120 */   357, 1498,  517,  524, 1485,  543, 1114,  543, 1114,  392,
- /*   130 */   405,  241,  208,  114,  111,  211,   98,  290,  537,  221,
- /*   140 */  1029,  118,  118,  118,  118,  117,  117,  116,  116,  116,
- /*   150 */   115,  424, 1142,  121,  122,  112, 1165, 1165, 1006, 1009,
- /*   160 */   999,  999,  119,  119,  120,  120,  120,  120,  406,  428,
- /*   170 */   117,  117,  116,  116,  116,  115,  424, 1418,  468,  123,
- /*   180 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,
- /*   190 */   424,  116,  116,  116,  115,  424,  540,  540,  540,  392,
- /*   200 */   505,  120,  120,  120,  120,  113, 1051, 1142, 1143, 1144,
- /*   210 */  1051,  118,  118,  118,  118,  117,  117,  116,  116,  116,
- /*   220 */   115,  424, 1461,  121,  122,  112, 1165, 1165, 1006, 1009,
- /*   230 */   999,  999,  119,  119,  120,  120,  120,  120,  392,  444,
- /*   240 */   316,   83,  463,   81,  359,  382, 1142,   80,  118,  118,
- /*   250 */   118,  118,  117,  117,  116,  116,  116,  115,  424,  179,
- /*   260 */   434,  424,  121,  122,  112, 1165, 1165, 1006, 1009,  999,
- /*   270 */   999,  119,  119,  120,  120,  120,  120,  434,  433,  266,
- /*   280 */   266,  118,  118,  118,  118,  117,  117,  116,  116,  116,
- /*   290 */   115,  424,  543, 1109,  903,  506, 1142,  114,  111,  211,
- /*   300 */  1431, 1142, 1143, 1144,  206,  491, 1109,  392,  449, 1109,
- /*   310 */   545,  330,  120,  120,  120,  120,  298, 1431, 1433,   17,
- /*   320 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,
- /*   330 */   424,  121,  122,  112, 1165, 1165, 1006, 1009,  999,  999,
- /*   340 */   119,  119,  120,  120,  120,  120,  392, 1358,  434, 1142,
- /*   350 */   482, 1142, 1143, 1144,  996,  996, 1007, 1010,  445,  118,
- /*   360 */   118,  118,  118,  117,  117,  116,  116,  116,  115,  424,
- /*   370 */   121,  122,  112, 1165, 1165, 1006, 1009,  999,  999,  119,
- /*   380 */   119,  120,  120,  120,  120, 1054, 1054,  465, 1431,  118,
- /*   390 */   118,  118,  118,  117,  117,  116,  116,  116,  115,  424,
- /*   400 */  1142,  451,  546, 1426, 1142, 1143, 1144,  233,  966, 1142,
- /*   410 */   481,  478,  477,  171,  360,  392,  164,  407,  414,  842,
- /*   420 */   476,  164,  185,  334,   71,   71, 1243, 1000,  118,  118,
- /*   430 */   118,  118,  117,  117,  116,  116,  116,  115,  424,  121,
- /*   440 */   122,  112, 1165, 1165, 1006, 1009,  999,  999,  119,  119,
- /*   450 */   120,  120,  120,  120,  392, 1142, 1143, 1144,  835,   12,
- /*   460 */   314,  509,  163,  356, 1142, 1143, 1144,  114,  111,  211,
- /*   470 */   508,  290,  537,  546,  276,  180,  290,  537,  121,  122,
- /*   480 */   112, 1165, 1165, 1006, 1009,  999,  999,  119,  119,  120,
- /*   490 */   120,  120,  120,  345,  484,   71,   71,  118,  118,  118,
- /*   500 */   118,  117,  117,  116,  116,  116,  115,  424, 1142,  209,
- /*   510 */   411,  523, 1142, 1109, 1571,  378,  252,  269,  342,  487,
- /*   520 */   337,  486,  238,  392,  513,  364, 1109, 1127,  333, 1109,
- /*   530 */   191,  409,  286,   32,  457,  443,  118,  118,  118,  118,
- /*   540 */   117,  117,  116,  116,  116,  115,  424,  121,  122,  112,
- /*   550 */  1165, 1165, 1006, 1009,  999,  999,  119,  119,  120,  120,
- /*   560 */   120,  120,  392, 1142, 1143, 1144,  987, 1142, 1143, 1144,
- /*   570 */  1142,  233,  492, 1492,  481,  478,  477,    6,  163,  546,
- /*   580 */   512,  546,  115,  424,  476,    5,  121,  122,  112, 1165,
- /*   590 */  1165, 1006, 1009,  999,  999,  119,  119,  120,  120,  120,
- /*   600 */   120,   13,   13,   13,   13,  118,  118,  118,  118,  117,
- /*   610 */   117,  116,  116,  116,  115,  424,  403,  502,  408,  546,
- /*   620 */  1486,  544, 1142,  892,  892, 1142, 1143, 1144, 1473, 1142,
- /*   630 */   275,  392,  808,  809,  810,  971,  422,  422,  422,   16,
- /*   640 */    16,   55,   55, 1242,  118,  118,  118,  118,  117,  117,
- /*   650 */   116,  116,  116,  115,  424,  121,  122,  112, 1165, 1165,
- /*   660 */  1006, 1009,  999,  999,  119,  119,  120,  120,  120,  120,
- /*   670 */   392, 1189,    1,    1,  552,    2, 1193, 1142, 1143, 1144,
- /*   680 */   194,  291,  898,  136, 1142, 1143, 1144,  897,  521, 1492,
- /*   690 */  1273,    3,  380,    6,  121,  122,  112, 1165, 1165, 1006,
- /*   700 */  1009,  999,  999,  119,  119,  120,  120,  120,  120,  858,
- /*   710 */   546,  924,  546,  118,  118,  118,  118,  117,  117,  116,
- /*   720 */   116,  116,  115,  424,  266,  266, 1092, 1569, 1142,  551,
- /*   730 */  1569, 1193,   13,   13,   13,   13,  291,  543,  136,  392,
- /*   740 */   485,  421,  420,  966,  344, 1273,  468,  410,  859,  279,
- /*   750 */   140,  221,  118,  118,  118,  118,  117,  117,  116,  116,
- /*   760 */   116,  115,  424,  121,  122,  112, 1165, 1165, 1006, 1009,
- /*   770 */   999,  999,  119,  119,  120,  120,  120,  120,  546,  266,
- /*   780 */   266,  428,  392, 1142, 1143, 1144, 1172,  830, 1172,  468,
- /*   790 */   431,  145,  543, 1146,  401,  314,  439,  302,  838, 1490,
- /*   800 */    71,   71,  412,    6, 1090,  473,  221,  100,  112, 1165,
- /*   810 */  1165, 1006, 1009,  999,  999,  119,  119,  120,  120,  120,
- /*   820 */   120,  118,  118,  118,  118,  117,  117,  116,  116,  116,
- /*   830 */   115,  424,  237, 1425,  546,  451,  428,  287,  986,  546,
- /*   840 */   236,  235,  234,  830,   97,  529,  429, 1265, 1265, 1146,
- /*   850 */   494,  307,  430,  838,  977,  546,   71,   71,  976, 1241,
- /*   860 */   546,   51,   51,  300,  118,  118,  118,  118,  117,  117,
- /*   870 */   116,  116,  116,  115,  424,  194,  103,   70,   70,  266,
- /*   880 */   266,  546,   71,   71,  266,  266,   30,  391,  344,  976,
- /*   890 */   976,  978,  543,  528, 1109,  328,  392,  543,  495,  397,
- /*   900 */  1470,  195,  530,   13,   13, 1358,  240, 1109,  277,  280,
- /*   910 */  1109,  280,  304,  457,  306,  333,  392,   31,  188,  419,
- /*   920 */   121,  122,  112, 1165, 1165, 1006, 1009,  999,  999,  119,
- /*   930 */   119,  120,  120,  120,  120,  142,  392,  365,  457,  986,
- /*   940 */   121,  122,  112, 1165, 1165, 1006, 1009,  999,  999,  119,
- /*   950 */   119,  120,  120,  120,  120,  977,  323, 1142,  326,  976,
- /*   960 */   121,  110,  112, 1165, 1165, 1006, 1009,  999,  999,  119,
- /*   970 */   119,  120,  120,  120,  120,  464,  377, 1185,  118,  118,
- /*   980 */   118,  118,  117,  117,  116,  116,  116,  115,  424, 1142,
- /*   990 */   976,  976,  978,  305,    9,  366,  244,  362,  118,  118,
- /*  1000 */   118,  118,  117,  117,  116,  116,  116,  115,  424,  313,
- /*  1010 */   546,  344, 1142, 1143, 1144,  299,  290,  537,  118,  118,
- /*  1020 */   118,  118,  117,  117,  116,  116,  116,  115,  424, 1263,
- /*  1030 */  1263, 1163,   13,   13,  278,  421,  420,  468,  392,  923,
- /*  1040 */   260,  260,  289, 1169, 1142, 1143, 1144,  189, 1171,  266,
- /*  1050 */   266,  468,  390,  543, 1186,  546, 1170,  263,  144,  489,
- /*  1060 */   922,  546,  543,  122,  112, 1165, 1165, 1006, 1009,  999,
- /*  1070 */   999,  119,  119,  120,  120,  120,  120,   71,   71, 1142,
- /*  1080 */  1172, 1272, 1172,   13,   13,  898, 1070, 1163,  546,  468,
- /*  1090 */   897,  107,  538, 1491,    4, 1268, 1109,    6,  525, 1049,
- /*  1100 */    12, 1071, 1092, 1570,  312,  455, 1570,  520,  541, 1109,
- /*  1110 */    56,   56, 1109, 1489,  423, 1358, 1072,    6,  345,  285,
- /*  1120 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,
- /*  1130 */   424,  425, 1271,  321, 1142, 1143, 1144,  878,  266,  266,
- /*  1140 */  1277,  107,  538,  535,    4, 1488,  293,  879, 1211,    6,
- /*  1150 */   210,  543,  543,  164,  294,  496,  416,  204,  541,  267,
- /*  1160 */   267, 1214,  398,  511,  499,  204,  266,  266,  396,  531,
- /*  1170 */     8,  986,  543,  519,  546,  922,  458,  105,  105,  543,
- /*  1180 */  1090,  425,  266,  266,  106,  417,  425,  548,  547,  266,
- /*  1190 */   266,  976,  518,  535, 1373,  543,   15,   15,  266,  266,
- /*  1200 */   456, 1120,  543,  266,  266, 1070, 1372,  515,  290,  537,
- /*  1210 */   546,  543,  514,   97,  444,  316,  543,  546,  922,  125,
- /*  1220 */  1071,  986,  976,  976,  978,  979,   27,  105,  105,  401,
- /*  1230 */   343, 1511,   44,   44,  106, 1072,  425,  548,  547,   57,
- /*  1240 */    57,  976,  343, 1511,  107,  538,  546,    4,  462,  401,
- /*  1250 */   214, 1120,  459,  297,  377, 1091,  534, 1309,  546,  539,
- /*  1260 */   398,  541,  290,  537,  104,  244,  102,  526,   58,   58,
- /*  1270 */   546,  199,  976,  976,  978,  979,   27, 1516, 1131,  427,
- /*  1280 */    59,   59,  270,  237,  425,  138,   95,  375,  375,  374,
- /*  1290 */   255,  372,   60,   60,  817, 1180,  535,  546,  273,  546,
- /*  1300 */  1163, 1308,  389,  388,  546,  438,  546,  215,  210,  296,
- /*  1310 */   515,  849,  546,  265,  208,  516, 1476,  295,  274,   61,
- /*  1320 */    61,   62,   62,  308,  986,  109,   45,   45,   46,   46,
- /*  1330 */   105,  105, 1186,  922,   47,   47,  341,  106,  546,  425,
- /*  1340 */   548,  547, 1542,  546,  976,  867,  340,  217,  546,  937,
- /*  1350 */   397,  107,  538,  218,    4,  156, 1163,  938,  158,  546,
- /*  1360 */    49,   49, 1162,  546,  268,   50,   50,  546,  541, 1450,
- /*  1370 */    63,   63,  546, 1449,  216,  976,  976,  978,  979,   27,
- /*  1380 */   446,   64,   64,  546,  460,   65,   65,  546,  318,   14,
- /*  1390 */    14,  425, 1305,  546,   66,   66, 1087,  546,  141,  379,
- /*  1400 */    38,  546,  963,  535,  322,  127,  127,  546,  393,   67,
- /*  1410 */    67,  546,  325,  290,  537,   52,   52,  515,  546,   68,
- /*  1420 */    68,  845,  514,   69,   69,  399,  165,  857,  856,   53,
- /*  1430 */    53,  986,  311,  151,  151,   97,  432,  105,  105,  327,
- /*  1440 */   152,  152,  526, 1048,  106, 1048,  425,  548,  547, 1131,
- /*  1450 */   427,  976, 1032,  270,  968,  239,  329,  243,  375,  375,
- /*  1460 */   374,  255,  372,  940,  941,  817, 1296,  546,  220,  546,
- /*  1470 */   107,  538,  546,    4,  546, 1256,  199,  845,  215, 1036,
- /*  1480 */   296, 1530,  976,  976,  978,  979,   27,  541,  295,   76,
- /*  1490 */    76,   54,   54,  980,   72,   72,  128,  128,  864,  865,
- /*  1500 */   107,  538,  546,    4, 1047,  546, 1047,  533,  469,  546,
- /*  1510 */   425,  546,  450, 1240,  546,  243,  546,  541,  217,  546,
- /*  1520 */   452,  197,  535,  243,   73,   73,  156,  129,  129,  158,
- /*  1530 */   336,  130,  130,  126,  126, 1036,  150,  150,  149,  149,
- /*  1540 */   425,  134,  134,  317,  474,  216,   97,  239,  331,  980,
- /*  1550 */   986,   97,  535,  346,  347,  546,  105,  105,  902,  931,
- /*  1560 */   546,  895,  243,  106,  109,  425,  548,  547,  546, 1505,
- /*  1570 */   976,  828,   99,  538,  139,    4,  546,  133,  133,  393,
- /*  1580 */   986, 1317,  131,  131,  290,  537,  105,  105, 1357,  541,
- /*  1590 */   132,  132, 1292,  106, 1303,  425,  548,  547,   75,   75,
- /*  1600 */   976,  976,  976,  978,  979,   27,  546,  432,  896, 1289,
- /*  1610 */   532,  109,  425, 1363,  546, 1221, 1213, 1202,  258,  546,
- /*  1620 */   349,  546, 1201,   11,  535, 1203, 1524,  351,   77,   77,
- /*  1630 */   376,  976,  976,  978,  979,   27,   74,   74,  353,  213,
- /*  1640 */   301,   43,   43,   48,   48,  437,  310,  201,  303, 1350,
- /*  1650 */   315,  355,  986,  454,  479, 1239,  339,  192,  105,  105,
- /*  1660 */  1422, 1421,  193,  536,  205,  106, 1527,  425,  548,  547,
- /*  1670 */  1180,  167,  976,  270,  247, 1469, 1467, 1177,  375,  375,
- /*  1680 */   374,  255,  372,  200,  369,  817,  400,   83,   79,   82,
- /*  1690 */  1427,  448,  177,   95, 1342,  161,  169, 1339,  215,  440,
- /*  1700 */   296,  172,  173,  976,  976,  978,  979,   27,  295,  174,
- /*  1710 */   175,  441,  472,  223, 1347,  383,   35,  381,   36,  461,
- /*  1720 */    88, 1353,  181,  447,  384, 1416,  227,  467,  259,  229,
- /*  1730 */   186,  488,  470,  324, 1250,  230,  231,  320,  217, 1204,
- /*  1740 */  1438, 1259,  386, 1258,  413,   90,  156,  849, 1541,  158,
- /*  1750 */   206,  415, 1540,  507, 1300, 1257,   94,  348, 1229, 1301,
- /*  1760 */   387, 1510, 1228,  338, 1227,  216,  350, 1539,  498,  283,
- /*  1770 */   284, 1249,  501, 1299,  352,  245,  246,  418, 1298,  354,
- /*  1780 */  1496, 1495,  124,   10,  526,  363,  101, 1324,  253,   96,
- /*  1790 */   510, 1210,   34,  549, 1137,  254,  256,  257,  166,  393,
- /*  1800 */   550, 1199, 1282,  361,  290,  537, 1281,  196,  367,  368,
- /*  1810 */  1194,  153, 1454,  137,  281, 1323, 1455,  804,  154,  426,
- /*  1820 */   198,  155, 1453, 1452,  292,  212,  202,  432, 1402,  203,
- /*  1830 */   271,  135,  288,   78, 1046, 1044,  960,  168,  157,  881,
- /*  1840 */   170,  219,  309,  222, 1060,  176,  964,  159,  402,   84,
- /*  1850 */   178,  404,   85,   86,   87,  160, 1063,  224,  394,  395,
- /*  1860 */   225, 1059,  146,   18,  226,  319,  243, 1174,  466,  228,
- /*  1870 */  1052,  182,  183,   37,  819,  471,  340,  232,  332,  483,
- /*  1880 */   184,   89,  162,   19,   20,  475,   91,  480,  847,  335,
- /*  1890 */   147,  860,  282,   92,  490,   93, 1125,  148, 1012, 1095,
- /*  1900 */    39,  497, 1096,   40,  500,  262,  207,  264,  930,  187,
- /*  1910 */   925,  109, 1111, 1115, 1113,    7, 1099,  242,   33, 1119,
- /*  1920 */    21,  522,   22,   23,   24, 1118,   25,  190,   97,   26,
- /*  1930 */  1027, 1013, 1011, 1015, 1069, 1016, 1068,  249,  248,   28,
- /*  1940 */    41,  891,  981,  829,  108,   29,  250,  542,  251,  370,
- /*  1950 */   373, 1133, 1132, 1190, 1190, 1190, 1190, 1190, 1190, 1190,
- /*  1960 */  1532, 1531,
+ /*     0 */   563, 1295,  563, 1274,  168,  361,  115,  112,  218,  373,
+ /*    10 */   563, 1295,  374,  563,  488,  563,  115,  112,  218,  406,
+ /*    20 */  1300, 1300,   41,   41,   41,   41,  514, 1504,  520, 1298,
+ /*    30 */  1298,  959,   41,   41, 1257,   71,   71,   51,   51,  960,
+ /*    40 */   557,  557,  557,  122,  123,  113, 1200, 1200, 1035, 1038,
+ /*    50 */  1028, 1028,  120,  120,  121,  121,  121,  121,  414,  406,
+ /*    60 */   273,  273,  273,  273,  115,  112,  218,  115,  112,  218,
+ /*    70 */   197,  268,  545,  560,  515,  560, 1260,  563,  385,  248,
+ /*    80 */   215,  521,  399,  122,  123,  113, 1200, 1200, 1035, 1038,
+ /*    90 */  1028, 1028,  120,  120,  121,  121,  121,  121,  540,   13,
+ /*   100 */    13, 1259,  119,  119,  119,  119,  118,  118,  117,  117,
+ /*   110 */   117,  116,  441, 1176,  419, 1531,  446,  137,  512, 1539,
+ /*   120 */  1545,  372, 1547,    6,  371, 1176, 1148, 1584, 1148,  406,
+ /*   130 */  1545,  534,  115,  112,  218, 1267,   99,  441,  121,  121,
+ /*   140 */   121,  121,  119,  119,  119,  119,  118,  118,  117,  117,
+ /*   150 */   117,  116,  441,  122,  123,  113, 1200, 1200, 1035, 1038,
+ /*   160 */  1028, 1028,  120,  120,  121,  121,  121,  121,  197, 1176,
+ /*   170 */  1177, 1178,  241,  304,  554,  501,  498,  497,  473,  124,
+ /*   180 */   394, 1176, 1177, 1178, 1176,  496,  119,  119,  119,  119,
+ /*   190 */   118,  118,  117,  117,  117,  116,  441,  139,  540,  406,
+ /*   200 */   121,  121,  121,  121,  114,  117,  117,  117,  116,  441,
+ /*   210 */   541, 1532,  119,  119,  119,  119,  118,  118,  117,  117,
+ /*   220 */   117,  116,  441,  122,  123,  113, 1200, 1200, 1035, 1038,
+ /*   230 */  1028, 1028,  120,  120,  121,  121,  121,  121,  406,  320,
+ /*   240 */  1176, 1177, 1178,   81,  342, 1590,  396,   80,  119,  119,
+ /*   250 */   119,  119,  118,  118,  117,  117,  117,  116,  441, 1176,
+ /*   260 */   211,  450,  122,  123,  113, 1200, 1200, 1035, 1038, 1028,
+ /*   270 */  1028,  120,  120,  121,  121,  121,  121,  251,  450,  449,
+ /*   280 */   273,  273,  119,  119,  119,  119,  118,  118,  117,  117,
+ /*   290 */   117,  116,  441,  560, 1224,    1,    1,  569,    2, 1228,
+ /*   300 */   317, 1176,  319, 1561,  305,  337,  140,  340,  406,  430,
+ /*   310 */   469, 1533, 1197, 1308,  348, 1176, 1177, 1178,  168,  462,
+ /*   320 */   330,  119,  119,  119,  119,  118,  118,  117,  117,  117,
+ /*   330 */   116,  441,  122,  123,  113, 1200, 1200, 1035, 1038, 1028,
+ /*   340 */  1028,  120,  120,  121,  121,  121,  121,  273,  273,  563,
+ /*   350 */    83,  450,  416, 1564,  569,    2, 1228, 1176, 1177, 1178,
+ /*   360 */   560,  305,  471,  140,  944,  995,  860,  563,  467, 1197,
+ /*   370 */  1308,   13,   13,  137,  229,  118,  118,  117,  117,  117,
+ /*   380 */   116,  441,   96,  318,  946,  504,  424,  361,  562,   71,
+ /*   390 */    71,  119,  119,  119,  119,  118,  118,  117,  117,  117,
+ /*   400 */   116,  441,  427,  205,  273,  273,  445, 1015,  259,  276,
+ /*   410 */   356,  507,  351,  506,  246,  406,  959,  560,  328,  344,
+ /*   420 */   347,  315,  860, 1006,  960,  126,  545, 1005,  313,  304,
+ /*   430 */   554,  229,  538, 1539,  148,  544,  281,    6,  203,  122,
+ /*   440 */   123,  113, 1200, 1200, 1035, 1038, 1028, 1028,  120,  120,
+ /*   450 */   121,  121,  121,  121,  563,  217,  563,   12,  406, 1005,
+ /*   460 */  1005, 1007,  502,  445,  119,  119,  119,  119,  118,  118,
+ /*   470 */   117,  117,  117,  116,  441,  452,   71,   71,   70,   70,
+ /*   480 */   944,  137,  122,  123,  113, 1200, 1200, 1035, 1038, 1028,
+ /*   490 */  1028,  120,  120,  121,  121,  121,  121, 1530,  119,  119,
+ /*   500 */   119,  119,  118,  118,  117,  117,  117,  116,  441,  403,
+ /*   510 */   402,  241, 1176,  545,  501,  498,  497, 1468, 1143,  451,
+ /*   520 */   267,  267,  513, 1540,  496,  142, 1176,    6,  406,  530,
+ /*   530 */   194, 1143,  864,  560, 1143,  461,  182,  304,  554,   32,
+ /*   540 */   379,  119,  119,  119,  119,  118,  118,  117,  117,  117,
+ /*   550 */   116,  441,  122,  123,  113, 1200, 1200, 1035, 1038, 1028,
+ /*   560 */  1028,  120,  120,  121,  121,  121,  121,  406, 1176, 1177,
+ /*   570 */  1178,  857,  568, 1176, 1228,  925, 1176,  454,  361,  305,
+ /*   580 */   189,  140, 1176, 1177, 1178,  519,  529,  404, 1308,  183,
+ /*   590 */  1015,  122,  123,  113, 1200, 1200, 1035, 1038, 1028, 1028,
+ /*   600 */   120,  120,  121,  121,  121,  121, 1006,   16,   16,  370,
+ /*   610 */  1005,  119,  119,  119,  119,  118,  118,  117,  117,  117,
+ /*   620 */   116,  441,  273,  273, 1537,  150, 1176,   98,    6, 1176,
+ /*   630 */  1177, 1178, 1176, 1177, 1178,  560,  380,  406,  376,  438,
+ /*   640 */   437, 1161, 1005, 1005, 1007, 1025, 1025, 1036, 1039,  229,
+ /*   650 */   119,  119,  119,  119,  118,  118,  117,  117,  117,  116,
+ /*   660 */   441,  122,  123,  113, 1200, 1200, 1035, 1038, 1028, 1028,
+ /*   670 */   120,  120,  121,  121,  121,  121,  406, 1143, 1619,  392,
+ /*   680 */  1016,  445, 1176, 1177, 1178, 1207,  525, 1207, 1530,  995,
+ /*   690 */  1143,  304,  554, 1143,    5,  563,  543,    3,  361,  216,
+ /*   700 */   122,  123,  113, 1200, 1200, 1035, 1038, 1028, 1028,  120,
+ /*   710 */   120,  121,  121,  121,  121,  143,  563,   13,   13, 1029,
+ /*   720 */   119,  119,  119,  119,  118,  118,  117,  117,  117,  116,
+ /*   730 */   441, 1176,  426,  563, 1176,  563,  274,  274,   13,   13,
+ /*   740 */  1078, 1176,  328,  457,  316,  147,  406,  211,  361,  560,
+ /*   750 */  1000,  213,  511,  293,  477,   55,   55,   71,   71,  119,
+ /*   760 */   119,  119,  119,  118,  118,  117,  117,  117,  116,  441,
+ /*   770 */   122,  123,  113, 1200, 1200, 1035, 1038, 1028, 1028,  120,
+ /*   780 */   120,  121,  121,  121,  121,  406,  455, 1176, 1177, 1178,
+ /*   790 */  1176, 1177, 1178,  471,  526,  149,  404, 1176, 1177, 1178,
+ /*   800 */   105,  270,  103,  563,  944,  563,  116,  441, 1530,  122,
+ /*   810 */   123,  113, 1200, 1200, 1035, 1038, 1028, 1028,  120,  120,
+ /*   820 */   121,  121,  121,  121,  945,   13,   13,   13,   13,  119,
+ /*   830 */   119,  119,  119,  118,  118,  117,  117,  117,  116,  441,
+ /*   840 */   191,  563,  192,  563,  416,  439,  439,  439, 1083, 1083,
+ /*   850 */   485,  561,  285,  914,  914,  406,  462,  330, 1530,  830,
+ /*   860 */   831,  832,  206,   71,   71,   71,   71,  286,  119,  119,
+ /*   870 */   119,  119,  118,  118,  117,  117,  117,  116,  441,  122,
+ /*   880 */   123,  113, 1200, 1200, 1035, 1038, 1028, 1028,  120,  120,
+ /*   890 */   121,  121,  121,  121,  563,  217,  563, 1122, 1617,  406,
+ /*   900 */   300, 1617,  301,  416, 1278, 1473,  244,  243,  242, 1249,
+ /*   910 */   412,  556,  412,  282,  842,  279,   71,   71,   71,   71,
+ /*   920 */   944, 1415, 1473, 1475,  101,  113, 1200, 1200, 1035, 1038,
+ /*   930 */  1028, 1028,  120,  120,  121,  121,  121,  121,  119,  119,
+ /*   940 */   119,  119,  118,  118,  117,  117,  117,  116,  441,  273,
+ /*   950 */   273, 1099,  563,  436, 1143,  440,  563, 1122, 1618,  357,
+ /*   960 */  1558, 1618,  560,  546,  488,  197, 1100, 1143,  378,  290,
+ /*   970 */  1143, 1306,  284,  460,   71,   71, 1120,  405,   13,   13,
+ /*   980 */   145, 1101,  119,  119,  119,  119,  118,  118,  117,  117,
+ /*   990 */   117,  116,  441,  542,  104, 1473,  509,  273,  273,  294,
+ /*  1000 */  1514,  294,  900,  273,  273,  273,  273,  563, 1503,  563,
+ /*  1010 */   560,  545,  901,  464,  406, 1058,  560,  852,  560,  198,
+ /*  1020 */   547, 1080,  920,  404, 1400, 1080,  146,  919,   38,   56,
+ /*  1030 */    56,   15,   15,  563,  406,   12, 1120,  471,  122,  123,
+ /*  1040 */   113, 1200, 1200, 1035, 1038, 1028, 1028,  120,  120,  121,
+ /*  1050 */   121,  121,  121, 1460,  406,   43,   43,  483,  122,  123,
+ /*  1060 */   113, 1200, 1200, 1035, 1038, 1028, 1028,  120,  120,  121,
+ /*  1070 */   121,  121,  121,  563,  852,    9,  471,  251,  122,  111,
+ /*  1080 */   113, 1200, 1200, 1035, 1038, 1028, 1028,  120,  120,  121,
+ /*  1090 */   121,  121,  121,  563,  421,   57,   57,  119,  119,  119,
+ /*  1100 */   119,  118,  118,  117,  117,  117,  116,  441, 1176,  493,
+ /*  1110 */   563,  289, 1197,  478, 1516,   44,   44,  119,  119,  119,
+ /*  1120 */   119,  118,  118,  117,  117,  117,  116,  441,  880,  563,
+ /*  1130 */   536,  563,   58,   58,  488, 1414,  245,  119,  119,  119,
+ /*  1140 */   119,  118,  118,  117,  117,  117,  116,  441,  563,  535,
+ /*  1150 */   291,   59,   59,   60,   60,  438,  437,  406, 1154,  505,
+ /*  1160 */   304,  554,  477, 1204, 1176, 1177, 1178,  881, 1206, 1197,
+ /*  1170 */    61,   61, 1246,  357, 1558, 1538, 1205,  563, 1467,    6,
+ /*  1180 */  1176,  488,  123,  113, 1200, 1200, 1035, 1038, 1028, 1028,
+ /*  1190 */   120,  120,  121,  121,  121,  121, 1400, 1143,  410,   62,
+ /*  1200 */    62, 1207, 1099, 1207,  411,  447,  273,  273,  537, 1154,
+ /*  1210 */  1143,  108,  555, 1143,    4,  391, 1220, 1100, 1512,  560,
+ /*  1220 */   347,  516,  428,  548,  308, 1307, 1536, 1077,  558, 1077,
+ /*  1230 */     6,  488, 1101, 1400,  488,  309, 1176, 1177, 1178,  563,
+ /*  1240 */   119,  119,  119,  119,  118,  118,  117,  117,  117,  116,
+ /*  1250 */   441,  442,  278,  551,  563,  273,  273,  273,  273,  563,
+ /*  1260 */   327,   45,   45,  552,  563,  528,  422,  563,  560, 1400,
+ /*  1270 */   560,  108,  555,  137,    4, 1303,   46,   46,  335,  563,
+ /*  1280 */   482,   47,   47,  477,  479,  307,   49,   49,  558,   50,
+ /*  1290 */    50,  563, 1015,  563, 1221,  563, 1400,  563,  106,  106,
+ /*  1300 */     8,   63,   63,  423,  563,  107,  312,  442,  565,  564,
+ /*  1310 */   563,  442, 1005,   64,   64,   65,   65,   14,   14,   66,
+ /*  1320 */    66,  391, 1121,  552, 1312, 1180,  128,  128,  563,  304,
+ /*  1330 */   554,  563,   67,   67,  563,  359,  560,  532,  563,  484,
+ /*  1340 */   563, 1196,  531,  222, 1005, 1005, 1007, 1008,   27,  522,
+ /*  1350 */    52,   52, 1015,   68,   68,  563,   69,   69,  106,  106,
+ /*  1360 */    53,   53,  156,  156,  563,  107,  434,  442,  565,  564,
+ /*  1370 */   272,  215, 1005,  425,  563,  359,  563,  157,  157,  563,
+ /*  1380 */  1535,  292, 1180,   98,    6, 1344,   76,   76, 1215,  475,
+ /*  1390 */   413,  169,  226,  563,  245,  563,   54,   54,   72,   72,
+ /*  1400 */  1221,  129,  129, 1343, 1005, 1005, 1007, 1008,   27, 1563,
+ /*  1410 */  1165,  444,  456,  433,  277,   73,   73,  130,  130,  389,
+ /*  1420 */   389,  388,  262,  386, 1165,  444,  839, 1519,  277,  108,
+ /*  1430 */   555,  321,    4,  389,  389,  388,  262,  386,  563,  223,
+ /*  1440 */   839,  311,  468,   84,  202,  523,  558, 1492,  303,  310,
+ /*  1450 */   563,  110,  404,  223,  563,  311,  206,   30,  404,  277,
+ /*  1460 */   131,  131,  411,  310,  389,  389,  388,  262,  386,  442,
+ /*  1470 */   920,  839,  127,  127,  563,  919,  155,  155, 1491,  225,
+ /*  1480 */   563,  552,  871,  563,  223,  476,  311,  161,   31,  563,
+ /*  1490 */   135,  563,  480,  225,  310,  532,  154,  154,  332,   17,
+ /*  1500 */   533,  161,  136,  136,  135,  134,  134,  224,  228,  355,
+ /*  1510 */  1015,  132,  132,  133,  133, 1589,  106,  106,  889,  354,
+ /*  1520 */   563,  224,  563,  107,  225,  442,  565,  564, 1117,  275,
+ /*  1530 */  1005,  393,  161,  518,  563,  135,  108,  555,  417,    4,
+ /*  1540 */  1340,  407,   75,   75,   77,   77,  304,  554,  867,  563,
+ /*  1550 */   336,  563,  224,  558,  463,  407,   74,   74,  465, 1065,
+ /*  1560 */   304,  554, 1005, 1005, 1007, 1008,   27,  962,  963,  543,
+ /*  1570 */   448,   42,   42,   48,   48,  326,  442,  325,   98,  997,
+ /*  1580 */   470,  287,  250,  250,  448, 1009,  407,  472,  552,  339,
+ /*  1590 */   250,  304,  554,  879,  878,  331,  108,  555,   98,    4,
+ /*  1600 */  1277,  494,  532,  345,  247,  867,   98,  531,  341,  886,
+ /*  1610 */   887, 1126, 1076,  558, 1076,  448, 1065, 1015, 1061,  953,
+ /*  1620 */   343,  247,  250,  106,  106, 1291,  917, 1276,  850,  110,
+ /*  1630 */   107,  144,  442,  565,  564,  918,  442, 1005,  110, 1275,
+ /*  1640 */   350,  360, 1009, 1331, 1352,  299, 1399, 1577,  552, 1327,
+ /*  1650 */  1552,  550, 1338,  549, 1405, 1256, 1248, 1237, 1236, 1238,
+ /*  1660 */  1571,  489,  265,  200, 1324,  363,  365,  367,   11, 1005,
+ /*  1670 */  1005, 1007, 1008,   27,  390,  221, 1386, 1015,  280, 1391,
+ /*  1680 */  1381,  208,  323,  106,  106,  924, 1374,  453,  283,  324,
+ /*  1690 */   107,  474,  442,  565,  564, 1390,  499, 1005,  212,  288,
+ /*  1700 */  1274,  397,  353,  108,  555,  195,    4, 1464,  369, 1463,
+ /*  1710 */  1574, 1215, 1212,  329,  553,  171,  207,  383, 1511,  196,
+ /*  1720 */   558,  254, 1509,  415,  100,  555,   83,    4,  204, 1005,
+ /*  1730 */  1005, 1007, 1008,   27,  219,   79,   82, 1469,  180,  166,
+ /*  1740 */   173,  558,  458,  442,  175,  176,  177,  178,   35, 1387,
+ /*  1750 */   492,  459,  231, 1395,   96,  552, 1393, 1392,  395,  184,
+ /*  1760 */   481,  466,   36,  235,  442,   89,  398,  266,  487, 1480,
+ /*  1770 */  1458,  237,  188,  338,  508,  429,  552,  490,  400,  238,
+ /*  1780 */   334, 1239,  239, 1294, 1015, 1293, 1292, 1285,   91,  871,
+ /*  1790 */   106,  106,  213,  431, 1588,  432,  524,  107,  517,  442,
+ /*  1800 */   565,  564,  401, 1264, 1005, 1015, 1263, 1587,  352, 1262,
+ /*  1810 */  1557,  106,  106, 1586, 1284,  297,  298,  358,  107, 1335,
+ /*  1820 */   442,  565,  564,   95,  362, 1005,  253,  252,  435,  125,
+ /*  1830 */   543,   10, 1444, 1543,  377, 1542, 1005, 1005, 1007, 1008,
+ /*  1840 */    27,  302,  102,   97,  527, 1336,  260, 1317,  364, 1245,
+ /*  1850 */  1334,   34,  566, 1171,  366,  381,  375, 1005, 1005, 1007,
+ /*  1860 */  1008,   27, 1333, 1359,  368, 1316,  199,  382,  261,  263,
+ /*  1870 */   264, 1358,  158, 1496,  141, 1497, 1495,  567, 1234, 1229,
+ /*  1880 */  1494,  295,  159,  209,  210,   78,  826,  443,  201,  306,
+ /*  1890 */   220, 1075,  138, 1073,  160,  314,  162,  172, 1196,  174,
+ /*  1900 */   903,  227,  230,  322, 1089,  179,  163,  164,  418,   85,
+ /*  1910 */   420,  181,  170,  408,  409,   86,   87,  165,   88, 1092,
+ /*  1920 */   232,  233, 1088,  151,   18,  234, 1081,  250,  333,  185,
+ /*  1930 */  1209,  486,  236,  186,   37,  841,  491,  354,  240,  346,
+ /*  1940 */   503,  187,   90,  167,   19,  495,   20,  869,  500,  349,
+ /*  1950 */    92,  882,  296,  152,   93,  510, 1127, 1159,  153, 1041,
+ /*  1960 */   214, 1128,   39,   94,  269,  271,  952,  190,  947,  110,
+ /*  1970 */  1149, 1145, 1153,  249, 1133, 1147,    7,   33,   21,  193,
+ /*  1980 */    22,   23,   24,   25, 1152,  539,   98, 1056,   26, 1042,
+ /*  1990 */  1040, 1044, 1098, 1045, 1097,  256,  255,   28,   40,  387,
+ /*  2000 */  1010,  851,  109,   29, 1167,  559,  384,  257,  913,  258,
+ /*  2010 */  1166, 1579, 1225, 1225, 1225, 1225, 1225, 1225, 1225, 1578,
 };
 static const YYCODETYPE yy_lookahead[] = {
- /*     0 */   189,  211,  189,  189,  218,  189,  220,  189,  267,  268,
- /*    10 */   269,  189,  210,  189,  228,  189,  267,  268,  269,   19,
- /*    20 */   218,  189,  211,  212,  211,  212,  211,  211,  212,  211,
- /*    30 */   212,   31,  211,  211,  212,  211,  212,  288,  300,   39,
- /*    40 */    21,  189,  304,   43,   44,   45,   46,   47,   48,   49,
- /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  225,   19,
- /*    60 */   189,  183,  184,  185,  186,  189,  248,  263,  236,  191,
- /*    70 */   248,  193,  248,  197,  208,  257,  262,  201,  200,  257,
- /*    80 */   200,  257,   81,   43,   44,   45,   46,   47,   48,   49,
- /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  189,   80,
- /*   100 */   189,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   110 */   110,  111,  234,  235,  234,  235,  305,  306,  305,  118,
- /*   120 */   307,  305,  306,  297,  298,  247,   86,  247,   88,   19,
- /*   130 */   259,  251,  252,  267,  268,  269,   26,  136,  137,  261,
- /*   140 */   121,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   150 */   110,  111,   59,   43,   44,   45,   46,   47,   48,   49,
- /*   160 */    50,   51,   52,   53,   54,   55,   56,   57,  259,  291,
- /*   170 */   105,  106,  107,  108,  109,  110,  111,  158,  189,   69,
- /*   180 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,
- /*   190 */   111,  107,  108,  109,  110,  111,  205,  206,  207,   19,
- /*   200 */    19,   54,   55,   56,   57,   58,   29,  114,  115,  116,
- /*   210 */    33,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   220 */   110,  111,  233,   43,   44,   45,   46,   47,   48,   49,
- /*   230 */    50,   51,   52,   53,   54,   55,   56,   57,   19,  126,
- /*   240 */   127,  148,   65,   24,  214,  200,   59,   67,  101,  102,
- /*   250 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   22,
- /*   260 */   189,  111,   43,   44,   45,   46,   47,   48,   49,   50,
- /*   270 */    51,   52,   53,   54,   55,   56,   57,  206,  207,  234,
- /*   280 */   235,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   290 */   110,  111,  247,   76,  107,  114,   59,  267,  268,  269,
- /*   300 */   189,  114,  115,  116,  162,  163,   89,   19,  263,   92,
- /*   310 */   189,   23,   54,   55,   56,   57,  189,  206,  207,   22,
- /*   320 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,
- /*   330 */   111,   43,   44,   45,   46,   47,   48,   49,   50,   51,
- /*   340 */    52,   53,   54,   55,   56,   57,   19,  189,  277,   59,
- /*   350 */    23,  114,  115,  116,   46,   47,   48,   49,   61,  101,
- /*   360 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
- /*   370 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   380 */    53,   54,   55,   56,   57,  125,  126,  127,  277,  101,
- /*   390 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
- /*   400 */    59,  189,  189,  276,  114,  115,  116,  117,   73,   59,
- /*   410 */   120,  121,  122,   72,  214,   19,   81,  259,   19,   23,
- /*   420 */   130,   81,   72,   24,  211,  212,  221,  119,  101,  102,
- /*   430 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   43,
+ /*     0 */   191,  220,  191,  222,  191,  191,  271,  272,  273,  216,
+ /*    10 */   191,  230,  216,  191,  191,  191,  271,  272,  273,   19,
+ /*    20 */   232,  233,  213,  214,  213,  214,  202,  292,  202,  232,
+ /*    30 */   233,   31,  213,  214,  213,  213,  214,  213,  214,   39,
+ /*    40 */   207,  208,  209,   43,   44,   45,   46,   47,   48,   49,
+ /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  235,   19,
+ /*    60 */   236,  237,  236,  237,  271,  272,  273,  271,  272,  273,
+ /*    70 */   191,  210,  250,  249,  250,  249,  213,  191,  199,  253,
+ /*    80 */   254,  259,  203,   43,   44,   45,   46,   47,   48,   49,
+ /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  191,  213,
+ /*   100 */   214,  213,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   110 */   110,  111,  112,   59,  228,  301,  293,   81,  305,  306,
+ /*   120 */   311,  312,  311,  310,  313,   59,   86,  212,   88,   19,
+ /*   130 */   311,  312,  271,  272,  273,  220,   26,  112,   54,   55,
+ /*   140 */    56,   57,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   150 */   110,  111,  112,   43,   44,   45,   46,   47,   48,   49,
+ /*   160 */    50,   51,   52,   53,   54,   55,   56,   57,  191,  115,
+ /*   170 */   116,  117,  118,  137,  138,  121,  122,  123,  191,   69,
+ /*   180 */   203,  115,  116,  117,   59,  131,  102,  103,  104,  105,
+ /*   190 */   106,  107,  108,  109,  110,  111,  112,   72,  191,   19,
+ /*   200 */    54,   55,   56,   57,   58,  108,  109,  110,  111,  112,
+ /*   210 */   303,  304,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   220 */   110,  111,  112,   43,   44,   45,   46,   47,   48,   49,
+ /*   230 */    50,   51,   52,   53,   54,   55,   56,   57,   19,   16,
+ /*   240 */   115,  116,  117,   24,   16,  227,  202,   67,  102,  103,
+ /*   250 */   104,  105,  106,  107,  108,  109,  110,  111,  112,   59,
+ /*   260 */    26,  191,   43,   44,   45,   46,   47,   48,   49,   50,
+ /*   270 */    51,   52,   53,   54,   55,   56,   57,   24,  208,  209,
+ /*   280 */   236,  237,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   290 */   110,  111,  112,  249,  183,  184,  185,  186,  187,  188,
+ /*   300 */    77,   59,   79,  191,  193,   77,  195,   79,   19,   19,
+ /*   310 */   266,  304,   59,  202,   24,  115,  116,  117,  191,  127,
+ /*   320 */   128,  102,  103,  104,  105,  106,  107,  108,  109,  110,
+ /*   330 */   111,  112,   43,   44,   45,   46,   47,   48,   49,   50,
+ /*   340 */    51,   52,   53,   54,   55,   56,   57,  236,  237,  191,
+ /*   350 */   150,  281,  191,  185,  186,  187,  188,  115,  116,  117,
+ /*   360 */   249,  193,  191,  195,   26,   73,   59,  191,  114,  116,
+ /*   370 */   202,  213,  214,   81,  263,  106,  107,  108,  109,  110,
+ /*   380 */   111,  112,  148,  160,  142,   95,  228,  191,  191,  213,
+ /*   390 */   214,  102,  103,  104,  105,  106,  107,  108,  109,  110,
+ /*   400 */   111,  112,  112,  149,  236,  237,  295,  100,  118,  119,
+ /*   410 */   120,  121,  122,  123,  124,   19,   31,  249,  126,   23,
+ /*   420 */   130,  260,  115,  116,   39,   22,  250,  120,  191,  137,
+ /*   430 */   138,  263,  305,  306,  238,  259,  265,  310,  149,   43,
  /*   440 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
- /*   450 */    54,   55,   56,   57,   19,  114,  115,  116,   23,  208,
- /*   460 */   125,  248,  189,  189,  114,  115,  116,  267,  268,  269,
- /*   470 */   189,  136,  137,  189,  262,   22,  136,  137,   43,   44,
- /*   480 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,
- /*   490 */    55,   56,   57,  189,   95,  211,  212,  101,  102,  103,
- /*   500 */   104,  105,  106,  107,  108,  109,  110,  111,   59,  189,
- /*   510 */   111,  189,   59,   76,  294,  295,  117,  118,  119,  120,
- /*   520 */   121,  122,  123,   19,   87,  189,   89,   23,  129,   92,
- /*   530 */   279,  227,  248,   22,  189,  284,  101,  102,  103,  104,
- /*   540 */   105,  106,  107,  108,  109,  110,  111,   43,   44,   45,
- /*   550 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
- /*   560 */    56,   57,   19,  114,  115,  116,   23,  114,  115,  116,
- /*   570 */    59,  117,  299,  300,  120,  121,  122,  304,  189,  189,
- /*   580 */   143,  189,  110,  111,  130,   22,   43,   44,   45,   46,
- /*   590 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
- /*   600 */    57,  211,  212,  211,  212,  101,  102,  103,  104,  105,
- /*   610 */   106,  107,  108,  109,  110,  111,  226,  189,  226,  189,
- /*   620 */   298,  132,   59,  134,  135,  114,  115,  116,  189,   59,
- /*   630 */   285,   19,    7,    8,    9,   23,  205,  206,  207,  211,
- /*   640 */   212,  211,  212,  221,  101,  102,  103,  104,  105,  106,
- /*   650 */   107,  108,  109,  110,  111,   43,   44,   45,   46,   47,
- /*   660 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
- /*   670 */    19,  181,  182,  183,  184,  185,  186,  114,  115,  116,
- /*   680 */   189,  191,  133,  193,  114,  115,  116,  138,  299,  300,
- /*   690 */   200,   22,  201,  304,   43,   44,   45,   46,   47,   48,
- /*   700 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   35,
- /*   710 */   189,  141,  189,  101,  102,  103,  104,  105,  106,  107,
- /*   720 */   108,  109,  110,  111,  234,  235,   22,   23,   59,  184,
- /*   730 */    26,  186,  211,  212,  211,  212,  191,  247,  193,   19,
- /*   740 */    66,  105,  106,   73,  189,  200,  189,  226,   74,  226,
- /*   750 */    22,  261,  101,  102,  103,  104,  105,  106,  107,  108,
- /*   760 */   109,  110,  111,   43,   44,   45,   46,   47,   48,   49,
- /*   770 */    50,   51,   52,   53,   54,   55,   56,   57,  189,  234,
- /*   780 */   235,  291,   19,  114,  115,  116,  150,   59,  152,  189,
- /*   790 */   233,  236,  247,   59,  189,  125,  126,  127,   59,  300,
- /*   800 */   211,  212,  128,  304,  100,   19,  261,  156,   45,   46,
- /*   810 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
- /*   820 */    57,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   830 */   110,  111,   46,  233,  189,  189,  291,  248,   99,  189,
- /*   840 */   125,  126,  127,  115,   26,  200,  289,  230,  231,  115,
- /*   850 */   200,   16,  189,  114,  115,  189,  211,  212,  119,  221,
- /*   860 */   189,  211,  212,  258,  101,  102,  103,  104,  105,  106,
- /*   870 */   107,  108,  109,  110,  111,  189,  156,  211,  212,  234,
- /*   880 */   235,  189,  211,  212,  234,  235,   22,  201,  189,  150,
- /*   890 */   151,  152,  247,  248,   76,   16,   19,  247,  248,  113,
- /*   900 */   189,   24,  257,  211,  212,  189,   26,   89,  262,  223,
- /*   910 */    92,  225,   77,  189,   79,  129,   19,   53,  226,  248,
- /*   920 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   930 */    53,   54,   55,   56,   57,  236,   19,  271,  189,   99,
- /*   940 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   950 */    53,   54,   55,   56,   57,  115,   77,   59,   79,  119,
- /*   960 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   970 */    53,   54,   55,   56,   57,  259,   22,   23,  101,  102,
- /*   980 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   59,
- /*   990 */   150,  151,  152,  158,   22,  244,   24,  246,  101,  102,
- /*  1000 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  285,
- /*  1010 */   189,  189,  114,  115,  116,  200,  136,  137,  101,  102,
- /*  1020 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  230,
- /*  1030 */   231,   59,  211,  212,  285,  105,  106,  189,   19,  141,
- /*  1040 */   234,  235,  239,  113,  114,  115,  116,  226,  118,  234,
- /*  1050 */   235,  189,  249,  247,  100,  189,  126,   23,  236,  107,
- /*  1060 */    26,  189,  247,   44,   45,   46,   47,   48,   49,   50,
- /*  1070 */    51,   52,   53,   54,   55,   56,   57,  211,  212,   59,
- /*  1080 */   150,  233,  152,  211,  212,  133,   12,  115,  189,  189,
- /*  1090 */   138,   19,   20,  300,   22,  233,   76,  304,  226,   11,
- /*  1100 */   208,   27,   22,   23,  200,   19,   26,   87,   36,   89,
- /*  1110 */   211,  212,   92,  300,  248,  189,   42,  304,  189,  250,
- /*  1120 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,
- /*  1130 */   111,   59,  200,  233,  114,  115,  116,   63,  234,  235,
- /*  1140 */   235,   19,   20,   71,   22,  300,  189,   73,  200,  304,
- /*  1150 */   116,  247,  247,   81,  189,  200,  227,   26,   36,  234,
- /*  1160 */   235,  203,  204,  143,  200,   26,  234,  235,  194,  200,
- /*  1170 */    48,   99,  247,   66,  189,  141,  284,  105,  106,  247,
- /*  1180 */   100,   59,  234,  235,  112,  259,  114,  115,  116,  234,
- /*  1190 */   235,  119,   85,   71,  266,  247,  211,  212,  234,  235,
- /*  1200 */   114,   94,  247,  234,  235,   12,  266,   85,  136,  137,
- /*  1210 */   189,  247,   90,   26,  126,  127,  247,  189,   26,   22,
- /*  1220 */    27,   99,  150,  151,  152,  153,  154,  105,  106,  189,
- /*  1230 */   302,  303,  211,  212,  112,   42,  114,  115,  116,  211,
- /*  1240 */   212,  119,  302,  303,   19,   20,  189,   22,  274,  189,
- /*  1250 */    15,  144,  278,  189,   22,   23,   63,  189,  189,  203,
- /*  1260 */   204,   36,  136,  137,  155,   24,  157,  143,  211,  212,
- /*  1270 */   189,  140,  150,  151,  152,  153,  154,    0,    1,    2,
- /*  1280 */   211,  212,    5,   46,   59,  161,  147,   10,   11,   12,
- /*  1290 */    13,   14,  211,  212,   17,   60,   71,  189,  258,  189,
- /*  1300 */    59,  189,  105,  106,  189,  189,  189,   30,  116,   32,
- /*  1310 */    85,  124,  189,  251,  252,   90,  189,   40,  258,  211,
- /*  1320 */   212,  211,  212,  189,   99,   26,  211,  212,  211,  212,
- /*  1330 */   105,  106,  100,  141,  211,  212,  119,  112,  189,  114,
- /*  1340 */   115,  116,   23,  189,  119,   26,  129,   70,  189,   31,
- /*  1350 */   113,   19,   20,   24,   22,   78,  115,   39,   81,  189,
- /*  1360 */   211,  212,   26,  189,   22,  211,  212,  189,   36,  189,
- /*  1370 */   211,  212,  189,  189,   97,  150,  151,  152,  153,  154,
- /*  1380 */   127,  211,  212,  189,  189,  211,  212,  189,  189,  211,
- /*  1390 */   212,   59,  189,  189,  211,  212,   23,  189,   22,   26,
- /*  1400 */    24,  189,  149,   71,  189,  211,  212,  189,  131,  211,
- /*  1410 */   212,  189,  189,  136,  137,  211,  212,   85,  189,  211,
- /*  1420 */   212,   59,   90,  211,  212,  292,  293,  118,  119,  211,
- /*  1430 */   212,   99,   23,  211,  212,   26,  159,  105,  106,  189,
- /*  1440 */   211,  212,  143,  150,  112,  152,  114,  115,  116,    1,
- /*  1450 */     2,  119,   23,    5,   23,   26,  189,   26,   10,   11,
- /*  1460 */    12,   13,   14,   83,   84,   17,  253,  189,  139,  189,
- /*  1470 */    19,   20,  189,   22,  189,  189,  140,  115,   30,   59,
- /*  1480 */    32,  139,  150,  151,  152,  153,  154,   36,   40,  211,
- /*  1490 */   212,  211,  212,   59,  211,  212,  211,  212,    7,    8,
- /*  1500 */    19,   20,  189,   22,  150,  189,  152,  231,  281,  189,
- /*  1510 */    59,  189,   23,  189,  189,   26,  189,   36,   70,  189,
- /*  1520 */    23,  237,   71,   26,  211,  212,   78,  211,  212,   81,
- /*  1530 */   189,  211,  212,  211,  212,  115,  211,  212,  211,  212,
- /*  1540 */    59,  211,  212,   23,   23,   97,   26,   26,   23,  115,
- /*  1550 */    99,   26,   71,  189,  189,  189,  105,  106,  107,   23,
- /*  1560 */   189,   23,   26,  112,   26,  114,  115,  116,  189,  309,
- /*  1570 */   119,   23,   19,   20,   26,   22,  189,  211,  212,  131,
- /*  1580 */    99,  189,  211,  212,  136,  137,  105,  106,  189,   36,
- /*  1590 */   211,  212,  189,  112,  189,  114,  115,  116,  211,  212,
- /*  1600 */   119,  150,  151,  152,  153,  154,  189,  159,   23,  250,
- /*  1610 */   189,   26,   59,  189,  189,  189,  189,  189,  280,  189,
- /*  1620 */   250,  189,  189,  238,   71,  189,  189,  250,  211,  212,
- /*  1630 */   187,  150,  151,  152,  153,  154,  211,  212,  250,  290,
- /*  1640 */   240,  211,  212,  211,  212,  254,  286,  209,  254,  241,