From 023e6b333dba4d11bb94648f9ba18e3be85d3548 Mon Sep 17 00:00:00 2001
From: renovate <renovate-bot@autistici.org>
Date: Tue, 28 Jun 2022 18:26:58 +0000
Subject: [PATCH] fix(deps): update module github.com/mattn/go-sqlite3 to
 v1.14.14

---
 go.mod                                        |     2 +-
 go.sum                                        |     2 +
 vendor/github.com/mattn/go-sqlite3/README.md  |   111 +-
 vendor/github.com/mattn/go-sqlite3/backup.go  |     2 +-
 .../github.com/mattn/go-sqlite3/callback.go   |    21 +-
 vendor/github.com/mattn/go-sqlite3/error.go   |     2 +-
 .../mattn/go-sqlite3/sqlite3-binding.c        | 23530 ++++++++++------
 .../mattn/go-sqlite3/sqlite3-binding.h        |   666 +-
 vendor/github.com/mattn/go-sqlite3/sqlite3.go |    99 +-
 .../mattn/go-sqlite3/sqlite3_context.go       |     2 +-
 .../go-sqlite3/sqlite3_load_extension.go      |     2 +-
 .../mattn/go-sqlite3/sqlite3_opt_json1.go     |    13 -
 .../go-sqlite3/sqlite3_opt_preupdate_hook.go  |     4 +-
 .../go-sqlite3/sqlite3_opt_preupdate_omit.go  |     2 +-
 .../go-sqlite3/sqlite3_opt_unlock_notify.c    |     2 +-
 .../go-sqlite3/sqlite3_opt_unlock_notify.go   |     2 +-
 .../mattn/go-sqlite3/sqlite3_opt_userauth.go  |     2 +-
 .../mattn/go-sqlite3/sqlite3_opt_vtable.go    |    21 +-
 .../mattn/go-sqlite3/sqlite3_trace.go         |     2 +-
 .../mattn/go-sqlite3/sqlite3_type.go          |    94 +-
 .../github.com/mattn/go-sqlite3/sqlite3ext.h  |    30 +
 vendor/modules.txt                            |     2 +-
 22 files changed, 15280 insertions(+), 9333 deletions(-)
 delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_json1.go

diff --git a/go.mod b/go.mod
index b9e42e0..dd8b525 100644
--- a/go.mod
+++ b/go.mod
@@ -11,7 +11,7 @@ require (
 	github.com/google/go-cmp v0.5.5
 	github.com/google/subcommands v1.2.0
 	github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0
-	github.com/mattn/go-sqlite3 v1.14.7
+	github.com/mattn/go-sqlite3 v1.14.14
 	github.com/oschwald/maxminddb-golang v1.8.0
 	github.com/prometheus/client_golang v1.11.0
 	github.com/syndtr/goleveldb v1.0.0
diff --git a/go.sum b/go.sum
index 07067a7..8254e7f 100644
--- a/go.sum
+++ b/go.sum
@@ -340,6 +340,8 @@ github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK86
 github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
 github.com/mattn/go-sqlite3 v1.14.7 h1:fxWBnXkxfM6sRiuH3bqJ4CfzZojMOLVc0UTsTglEghA=
 github.com/mattn/go-sqlite3 v1.14.7/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
+github.com/mattn/go-sqlite3 v1.14.14 h1:qZgc/Rwetq+MtyE18WhzjokPD93dNqLGNT3QJuLvBGw=
+github.com/mattn/go-sqlite3 v1.14.14/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
 github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
 github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
 github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
diff --git a/vendor/github.com/mattn/go-sqlite3/README.md b/vendor/github.com/mattn/go-sqlite3/README.md
index 746621f..e455133 100644
--- a/vendor/github.com/mattn/go-sqlite3/README.md
+++ b/vendor/github.com/mattn/go-sqlite3/README.md
@@ -7,17 +7,17 @@ go-sqlite3
 [![codecov](https://codecov.io/gh/mattn/go-sqlite3/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-sqlite3)
 [![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-sqlite3)](https://goreportcard.com/report/github.com/mattn/go-sqlite3)
 
-Latest stable version is v1.14 or later not v2.
+Latest stable version is v1.14 or later, not v2.
 
 ~~**NOTE:** The increase to v2 was an accident. There were no major changes or features.~~
 
 # Description
 
-sqlite3 driver conforming to the built-in database/sql interface
+A sqlite3 driver that conforms to the built-in database/sql interface.
 
-Supported Golang version: See [.github/workflows/go.yaml](./.github/workflows/go.yaml)
+Supported Golang version: See [.github/workflows/go.yaml](./.github/workflows/go.yaml).
 
-[This package follows the official Golang Release Policy.](https://golang.org/doc/devel/release.html#policy)
+This package follows the official [Golang Release Policy](https://golang.org/doc/devel/release.html#policy).
 
 ### Overview
 
@@ -64,7 +64,7 @@ Supported Golang version: See [.github/workflows/go.yaml](./.github/workflows/go
 
 # Installation
 
-This package can be installed with the go get command:
+This package can be installed with the `go get` command:
 
     go get github.com/mattn/go-sqlite3
 
@@ -72,28 +72,28 @@ _go-sqlite3_ is *cgo* package.
 If you want to build your app using go-sqlite3, you need gcc.
 However, after you have built and installed _go-sqlite3_ with `go install github.com/mattn/go-sqlite3` (which requires gcc), you can build your app without relying on gcc in future.
 
-***Important: because this is a `CGO` enabled package you are required to set the environment variable `CGO_ENABLED=1` and have a `gcc` compile present within your path.***
+***Important: because this is a `CGO` enabled package, you are required to set the environment variable `CGO_ENABLED=1` and have a `gcc` compile present within your path.***
 
 # API Reference
 
-API documentation can be found here: http://godoc.org/github.com/mattn/go-sqlite3
+API documentation can be found [here](http://godoc.org/github.com/mattn/go-sqlite3).
 
-Examples can be found under the [examples](./_example) directory
+Examples can be found under the [examples](./_example) directory.
 
 # Connection String
 
 When creating a new SQLite database or connection to an existing one, with the file name additional options can be given.
-This is also known as a DSN string. (Data Source Name).
+This is also known as a DSN (Data Source Name) string.
 
 Options are append after the filename of the SQLite database.
-The database filename and options are seperated by an `?` (Question Mark).
+The database filename and options are separated by an `?` (Question Mark).
 Options should be URL-encoded (see [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)).
 
 This also applies when using an in-memory database instead of a file.
 
 Options can be given using the following format: `KEYWORD=VALUE` and multiple options can be combined with the `&` ampersand.
 
-This library supports dsn options of SQLite itself and provides additional options.
+This library supports DSN options of SQLite itself and provides additional options.
 
 Boolean values can be one of:
 * `0` `no` `false` `off`
@@ -138,19 +138,18 @@ file:test.db?cache=shared&mode=memory
 
 This package allows additional configuration of features available within SQLite3 to be enabled or disabled by golang build constraints also known as build `tags`.
 
-[Click here for more information about build tags / constraints.](https://golang.org/pkg/go/build/#hdr-Build_Constraints)
+Click [here](https://golang.org/pkg/go/build/#hdr-Build_Constraints) for more information about build tags / constraints.
 
 ### Usage
 
-If you wish to build this library with additional extensions / features.
-Use the following command.
+If you wish to build this library with additional extensions / features, use the following command:
 
 ```bash
 go build --tags "<FEATURE>"
 ```
 
-For available features see the extension list.
-When using multiple build tags, all the different tags should be space delimted.
+For available features, see the extension list.
+When using multiple build tags, all the different tags should be space delimited.
 
 Example:
 
@@ -181,9 +180,9 @@ go build --tags "icu json1 fts5 secure_delete"
 
 # Compilation
 
-This package requires `CGO_ENABLED=1` ennvironment variable if not set by default, and the presence of the `gcc` compiler.
+This package requires the `CGO_ENABLED=1` ennvironment variable if not set by default, and the presence of the `gcc` compiler.
 
-If you need to add additional CFLAGS or LDFLAGS to the build command, and do not want to modify this package. Then this can be achieved by  using the `CGO_CFLAGS` and `CGO_LDFLAGS` environment variables.
+If you need to add additional CFLAGS or LDFLAGS to the build command, and do not want to modify this package, then this can be achieved by using the `CGO_CFLAGS` and `CGO_LDFLAGS` environment variables.
 
 ## Android
 
@@ -198,7 +197,7 @@ For more information see [#201](https://github.com/mattn/go-sqlite3/issues/201)
 
 # ARM
 
-To compile for `ARM` use the following environment.
+To compile for `ARM` use the following environment:
 
 ```bash
 env CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ \
@@ -234,7 +233,7 @@ Please work only with compiled final binaries.
 
 ## Linux
 
-To compile this package on Linux you must install the development tools for your linux distribution.
+To compile this package on Linux, you must install the development tools for your linux distribution.
 
 To compile under linux use the build tag `linux`.
 
@@ -250,7 +249,7 @@ go build --tags "libsqlite3 linux"
 
 ### Alpine
 
-When building in an `alpine` container run the following command before building.
+When building in an `alpine` container  run the following command before building:
 
 ```
 apk add --update gcc musl-dev
@@ -270,29 +269,29 @@ sudo apt-get install build-essential
 
 ## Mac OSX
 
-OSX should have all the tools present to compile this package, if not install XCode this will add all the developers tools.
+OSX should have all the tools present to compile this package. If not, install XCode to add all the developers tools.
 
-Required dependency
+Required dependency:
 
 ```bash
 brew install sqlite3
 ```
 
-For OSX there is an additional package install which is required if you wish to build the `icu` extension.
+For OSX, there is an additional package to install which is required if you wish to build the `icu` extension.
 
-This additional package can be installed with `homebrew`.
+This additional package can be installed with `homebrew`:
 
 ```bash
 brew upgrade icu4c
 ```
 
-To compile for Mac OSX.
+To compile for Mac OSX:
 
 ```bash
 go build --tags "darwin"
 ```
 
-If you wish to link directly to libsqlite3 then you can use the `libsqlite3` build tag.
+If you wish to link directly to libsqlite3, use the `libsqlite3` build tag:
 
 ```
 go build --tags "libsqlite3 darwin"
@@ -304,14 +303,14 @@ Additional information:
 
 ## Windows
 
-To compile this package on Windows OS you must have the `gcc` compiler installed.
+To compile this package on Windows, you must have the `gcc` compiler installed.
 
 1) Install a Windows `gcc` toolchain.
-2) Add the `bin` folders to the Windows path if the installer did not do this by default.
-3) Open a terminal for the TDM-GCC toolchain, can be found in the Windows Start menu.
+2) Add the `bin` folder to the Windows path, if the installer did not do this by default.
+3) Open a terminal for the TDM-GCC toolchain, which can be found in the Windows Start menu.
 4) Navigate to your project folder and run the `go build ...` command for this package.
 
-For example the TDM-GCC Toolchain can be found [here](https://sourceforge.net/projects/tdm-gcc/).
+For example the TDM-GCC Toolchain can be found [here](https://jmeubank.github.io/tdm-gcc/).
 
 ## Errors
 
@@ -349,28 +348,28 @@ This package supports the SQLite User Authentication module.
 
 ## Compile
 
-To use the User authentication module the package has to be compiled with the tag `sqlite_userauth`. See [Features](#features).
+To use the User authentication module, the package has to be compiled with the tag `sqlite_userauth`. See [Features](#features).
 
 ## Usage
 
 ### Create protected database
 
-To create a database protected by user authentication provide the following argument to the connection string `_auth`.
+To create a database protected by user authentication, provide the following argument to the connection string `_auth`.
 This will enable user authentication within the database. This option however requires two additional arguments:
 
 - `_auth_user`
 - `_auth_pass`
 
-When `_auth` is present on the connection string user authentication will be enabled and the provided user will be created
+When `_auth` is present in the connection string user authentication will be enabled and the provided user will be created
 as an `admin` user. After initial creation, the parameter `_auth` has no effect anymore and can be omitted from the connection string.
 
-Example connection string:
+Example connection strings:
 
-Create an user authentication database with user `admin` and password `admin`.
+Create an user authentication database with user `admin` and password `admin`:
 
 `file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin`
 
-Create an user authentication database with user `admin` and password `admin` and use `SHA1` for the password encoding.
+Create an user authentication database with user `admin` and password `admin` and use `SHA1` for the password encoding:
 
 `file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin&_auth_crypt=sha1`
 
@@ -396,11 +395,11 @@ salt this can be configured with `_auth_salt`.
 
 ### Restrictions
 
-Operations on the database regarding to user management can only be preformed by an administrator user.
+Operations on the database regarding user management can only be preformed by an administrator user.
 
 ### Support
 
-The user authentication supports two kinds of users
+The user authentication supports two kinds of users:
 
 - administrators
 - regular users
@@ -411,7 +410,7 @@ User management can be done by directly using the `*SQLiteConn` or by SQL.
 
 #### SQL
 
-The following sql functions are available for user management.
+The following sql functions are available for user management:
 
 | Function | Arguments | Description |
 |----------|-----------|-------------|
@@ -420,7 +419,7 @@ The following sql functions are available for user management.
 | `auth_user_change` | username `string`, password `string`, admin `int` | Function to modify an user. Users can change their own password, but only an administrator can change the administrator flag. |
 | `authUserDelete` | username `string` | Delete an user from the database. Can only be used by an administrator. The current logged in administrator cannot be deleted. This is to make sure their is always an administrator remaining. |
 
-These functions will return an integer.
+These functions will return an integer:
 
 - 0 (SQLITE_OK)
 - 23 (SQLITE_AUTH) Failed to perform due to authentication or insufficient privileges
@@ -441,7 +440,7 @@ SELECT user_delete('user');
 
 #### *SQLiteConn
 
-The following functions are available for User authentication from the `*SQLiteConn`.
+The following functions are available for User authentication from the `*SQLiteConn`:
 
 | Function | Description |
 |----------|-------------|
@@ -452,16 +451,16 @@ The following functions are available for User authentication from the `*SQLiteC
 
 ### Attached database
 
-When using attached databases. SQLite will use the authentication from the `main` database for the attached database(s).
+When using attached databases, SQLite will use the authentication from the `main` database for the attached database(s).
 
 # Extensions
 
-If you want your own extension to be listed here or you want to add a reference to an extension; please submit an Issue for this.
+If you want your own extension to be listed here, or you want to add a reference to an extension; please submit an Issue for this.
 
 ## Spatialite
 
 Spatialite is available as an extension to SQLite, and can be used in combination with this repository.
-For an example see [shaxbee/go-spatialite](https://github.com/shaxbee/go-spatialite).
+For an example, see [shaxbee/go-spatialite](https://github.com/shaxbee/go-spatialite).
 
 ## extension-functions.c from SQLite3 Contrib
 
@@ -471,7 +470,7 @@ extension-functions.c is available as an extension to SQLite, and provides the f
 - String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim, replace, reverse, proper, padl, padr, padc, strfilter.
 - Aggregate: stdev, variance, mode, median, lower_quartile, upper_quartile
 
-For an example see [dinedal/go-sqlite3-extension-functions](https://github.com/dinedal/go-sqlite3-extension-functions).
+For an example, see [dinedal/go-sqlite3-extension-functions](https://github.com/dinedal/go-sqlite3-extension-functions).
 
 # FAQ
 
@@ -491,7 +490,7 @@ For an example see [dinedal/go-sqlite3-extension-functions](https://github.com/d
 
 - Can I use this in multiple routines concurrently?
 
-    Yes for readonly. But, No for writable. See [#50](https://github.com/mattn/go-sqlite3/issues/50), [#51](https://github.com/mattn/go-sqlite3/issues/51), [#209](https://github.com/mattn/go-sqlite3/issues/209), [#274](https://github.com/mattn/go-sqlite3/issues/274).
+    Yes for readonly. But not for writable. See [#50](https://github.com/mattn/go-sqlite3/issues/50), [#51](https://github.com/mattn/go-sqlite3/issues/51), [#209](https://github.com/mattn/go-sqlite3/issues/209), [#274](https://github.com/mattn/go-sqlite3/issues/274).
 
 - Why I'm getting `no such table` error?
 
@@ -505,7 +504,7 @@ For an example see [dinedal/go-sqlite3-extension-functions](https://github.com/d
     
     Note that if the last database connection in the pool closes, the in-memory database is deleted. Make sure the [max idle connection limit](https://golang.org/pkg/database/sql/#DB.SetMaxIdleConns) is > 0, and the [connection lifetime](https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime) is infinite.
     
-    For more information see
+    For more information see:
     * [#204](https://github.com/mattn/go-sqlite3/issues/204)
     * [#511](https://github.com/mattn/go-sqlite3/issues/511)
     * https://www.sqlite.org/sharedcache.html#shared_cache_and_in_memory_databases
@@ -515,20 +514,20 @@ For an example see [dinedal/go-sqlite3-extension-functions](https://github.com/d
 
     OS X limits OS-wide to not have more than 1000 files open simultaneously by default.
 
-    For more information see [#289](https://github.com/mattn/go-sqlite3/issues/289)
+    For more information, see [#289](https://github.com/mattn/go-sqlite3/issues/289)
 
 - Trying to execute a `.` (dot) command throws an error.
 
     Error: `Error: near ".": syntax error`
-    Dot command are part of SQLite3 CLI not of this library.
+    Dot command are part of SQLite3 CLI, not of this library.
 
     You need to implement the feature or call the sqlite3 cli.
 
-    More information see [#305](https://github.com/mattn/go-sqlite3/issues/305)
+    More information see [#305](https://github.com/mattn/go-sqlite3/issues/305).
 
 - Error: `database is locked`
 
-    When you get a database is locked. Please use the following options.
+    When you get a database is locked, please use the following options.
 
     Add to DSN: `cache=shared`
 
@@ -537,24 +536,24 @@ For an example see [dinedal/go-sqlite3-extension-functions](https://github.com/d
     db, err := sql.Open("sqlite3", "file:locked.sqlite?cache=shared")
     ```
 
-    Second please set the database connections of the SQL package to 1.
+    Next, please set the database connections of the SQL package to 1:
     
     ```go
     db.SetMaxOpenConns(1)
     ```
 
-    More information see [#209](https://github.com/mattn/go-sqlite3/issues/209)
+    For more information, see [#209](https://github.com/mattn/go-sqlite3/issues/209).
 
 ## Contributors
 
 ### Code Contributors
 
-This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
+This project exists thanks to all the people who [[contribute](CONTRIBUTING.md)].
 <a href="https://github.com/mattn/go-sqlite3/graphs/contributors"><img src="https://opencollective.com/mattn-go-sqlite3/contributors.svg?width=890&button=false" /></a>
 
 ### Financial Contributors
 
-Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/mattn-go-sqlite3/contribute)]
+Become a financial contributor and help us sustain our community. [[Contribute here](https://opencollective.com/mattn-go-sqlite3/contribute)].
 
 #### Individuals
 
diff --git a/vendor/github.com/mattn/go-sqlite3/backup.go b/vendor/github.com/mattn/go-sqlite3/backup.go
index e222cc8..ecbb469 100644
--- a/vendor/github.com/mattn/go-sqlite3/backup.go
+++ b/vendor/github.com/mattn/go-sqlite3/backup.go
@@ -7,7 +7,7 @@ package sqlite3
 
 /*
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
diff --git a/vendor/github.com/mattn/go-sqlite3/callback.go b/vendor/github.com/mattn/go-sqlite3/callback.go
index c3ce752..d305691 100644
--- a/vendor/github.com/mattn/go-sqlite3/callback.go
+++ b/vendor/github.com/mattn/go-sqlite3/callback.go
@@ -12,7 +12,7 @@ package sqlite3
 
 /*
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
@@ -353,6 +353,20 @@ func callbackRetNil(ctx *C.sqlite3_context, v reflect.Value) error {
 	return nil
 }
 
+func callbackRetGeneric(ctx *C.sqlite3_context, v reflect.Value) error {
+	if v.IsNil() {
+		C.sqlite3_result_null(ctx)
+		return nil
+	}
+
+	cb, err := callbackRet(v.Elem().Type())
+        if err != nil {
+                return err
+        }
+
+        return cb(ctx, v.Elem())
+}
+
 func callbackRet(typ reflect.Type) (callbackRetConverter, error) {
 	switch typ.Kind() {
 	case reflect.Interface:
@@ -360,6 +374,11 @@ func callbackRet(typ reflect.Type) (callbackRetConverter, error) {
 		if typ.Implements(errorInterface) {
 			return callbackRetNil, nil
 		}
+
+		if typ.NumMethod() == 0 {
+			return callbackRetGeneric, nil
+		}
+
 		fallthrough
 	case reflect.Slice:
 		if typ.Elem().Kind() != reflect.Uint8 {
diff --git a/vendor/github.com/mattn/go-sqlite3/error.go b/vendor/github.com/mattn/go-sqlite3/error.go
index 696281c..58ab252 100644
--- a/vendor/github.com/mattn/go-sqlite3/error.go
+++ b/vendor/github.com/mattn/go-sqlite3/error.go
@@ -7,7 +7,7 @@ package sqlite3
 
 /*
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c
index a974948..102821b 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c
@@ -1,7 +1,7 @@
 #ifndef USE_LIBSQLITE3
 /******************************************************************************
 ** This file is an amalgamation of many separate C source files from SQLite
-** version 3.35.4.  By combining all the individual C code files into this
+** version 3.38.5.  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
@@ -23,774 +23,6 @@
 #ifndef SQLITE_PRIVATE
 # define SQLITE_PRIVATE static
 #endif
-/************** Begin file ctime.c *******************************************/
-/*
-** 2010 February 23
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-*************************************************************************
-**
-** This file implements routines used to report what compile-time options
-** SQLite was built with.
-*/
-
-#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
-
-/*
-** Include the configuration header output by 'configure' if we're using the
-** autoconf-based build
-*/
-#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
-#include "config.h"
-#define SQLITECONFIG_H 1
-#endif
-
-/* These macros are provided to "stringify" the value of the define
-** for those options in which the value is meaningful. */
-#define CTIMEOPT_VAL_(opt) #opt
-#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
-
-/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
-** option requires a separate macro because legal values contain a single
-** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
-#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
-#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
-
-/*
-** An array of names of all compile-time options.  This array should
-** be sorted A-Z.
-**
-** This array looks large, but in a typical installation actually uses
-** only a handful of compile-time options, so most times this array is usually
-** rather short and uses little memory space.
-*/
-static const char * const sqlite3azCompileOpt[] = {
-
-/*
-** BEGIN CODE GENERATED BY tool/mkctime.tcl
-*/
-#if SQLITE_32BIT_ROWID
-  "32BIT_ROWID",
-#endif
-#if SQLITE_4_BYTE_ALIGNED_MALLOC
-  "4_BYTE_ALIGNED_MALLOC",
-#endif
-#if SQLITE_64BIT_STATS
-  "64BIT_STATS",
-#endif
-#if SQLITE_ALLOW_COVERING_INDEX_SCAN
-  "ALLOW_COVERING_INDEX_SCAN",
-#endif
-#if SQLITE_ALLOW_URI_AUTHORITY
-  "ALLOW_URI_AUTHORITY",
-#endif
-#ifdef SQLITE_BITMASK_TYPE
-  "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
-#endif
-#if SQLITE_BUG_COMPATIBLE_20160819
-  "BUG_COMPATIBLE_20160819",
-#endif
-#if SQLITE_CASE_SENSITIVE_LIKE
-  "CASE_SENSITIVE_LIKE",
-#endif
-#if SQLITE_CHECK_PAGES
-  "CHECK_PAGES",
-#endif
-#if defined(__clang__) && defined(__clang_major__)
-  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
-                    CTIMEOPT_VAL(__clang_minor__) "."
-                    CTIMEOPT_VAL(__clang_patchlevel__),
-#elif defined(_MSC_VER)
-  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
-#elif defined(__GNUC__) && defined(__VERSION__)
-  "COMPILER=gcc-" __VERSION__,
-#endif
-#if SQLITE_COVERAGE_TEST
-  "COVERAGE_TEST",
-#endif
-#if SQLITE_DEBUG
-  "DEBUG",
-#endif
-#if SQLITE_DEFAULT_AUTOMATIC_INDEX
-  "DEFAULT_AUTOMATIC_INDEX",
-#endif
-#if SQLITE_DEFAULT_AUTOVACUUM
-  "DEFAULT_AUTOVACUUM",
-#endif
-#ifdef SQLITE_DEFAULT_CACHE_SIZE
-  "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
-#endif
-#if SQLITE_DEFAULT_CKPTFULLFSYNC
-  "DEFAULT_CKPTFULLFSYNC",
-#endif
-#ifdef SQLITE_DEFAULT_FILE_FORMAT
-  "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
-#endif
-#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
-  "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
-#endif
-#if SQLITE_DEFAULT_FOREIGN_KEYS
-  "DEFAULT_FOREIGN_KEYS",
-#endif
-#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
-  "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
-#endif
-#ifdef SQLITE_DEFAULT_LOCKING_MODE
-  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
-#endif
-#ifdef SQLITE_DEFAULT_LOOKASIDE
-  "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
-#endif
-#if SQLITE_DEFAULT_MEMSTATUS
-  "DEFAULT_MEMSTATUS",
-#endif
-#ifdef SQLITE_DEFAULT_MMAP_SIZE
-  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
-#endif
-#ifdef SQLITE_DEFAULT_PAGE_SIZE
-  "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
-#endif
-#ifdef SQLITE_DEFAULT_PCACHE_INITSZ
-  "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
-#endif
-#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
-  "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
-#endif
-#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
-  "DEFAULT_RECURSIVE_TRIGGERS",
-#endif
-#ifdef SQLITE_DEFAULT_ROWEST
-  "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
-#endif
-#ifdef SQLITE_DEFAULT_SECTOR_SIZE
-  "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
-#endif
-#ifdef SQLITE_DEFAULT_SYNCHRONOUS
-  "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
-#endif
-#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
-  "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
-#endif
-#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
-  "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
-#endif
-#ifdef SQLITE_DEFAULT_WORKER_THREADS
-  "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
-#endif
-#if SQLITE_DIRECT_OVERFLOW_READ
-  "DIRECT_OVERFLOW_READ",
-#endif
-#if SQLITE_DISABLE_DIRSYNC
-  "DISABLE_DIRSYNC",
-#endif
-#if SQLITE_DISABLE_FTS3_UNICODE
-  "DISABLE_FTS3_UNICODE",
-#endif
-#if SQLITE_DISABLE_FTS4_DEFERRED
-  "DISABLE_FTS4_DEFERRED",
-#endif
-#if SQLITE_DISABLE_INTRINSIC
-  "DISABLE_INTRINSIC",
-#endif
-#if SQLITE_DISABLE_LFS
-  "DISABLE_LFS",
-#endif
-#if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
-  "DISABLE_PAGECACHE_OVERFLOW_STATS",
-#endif
-#if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
-  "DISABLE_SKIPAHEAD_DISTINCT",
-#endif
-#ifdef SQLITE_ENABLE_8_3_NAMES
-  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
-#endif
-#if SQLITE_ENABLE_API_ARMOR
-  "ENABLE_API_ARMOR",
-#endif
-#if SQLITE_ENABLE_ATOMIC_WRITE
-  "ENABLE_ATOMIC_WRITE",
-#endif
-#if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
-  "ENABLE_BATCH_ATOMIC_WRITE",
-#endif
-#if SQLITE_ENABLE_BYTECODE_VTAB
-  "ENABLE_BYTECODE_VTAB",
-#endif
-#if SQLITE_ENABLE_CEROD
-  "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
-#endif
-#if SQLITE_ENABLE_COLUMN_METADATA
-  "ENABLE_COLUMN_METADATA",
-#endif
-#if SQLITE_ENABLE_COLUMN_USED_MASK
-  "ENABLE_COLUMN_USED_MASK",
-#endif
-#if SQLITE_ENABLE_COSTMULT
-  "ENABLE_COSTMULT",
-#endif
-#if SQLITE_ENABLE_CURSOR_HINTS
-  "ENABLE_CURSOR_HINTS",
-#endif
-#if SQLITE_ENABLE_DBSTAT_VTAB
-  "ENABLE_DBSTAT_VTAB",
-#endif
-#if SQLITE_ENABLE_EXPENSIVE_ASSERT
-  "ENABLE_EXPENSIVE_ASSERT",
-#endif
-#if SQLITE_ENABLE_FTS1
-  "ENABLE_FTS1",
-#endif
-#if SQLITE_ENABLE_FTS2
-  "ENABLE_FTS2",
-#endif
-#if SQLITE_ENABLE_FTS3
-  "ENABLE_FTS3",
-#endif
-#if SQLITE_ENABLE_FTS3_PARENTHESIS
-  "ENABLE_FTS3_PARENTHESIS",
-#endif
-#if SQLITE_ENABLE_FTS3_TOKENIZER
-  "ENABLE_FTS3_TOKENIZER",
-#endif
-#if SQLITE_ENABLE_FTS4
-  "ENABLE_FTS4",
-#endif
-#if SQLITE_ENABLE_FTS5
-  "ENABLE_FTS5",
-#endif
-#if SQLITE_ENABLE_GEOPOLY
-  "ENABLE_GEOPOLY",
-#endif
-#if SQLITE_ENABLE_HIDDEN_COLUMNS
-  "ENABLE_HIDDEN_COLUMNS",
-#endif
-#if SQLITE_ENABLE_ICU
-  "ENABLE_ICU",
-#endif
-#if SQLITE_ENABLE_IOTRACE
-  "ENABLE_IOTRACE",
-#endif
-#if SQLITE_ENABLE_JSON1
-  "ENABLE_JSON1",
-#endif
-#if SQLITE_ENABLE_LOAD_EXTENSION
-  "ENABLE_LOAD_EXTENSION",
-#endif
-#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
-#if SQLITE_ENABLE_MEMSYS3
-  "ENABLE_MEMSYS3",
-#endif
-#if SQLITE_ENABLE_MEMSYS5
-  "ENABLE_MEMSYS5",
-#endif
-#if SQLITE_ENABLE_MULTIPLEX
-  "ENABLE_MULTIPLEX",
-#endif
-#if SQLITE_ENABLE_NORMALIZE
-  "ENABLE_NORMALIZE",
-#endif
-#if SQLITE_ENABLE_NULL_TRIM
-  "ENABLE_NULL_TRIM",
-#endif
-#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
-  "ENABLE_OVERSIZE_CELL_CHECK",
-#endif
-#if SQLITE_ENABLE_PREUPDATE_HOOK
-  "ENABLE_PREUPDATE_HOOK",
-#endif
-#if SQLITE_ENABLE_QPSG
-  "ENABLE_QPSG",
-#endif
-#if SQLITE_ENABLE_RBU
-  "ENABLE_RBU",
-#endif
-#if SQLITE_ENABLE_RTREE
-  "ENABLE_RTREE",
-#endif
-#if SQLITE_ENABLE_SELECTTRACE
-  "ENABLE_SELECTTRACE",
-#endif
-#if SQLITE_ENABLE_SESSION
-  "ENABLE_SESSION",
-#endif
-#if SQLITE_ENABLE_SNAPSHOT
-  "ENABLE_SNAPSHOT",
-#endif
-#if SQLITE_ENABLE_SORTER_REFERENCES
-  "ENABLE_SORTER_REFERENCES",
-#endif
-#if SQLITE_ENABLE_SQLLOG
-  "ENABLE_SQLLOG",
-#endif
-#if defined(SQLITE_ENABLE_STAT4)
-  "ENABLE_STAT4",
-#endif
-#if SQLITE_ENABLE_STMTVTAB
-  "ENABLE_STMTVTAB",
-#endif
-#if SQLITE_ENABLE_STMT_SCANSTATUS
-  "ENABLE_STMT_SCANSTATUS",
-#endif
-#if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
-  "ENABLE_UNKNOWN_SQL_FUNCTION",
-#endif
-#if SQLITE_ENABLE_UNLOCK_NOTIFY
-  "ENABLE_UNLOCK_NOTIFY",
-#endif
-#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
-  "ENABLE_UPDATE_DELETE_LIMIT",
-#endif
-#if SQLITE_ENABLE_URI_00_ERROR
-  "ENABLE_URI_00_ERROR",
-#endif
-#if SQLITE_ENABLE_VFSTRACE
-  "ENABLE_VFSTRACE",
-#endif
-#if SQLITE_ENABLE_WHERETRACE
-  "ENABLE_WHERETRACE",
-#endif
-#if SQLITE_ENABLE_ZIPVFS
-  "ENABLE_ZIPVFS",
-#endif
-#if SQLITE_EXPLAIN_ESTIMATED_ROWS
-  "EXPLAIN_ESTIMATED_ROWS",
-#endif
-#if SQLITE_EXTRA_IFNULLROW
-  "EXTRA_IFNULLROW",
-#endif
-#ifdef SQLITE_EXTRA_INIT
-  "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
-#endif
-#ifdef SQLITE_EXTRA_SHUTDOWN
-  "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
-#endif
-#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
-  "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
-#endif
-#if SQLITE_FTS5_ENABLE_TEST_MI
-  "FTS5_ENABLE_TEST_MI",
-#endif
-#if SQLITE_FTS5_NO_WITHOUT_ROWID
-  "FTS5_NO_WITHOUT_ROWID",
-#endif
-#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
-  "HAVE_ISNAN",
-#endif
-#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
-  "HOMEGROWN_RECURSIVE_MUTEX",
-#endif
-#if SQLITE_IGNORE_AFP_LOCK_ERRORS
-  "IGNORE_AFP_LOCK_ERRORS",
-#endif
-#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
-  "IGNORE_FLOCK_LOCK_ERRORS",
-#endif
-#if SQLITE_INLINE_MEMCPY
-  "INLINE_MEMCPY",
-#endif
-#if SQLITE_INT64_TYPE
-  "INT64_TYPE",
-#endif
-#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
-  "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
-#endif
-#if SQLITE_LIKE_DOESNT_MATCH_BLOBS
-  "LIKE_DOESNT_MATCH_BLOBS",
-#endif
-#if SQLITE_LOCK_TRACE
-  "LOCK_TRACE",
-#endif
-#if SQLITE_LOG_CACHE_SPILL
-  "LOG_CACHE_SPILL",
-#endif
-#ifdef SQLITE_MALLOC_SOFT_LIMIT
-  "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
-#endif
-#ifdef SQLITE_MAX_ATTACHED
-  "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
-#endif
-#ifdef SQLITE_MAX_COLUMN
-  "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
-#endif
-#ifdef SQLITE_MAX_COMPOUND_SELECT
-  "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
-#endif
-#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
-  "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
-#endif
-#ifdef SQLITE_MAX_EXPR_DEPTH
-  "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
-#endif
-#ifdef SQLITE_MAX_FUNCTION_ARG
-  "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
-#endif
-#ifdef SQLITE_MAX_LENGTH
-  "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
-#endif
-#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
-  "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
-#endif
-#ifdef SQLITE_MAX_MEMORY
-  "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
-#endif
-#ifdef SQLITE_MAX_MMAP_SIZE
-  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
-#endif
-#ifdef SQLITE_MAX_MMAP_SIZE_
-  "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
-#endif
-#ifdef SQLITE_MAX_PAGE_COUNT
-  "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
-#endif
-#ifdef SQLITE_MAX_PAGE_SIZE
-  "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
-#endif
-#ifdef SQLITE_MAX_SCHEMA_RETRY
-  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
-#endif
-#ifdef SQLITE_MAX_SQL_LENGTH
-  "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
-#endif
-#ifdef SQLITE_MAX_TRIGGER_DEPTH
-  "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
-#endif
-#ifdef SQLITE_MAX_VARIABLE_NUMBER
-  "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
-#endif
-#ifdef SQLITE_MAX_VDBE_OP
-  "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
-#endif
-#ifdef SQLITE_MAX_WORKER_THREADS
-  "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
-#endif
-#if SQLITE_MEMDEBUG
-  "MEMDEBUG",
-#endif
-#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
-  "MIXED_ENDIAN_64BIT_FLOAT",
-#endif
-#if SQLITE_MMAP_READWRITE
-  "MMAP_READWRITE",
-#endif
-#if SQLITE_MUTEX_NOOP
-  "MUTEX_NOOP",
-#endif
-#if SQLITE_MUTEX_NREF
-  "MUTEX_NREF",
-#endif
-#if SQLITE_MUTEX_OMIT
-  "MUTEX_OMIT",
-#endif
-#if SQLITE_MUTEX_PTHREADS
-  "MUTEX_PTHREADS",
-#endif
-#if SQLITE_MUTEX_W32
-  "MUTEX_W32",
-#endif
-#if SQLITE_NEED_ERR_NAME
-  "NEED_ERR_NAME",
-#endif
-#if SQLITE_NOINLINE
-  "NOINLINE",
-#endif
-#if SQLITE_NO_SYNC
-  "NO_SYNC",
-#endif
-#if SQLITE_OMIT_ALTERTABLE
-  "OMIT_ALTERTABLE",
-#endif
-#if SQLITE_OMIT_ANALYZE
-  "OMIT_ANALYZE",
-#endif
-#if SQLITE_OMIT_ATTACH
-  "OMIT_ATTACH",
-#endif
-#if SQLITE_OMIT_AUTHORIZATION
-  "OMIT_AUTHORIZATION",
-#endif
-#if SQLITE_OMIT_AUTOINCREMENT
-  "OMIT_AUTOINCREMENT",
-#endif
-#if SQLITE_OMIT_AUTOINIT
-  "OMIT_AUTOINIT",
-#endif
-#if SQLITE_OMIT_AUTOMATIC_INDEX
-  "OMIT_AUTOMATIC_INDEX",
-#endif
-#if SQLITE_OMIT_AUTORESET
-  "OMIT_AUTORESET",
-#endif
-#if SQLITE_OMIT_AUTOVACUUM
-  "OMIT_AUTOVACUUM",
-#endif
-#if SQLITE_OMIT_BETWEEN_OPTIMIZATION
-  "OMIT_BETWEEN_OPTIMIZATION",
-#endif
-#if SQLITE_OMIT_BLOB_LITERAL
-  "OMIT_BLOB_LITERAL",
-#endif
-#if SQLITE_OMIT_CAST
-  "OMIT_CAST",
-#endif
-#if SQLITE_OMIT_CHECK
-  "OMIT_CHECK",
-#endif
-#if SQLITE_OMIT_COMPLETE
-  "OMIT_COMPLETE",
-#endif
-#if SQLITE_OMIT_COMPOUND_SELECT
-  "OMIT_COMPOUND_SELECT",
-#endif
-#if SQLITE_OMIT_CONFLICT_CLAUSE
-  "OMIT_CONFLICT_CLAUSE",
-#endif
-#if SQLITE_OMIT_CTE
-  "OMIT_CTE",
-#endif
-#if SQLITE_OMIT_DATETIME_FUNCS
-  "OMIT_DATETIME_FUNCS",
-#endif
-#if SQLITE_OMIT_DECLTYPE
-  "OMIT_DECLTYPE",
-#endif
-#if SQLITE_OMIT_DEPRECATED
-  "OMIT_DEPRECATED",
-#endif
-#if SQLITE_OMIT_DISKIO
-  "OMIT_DISKIO",
-#endif
-#if SQLITE_OMIT_EXPLAIN
-  "OMIT_EXPLAIN",
-#endif
-#if SQLITE_OMIT_FLAG_PRAGMAS
-  "OMIT_FLAG_PRAGMAS",
-#endif
-#if SQLITE_OMIT_FLOATING_POINT
-  "OMIT_FLOATING_POINT",
-#endif
-#if SQLITE_OMIT_FOREIGN_KEY
-  "OMIT_FOREIGN_KEY",
-#endif
-#if SQLITE_OMIT_GET_TABLE
-  "OMIT_GET_TABLE",
-#endif
-#if SQLITE_OMIT_HEX_INTEGER
-  "OMIT_HEX_INTEGER",
-#endif
-#if SQLITE_OMIT_INCRBLOB
-  "OMIT_INCRBLOB",
-#endif
-#if SQLITE_OMIT_INTEGRITY_CHECK
-  "OMIT_INTEGRITY_CHECK",
-#endif
-#if SQLITE_OMIT_LIKE_OPTIMIZATION
-  "OMIT_LIKE_OPTIMIZATION",
-#endif
-#if SQLITE_OMIT_LOAD_EXTENSION
-  "OMIT_LOAD_EXTENSION",
-#endif
-#if SQLITE_OMIT_LOCALTIME
-  "OMIT_LOCALTIME",
-#endif
-#if SQLITE_OMIT_LOOKASIDE
-  "OMIT_LOOKASIDE",
-#endif
-#if SQLITE_OMIT_MEMORYDB
-  "OMIT_MEMORYDB",
-#endif
-#if SQLITE_OMIT_OR_OPTIMIZATION
-  "OMIT_OR_OPTIMIZATION",
-#endif
-#if SQLITE_OMIT_PAGER_PRAGMAS
-  "OMIT_PAGER_PRAGMAS",
-#endif
-#if SQLITE_OMIT_PARSER_TRACE
-  "OMIT_PARSER_TRACE",
-#endif
-#if SQLITE_OMIT_POPEN
-  "OMIT_POPEN",
-#endif
-#if SQLITE_OMIT_PRAGMA
-  "OMIT_PRAGMA",
-#endif
-#if SQLITE_OMIT_PROGRESS_CALLBACK
-  "OMIT_PROGRESS_CALLBACK",
-#endif
-#if SQLITE_OMIT_QUICKBALANCE
-  "OMIT_QUICKBALANCE",
-#endif
-#if SQLITE_OMIT_REINDEX
-  "OMIT_REINDEX",
-#endif
-#if SQLITE_OMIT_SCHEMA_PRAGMAS
-  "OMIT_SCHEMA_PRAGMAS",
-#endif
-#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
-  "OMIT_SCHEMA_VERSION_PRAGMAS",
-#endif
-#if SQLITE_OMIT_SHARED_CACHE
-  "OMIT_SHARED_CACHE",
-#endif
-#if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
-  "OMIT_SHUTDOWN_DIRECTORIES",
-#endif
-#if SQLITE_OMIT_SUBQUERY
-  "OMIT_SUBQUERY",
-#endif
-#if SQLITE_OMIT_TCL_VARIABLE
-  "OMIT_TCL_VARIABLE",
-#endif
-#if SQLITE_OMIT_TEMPDB
-  "OMIT_TEMPDB",
-#endif
-#if SQLITE_OMIT_TEST_CONTROL
-  "OMIT_TEST_CONTROL",
-#endif
-#if SQLITE_OMIT_TRACE
-  "OMIT_TRACE",
-#endif
-#if SQLITE_OMIT_TRIGGER
-  "OMIT_TRIGGER",
-#endif
-#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
-  "OMIT_TRUNCATE_OPTIMIZATION",
-#endif
-#if SQLITE_OMIT_UTF16
-  "OMIT_UTF16",
-#endif
-#if SQLITE_OMIT_VACUUM
-  "OMIT_VACUUM",
-#endif
-#if SQLITE_OMIT_VIEW
-  "OMIT_VIEW",
-#endif
-#if SQLITE_OMIT_VIRTUALTABLE
-  "OMIT_VIRTUALTABLE",
-#endif
-#if SQLITE_OMIT_WAL
-  "OMIT_WAL",
-#endif
-#if SQLITE_OMIT_WSD
-  "OMIT_WSD",
-#endif
-#if SQLITE_OMIT_XFER_OPT
-  "OMIT_XFER_OPT",
-#endif
-#if SQLITE_PCACHE_SEPARATE_HEADER
-  "PCACHE_SEPARATE_HEADER",
-#endif
-#if SQLITE_PERFORMANCE_TRACE
-  "PERFORMANCE_TRACE",
-#endif
-#if SQLITE_POWERSAFE_OVERWRITE
-  "POWERSAFE_OVERWRITE",
-#endif
-#if SQLITE_PREFER_PROXY_LOCKING
-  "PREFER_PROXY_LOCKING",
-#endif
-#if SQLITE_PROXY_DEBUG
-  "PROXY_DEBUG",
-#endif
-#if SQLITE_REVERSE_UNORDERED_SELECTS
-  "REVERSE_UNORDERED_SELECTS",
-#endif
-#if SQLITE_RTREE_INT_ONLY
-  "RTREE_INT_ONLY",
-#endif
-#if SQLITE_SECURE_DELETE
-  "SECURE_DELETE",
-#endif
-#if SQLITE_SMALL_STACK
-  "SMALL_STACK",
-#endif
-#ifdef SQLITE_SORTER_PMASZ
-  "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
-#endif
-#if SQLITE_SOUNDEX
-  "SOUNDEX",
-#endif
-#ifdef SQLITE_STAT4_SAMPLES
-  "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
-#endif
-#ifdef SQLITE_STMTJRNL_SPILL
-  "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
-#endif
-#if SQLITE_SUBSTR_COMPATIBILITY
-  "SUBSTR_COMPATIBILITY",
-#endif
-#if SQLITE_SYSTEM_MALLOC
-  "SYSTEM_MALLOC",
-#endif
-#if SQLITE_TCL
-  "TCL",
-#endif
-#ifdef SQLITE_TEMP_STORE
-  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
-#endif
-#if SQLITE_TEST
-  "TEST",
-#endif
-#if defined(SQLITE_THREADSAFE)
-  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
-#elif defined(THREADSAFE)
-  "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
-#else
-  "THREADSAFE=1",
-#endif
-#if SQLITE_UNLINK_AFTER_CLOSE
-  "UNLINK_AFTER_CLOSE",
-#endif
-#if SQLITE_UNTESTABLE
-  "UNTESTABLE",
-#endif
-#if SQLITE_USER_AUTHENTICATION
-  "USER_AUTHENTICATION",
-#endif
-#if SQLITE_USE_ALLOCA
-  "USE_ALLOCA",
-#endif
-#if SQLITE_USE_FCNTL_TRACE
-  "USE_FCNTL_TRACE",
-#endif
-#if SQLITE_USE_URI
-  "USE_URI",
-#endif
-#if SQLITE_VDBE_COVERAGE
-  "VDBE_COVERAGE",
-#endif
-#if SQLITE_WIN32_MALLOC
-  "WIN32_MALLOC",
-#endif
-#if SQLITE_ZERO_MALLOC
-  "ZERO_MALLOC",
-#endif
-/*
-** END CODE GENERATED BY tool/mkctime.tcl
-*/
-};
-
-SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
-  *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
-  return (const char**)sqlite3azCompileOpt;
-}
-
-#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
-
-/************** End of ctime.c ***********************************************/
 /************** Begin file sqliteInt.h ***************************************/
 /*
 ** 2001 September 15
@@ -1056,6 +288,17 @@ SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
 # define _USE_32BIT_TIME_T
 #endif
 
+/* Optionally #include a user-defined header, whereby compilation options
+** may be set prior to where they take effect, but after platform setup.
+** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
+** file.
+*/
+#ifdef SQLITE_CUSTOM_INCLUDE
+# define INC_STRINGIFY_(f) #f
+# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
+# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
+#endif
+
 /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
 ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
 ** MinGW.
@@ -1107,7 +350,30 @@ extern "C" {
 
 
 /*
-** Provide the ability to override linkage features of the interface.
+** Facilitate override of interface linkage and calling conventions.
+** Be aware that these macros may not be used within this particular
+** translation of the amalgamation and its associated header file.
+**
+** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
+** compiler that the target identifier should have external linkage.
+**
+** The SQLITE_CDECL macro is used to set the calling convention for
+** public functions that accept a variable number of arguments.
+**
+** The SQLITE_APICALL macro is used to set the calling convention for
+** public functions that accept a fixed number of arguments.
+**
+** The SQLITE_STDCALL macro is no longer used and is now deprecated.
+**
+** The SQLITE_CALLBACK macro is used to set the calling convention for
+** function pointers.
+**
+** The SQLITE_SYSAPI macro is used to set the calling convention for
+** functions provided by the operating system.
+**
+** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
+** SQLITE_SYSAPI macros are used only when building for environments
+** that require non-default calling conventions.
 */
 #ifndef SQLITE_EXTERN
 # define SQLITE_EXTERN extern
@@ -1187,9 +453,9 @@ extern "C" {
 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
 ** [sqlite_version()] and [sqlite_source_id()].
 */
-#define SQLITE_VERSION        "3.35.4"
-#define SQLITE_VERSION_NUMBER 3035004
-#define SQLITE_SOURCE_ID      "2021-04-02 15:20:15 5d4c65779dab868b285519b19e4cf9d451d50c6048f06f653aa701ec212df45e"
+#define SQLITE_VERSION        "3.38.5"
+#define SQLITE_VERSION_NUMBER 3038005
+#define SQLITE_SOURCE_ID      "2022-05-06 15:25:27 78d9c993d404cdfaa7fdd2973fa1052e3da9f66215cff9c5540ebe55c407d9fe"
 
 /*
 ** CAPI3REF: Run-Time Library Version Numbers
@@ -1601,12 +867,13 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
 #define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
+#define SQLITE_CONSTRAINT_DATATYPE     (SQLITE_CONSTRAINT |(12<<8))
 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
 #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
-#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))
+#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8)) /* internal use only */
 
 /*
 ** CAPI3REF: Flags For File Open Operations
@@ -1614,6 +881,19 @@ SQLITE_API int sqlite3_exec(
 ** These bit values are intended for use in the
 ** 3rd parameter to the [sqlite3_open_v2()] interface and
 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
+**
+** Only those flags marked as "Ok for sqlite3_open_v2()" may be
+** used as the third argument to the [sqlite3_open_v2()] interface.
+** The other flags have historically been ignored by sqlite3_open_v2(),
+** though future versions of SQLite might change so that an error is
+** raised if any of the disallowed bits are passed into sqlite3_open_v2().
+** Applications should not depend on the historical behavior.
+**
+** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
+** [sqlite3_open_v2()] does *not* cause the underlying database file
+** to be opened using O_EXCL.  Passing SQLITE_OPEN_EXCLUSIVE into
+** [sqlite3_open_v2()] has historically be a no-op and might become an
+** error in future versions of SQLite.
 */
 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
@@ -1636,6 +916,7 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
 #define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_EXRESCODE        0x02000000  /* Extended result codes */
 
 /* Reserved:                         0x00F00000 */
 /* Legacy compatibility: */
@@ -2192,6 +1473,23 @@ struct sqlite3_io_methods {
 ** file to the database file, but before the *-shm file is updated to
 ** record the fact that the pages have been checkpointed.
 ** </ul>
+**
+** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
+** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
+** whether or not there is a database client in another process with a wal-mode
+** transaction open on the database or not. It is only available on unix.The
+** (void*) argument passed with this file-control should be a pointer to a
+** value of type (int). The integer value is set to 1 if the database is a wal
+** mode database and there exists at least one client in another process that
+** currently has an SQL transaction open on the database. It is set to 0 if
+** the database is not a wal-mode db, or if there is no such connection in any
+** other process. This opcode cannot be used to detect transactions opened
+** by clients within the current process, only within other processes.
+** </ul>
+**
+** <li>[[SQLITE_FCNTL_CKSM_FILE]]
+** Used by the cksmvfs VFS module only.
+** </ul>
 */
 #define SQLITE_FCNTL_LOCKSTATE               1
 #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
@@ -2231,6 +1529,8 @@ struct sqlite3_io_methods {
 #define SQLITE_FCNTL_CKPT_DONE              37
 #define SQLITE_FCNTL_RESERVE_BYTES          38
 #define SQLITE_FCNTL_CKPT_START             39
+#define SQLITE_FCNTL_EXTERNAL_READER        40
+#define SQLITE_FCNTL_CKSM_FILE              41
 
 /* deprecated names */
 #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
@@ -3509,11 +2809,14 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
 ** CAPI3REF: Count The Number Of Rows Modified
 ** METHOD: sqlite3
 **
-** ^This function returns the number of rows modified, inserted or
+** ^These functions return the number of rows modified, inserted or
 ** deleted by the most recently completed INSERT, UPDATE or DELETE
 ** statement on the database connection specified by the only parameter.
-** ^Executing any other type of SQL statement does not modify the value
-** returned by this function.
+** The two functions are identical except for the type of the return value
+** and that if the number of rows modified by the most recent INSERT, UPDATE
+** or DELETE is greater than the maximum value supported by type "int", then
+** the return value of sqlite3_changes() is undefined. ^Executing any other
+** type of SQL statement does not modify the value returned by these functions.
 **
 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
@@ -3562,16 +2865,21 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
 ** </ul>
 */
 SQLITE_API int sqlite3_changes(sqlite3*);
+SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*);
 
 /*
 ** CAPI3REF: Total Number Of Rows Modified
 ** METHOD: sqlite3
 **
-** ^This function returns the total number of rows inserted, modified or
+** ^These functions return the total number of rows inserted, modified or
 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
 ** since the database connection was opened, including those executed as
-** part of trigger programs. ^Executing any other type of SQL statement
-** does not affect the value returned by sqlite3_total_changes().
+** part of trigger programs. The two functions are identical except for the
+** type of the return value and that if the number of rows modified by the
+** connection exceeds the maximum value supported by type "int", then
+** the return value of sqlite3_total_changes() is undefined. ^Executing
+** any other type of SQL statement does not affect the value returned by
+** sqlite3_total_changes().
 **
 ** ^Changes made as part of [foreign key actions] are included in the
 ** count, but those made as part of REPLACE constraint resolution are
@@ -3599,6 +2907,7 @@ SQLITE_API int sqlite3_changes(sqlite3*);
 ** </ul>
 */
 SQLITE_API int sqlite3_total_changes(sqlite3*);
+SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*);
 
 /*
 ** CAPI3REF: Interrupt A Long-Running Query
@@ -4428,6 +3737,14 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** the default shared cache setting provided by
 ** [sqlite3_enable_shared_cache()].)^
 **
+** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
+** <dd>The database connection comes up in "extended result code mode".
+** In other words, the database behaves has if
+** [sqlite3_extended_result_codes(db,1)] where called on the database
+** connection as soon as the connection is created. In addition to setting
+** the extended result code mode, this flag also causes [sqlite3_open_v2()]
+** to return an extended result code.</dd>
+**
 ** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
 ** <dd>The database filename is not allowed to be a symbolic link</dd>
 ** </dl>)^
@@ -4435,7 +3752,15 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
 ** required combinations shown above optionally combined with other
 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
-** then the behavior is undefined.
+** then the behavior is undefined.  Historic versions of SQLite
+** have silently ignored surplus bits in the flags parameter to
+** sqlite3_open_v2(), however that behavior might not be carried through
+** into future versions of SQLite and so applications should not rely
+** upon it.  Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
+** for sqlite3_open_v2().  The SQLITE_OPEN_EXCLUSIVE does *not* cause
+** the open to fail if the database already exists.  The SQLITE_OPEN_EXCLUSIVE
+** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not
+** by sqlite3_open_v2().
 **
 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
 ** [sqlite3_vfs] object that defines the operating system interface that
@@ -4806,13 +4131,14 @@ SQLITE_API void sqlite3_free_filename(char*);
 ** sqlite3_extended_errcode() might change with each API call.
 ** Except, there are some interfaces that are guaranteed to never
 ** change the value of the error code.  The error-code preserving
-** interfaces are:
+** interfaces include the following:
 **
 ** <ul>
 ** <li> sqlite3_errcode()
 ** <li> sqlite3_extended_errcode()
 ** <li> sqlite3_errmsg()
 ** <li> sqlite3_errmsg16()
+** <li> sqlite3_error_offset()
 ** </ul>
 **
 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
@@ -4827,6 +4153,13 @@ SQLITE_API void sqlite3_free_filename(char*);
 ** ^(Memory to hold the error message string is managed internally
 ** and must not be freed by the application)^.
 **
+** ^If the most recent error references a specific token in the input
+** SQL, the sqlite3_error_offset() interface returns the byte offset
+** of the start of that token.  ^The byte offset returned by
+** sqlite3_error_offset() assumes that the input SQL is UTF8.
+** ^If the most recent error does not reference a specific token in the input
+** SQL, then the sqlite3_error_offset() function returns -1.
+**
 ** When the serialized [threading mode] is in use, it might be the
 ** case that a second error occurs on a separate thread in between
 ** the time of the first error and the call to these interfaces.
@@ -4846,6 +4179,7 @@ SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
 SQLITE_API const char *sqlite3_errstr(int);
+SQLITE_API int sqlite3_error_offset(sqlite3 *db);
 
 /*
 ** CAPI3REF: Prepared Statement Object
@@ -5203,12 +4537,17 @@ SQLITE_API int sqlite3_prepare16_v3(
 ** are managed by SQLite and are automatically freed when the prepared
 ** statement is finalized.
 ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
-** is obtained from [sqlite3_malloc()] and must be free by the application
+** is obtained from [sqlite3_malloc()] and must be freed by the application
 ** by passing it to [sqlite3_free()].
+**
+** ^The sqlite3_normalized_sql() interface is only available if
+** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
 */
 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
+#ifdef SQLITE_ENABLE_NORMALIZE
 SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
+#endif
 
 /*
 ** CAPI3REF: Determine If An SQL Statement Writes The Database
@@ -5243,6 +4582,19 @@ SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
 ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
 ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
 ** sqlite3_stmt_readonly() returns false for those commands.
+**
+** ^This routine returns false if there is any possibility that the
+** statement might change the database file.  ^A false return does
+** not guarantee that the statement will change the database file.
+** ^For example, an UPDATE statement might have a WHERE clause that
+** makes it a no-op, but the sqlite3_stmt_readonly() result would still
+** be false.  ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
+** read-only no-op if the table already exists, but
+** sqlite3_stmt_readonly() still returns false for such a statement.
+**
+** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN]
+** statement, then sqlite3_stmt_readonly(X) returns the same value as
+** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted.
 */
 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
 
@@ -5311,6 +4663,8 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
 **
 ** ^The sqlite3_value objects that are passed as parameters into the
 ** implementation of [application-defined SQL functions] are protected.
+** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()]
+** are protected.
 ** ^The sqlite3_value object returned by
 ** [sqlite3_column_value()] is unprotected.
 ** Unprotected sqlite3_value objects may only be used as arguments
@@ -5412,18 +4766,22 @@ typedef struct sqlite3_context sqlite3_context;
 ** contain embedded NULs.  The result of expressions involving strings
 ** with embedded NULs is undefined.
 **
-** ^The fifth argument to the BLOB and string binding interfaces
-** is a destructor used to dispose of the BLOB or
-** string after SQLite has finished with it.  ^The destructor is called
-** to dispose of the BLOB or string even if the call to the bind API fails,
-** except the destructor is not called if the third parameter is a NULL
-** pointer or the fourth parameter is negative.
-** ^If the fifth argument is
-** the special value [SQLITE_STATIC], then SQLite assumes that the
-** information is in static, unmanaged space and does not need to be freed.
-** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
-** SQLite makes its own private copy of the data immediately, before
-** the sqlite3_bind_*() routine returns.
+** ^The fifth argument to the BLOB and string binding interfaces controls
+** or indicates the lifetime of the object referenced by the third parameter.
+** These three options exist:
+** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
+** with it may be passed. ^It is called to dispose of the BLOB or string even
+** if the call to the bind API fails, except the destructor is not called if
+** the third parameter is a NULL pointer or the fourth parameter is negative.
+** ^ (2) The special constant, [SQLITE_STATIC], may be passsed to indicate that
+** the application remains responsible for disposing of the object. ^In this
+** case, the object and the provided pointer to it must remain valid until
+** either the prepared statement is finalized or the same SQL parameter is
+** bound to something else, whichever occurs sooner.
+** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the
+** object is to be copied prior to the return from sqlite3_bind_*(). ^The
+** object and pointer to it must remain valid until then. ^SQLite will then
+** manage the lifetime of its private copy.
 **
 ** ^The sixth argument to sqlite3_bind_text64() must be one of
 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
@@ -5928,6 +5286,10 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** even empty strings, are always zero-terminated.  ^The return
 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
 **
+** ^Strings returned by sqlite3_column_text16() always have the endianness
+** which is native to the platform, regardless of the text encoding set
+** for the database.
+**
 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
 ** [unprotected sqlite3_value] object.  In a multithreaded environment,
 ** an unprotected sqlite3_value object may only be used safely with
@@ -5941,7 +5303,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** [application-defined SQL functions] or [virtual tables], not within
 ** top-level application code.
 **
-** The these routines may attempt to convert the datatype of the result.
+** These routines may attempt to convert the datatype of the result.
 ** ^For example, if the internal representation is FLOAT and a text result
 ** is requested, [sqlite3_snprintf()] is used internally to perform the
 ** conversion automatically.  ^(The following table details the conversions
@@ -5966,7 +5328,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
-** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
+** <tr><td>  BLOB    <td>   TEXT    <td> [CAST] to TEXT, ensure zero terminator
 ** </table>
 ** </blockquote>)^
 **
@@ -6165,7 +5527,6 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
 ** index expressions, or the WHERE clause of partial indexes.
 **
-** <span style="background-color:#ffff90;">
 ** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
 ** all application-defined SQL functions that do not need to be
 ** used inside of triggers, view, CHECK constraints, or other elements of
@@ -6175,7 +5536,6 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** a database file to include invocations of the function with parameters
 ** chosen by the attacker, which the application will then execute when
 ** the database file is opened and read.
-** </span>
 **
 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
 ** function can gain access to this pointer using [sqlite3_user_data()].)^
@@ -7381,6 +6741,72 @@ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
 
+/*
+** CAPI3REF: Autovacuum Compaction Amount Callback
+** METHOD: sqlite3
+**
+** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback
+** function C that is invoked prior to each autovacuum of the database
+** file.  ^The callback is passed a copy of the generic data pointer (P),
+** the schema-name of the attached database that is being autovacuumed,
+** the the size of the database file in pages, the number of free pages,
+** and the number of bytes per page, respectively.  The callback should
+** return the number of free pages that should be removed by the
+** autovacuum.  ^If the callback returns zero, then no autovacuum happens.
+** ^If the value returned is greater than or equal to the number of
+** free pages, then a complete autovacuum happens.
+**
+** <p>^If there are multiple ATTACH-ed database files that are being
+** modified as part of a transaction commit, then the autovacuum pages
+** callback is invoked separately for each file.
+**
+** <p><b>The callback is not reentrant.</b> The callback function should
+** not attempt to invoke any other SQLite interface.  If it does, bad
+** things may happen, including segmentation faults and corrupt database
+** files.  The callback function should be a simple function that
+** does some arithmetic on its input parameters and returns a result.
+**
+** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
+** destructor for the P parameter.  ^If X is not NULL, then X(P) is
+** invoked whenever the database connection closes or when the callback
+** is overwritten by another invocation of sqlite3_autovacuum_pages().
+**
+** <p>^There is only one autovacuum pages callback per database connection.
+** ^Each call to the sqlite3_autovacuum_pages() interface overrides all
+** previous invocations for that database connection.  ^If the callback
+** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,
+** then the autovacuum steps callback is cancelled.  The return value
+** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might
+** be some other error code if something goes wrong.  The current
+** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other
+** return codes might be added in future releases.
+**
+** <p>If no autovacuum pages callback is specified (the usual case) or
+** a NULL pointer is provided for the callback,
+** then the default behavior is to vacuum all free pages.  So, in other
+** words, the default behavior is the same as if the callback function
+** were something like this:
+**
+** <blockquote><pre>
+** &nbsp;   unsigned int demonstration_autovac_pages_callback(
+** &nbsp;     void *pClientData,
+** &nbsp;     const char *zSchema,
+** &nbsp;     unsigned int nDbPage,
+** &nbsp;     unsigned int nFreePage,
+** &nbsp;     unsigned int nBytePerPage
+** &nbsp;   ){
+** &nbsp;     return nFreePage;
+** &nbsp;   }
+** </pre></blockquote>
+*/
+SQLITE_API int sqlite3_autovacuum_pages(
+  sqlite3 *db,
+  unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
+  void*,
+  void(*)(void*)
+);
+
+
 /*
 ** CAPI3REF: Data Change Notification Callbacks
 ** METHOD: sqlite3
@@ -8022,24 +7448,56 @@ struct sqlite3_index_info {
 **
 ** These macros define the allowed values for the
 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
-** an operator that is part of a constraint term in the wHERE clause of
+** an operator that is part of a constraint term in the WHERE clause of
 ** a query that uses a [virtual table].
-*/
-#define SQLITE_INDEX_CONSTRAINT_EQ         2
-#define SQLITE_INDEX_CONSTRAINT_GT         4
-#define SQLITE_INDEX_CONSTRAINT_LE         8
-#define SQLITE_INDEX_CONSTRAINT_LT        16
-#define SQLITE_INDEX_CONSTRAINT_GE        32
-#define SQLITE_INDEX_CONSTRAINT_MATCH     64
-#define SQLITE_INDEX_CONSTRAINT_LIKE      65
-#define SQLITE_INDEX_CONSTRAINT_GLOB      66
-#define SQLITE_INDEX_CONSTRAINT_REGEXP    67
-#define SQLITE_INDEX_CONSTRAINT_NE        68
-#define SQLITE_INDEX_CONSTRAINT_ISNOT     69
-#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
-#define SQLITE_INDEX_CONSTRAINT_ISNULL    71
-#define SQLITE_INDEX_CONSTRAINT_IS        72
-#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
+**
+** ^The left-hand operand of the operator is given by the corresponding
+** aConstraint[].iColumn field.  ^An iColumn of -1 indicates the left-hand
+** operand is the rowid.
+** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET
+** operators have no left-hand operand, and so for those operators the
+** corresponding aConstraint[].iColumn is meaningless and should not be
+** used.
+**
+** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through
+** value 255 are reserved to represent functions that are overloaded
+** by the [xFindFunction|xFindFunction method] of the virtual table
+** implementation.
+**
+** The right-hand operands for each constraint might be accessible using
+** the [sqlite3_vtab_rhs_value()] interface.  Usually the right-hand
+** operand is only available if it appears as a single constant literal
+** in the input SQL.  If the right-hand operand is another column or an
+** expression (even a constant expression) or a parameter, then the
+** sqlite3_vtab_rhs_value() probably will not be able to extract it.
+** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and
+** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand
+** and hence calls to sqlite3_vtab_rhs_value() for those operators will
+** always return SQLITE_NOTFOUND.
+**
+** The collating sequence to be used for comparison can be found using
+** the [sqlite3_vtab_collation()] interface.  For most real-world virtual
+** tables, the collating sequence of constraints does not matter (for example
+** because the constraints are numeric) and so the sqlite3_vtab_collation()
+** interface is no commonly needed.
+*/
+#define SQLITE_INDEX_CONSTRAINT_EQ          2
+#define SQLITE_INDEX_CONSTRAINT_GT          4
+#define SQLITE_INDEX_CONSTRAINT_LE          8
+#define SQLITE_INDEX_CONSTRAINT_LT         16
+#define SQLITE_INDEX_CONSTRAINT_GE         32
+#define SQLITE_INDEX_CONSTRAINT_MATCH      64
+#define SQLITE_INDEX_CONSTRAINT_LIKE       65
+#define SQLITE_INDEX_CONSTRAINT_GLOB       66
+#define SQLITE_INDEX_CONSTRAINT_REGEXP     67
+#define SQLITE_INDEX_CONSTRAINT_NE         68
+#define SQLITE_INDEX_CONSTRAINT_ISNOT      69
+#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL  70
+#define SQLITE_INDEX_CONSTRAINT_ISNULL     71
+#define SQLITE_INDEX_CONSTRAINT_IS         72
+#define SQLITE_INDEX_CONSTRAINT_LIMIT      73
+#define SQLITE_INDEX_CONSTRAINT_OFFSET     74
+#define SQLITE_INDEX_CONSTRAINT_FUNCTION  150
 
 /*
 ** CAPI3REF: Register A Virtual Table Implementation
@@ -8068,7 +7526,7 @@ struct sqlite3_index_info {
 ** destructor.
 **
 ** ^If the third parameter (the pointer to the sqlite3_module object) is
-** NULL then no new module is create and any existing modules with the
+** NULL then no new module is created and any existing modules with the
 ** same name are dropped.
 **
 ** See also: [sqlite3_drop_modules()]
@@ -8843,7 +8301,9 @@ SQLITE_API int sqlite3_test_control(int op, ...);
 #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
 #define SQLITE_TESTCTRL_SEEK_COUNT              30
 #define SQLITE_TESTCTRL_TRACEFLAGS              31
-#define SQLITE_TESTCTRL_LAST                    31  /* Largest TESTCTRL */
+#define SQLITE_TESTCTRL_TUNE                    32
+#define SQLITE_TESTCTRL_LOGEST                  33
+#define SQLITE_TESTCTRL_LAST                    33  /* Largest TESTCTRL */
 
 /*
 ** CAPI3REF: SQL Keyword Checking
@@ -9366,6 +8826,16 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 ** The counter is incremented on the first [sqlite3_step()] call of each
 ** cycle.
 **
+** [[SQLITE_STMTSTATUS_FILTER_MISS]]
+** [[SQLITE_STMTSTATUS_FILTER HIT]]
+** <dt>SQLITE_STMTSTATUS_FILTER_HIT<br>
+** SQLITE_STMTSTATUS_FILTER_MISS</dt>
+** <dd>^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join
+** step was bypassed because a Bloom filter returned not-found.  The
+** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of
+** times that the Bloom filter returned a find, and thus the join step
+** had to be processed as normal.
+**
 ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
 ** <dd>^This is the approximate number of bytes of heap memory
 ** used to store the prepared statement.  ^This value is not actually
@@ -9380,6 +8850,8 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 #define SQLITE_STMTSTATUS_VM_STEP           4
 #define SQLITE_STMTSTATUS_REPREPARE         5
 #define SQLITE_STMTSTATUS_RUN               6
+#define SQLITE_STMTSTATUS_FILTER_MISS       7
+#define SQLITE_STMTSTATUS_FILTER_HIT        8
 #define SQLITE_STMTSTATUS_MEMUSED           99
 
 /*
@@ -10043,8 +9515,9 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 **
 ** A single database handle may have at most a single write-ahead log callback
 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
-** previously registered write-ahead log callback. ^Note that the
-** [sqlite3_wal_autocheckpoint()] interface and the
+** previously registered write-ahead log callback. ^The return value is
+** a copy of the third parameter from the previous call, if any, or 0.
+** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the
 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
 ** overwrite any prior [sqlite3_wal_hook()] settings.
 */
@@ -10347,19 +9820,269 @@ SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
 
 /*
 ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
+** METHOD: sqlite3_index_info
 **
 ** This function may only be called from within a call to the [xBestIndex]
-** method of a [virtual table].
+** method of a [virtual table].  This function returns a pointer to a string
+** that is the name of the appropriate collation sequence to use for text
+** comparisons on the constraint identified by its arguments.
 **
-** The first argument must be the sqlite3_index_info object that is the
-** first parameter to the xBestIndex() method. The second argument must be
-** an index into the aConstraint[] array belonging to the sqlite3_index_info
-** structure passed to xBestIndex. This function returns a pointer to a buffer
-** containing the name of the collation sequence for the corresponding
-** constraint.
+** The first argument must be the pointer to the [sqlite3_index_info] object
+** that is the first parameter to the xBestIndex() method. The second argument
+** must be an index into the aConstraint[] array belonging to the
+** sqlite3_index_info structure passed to xBestIndex.
+**
+** Important:
+** The first parameter must be the same pointer that is passed into the
+** xBestMethod() method.  The first parameter may not be a pointer to a
+** different [sqlite3_index_info] object, even an exact copy.
+**
+** The return value is computed as follows:
+**
+** <ol>
+** <li><p> If the constraint comes from a WHERE clause expression that contains
+**         a [COLLATE operator], then the name of the collation specified by
+**         that COLLATE operator is returned.
+** <li><p> If there is no COLLATE operator, but the column that is the subject
+**         of the constraint specifies an alternative collating sequence via
+**         a [COLLATE clause] on the column definition within the CREATE TABLE
+**         statement that was passed into [sqlite3_declare_vtab()], then the
+**         name of that alternative collating sequence is returned.
+** <li><p> Otherwise, "BINARY" is returned.
+** </ol>
 */
 SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
 
+/*
+** CAPI3REF: Determine if a virtual table query is DISTINCT
+** METHOD: sqlite3_index_info
+**
+** This API may only be used from within an [xBestIndex|xBestIndex method]
+** of a [virtual table] implementation. The result of calling this
+** interface from outside of xBestIndex() is undefined and probably harmful.
+**
+** ^The sqlite3_vtab_distinct() interface returns an integer that is
+** either 0, 1, or 2.  The integer returned by sqlite3_vtab_distinct()
+** gives the virtual table additional information about how the query
+** planner wants the output to be ordered. As long as the virtual table
+** can meet the ordering requirements of the query planner, it may set
+** the "orderByConsumed" flag.
+**
+** <ol><li value="0"><p>
+** ^If the sqlite3_vtab_distinct() interface returns 0, that means
+** that the query planner needs the virtual table to return all rows in the
+** sort order defined by the "nOrderBy" and "aOrderBy" fields of the
+** [sqlite3_index_info] object.  This is the default expectation.  If the
+** virtual table outputs all rows in sorted order, then it is always safe for
+** the xBestIndex method to set the "orderByConsumed" flag, regardless of
+** the return value from sqlite3_vtab_distinct().
+** <li value="1"><p>
+** ^(If the sqlite3_vtab_distinct() interface returns 1, that means
+** that the query planner does not need the rows to be returned in sorted order
+** as long as all rows with the same values in all columns identified by the
+** "aOrderBy" field are adjacent.)^  This mode is used when the query planner
+** is doing a GROUP BY.
+** <li value="2"><p>
+** ^(If the sqlite3_vtab_distinct() interface returns 2, that means
+** that the query planner does not need the rows returned in any particular
+** order, as long as rows with the same values in all "aOrderBy" columns
+** are adjacent.)^  ^(Furthermore, only a single row for each particular
+** combination of values in the columns identified by the "aOrderBy" field
+** needs to be returned.)^  ^It is always ok for two or more rows with the same
+** values in all "aOrderBy" columns to be returned, as long as all such rows
+** are adjacent.  ^The virtual table may, if it chooses, omit extra rows
+** that have the same value for all columns identified by "aOrderBy".
+** ^However omitting the extra rows is optional.
+** This mode is used for a DISTINCT query.
+** </ol>
+**
+** ^For the purposes of comparing virtual table output values to see if the
+** values are same value for sorting purposes, two NULL values are considered
+** to be the same.  In other words, the comparison operator is "IS"
+** (or "IS NOT DISTINCT FROM") and not "==".
+**
+** If a virtual table implementation is unable to meet the requirements
+** specified above, then it must not set the "orderByConsumed" flag in the
+** [sqlite3_index_info] object or an incorrect answer may result.
+**
+** ^A virtual table implementation is always free to return rows in any order
+** it wants, as long as the "orderByConsumed" flag is not set.  ^When the
+** the "orderByConsumed" flag is unset, the query planner will add extra
+** [bytecode] to ensure that the final results returned by the SQL query are
+** ordered correctly.  The use of the "orderByConsumed" flag and the
+** sqlite3_vtab_distinct() interface is merely an optimization.  ^Careful
+** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed"
+** flag might help queries against a virtual table to run faster.  Being
+** overly aggressive and setting the "orderByConsumed" flag when it is not
+** valid to do so, on the other hand, might cause SQLite to return incorrect
+** results.
+*/
+SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*);
+
+/*
+** CAPI3REF: Identify and handle IN constraints in xBestIndex
+**
+** This interface may only be used from within an
+** [xBestIndex|xBestIndex() method] of a [virtual table] implementation.
+** The result of invoking this interface from any other context is
+** undefined and probably harmful.
+**
+** ^(A constraint on a virtual table of the form
+** "[IN operator|column IN (...)]" is
+** communicated to the xBestIndex method as a
+** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^  If xBestIndex wants to use
+** this constraint, it must set the corresponding
+** aConstraintUsage[].argvIndex to a postive integer.  ^(Then, under
+** the usual mode of handling IN operators, SQLite generates [bytecode]
+** that invokes the [xFilter|xFilter() method] once for each value
+** on the right-hand side of the IN operator.)^  Thus the virtual table
+** only sees a single value from the right-hand side of the IN operator
+** at a time.
+**
+** In some cases, however, it would be advantageous for the virtual
+** table to see all values on the right-hand of the IN operator all at
+** once.  The sqlite3_vtab_in() interfaces facilitates this in two ways:
+**
+** <ol>
+** <li><p>
+**   ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)
+**   if and only if the [sqlite3_index_info|P->aConstraint][N] constraint
+**   is an [IN operator] that can be processed all at once.  ^In other words,
+**   sqlite3_vtab_in() with -1 in the third argument is a mechanism
+**   by which the virtual table can ask SQLite if all-at-once processing
+**   of the IN operator is even possible.
+**
+** <li><p>
+**   ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates
+**   to SQLite that the virtual table does or does not want to process
+**   the IN operator all-at-once, respectively.  ^Thus when the third
+**   parameter (F) is non-negative, this interface is the mechanism by
+**   which the virtual table tells SQLite how it wants to process the
+**   IN operator.
+** </ol>
+**
+** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times
+** within the same xBestIndex method call.  ^For any given P,N pair,
+** the return value from sqlite3_vtab_in(P,N,F) will always be the same
+** within the same xBestIndex call.  ^If the interface returns true
+** (non-zero), that means that the constraint is an IN operator
+** that can be processed all-at-once.  ^If the constraint is not an IN
+** operator or cannot be processed all-at-once, then the interface returns
+** false.
+**
+** ^(All-at-once processing of the IN operator is selected if both of the
+** following conditions are met:
+**
+** <ol>
+** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive
+** integer.  This is how the virtual table tells SQLite that it wants to
+** use the N-th constraint.
+**
+** <li><p> The last call to sqlite3_vtab_in(P,N,F) for which F was
+** non-negative had F>=1.
+** </ol>)^
+**
+** ^If either or both of the conditions above are false, then SQLite uses
+** the traditional one-at-a-time processing strategy for the IN constraint.
+** ^If both conditions are true, then the argvIndex-th parameter to the
+** xFilter method will be an [sqlite3_value] that appears to be NULL,
+** but which can be passed to [sqlite3_vtab_in_first()] and
+** [sqlite3_vtab_in_next()] to find all values on the right-hand side
+** of the IN constraint.
+*/
+SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);
+
+/*
+** CAPI3REF: Find all elements on the right-hand side of an IN constraint.
+**
+** These interfaces are only useful from within the
+** [xFilter|xFilter() method] of a [virtual table] implementation.
+** The result of invoking these interfaces from any other context
+** is undefined and probably harmful.
+**
+** The X parameter in a call to sqlite3_vtab_in_first(X,P) or
+** sqlite3_vtab_in_next(X,P) must be one of the parameters to the
+** xFilter method which invokes these routines, and specifically
+** a parameter that was previously selected for all-at-once IN constraint
+** processing use the [sqlite3_vtab_in()] interface in the
+** [xBestIndex|xBestIndex method].  ^(If the X parameter is not
+** an xFilter argument that was selected for all-at-once IN constraint
+** processing, then these routines return [SQLITE_MISUSE])^ or perhaps
+** exhibit some other undefined or harmful behavior.
+**
+** ^(Use these routines to access all values on the right-hand side
+** of the IN constraint using code like the following:
+**
+** <blockquote><pre>
+** &nbsp;  for(rc=sqlite3_vtab_in_first(pList, &pVal);
+** &nbsp;      rc==SQLITE_OK && pVal
+** &nbsp;      rc=sqlite3_vtab_in_next(pList, &pVal)
+** &nbsp;  ){
+** &nbsp;    // do something with pVal
+** &nbsp;  }
+** &nbsp;  if( rc!=SQLITE_OK ){
+** &nbsp;    // an error has occurred
+** &nbsp;  }
+** </pre></blockquote>)^
+**
+** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P)
+** routines return SQLITE_OK and set *P to point to the first or next value
+** on the RHS of the IN constraint.  ^If there are no more values on the
+** right hand side of the IN constraint, then *P is set to NULL and these
+** routines return [SQLITE_DONE].  ^The return value might be
+** some other value, such as SQLITE_NOMEM, in the event of a malfunction.
+**
+** The *ppOut values returned by these routines are only valid until the
+** next call to either of these routines or until the end of the xFilter
+** method from which these routines were called.  If the virtual table
+** implementation needs to retain the *ppOut values for longer, it must make
+** copies.  The *ppOut values are [protected sqlite3_value|protected].
+*/
+SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut);
+SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);
+
+/*
+** CAPI3REF: Constraint values in xBestIndex()
+** METHOD: sqlite3_index_info
+**
+** This API may only be used from within the [xBestIndex|xBestIndex method]
+** of a [virtual table] implementation. The result of calling this interface
+** from outside of an xBestIndex method are undefined and probably harmful.
+**
+** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within
+** the [xBestIndex] method of a [virtual table] implementation, with P being
+** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and
+** J being a 0-based index into P->aConstraint[], then this routine
+** attempts to set *V to the value of the right-hand operand of
+** that constraint if the right-hand operand is known.  ^If the
+** right-hand operand is not known, then *V is set to a NULL pointer.
+** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if
+** and only if *V is set to a value.  ^The sqlite3_vtab_rhs_value(P,J,V)
+** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th
+** constraint is not available.  ^The sqlite3_vtab_rhs_value() interface
+** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if
+** something goes wrong.
+**
+** The sqlite3_vtab_rhs_value() interface is usually only successful if
+** the right-hand operand of a constraint is a literal value in the original
+** SQL statement.  If the right-hand operand is an expression or a reference
+** to some other column or a [host parameter], then sqlite3_vtab_rhs_value()
+** will probably return [SQLITE_NOTFOUND].
+**
+** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and
+** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand.  For such
+** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^
+**
+** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value
+** and remains valid for the duration of the xBestIndex method call.
+** ^When xBestIndex returns, the sqlite3_value object returned by
+** sqlite3_vtab_rhs_value() is automatically deallocated.
+**
+** The "_rhs_" in the name of this routine is an abbreviation for
+** "Right-Hand Side".
+*/
+SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal);
+
 /*
 ** CAPI3REF: Conflict resolution modes
 ** KEYWORDS: {conflict resolution mode}
@@ -10595,6 +10318,15 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 ** triggers; or 2 for changes resulting from triggers called by top-level
 ** triggers; and so forth.
 **
+** When the [sqlite3_blob_write()] API is used to update a blob column,
+** the pre-update hook is invoked with SQLITE_DELETE. This is because the
+** in this case the new values are not available. In this case, when a
+** callback made with op==SQLITE_DELETE is actuall a write using the
+** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns
+** the index of the column being written. In other cases, where the
+** pre-update hook is being invoked for some other reason, including a
+** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
+**
 ** See also:  [sqlite3_update_hook()]
 */
 #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
@@ -10615,6 +10347,7 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
 SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
 SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
 SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
+SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *);
 #endif
 
 /*
@@ -10853,8 +10586,8 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c
 ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
 ** allocation error occurs.
 **
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_DESERIALIZE] option.
+** This interface is omitted if SQLite is compiled with the
+** [SQLITE_OMIT_DESERIALIZE] option.
 */
 SQLITE_API unsigned char *sqlite3_serialize(
   sqlite3 *db,           /* The database connection */
@@ -10901,12 +10634,16 @@ SQLITE_API unsigned char *sqlite3_serialize(
 ** database is currently in a read transaction or is involved in a backup
 ** operation.
 **
+** It is not possible to deserialized into the TEMP database.  If the
+** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
+** function returns SQLITE_ERROR.
+**
 ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
 ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
 ** [sqlite3_free()] is invoked on argument P prior to returning.
 **
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_DESERIALIZE] option.
+** This interface is omitted if SQLite is compiled with the
+** [SQLITE_OMIT_DESERIALIZE] option.
 */
 SQLITE_API int sqlite3_deserialize(
   sqlite3 *db,            /* The database connection */
@@ -11155,6 +10892,38 @@ SQLITE_API int sqlite3session_create(
 */
 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
 
+/*
+** CAPIREF: Conigure a Session Object
+** METHOD: sqlite3_session
+**
+** This method is used to configure a session object after it has been
+** created. At present the only valid value for the second parameter is
+** [SQLITE_SESSION_OBJCONFIG_SIZE].
+**
+** Arguments for sqlite3session_object_config()
+**
+** The following values may passed as the the 4th parameter to
+** sqlite3session_object_config().
+**
+** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
+**   This option is used to set, clear or query the flag that enables
+**   the [sqlite3session_changeset_size()] API. Because it imposes some
+**   computational overhead, this API is disabled by default. Argument
+**   pArg must point to a value of type (int). If the value is initially
+**   0, then the sqlite3session_changeset_size() API is disabled. If it
+**   is greater than 0, then the same API is enabled. Or, if the initial
+**   value is less than zero, no change is made. In all cases the (int)
+**   variable is set to 1 if the sqlite3session_changeset_size() API is
+**   enabled following the current call, or 0 otherwise.
+**
+**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
+**   the first table has been attached to the session object.
+*/
+SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);
+
+/*
+*/
+#define SQLITE_SESSION_OBJCONFIG_SIZE 1
 
 /*
 ** CAPI3REF: Enable Or Disable A Session Object
@@ -11399,6 +11168,22 @@ SQLITE_API int sqlite3session_changeset(
   void **ppChangeset              /* OUT: Buffer containing changeset */
 );
 
+/*
+** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
+** METHOD: sqlite3_session
+**
+** By default, this function always returns 0. For it to return
+** a useful result, the sqlite3_session object must have been configured
+** to enable this API using sqlite3session_object_config() with the
+** SQLITE_SESSION_OBJCONFIG_SIZE verb.
+**
+** When enabled, this function returns an upper limit, in bytes, for the size
+** of the changeset that might be produced if sqlite3session_changeset() were
+** called. The final changeset size might be equal to or smaller than the
+** size in bytes returned by this function.
+*/
+SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession);
+
 /*
 ** CAPI3REF: Load The Difference Between Tables Into A Session
 ** METHOD: sqlite3_session
@@ -13335,7 +13120,7 @@ struct fts5_api {
 ** autoconf-based build
 */
 #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
-/* #include "config.h" */
+#include "config.h"
 #define SQLITECONFIG_H 1
 #endif
 
@@ -13571,11 +13356,12 @@ struct fts5_api {
 #ifndef __has_extension
 # define __has_extension(x) 0     /* compatibility with non-clang compilers */
 #endif
-#if GCC_VERSION>=4007000 || \
-    (__has_extension(c_atomic) && __has_extension(c_atomic_store_n))
+#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
+# define SQLITE_ATOMIC_INTRINSICS 1
 # define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
 # define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
 #else
+# define SQLITE_ATOMIC_INTRINSICS 0
 # define AtomicLoad(PTR)       (*(PTR))
 # define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))
 #endif
@@ -13780,11 +13566,12 @@ struct fts5_api {
 ** is significant and used at least once.  On switch statements
 ** where multiple cases go to the same block of code, testcase()
 ** can insure that all cases are evaluated.
-**
 */
-#ifdef SQLITE_COVERAGE_TEST
-SQLITE_PRIVATE   void sqlite3Coverage(int);
-# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
+# ifndef SQLITE_AMALGAMATION
+    extern unsigned int sqlite3CoverageCounter;
+# endif
+# define testcase(X)  if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
 #else
 # define testcase(X)
 #endif
@@ -13814,6 +13601,14 @@ SQLITE_PRIVATE   void sqlite3Coverage(int);
 # define VVA_ONLY(X)
 #endif
 
+/*
+** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
+** and mutation testing
+*/
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
+# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS  1
+#endif
+
 /*
 ** The ALWAYS and NEVER macros surround boolean expressions which
 ** are intended to always be true or false, respectively.  Such
@@ -13829,7 +13624,7 @@ SQLITE_PRIVATE   void sqlite3Coverage(int);
 ** be true and false so that the unreachable code they specify will
 ** not be counted as untested code.
 */
-#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
+#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
 # define ALWAYS(X)      (1)
 # define NEVER(X)       (0)
 #elif !defined(NDEBUG)
@@ -13840,26 +13635,6 @@ SQLITE_PRIVATE   void sqlite3Coverage(int);
 # define NEVER(X)       (X)
 #endif
 
-/*
-** The harmless(X) macro indicates that expression X is usually false
-** but can be true without causing any problems, but we don't know of
-** any way to cause X to be true.
-**
-** In debugging and testing builds, this macro will abort if X is ever
-** true.  In this way, developers are alerted to a possible test case
-** that causes X to be true.  If a harmless macro ever fails, that is
-** an opportunity to change the macro into a testcase() and add a new
-** test case to the test suite.
-**
-** For normal production builds, harmless(X) is a no-op, since it does
-** not matter whether expression X is true or false.
-*/
-#ifdef SQLITE_DEBUG
-# define harmless(X)  assert(!(X));
-#else
-# define harmless(X)
-#endif
-
 /*
 ** Some conditionals are optimizations only.  In other words, if the
 ** conditionals are replaced with a constant 1 (true) or 0 (false) then
@@ -13923,6 +13698,13 @@ SQLITE_PRIVATE   void sqlite3Coverage(int);
 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
 #endif
 
+/*
+** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE
+*/
+#if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE)
+# define SQLITE_OMIT_ALTERTABLE
+#endif
+
 /*
 ** Return true (non-zero) if the input is an integer that is too large
 ** to fit in 32-bits.  This macro is used inside of various testcase()
@@ -14035,7 +13817,7 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 /*
 ** Number of entries in a hash table
 */
-/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
+#define sqliteHashCount(H)  ((H)->count)
 
 #endif /* SQLITE_HASH_H */
 
@@ -14067,8 +13849,8 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 #define TK_LP                              22
 #define TK_RP                              23
 #define TK_AS                              24
-#define TK_WITHOUT                         25
-#define TK_COMMA                           26
+#define TK_COMMA                           25
+#define TK_WITHOUT                         26
 #define TK_ABORT                           27
 #define TK_ACTION                          28
 #define TK_AFTER                           29
@@ -14154,77 +13936,79 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 #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
+#define TK_PTR                            112
+#define TK_COLLATE                        113
+#define TK_BITNOT                         114
+#define TK_ON                             115
+#define TK_INDEXED                        116
+#define TK_STRING                         117
+#define TK_JOIN_KW                        118
+#define TK_CONSTRAINT                     119
+#define TK_DEFAULT                        120
+#define TK_NULL                           121
+#define TK_PRIMARY                        122
+#define TK_UNIQUE                         123
+#define TK_CHECK                          124
+#define TK_REFERENCES                     125
+#define TK_AUTOINCR                       126
+#define TK_INSERT                         127
+#define TK_DELETE                         128
+#define TK_UPDATE                         129
+#define TK_SET                            130
+#define TK_DEFERRABLE                     131
+#define TK_FOREIGN                        132
+#define TK_DROP                           133
+#define TK_UNION                          134
+#define TK_ALL                            135
+#define TK_EXCEPT                         136
+#define TK_INTERSECT                      137
+#define TK_SELECT                         138
+#define TK_VALUES                         139
+#define TK_DISTINCT                       140
+#define TK_DOT                            141
+#define TK_FROM                           142
+#define TK_JOIN                           143
+#define TK_USING                          144
+#define TK_ORDER                          145
+#define TK_GROUP                          146
+#define TK_HAVING                         147
+#define TK_LIMIT                          148
+#define TK_WHERE                          149
+#define TK_RETURNING                      150
+#define TK_INTO                           151
+#define TK_NOTHING                        152
+#define TK_FLOAT                          153
+#define TK_BLOB                           154
+#define TK_INTEGER                        155
+#define TK_VARIABLE                       156
+#define TK_CASE                           157
+#define TK_WHEN                           158
+#define TK_THEN                           159
+#define TK_ELSE                           160
+#define TK_INDEX                          161
+#define TK_ALTER                          162
+#define TK_ADD                            163
+#define TK_WINDOW                         164
+#define TK_OVER                           165
+#define TK_FILTER                         166
+#define TK_COLUMN                         167
+#define TK_AGG_FUNCTION                   168
+#define TK_AGG_COLUMN                     169
+#define TK_TRUEFALSE                      170
+#define TK_ISNOT                          171
+#define TK_FUNCTION                       172
+#define TK_UMINUS                         173
+#define TK_UPLUS                          174
+#define TK_TRUTH                          175
+#define TK_REGISTER                       176
+#define TK_VECTOR                         177
+#define TK_SELECT_COLUMN                  178
+#define TK_IF_NULL_ROW                    179
+#define TK_ASTERISK                       180
+#define TK_SPAN                           181
+#define TK_ERROR                          182
+#define TK_SPACE                          183
+#define TK_ILLEGAL                        184
 
 /************** End of parse.h ***********************************************/
 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -14330,7 +14114,7 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 ** number of pages.  A negative number N translations means that a buffer
 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
 **
-** The default value of "20" was choosen to minimize the run-time of the
+** The default value of "20" was chosen to minimize the run-time of the
 ** speedtest1 test program with options: --shrink-memory --reprepare
 */
 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
@@ -14492,6 +14276,7 @@ typedef INT16_TYPE LogEst;
 #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
 # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
        defined(_M_ARM)   || defined(__arm__)    || defined(__x86)   ||    \
+      (defined(__APPLE__) && defined(__POWERPC__)) ||                     \
       (defined(__TOS_AIX__) && !defined(__64BIT__))
 #   define SQLITE_PTRSIZE 4
 # else
@@ -14686,11 +14471,25 @@ struct BusyHandler {
 
 /*
 ** Name of table that holds the database schema.
+**
+** The PREFERRED names are used whereever possible.  But LEGACY is also
+** used for backwards compatibility.
+**
+**  1.  Queries can use either the PREFERRED or the LEGACY names
+**  2.  The sqlite3_set_authorizer() callback uses the LEGACY name
+**  3.  The PRAGMA table_list statement uses the PREFERRED name
+**
+** The LEGACY names are stored in the internal symbol hash table
+** in support of (2).  Names are translated using sqlite3PreferredTableName()
+** for (3).  The sqlite3FindTable() function takes care of translating
+** names for (1).
+**
+** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema".
 */
-#define DFLT_SCHEMA_TABLE          "sqlite_master"
-#define DFLT_TEMP_SCHEMA_TABLE     "sqlite_temp_master"
-#define ALT_SCHEMA_TABLE           "sqlite_schema"
-#define ALT_TEMP_SCHEMA_TABLE      "sqlite_temp_schema"
+#define LEGACY_SCHEMA_TABLE          "sqlite_master"
+#define LEGACY_TEMP_SCHEMA_TABLE     "sqlite_temp_master"
+#define PREFERRED_SCHEMA_TABLE       "sqlite_schema"
+#define PREFERRED_TEMP_SCHEMA_TABLE  "sqlite_temp_schema"
 
 
 /*
@@ -14702,7 +14501,7 @@ struct BusyHandler {
 ** The name of the schema table.  The name is different for TEMP.
 */
 #define SCHEMA_TABLE(x) \
-    ((!OMIT_TEMPDB)&&(x==1)?DFLT_TEMP_SCHEMA_TABLE:DFLT_SCHEMA_TABLE)
+    ((!OMIT_TEMPDB)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE:LEGACY_SCHEMA_TABLE)
 
 /*
 ** A convenience macro that returns the number of elements in
@@ -14851,10 +14650,11 @@ typedef struct With With;
 /*
 ** A bit in a Bitmask
 */
-#define MASKBIT(n)   (((Bitmask)1)<<(n))
-#define MASKBIT64(n) (((u64)1)<<(n))
-#define MASKBIT32(n) (((unsigned int)1)<<(n))
-#define ALLBITS      ((Bitmask)-1)
+#define MASKBIT(n)    (((Bitmask)1)<<(n))
+#define MASKBIT64(n)  (((u64)1)<<(n))
+#define MASKBIT32(n)  (((unsigned int)1)<<(n))
+#define SMASKBIT32(n) ((n)<=31?((unsigned int)1)<<(n):0)
+#define ALLBITS       ((Bitmask)-1)
 
 /* A VList object records a mapping between parameters/variables/wildcards
 ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
@@ -15243,7 +15043,7 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
 
 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
-SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
+SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, i64*);
 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
 
@@ -15367,13 +15167,17 @@ SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
 #endif
 
 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
+SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
   BtCursor*,
-  UnpackedRecord *pUnKey,
   i64 intKey,
   int bias,
   int *pRes
 );
+SQLITE_PRIVATE int sqlite3BtreeIndexMoveto(
+  BtCursor*,
+  UnpackedRecord *pUnKey,
+  int *pRes
+);
 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
@@ -15724,35 +15528,35 @@ typedef struct VdbeOpList VdbeOpList;
 #define OP_If             18 /* jump                                       */
 #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
 #define OP_IfNot          20 /* jump                                       */
-#define OP_IfNullRow      21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
-#define OP_SeekLT         22 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_SeekLE         23 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_SeekGE         24 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_SeekGT         25 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IfNotOpen      26 /* jump, synopsis: if( !csr[P1] ) goto P2     */
-#define OP_IfNoHope       27 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_NoConflict     28 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_NotFound       29 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_Found          30 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_SeekRowid      31 /* jump, synopsis: intkey=r[P3]               */
-#define OP_NotExists      32 /* jump, synopsis: intkey=r[P3]               */
-#define OP_Last           33 /* jump                                       */
-#define OP_IfSmaller      34 /* jump                                       */
-#define OP_SorterSort     35 /* jump                                       */
-#define OP_Sort           36 /* jump                                       */
-#define OP_Rewind         37 /* jump                                       */
-#define OP_IdxLE          38 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IdxGT          39 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IdxLT          40 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IdxGE          41 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_RowSetRead     42 /* jump, synopsis: r[P3]=rowset(P1)           */
+#define OP_IsNullOrType   21 /* jump, synopsis: if typeof(r[P1]) IN (P3,5) goto P2 */
+#define OP_IfNullRow      22 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
+#define OP_SeekLT         23 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_SeekLE         24 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_SeekGE         25 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_SeekGT         26 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_IfNotOpen      27 /* jump, synopsis: if( !csr[P1] ) goto P2     */
+#define OP_IfNoHope       28 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_NoConflict     29 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_NotFound       30 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_Found          31 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_SeekRowid      32 /* jump, synopsis: intkey=r[P3]               */
+#define OP_NotExists      33 /* jump, synopsis: intkey=r[P3]               */
+#define OP_Last           34 /* jump                                       */
+#define OP_IfSmaller      35 /* jump                                       */
+#define OP_SorterSort     36 /* jump                                       */
+#define OP_Sort           37 /* jump                                       */
+#define OP_Rewind         38 /* jump                                       */
+#define OP_IdxLE          39 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_IdxGT          40 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_IdxLT          41 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_IdxGE          42 /* jump, synopsis: key=r[P3@P4]               */
 #define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
 #define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
-#define OP_RowSetTest     45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
-#define OP_Program        46 /* jump                                       */
-#define OP_FkIfZero       47 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
-#define OP_IfPos          48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
-#define OP_IfNotZero      49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
+#define OP_RowSetRead     45 /* jump, synopsis: r[P3]=rowset(P1)           */
+#define OP_RowSetTest     46 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
+#define OP_Program        47 /* jump                                       */
+#define OP_FkIfZero       48 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
+#define OP_IfPos          49 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
 #define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
 #define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
 #define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
@@ -15761,50 +15565,50 @@ typedef struct VdbeOpList VdbeOpList;
 #define OP_Le             55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
 #define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
 #define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
-#define OP_ElseNotEq      58 /* jump, same as TK_ESCAPE                    */
-#define OP_DecrJumpZero   59 /* jump, synopsis: if (--r[P1])==0 goto P2    */
-#define OP_IncrVacuum     60 /* jump                                       */
-#define OP_VNext          61 /* jump                                       */
-#define OP_Init           62 /* jump, synopsis: Start at P2                */
-#define OP_PureFunc       63 /* synopsis: r[P3]=func(r[P2@NP])             */
-#define OP_Function       64 /* synopsis: r[P3]=func(r[P2@NP])             */
-#define OP_Return         65
-#define OP_EndCoroutine   66
-#define OP_HaltIfNull     67 /* synopsis: if r[P3]=null halt               */
-#define OP_Halt           68
-#define OP_Integer        69 /* synopsis: r[P2]=P1                         */
-#define OP_Int64          70 /* synopsis: r[P2]=P4                         */
-#define OP_String         71 /* synopsis: r[P2]='P4' (len=P1)              */
-#define OP_Null           72 /* synopsis: r[P2..P3]=NULL                   */
-#define OP_SoftNull       73 /* synopsis: r[P1]=NULL                       */
-#define OP_Blob           74 /* synopsis: r[P2]=P4 (len=P1)                */
-#define OP_Variable       75 /* synopsis: r[P2]=parameter(P1,P4)           */
-#define OP_Move           76 /* synopsis: r[P2@P3]=r[P1@P3]                */
-#define OP_Copy           77 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
-#define OP_SCopy          78 /* synopsis: r[P2]=r[P1]                      */
-#define OP_IntCopy        79 /* synopsis: r[P2]=r[P1]                      */
-#define OP_ChngCntRow     80 /* synopsis: output=r[P1]                     */
-#define OP_ResultRow      81 /* synopsis: output=r[P1@P2]                  */
-#define OP_CollSeq        82
-#define OP_AddImm         83 /* synopsis: r[P1]=r[P1]+P2                   */
-#define OP_RealAffinity   84
-#define OP_Cast           85 /* synopsis: affinity(r[P1])                  */
-#define OP_Permutation    86
-#define OP_Compare        87 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
-#define OP_IsTrue         88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
-#define OP_Offset         89 /* synopsis: r[P3] = sqlite_offset(P1)        */
-#define OP_Column         90 /* synopsis: r[P3]=PX                         */
-#define OP_Affinity       91 /* synopsis: affinity(r[P1@P2])               */
-#define OP_MakeRecord     92 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
-#define OP_Count          93 /* synopsis: r[P2]=count()                    */
-#define OP_ReadCookie     94
-#define OP_SetCookie      95
-#define OP_ReopenIdx      96 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenRead       97 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenWrite      98 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenDup        99
-#define OP_OpenAutoindex 100 /* synopsis: nColumn=P2                       */
-#define OP_OpenEphemeral 101 /* synopsis: nColumn=P2                       */
+#define OP_ElseEq         58 /* jump, same as TK_ESCAPE                    */
+#define OP_IfNotZero      59 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
+#define OP_DecrJumpZero   60 /* jump, synopsis: if (--r[P1])==0 goto P2    */
+#define OP_IncrVacuum     61 /* jump                                       */
+#define OP_VNext          62 /* jump                                       */
+#define OP_Filter         63 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */
+#define OP_Init           64 /* jump, synopsis: Start at P2                */
+#define OP_PureFunc       65 /* synopsis: r[P3]=func(r[P2@NP])             */
+#define OP_Function       66 /* synopsis: r[P3]=func(r[P2@NP])             */
+#define OP_Return         67
+#define OP_EndCoroutine   68
+#define OP_HaltIfNull     69 /* synopsis: if r[P3]=null halt               */
+#define OP_Halt           70
+#define OP_Integer        71 /* synopsis: r[P2]=P1                         */
+#define OP_Int64          72 /* synopsis: r[P2]=P4                         */
+#define OP_String         73 /* synopsis: r[P2]='P4' (len=P1)              */
+#define OP_Null           74 /* synopsis: r[P2..P3]=NULL                   */
+#define OP_SoftNull       75 /* synopsis: r[P1]=NULL                       */
+#define OP_Blob           76 /* synopsis: r[P2]=P4 (len=P1)                */
+#define OP_Variable       77 /* synopsis: r[P2]=parameter(P1,P4)           */
+#define OP_Move           78 /* synopsis: r[P2@P3]=r[P1@P3]                */
+#define OP_Copy           79 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
+#define OP_SCopy          80 /* synopsis: r[P2]=r[P1]                      */
+#define OP_IntCopy        81 /* synopsis: r[P2]=r[P1]                      */
+#define OP_FkCheck        82
+#define OP_ResultRow      83 /* synopsis: output=r[P1@P2]                  */
+#define OP_CollSeq        84
+#define OP_AddImm         85 /* synopsis: r[P1]=r[P1]+P2                   */
+#define OP_RealAffinity   86
+#define OP_Cast           87 /* synopsis: affinity(r[P1])                  */
+#define OP_Permutation    88
+#define OP_Compare        89 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
+#define OP_IsTrue         90 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
+#define OP_ZeroOrNull     91 /* synopsis: r[P2] = 0 OR NULL                */
+#define OP_Offset         92 /* synopsis: r[P3] = sqlite_offset(P1)        */
+#define OP_Column         93 /* synopsis: r[P3]=PX                         */
+#define OP_TypeCheck      94 /* synopsis: typecheck(r[P1@P2])              */
+#define OP_Affinity       95 /* synopsis: affinity(r[P1@P2])               */
+#define OP_MakeRecord     96 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
+#define OP_Count          97 /* synopsis: r[P2]=count()                    */
+#define OP_ReadCookie     98
+#define OP_SetCookie      99
+#define OP_ReopenIdx     100 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenRead      101 /* synopsis: root=P2 iDb=P3                   */
 #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] */
@@ -15815,73 +15619,79 @@ typedef struct VdbeOpList VdbeOpList;
 #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
+#define OP_OpenWrite     112 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenDup       113
+#define OP_BitNot        114 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
+#define OP_OpenAutoindex 115 /* synopsis: nColumn=P2                       */
+#define OP_OpenEphemeral 116 /* synopsis: nColumn=P2                       */
+#define OP_String8       117 /* same as TK_STRING, synopsis: r[P2]='P4'    */
+#define OP_SorterOpen    118
+#define OP_SequenceTest  119 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
+#define OP_OpenPseudo    120 /* synopsis: P3 columns in r[P2]              */
+#define OP_Close         121
+#define OP_ColumnsUsed   122
+#define OP_SeekScan      123 /* synopsis: Scan-ahead up to P1 rows         */
+#define OP_SeekHit       124 /* synopsis: set P2<=seekHit<=P3              */
+#define OP_Sequence      125 /* synopsis: r[P2]=cursor[P1].ctr++           */
+#define OP_NewRowid      126 /* synopsis: r[P2]=rowid                      */
+#define OP_Insert        127 /* synopsis: intkey=r[P3] data=r[P2]          */
+#define OP_RowCell       128
+#define OP_Delete        129
+#define OP_ResetCount    130
+#define OP_SorterCompare 131 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
+#define OP_SorterData    132 /* synopsis: r[P2]=data                       */
+#define OP_RowData       133 /* synopsis: r[P2]=data                       */
+#define OP_Rowid         134 /* synopsis: r[P2]=rowid                      */
+#define OP_NullRow       135
+#define OP_SeekEnd       136
+#define OP_IdxInsert     137 /* synopsis: key=r[P2]                        */
+#define OP_SorterInsert  138 /* synopsis: key=r[P2]                        */
+#define OP_IdxDelete     139 /* synopsis: key=r[P2@P3]                     */
+#define OP_DeferredSeek  140 /* synopsis: Move P3 to P1.rowid if needed    */
+#define OP_IdxRowid      141 /* synopsis: r[P2]=rowid                      */
+#define OP_FinishSeek    142
+#define OP_Destroy       143
+#define OP_Clear         144
+#define OP_ResetSorter   145
+#define OP_CreateBtree   146 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
+#define OP_SqlExec       147
+#define OP_ParseSchema   148
+#define OP_LoadAnalysis  149
+#define OP_DropTable     150
+#define OP_DropIndex     151
+#define OP_DropTrigger   152
+#define OP_Real          153 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
+#define OP_IntegrityCk   154
+#define OP_RowSetAdd     155 /* synopsis: rowset(P1)=r[P2]                 */
+#define OP_Param         156
+#define OP_FkCounter     157 /* synopsis: fkctr[P1]+=P2                    */
+#define OP_MemMax        158 /* synopsis: r[P1]=max(r[P1],r[P2])           */
+#define OP_OffsetLimit   159 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
+#define OP_AggInverse    160 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
+#define OP_AggStep       161 /* synopsis: accum=r[P3] step(r[P2@P5])       */
+#define OP_AggStep1      162 /* synopsis: accum=r[P3] step(r[P2@P5])       */
+#define OP_AggValue      163 /* synopsis: r[P3]=value N=P2                 */
+#define OP_AggFinal      164 /* synopsis: accum=r[P1] N=P2                 */
+#define OP_Expire        165
+#define OP_CursorLock    166
+#define OP_CursorUnlock  167
+#define OP_TableLock     168 /* synopsis: iDb=P1 root=P2 write=P3          */
+#define OP_VBegin        169
+#define OP_VCreate       170
+#define OP_VDestroy      171
+#define OP_VOpen         172
+#define OP_VInitIn       173 /* synopsis: r[P2]=ValueList(P1,P3)           */
+#define OP_VColumn       174 /* synopsis: r[P3]=vcolumn(P2)                */
+#define OP_VRename       175
+#define OP_Pagecount     176
+#define OP_MaxPgcnt      177
+#define OP_FilterAdd     178 /* synopsis: filter(P1) += key(P3@P4)         */
+#define OP_Trace         179
+#define OP_CursorHint    180
+#define OP_ReleaseReg    181 /* synopsis: release r[P1@P2] mask P3         */
+#define OP_Noop          182
+#define OP_Explain       183
+#define OP_Abortable     184
 
 /* Properties such as "out2" or "jump" that are specified in
 ** comments following the "case" for each opcode in the vdbe.c
@@ -15896,35 +15706,36 @@ typedef struct VdbeOpList VdbeOpList;
 #define OPFLG_INITIALIZER {\
 /*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
 /*   8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
-/*  16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
-/*  24 */ 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09, 0x09,\
-/*  32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
-/*  40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
-/*  48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
-/*  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, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
-/*  88 */ 0x12, 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
-/*  96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26,\
+/*  16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x03, 0x01, 0x09,\
+/*  24 */ 0x09, 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09,\
+/*  32 */ 0x09, 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
+/*  40 */ 0x01, 0x01, 0x01, 0x26, 0x26, 0x23, 0x0b, 0x01,\
+/*  48 */ 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
+/*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x01, 0x01,\
+/*  64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\
+/*  72 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00,\
+/*  80 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02,\
+/*  88 */ 0x00, 0x00, 0x12, 0x1e, 0x20, 0x00, 0x00, 0x00,\
+/*  96 */ 0x00, 0x10, 0x10, 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,\
+/* 112 */ 0x00, 0x00, 0x12, 0x00, 0x00, 0x10, 0x00, 0x00,\
+/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
+/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,\
+/* 136 */ 0x00, 0x04, 0x04, 0x00, 0x00, 0x10, 0x00, 0x10,\
+/* 144 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 152 */ 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a,\
 /* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 168 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
-/* 176 */ 0x00, 0x00, 0x00,}
+/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,\
+/* 176 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 184 */ 0x00,}
 
-/* The sqlite3P2Values() routine is able to run faster if it knows
+/* The resolve3P2Values() routine is able to run faster if it knows
 ** the value of the largest JUMP opcode.  The smaller the maximum
 ** JUMP opcode the better, so the mkopcodeh.tcl script that
 ** generated this include file strives to group all JUMP opcodes
 ** together near the beginning of the list.
 */
-#define SQLITE_MX_JUMP_OPCODE  62  /* Maximum JUMP opcode */
+#define SQLITE_MX_JUMP_OPCODE  64  /* Maximum JUMP opcode */
 
 /************** End of opcodes.h *********************************************/
 /************** Continuing where we left off in vdbe.h ***********************/
@@ -16451,6 +16262,12 @@ SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 # define SET_FULLSYNC(x,y)
 #endif
 
+/* Maximum pathname length.  Note: FILENAME_MAX defined by stdio.h
+*/
+#ifndef SQLITE_MAX_PATHLEN
+# define SQLITE_MAX_PATHLEN FILENAME_MAX
+#endif
+
 /*
 ** The default size of a disk sector
 */
@@ -16979,6 +16796,7 @@ struct sqlite3 {
   u32 nSchemaLock;              /* Do not reset the schema when non-zero */
   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
   int errCode;                  /* Most recent error code (SQLITE_*) */
+  int errByteOffset;            /* Byte offset of error in SQL statement */
   int errMask;                  /* & result codes with this before returning */
   int iSysErrno;                /* Errno value from last system error */
   u32 dbOptFlags;               /* Flags to enable/disable optimizations */
@@ -16995,10 +16813,10 @@ struct sqlite3 {
   u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
   u8 noSharedCache;             /* True if no shared-cache backends */
   u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
+  u8 eOpenState;                /* Current condition of the connection */
   int nextPagesize;             /* Pagesize after VACUUM if >0 */
-  u32 magic;                    /* Magic number for detect library misuse */
-  int nChange;                  /* Value returned by sqlite3_changes() */
-  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
+  i64 nChange;                  /* Value returned by sqlite3_changes() */
+  i64 nTotalChange;             /* Value returned by sqlite3_total_changes() */
   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
   struct sqlite3InitInfo {      /* Information used during initialization */
@@ -17008,10 +16826,7 @@ struct sqlite3 {
     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 */
+    const char **azInit;        /* "type", "name", and "tbl_name" columns */
   } init;
   int nVdbeActive;              /* Number of VDBEs currently running */
   int nVdbeRead;                /* Number of active VDBEs that read or write */
@@ -17021,10 +16836,10 @@ struct sqlite3 {
   int nExtension;               /* Number of loaded extensions */
   void **aExtension;            /* Array of shared library handles */
   union {
-    void (*xLegacy)(void*,const char*);     /* Legacy trace function */
-    int (*xV2)(u32,void*,void*,void*);      /* V2 Trace function */
+    void (*xLegacy)(void*,const char*);   /* mTrace==SQLITE_TRACE_LEGACY */
+    int (*xV2)(u32,void*,void*,void*);    /* All other mTrace values */
   } trace;
-  void *pTraceArg;                          /* Argument to the trace function */
+  void *pTraceArg;                        /* Argument to the trace function */
 #ifndef SQLITE_OMIT_DEPRECATED
   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
   void *pProfileArg;                        /* Argument to profile function */
@@ -17035,6 +16850,9 @@ struct sqlite3 {
   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
   void *pUpdateArg;
   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
+  void *pAutovacPagesArg;           /* Client argument to autovac_pages */
+  void (*xAutovacDestr)(void*);     /* Destructor for pAutovacPAgesArg */
+  unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32);
   Parse *pParse;                /* Current parse */
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
@@ -17164,6 +16982,7 @@ struct sqlite3 {
 #define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */
                                           /*   DELETE, or UPDATE and return */
                                           /*   the count using a callback. */
+#define SQLITE_CorruptRdOnly  HI(0x00002) /* Prohibit writes due to error */
 
 /* Flags used only if debugging */
 #ifdef SQLITE_DEBUG
@@ -17209,7 +17028,12 @@ struct sqlite3 {
 #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_SeekScan       0x00020000 /* The OP_SeekScan optimization */
+#define SQLITE_OmitOrderBy    0x00040000 /* Omit pointless ORDER BY */
+   /* TH3 expects this value  ^^^^^^^^^^ to be 0x40000. Coordinate any change */
+#define SQLITE_BloomFilter    0x00080000 /* Use a Bloom filter on searches */
+#define SQLITE_BloomPulldown  0x00100000 /* Run Bloom filters early */
+#define SQLITE_BalancedMerge  0x00200000 /* Balance multi-way merges */
 #define SQLITE_AllOpts        0xffffffff /* All optimizations */
 
 /*
@@ -17224,17 +17048,16 @@ struct sqlite3 {
 */
 #define ConstFactorOk(P) ((P)->okConstFactor)
 
-/*
-** Possible values for the sqlite.magic field.
-** The numbers are obtained at random and have no special meaning, other
-** than being distinct from one another.
+/* Possible values for the sqlite3.eOpenState field.
+** The numbers are randomly selected such that a minimum of three bits must
+** change to convert any number to another or to zero
 */
-#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
-#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
-#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
-#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
-#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
-#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
+#define SQLITE_STATE_OPEN     0x76  /* Database is open */
+#define SQLITE_STATE_CLOSED   0xce  /* Database is closed */
+#define SQLITE_STATE_SICK     0xba  /* Error and awaiting close */
+#define SQLITE_STATE_BUSY     0x6d  /* Database currently in use */
+#define SQLITE_STATE_ERROR    0xd5  /* An SQLITE_MISUSE error occurred */
+#define SQLITE_STATE_ZOMBIE   0xa7  /* Close with last statement close */
 
 /*
 ** Each SQL function is defined by an instance of the following
@@ -17259,7 +17082,7 @@ struct FuncDef {
   union {
     FuncDef *pHash;      /* Next with a different name but the same hash */
     FuncDestructor *pDestructor;   /* Reference counted destructor function */
-  } u;
+  } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */
 };
 
 /*
@@ -17289,12 +17112,13 @@ struct FuncDestructor {
 ** are assert() statements in the code to verify this.
 **
 ** Value constraints (enforced via assert()):
-**     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
-**     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
-**     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
-**     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
-**     SQLITE_FUNC_DIRECT    ==  SQLITE_DIRECTONLY from the API
-**     SQLITE_FUNC_UNSAFE    ==  SQLITE_INNOCUOUS
+**     SQLITE_FUNC_MINMAX      ==  NC_MinMaxAgg      == SF_MinMaxAgg
+**     SQLITE_FUNC_ANYORDER    ==  NC_OrderAgg       == SF_OrderByReqd
+**     SQLITE_FUNC_LENGTH      ==  OPFLAG_LENGTHARG
+**     SQLITE_FUNC_TYPEOF      ==  OPFLAG_TYPEOFARG
+**     SQLITE_FUNC_CONSTANT    ==  SQLITE_DETERMINISTIC from the API
+**     SQLITE_FUNC_DIRECT      ==  SQLITE_DIRECTONLY from the API
+**     SQLITE_FUNC_UNSAFE      ==  SQLITE_INNOCUOUS
 **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
 */
 #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
@@ -17319,6 +17143,8 @@ struct FuncDestructor {
 #define SQLITE_FUNC_SUBTYPE  0x00100000 /* Result likely to have sub-type */
 #define SQLITE_FUNC_UNSAFE   0x00200000 /* Function has side effects */
 #define SQLITE_FUNC_INLINE   0x00400000 /* Functions implemented in-line */
+#define SQLITE_FUNC_BUILTIN  0x00800000 /* This is a built-in function */
+#define SQLITE_FUNC_ANYORDER 0x08000000 /* count/min/max aggregate */
 
 /* Identifier numbers for each in-line function */
 #define INLINEFUNC_coalesce             0
@@ -17381,7 +17207,7 @@ struct FuncDestructor {
 **     are interpreted in the same way as the first 4 parameters to
 **     FUNCTION().
 **
-**   WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
+**   WAGGREGATE(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
 **     Used to create an aggregate function definition implemented by
 **     the C functions xStep and xFinal. The first four parameters
 **     are interpreted in the same way as the first 4 parameters to
@@ -17396,44 +17222,55 @@ struct FuncDestructor {
 **     parameter.
 */
 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
-  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
+  {nArg, SQLITE_FUNC_BUILTIN|\
+   SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
-  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
+  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
 #define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
-  {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
+  {nArg, SQLITE_FUNC_BUILTIN|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, \
+  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
    xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
+#define JFUNCTION(zName, nArg, iArg, xFunc) \
+  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|\
+   SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
+   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
 #define INLINE_FUNC(zName, nArg, iArg, mFlags) \
-  {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
+  {nArg, SQLITE_FUNC_BUILTIN|\
+   SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
    SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
 #define TEST_FUNC(zName, nArg, iArg, mFlags) \
-  {nArg, SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
+  {nArg, SQLITE_FUNC_BUILTIN|\
+         SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
          SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
    SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
-  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
+  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
    0, 0, xFunc, 0, 0, 0, #zName, {0} }
 #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
-  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
+  {nArg, SQLITE_FUNC_BUILTIN|\
+         SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
    (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
-  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
+  {nArg, SQLITE_FUNC_BUILTIN|\
+   SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
-  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
+  {nArg, SQLITE_FUNC_BUILTIN|\
+   SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
    pArg, 0, xFunc, 0, 0, 0, #zName, }
 #define LIKEFUNC(zName, nArg, arg, flags) \
-  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
+  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
    (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
 #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
-  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
+  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
    SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
 #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
-  {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
+  {nArg, SQLITE_FUNC_BUILTIN|\
+   SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
    0, 0, xFunc, 0, 0, 0, #zName, {0} }
 
 
@@ -17489,18 +17326,42 @@ struct Module {
 **                            or equal to the table column index.  It is
 **                            equal if and only if there are no VIRTUAL
 **                            columns to the left.
+**
+** Notes on zCnName:
+** The zCnName field stores the name of the column, the datatype of the
+** column, and the collating sequence for the column, in that order, all in
+** a single allocation.  Each string is 0x00 terminated.  The datatype
+** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the
+** collating sequence name is only included if the COLFLAG_HASCOLL bit is
+** set.
 */
 struct Column {
-  char *zName;     /* Name of this column, \000, then the type */
-  Expr *pDflt;     /* Default value or GENERATED ALWAYS AS value */
-  char *zColl;     /* Collating sequence.  If NULL, use the default */
-  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
-  char affinity;   /* One of the SQLITE_AFF_... values */
-  u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
-  u8 hName;        /* Column name hash for faster lookup */
-  u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
+  char *zCnName;        /* Name of this column */
+  unsigned notNull :4;  /* An OE_ code for handling a NOT NULL constraint */
+  unsigned eCType :4;   /* One of the standard types */
+  char affinity;        /* One of the SQLITE_AFF_... values */
+  u8 szEst;             /* Est size of value in this column. sizeof(INT)==1 */
+  u8 hName;             /* Column name hash for faster lookup */
+  u16 iDflt;            /* 1-based index of DEFAULT.  0 means "none" */
+  u16 colFlags;         /* Boolean properties.  See COLFLAG_ defines below */
 };
 
+/* Allowed values for Column.eCType.
+**
+** Values must match entries in the global constant arrays
+** sqlite3StdTypeLen[] and sqlite3StdType[].  Each value is one more
+** than the offset into these arrays for the corresponding name.
+** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
+*/
+#define COLTYPE_CUSTOM      0   /* Type appended to zName */
+#define COLTYPE_ANY         1
+#define COLTYPE_BLOB        2
+#define COLTYPE_INT         3
+#define COLTYPE_INTEGER     4
+#define COLTYPE_REAL        5
+#define COLTYPE_TEXT        6
+#define SQLITE_N_STDTYPE    6  /* Number of standard types */
+
 /* Allowed values for Column.colFlags.
 **
 ** Constraints:
@@ -17517,6 +17378,7 @@ struct Column {
 #define COLFLAG_STORED    0x0040   /* GENERATED ALWAYS AS ... STORED */
 #define COLFLAG_NOTAVAIL  0x0080   /* STORED column not yet calculated */
 #define COLFLAG_BUSY      0x0100   /* Blocks recursion on GENERATED columns */
+#define COLFLAG_HASCOLL   0x0200   /* Has collating sequence name in zCnName */
 #define COLFLAG_GENERATED 0x0060   /* Combo: _STORED, _VIRTUAL */
 #define COLFLAG_NOINSERT  0x0062   /* Combo: _HIDDEN, _STORED, _VIRTUAL */
 
@@ -17582,9 +17444,7 @@ struct CollSeq {
 ** operator is NULL.  It is added to certain comparison operators to
 ** prove that the operands are always NOT NULL.
 */
-#define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */
 #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
-#define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
 #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
 
@@ -17648,15 +17508,13 @@ struct VTable {
 #define SQLITE_VTABRISK_High         2
 
 /*
-** The schema for each SQL table and view is represented in memory
-** by an instance of the following structure.
+** The schema for each SQL table, virtual table, and view is represented
+** in memory by an instance of the following structure.
 */
 struct Table {
   char *zName;         /* Name of the table or view */
   Column *aCol;        /* Information about each column */
   Index *pIndex;       /* List of SQL indexes on this table. */
-  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
-  FKey *pFKey;         /* Linked list of all foreign keys in this table */
   char *zColAff;       /* String defining the affinity of each column */
   ExprList *pCheck;    /* All CHECK constraints */
                        /*   ... also used as column name list in a VIEW */
@@ -17672,15 +17530,24 @@ struct Table {
   LogEst costMult;     /* Cost multiplier for using this table */
 #endif
   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
-#ifndef SQLITE_OMIT_ALTERTABLE
-  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
-#endif
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-  int nModuleArg;      /* Number of arguments to the module */
-  char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
-  VTable *pVTable;     /* List of VTable objects. */
-#endif
-  Trigger *pTrigger;   /* List of triggers stored in pSchema */
+  u8 eTabType;         /* 0: normal, 1: virtual, 2: view */
+  union {
+    struct {             /* Used by ordinary tables: */
+      int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
+      FKey *pFKey;         /* Linked list of all foreign keys in this table */
+      ExprList *pDfltList; /* DEFAULT clauses on various columns.
+                           ** Or the AS clause for generated columns. */
+    } tab;
+    struct {             /* Used by views: */
+      Select *pSelect;     /* View definition */
+    } view;
+    struct {             /* Used by virtual tables only: */
+      int nArg;            /* Number of arguments to the module */
+      char **azArg;        /* 0: module 1: schema 2: vtab name 3...: args */
+      VTable *p;           /* List of VTable objects. */
+    } vtab;
+  } u;
+  Trigger *pTrigger;   /* List of triggers on this object */
   Schema *pSchema;     /* Schema that contains this table */
 };
 
@@ -17699,23 +17566,35 @@ struct Table {
 **         TF_HasStored  == COLFLAG_STORED
 **         TF_HasHidden  == COLFLAG_HIDDEN
 */
-#define TF_Readonly        0x0001    /* Read-only system 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 */
-#define TF_HasVirtual      0x0020    /* Has one or more VIRTUAL columns */
-#define TF_HasStored       0x0040    /* Has one or more STORED columns */
-#define TF_HasGenerated    0x0060    /* Combo: HasVirtual + HasStored */
-#define TF_WithoutRowid    0x0080    /* No rowid.  PRIMARY KEY is the key */
-#define TF_StatsUsed       0x0100    /* Query planner decisions affected by
+#define TF_Readonly       0x00000001 /* Read-only system table */
+#define TF_HasHidden      0x00000002 /* Has one or more hidden columns */
+#define TF_HasPrimaryKey  0x00000004 /* Table has a primary key */
+#define TF_Autoincrement  0x00000008 /* Integer primary key is autoincrement */
+#define TF_HasStat1       0x00000010 /* nRowLogEst set from sqlite_stat1 */
+#define TF_HasVirtual     0x00000020 /* Has one or more VIRTUAL columns */
+#define TF_HasStored      0x00000040 /* Has one or more STORED columns */
+#define TF_HasGenerated   0x00000060 /* Combo: HasVirtual + HasStored */
+#define TF_WithoutRowid   0x00000080 /* No rowid.  PRIMARY KEY is the key */
+#define TF_StatsUsed      0x00000100 /* Query planner decisions affected by
                                      ** Index.aiRowLogEst[] values */
-#define TF_NoVisibleRowid  0x0200    /* No user-visible "rowid" column */
-#define TF_OOOHidden       0x0400    /* Out-of-Order hidden columns */
-#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 */
+#define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */
+#define TF_OOOHidden      0x00000400 /* Out-of-Order hidden columns */
+#define TF_HasNotNull     0x00000800 /* Contains NOT NULL constraints */
+#define TF_Shadow         0x00001000 /* True for a shadow table */
+#define TF_HasStat4       0x00002000 /* STAT4 info available for this table */
+#define TF_Ephemeral      0x00004000 /* An ephemeral table */
+#define TF_Eponymous      0x00008000 /* An eponymous virtual table */
+#define TF_Strict         0x00010000 /* STRICT mode */
+
+/*
+** Allowed values for Table.eTabType
+*/
+#define TABTYP_NORM      0     /* Ordinary table */
+#define TABTYP_VTAB      1     /* Virtual table */
+#define TABTYP_VIEW      2     /* A view */
+
+#define IsView(X)           ((X)->eTabType==TABTYP_VIEW)
+#define IsOrdinaryTable(X)  ((X)->eTabType==TABTYP_NORM)
 
 /*
 ** Test to see whether or not a table is a virtual table.  This is
@@ -17723,9 +17602,9 @@ struct Table {
 ** table support is omitted from the build.
 */
 #ifndef SQLITE_OMIT_VIRTUALTABLE
-#  define IsVirtual(X)      ((X)->nModuleArg)
+#  define IsVirtual(X)      ((X)->eTabType==TABTYP_VTAB)
 #  define ExprIsVtab(X)  \
-              ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->nModuleArg)
+    ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->eTabType==TABTYP_VTAB)
 #else
 #  define IsVirtual(X)      0
 #  define ExprIsVtab(X)     0
@@ -18081,6 +17960,7 @@ struct AggInfo {
     FuncDef *pFunc;          /* The aggregate function implementation */
     int iMem;                /* Memory location that acts as accumulator */
     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
+    int iDistAddr;           /* Address of OP_OpenEphemeral */
   } *aFunc;
   int nFunc;              /* Number of entries in aFunc[] */
   u32 selId;              /* Select to which this AggInfo belongs */
@@ -18113,10 +17993,10 @@ typedef int ynVar;
 ** tree.
 **
 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
-** or TK_STRING), then Expr.token contains the text of the SQL literal. If
-** the expression is a variable (TK_VARIABLE), then Expr.token contains the
+** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If
+** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the
 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
-** then Expr.token contains the name of the function.
+** then Expr.u.zToken contains the name of the function.
 **
 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
 ** binary operator. Either or both may be NULL.
@@ -18156,7 +18036,7 @@ typedef int ynVar;
 ** help reduce memory requirements, sometimes an Expr object will be
 ** truncated.  And to reduce the number of memory allocations, sometimes
 ** two or more Expr objects will be stored in a single memory allocation,
-** together with Expr.zToken strings.
+** together with Expr.u.zToken strings.
 **
 ** If the EP_Reduced and EP_TokenOnly flags are set when
 ** an Expr object is truncated.  When EP_Reduced is set, then all
@@ -18212,7 +18092,10 @@ struct Expr {
                          ** TK_VARIABLE: variable number (always >= 1).
                          ** TK_SELECT_COLUMN: column of the result vector */
   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
-  int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
+  union {
+    int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
+    int iOfst;             /* else: start of token from start of statement */
+  } w;
   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   union {
     Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL
@@ -18225,8 +18108,7 @@ struct Expr {
   } y;
 };
 
-/*
-** The following are the meanings of bits in the Expr.flags field.
+/* The following are the meanings of bits in the Expr.flags field.
 ** Value restrictions:
 **
 **          EP_Agg == NC_HasAgg == SF_HasAgg
@@ -18265,14 +18147,12 @@ struct Expr {
 #define EP_FromDDL  0x40000000 /* Originates from sqlite_schema */
                /*   0x80000000 // Available */
 
-/*
-** The EP_Propagate mask is a set of properties that automatically propagate
+/* The EP_Propagate mask is a set of properties that automatically propagate
 ** upwards into parent nodes.
 */
 #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
 
-/*
-** These macros can be used to test, set, or clear bits in the
+/* Macros can be used to test, set, or clear bits in the
 ** Expr.flags field.
 */
 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
@@ -18282,6 +18162,16 @@ struct Expr {
 #define ExprAlwaysTrue(E)   (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)
 #define ExprAlwaysFalse(E)  (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)
 
+/* Macros used to ensure that the correct members of unions are accessed
+** in Expr.
+*/
+#define ExprUseUToken(E)    (((E)->flags&EP_IntValue)==0)
+#define ExprUseUValue(E)    (((E)->flags&EP_IntValue)!=0)
+#define ExprUseXList(E)     (((E)->flags&EP_xIsSelect)==0)
+#define ExprUseXSelect(E)   (((E)->flags&EP_xIsSelect)!=0)
+#define ExprUseYTab(E)      (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)
+#define ExprUseYWin(E)      (((E)->flags&EP_WinFunc)!=0)
+#define ExprUseYSub(E)      (((E)->flags&EP_Subrtn)!=0)
 
 /* Flags for use with Expr.vvaFlags
 */
@@ -18353,6 +18243,7 @@ struct Expr {
 */
 struct ExprList {
   int nExpr;             /* Number of expressions on the list */
+  int nAlloc;            /* Number of a[] slots allocated */
   struct ExprList_item { /* For each expression in the list */
     Expr *pExpr;            /* The parse tree for this expression */
     char *zEName;           /* Token associated with this expression */
@@ -18363,11 +18254,12 @@ struct ExprList {
     unsigned bSorterRef :1; /* Defer evaluation until after sorting */
     unsigned bNulls: 1;     /* True if explicit "NULLS FIRST/LAST" */
     union {
-      struct {
+      struct {             /* Used by any ExprList other than Parse.pConsExpr */
         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
       } x;
-      int iConstExprReg;      /* Register in which Expr value is cached */
+      int iConstExprReg;   /* Register in which Expr value is cached. Used only
+                           ** by Parse.pConstExpr */
     } u;
   } a[1];                  /* One slot for each expression in the list */
 };
@@ -18405,6 +18297,13 @@ struct IdList {
 /*
 ** The SrcItem object represents a single term in the FROM clause of a query.
 ** The SrcList object is mostly an array of SrcItems.
+**
+** Union member validity:
+**
+**    u1.zIndexedBy          fg.isIndexedBy && !fg.isTabFunc
+**    u1.pFuncArg            fg.isTabFunc   && !fg.isIndexedBy
+**    u2.pIBIndex            fg.isIndexedBy && !fg.isCte
+**    u2.pCteUse             fg.isCte       && !fg.isIndexedBy
 */
 struct SrcItem {
   Schema *pSchema;  /* Schema to which this item is fixed */
@@ -18426,6 +18325,7 @@ struct SrcItem {
     unsigned isRecursive :1;   /* True for recursive reference in WITH */
     unsigned fromDDL :1;       /* Comes from sqlite_schema */
     unsigned isCte :1;         /* This is a CTE */
+    unsigned notCte :1;        /* This item may not match a CTE */
   } fg;
   int iCursor;      /* The VDBE cursor number used to access this table */
   Expr *pOn;        /* The ON clause of a join */
@@ -18497,7 +18397,7 @@ struct SrcList {
 #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
 #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
 #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
-                        /*     0x0400    not currently used */
+#define WHERE_AGG_DISTINCT     0x0400 /* Query is "SELECT agg(DISTINCT ...)" */
 #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
                         /*     0x1000    not currently used */
                         /*     0x2000    not currently used */
@@ -18543,7 +18443,7 @@ struct NameContext {
   } uNC;
   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   int nRef;            /* Number of names resolved by this context */
-  int nErr;            /* Number of errors encountered while resolving names */
+  int nNcErr;          /* Number of errors encountered while resolving names */
   int ncFlags;         /* Zero or more NC_* flags defined below */
   Select *pWinSelect;  /* SELECT statement for any window functions */
 };
@@ -18552,30 +18452,33 @@ struct NameContext {
 ** Allowed values for the NameContext, ncFlags field.
 **
 ** Value constraints (all checked via assert()):
-**    NC_HasAgg    == SF_HasAgg    == EP_Agg
-**    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
+**    NC_HasAgg    == SF_HasAgg       == EP_Agg
+**    NC_MinMaxAgg == SF_MinMaxAgg    == SQLITE_FUNC_MINMAX
+**    NC_OrderAgg  == SF_OrderByReqd  == SQLITE_FUNC_ANYORDER
 **    NC_HasWin    == EP_Win
 **
 */
-#define NC_AllowAgg  0x00001  /* Aggregate functions are allowed here */
-#define NC_PartIdx   0x00002  /* True if resolving a partial index WHERE */
-#define NC_IsCheck   0x00004  /* True if resolving a CHECK constraint */
-#define NC_GenCol    0x00008  /* True for a GENERATED ALWAYS AS clause */
-#define NC_HasAgg    0x00010  /* One or more aggregate functions seen */
-#define NC_IdxExpr   0x00020  /* True if resolving columns of CREATE INDEX */
-#define NC_SelfRef   0x0002e  /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
-#define NC_VarSelect 0x00040  /* A correlated subquery has been seen */
-#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 */
-#define NC_HasWin    0x08000  /* One or more window functions seen */
-#define NC_IsDDL     0x10000  /* Resolving names in a CREATE statement */
-#define NC_InAggFunc 0x20000  /* True if analyzing arguments to an agg func */
-#define NC_FromDDL   0x40000  /* SQL text comes from sqlite_schema */
+#define NC_AllowAgg  0x000001 /* Aggregate functions are allowed here */
+#define NC_PartIdx   0x000002 /* True if resolving a partial index WHERE */
+#define NC_IsCheck   0x000004 /* True if resolving a CHECK constraint */
+#define NC_GenCol    0x000008 /* True for a GENERATED ALWAYS AS clause */
+#define NC_HasAgg    0x000010 /* One or more aggregate functions seen */
+#define NC_IdxExpr   0x000020 /* True if resolving columns of CREATE INDEX */
+#define NC_SelfRef   0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
+#define NC_VarSelect 0x000040 /* A correlated subquery has been seen */
+#define NC_UEList    0x000080 /* True if uNC.pEList is used */
+#define NC_UAggInfo  0x000100 /* True if uNC.pAggInfo is used */
+#define NC_UUpsert   0x000200 /* True if uNC.pUpsert is used */
+#define NC_UBaseReg  0x000400 /* True if uNC.iBaseReg is used */
+#define NC_MinMaxAgg 0x001000 /* min/max aggregates seen.  See note above */
+#define NC_Complex   0x002000 /* True if a function or subquery seen */
+#define NC_AllowWin  0x004000 /* Window functions are allowed here */
+#define NC_HasWin    0x008000 /* One or more window functions seen */
+#define NC_IsDDL     0x010000 /* Resolving names in a CREATE statement */
+#define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
+#define NC_FromDDL   0x040000 /* SQL text comes from sqlite_schema */
+#define NC_NoSelect  0x080000 /* Do not descend into sub-selects */
+#define NC_OrderAgg 0x8000000 /* Has an aggregate other than count/min/max */
 
 /*
 ** An instance of the following object describes a single ON CONFLICT
@@ -18658,9 +18561,10 @@ struct Select {
 ** "Select Flag".
 **
 ** Value constraints (all checked via assert())
-**     SF_HasAgg     == NC_HasAgg
-**     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
-**     SF_FixedLimit == WHERE_USE_LIMIT
+**     SF_HasAgg      == NC_HasAgg
+**     SF_MinMaxAgg   == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
+**     SF_OrderByReqd == NC_OrderAgg      == SQLITE_FUNC_ANYORDER
+**     SF_FixedLimit  == WHERE_USE_LIMIT
 */
 #define SF_Distinct      0x0000001 /* Output should be DISTINCT */
 #define SF_All           0x0000002 /* Includes the ALL keyword */
@@ -18685,9 +18589,11 @@ struct Select {
 #define SF_WinRewrite    0x0100000 /* Window function rewrite accomplished */
 #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_UFSrcCheck    0x0800000 /* Check pSrc as required by UPDATE...FROM */
 #define SF_PushDown      0x1000000 /* SELECT has be modified by push-down opt */
 #define SF_MultiPart     0x2000000 /* Has multiple incompatible PARTITIONs */
+#define SF_CopyCte       0x4000000 /* SELECT statement is a copy of a CTE */
+#define SF_OrderByReqd   0x8000000 /* The ORDER BY clause may not be omitted */
 
 /*
 ** The results of a SELECT can be distributed in several ways, as defined
@@ -18929,7 +18835,8 @@ struct Parse {
   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
   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 */
+  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
+  ParseCleanup *pCleanup;   /* List of cleanup operations to run after parse */
   union {
     int addrCrTab;         /* Address of OP_CreateBtree on CREATE TABLE */
     Returning *pReturning; /* The RETURNING clause */
@@ -18950,6 +18857,7 @@ struct Parse {
   **************************************************************************/
 
   int aTempReg[8];        /* Holding area for temporary registers */
+  Parse *pOuterParse;     /* Outer Parse object when nested */
   Token sNameToken;       /* Token with unqualified schema object name */
 
   /************************************************************************
@@ -18984,14 +18892,14 @@ struct Parse {
   Token sArg;               /* Complete text of a module argument */
   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
 #endif
-  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
   With *pWith;              /* Current WITH clause, or NULL */
-  ParseCleanup *pCleanup;   /* List of cleanup operations to run after parse */
 #ifndef SQLITE_OMIT_ALTERTABLE
   RenameToken *pRename;     /* Tokens subject to renaming by ALTER TABLE */
 #endif
 };
 
+/* Allowed values for Parse.eParseMode
+*/
 #define PARSE_MODE_NORMAL        0
 #define PARSE_MODE_DECLARE_VTAB  1
 #define PARSE_MODE_RENAME        2
@@ -19000,7 +18908,8 @@ struct Parse {
 /*
 ** Sizes and pointers of various parts of the Parse object.
 */
-#define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
+#define PARSE_HDR(X)  (((char*)(X))+offsetof(Parse,zErrMsg))
+#define PARSE_HDR_SZ (offsetof(Parse,aTempReg)-offsetof(Parse,zErrMsg)) /* Recursive part w/o aColCache*/
 #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
 #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
@@ -19213,8 +19122,26 @@ typedef struct {
 /*
 ** Allowed values for mInitFlags
 */
+#define INITFLAG_AlterMask     0x0003  /* Types of ALTER */
 #define INITFLAG_AlterRename   0x0001  /* Reparse after a RENAME */
 #define INITFLAG_AlterDrop     0x0002  /* Reparse after a DROP COLUMN */
+#define INITFLAG_AlterAdd      0x0003  /* Reparse after an ADD COLUMN */
+
+/* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled
+** on debug-builds of the CLI using ".testctrl tune ID VALUE".  Tuning
+** parameters are for temporary use during development, to help find
+** optimial values for parameters in the query planner.  The should not
+** be used on trunk check-ins.  They are a temporary mechanism available
+** for transient development builds only.
+**
+** Tuning parameters are numbered starting with 1.
+*/
+#define SQLITE_NTUNE  6             /* Should be zero for all trunk check-ins */
+#ifdef SQLITE_DEBUG
+# define Tuning(X)  (sqlite3Config.aTune[(X)-1])
+#else
+# define Tuning(X)  0
+#endif
 
 /*
 ** Structure containing global configuration data for the SQLite library.
@@ -19270,16 +19197,21 @@ struct Sqlite3Config {
   void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx);  /* Callback */
   void *pVdbeBranchArg;                                     /* 1st argument */
 #endif
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
   sqlite3_int64 mxMemdbSize;        /* Default max memdb size */
 #endif
 #ifndef SQLITE_UNTESTABLE
   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
 #endif
   int bLocaltimeFault;              /* True to fail localtime() calls */
+  int (*xAltLocaltime)(const void*,void*); /* Alternative localtime() routine */
   int iOnceResetThreshold;          /* When to reset OP_Once counters */
   u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */
   unsigned int iPrngSeed;           /* Alternative fixed seed for the PRNG */
+  /* vvvv--- must be last ---vvv */
+#ifdef SQLITE_DEBUG
+  sqlite3_int64 aTune[SQLITE_NTUNE]; /* Tuning parameters */
+#endif
 };
 
 /*
@@ -19315,8 +19247,8 @@ struct Walker {
     int n;                                    /* A counter */
     int iCur;                                 /* A cursor number */
     SrcList *pSrcList;                        /* FROM clause */
-    struct SrcCount *pSrcCount;               /* Counting column references */
     struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
+    struct RefSrcList *pRefSrcList;           /* sqlite3ReferencesSrcList() */
     int *aiCol;                               /* array of column indexes */
     struct IdxCover *pIdxCover;               /* Check for index coverage */
     struct IdxExprTrans *pIdxTrans;           /* Convert idxed expr to column */
@@ -19357,11 +19289,18 @@ SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
 SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);
 SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);
+SQLITE_PRIVATE void sqlite3WalkWinDefnDummyCallback(Walker*,Select*);
 
 #ifdef SQLITE_DEBUG
 SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
 #endif
 
+#ifndef SQLITE_OMIT_CTE
+SQLITE_PRIVATE void sqlite3SelectPopWith(Walker*, Select*);
+#else
+# define sqlite3SelectPopWith 0
+#endif
+
 /*
 ** Return code from the parse-tree walking primitives and their
 ** callbacks.
@@ -19395,6 +19334,7 @@ struct Cte {
 */
 struct With {
   int nCte;               /* Number of CTEs in the WITH clause */
+  int bView;              /* Belongs to the outermost Select of a view */
   With *pOuter;           /* Containing WITH clause, or NULL */
   Cte a[1];               /* For each CTE in the WITH clause.... */
 };
@@ -19493,7 +19433,7 @@ SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
 SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
 SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
 SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);
-SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*, int);
+SQLITE_PRIVATE int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int);
 SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);
 SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
 SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
@@ -19625,8 +19565,8 @@ SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
 SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
-SQLITE_PRIVATE int sqlite3MallocSize(void*);
-SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
+SQLITE_PRIVATE int sqlite3MallocSize(const void*);
+SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, const void*);
 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
 SQLITE_PRIVATE void sqlite3PageFree(void*);
 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
@@ -19742,9 +19682,10 @@ SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
 SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
 SQLITE_PRIVATE void sqlite3Dequote(char*);
 SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
+SQLITE_PRIVATE void sqlite3DequoteToken(Token*);
 SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
-SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
+SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*);
 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
@@ -19761,16 +19702,17 @@ SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
 SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
 SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
-SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
-SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*);
+SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int);
+SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const 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*);
+SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
-SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
+SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
@@ -19786,7 +19728,12 @@ SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
+SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*);
+SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*);
+SQLITE_PRIVATE void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl);
+SQLITE_PRIVATE const char *sqlite3ColumnColl(Column*);
 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
+SQLITE_PRIVATE void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect);
 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*,char);
 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
@@ -19806,14 +19753,14 @@ SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
 #else
 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
 #endif
-SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
+SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token,Token);
 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
 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 sqlite3EndTable(Parse*,Token*,Token*,u32,Select*);
 SQLITE_PRIVATE void sqlite3AddReturning(Parse*,ExprList*);
 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
                     sqlite3_vfs**,char**,char **);
@@ -19899,10 +19846,12 @@ SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
 #endif
+SQLITE_PRIVATE void sqlite3CodeChangeCount(Vdbe*,int,const char*);
 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
                    Upsert*);
-SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
+SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,
+                             ExprList*,Select*,u16,int);
 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
@@ -19923,7 +19872,7 @@ SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int
 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
-SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Column*, int);
+SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int);
 #endif
 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
@@ -19942,23 +19891,24 @@ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
 #define LOCATE_VIEW    0x01
 #define LOCATE_NOERR   0x02
 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
+SQLITE_PRIVATE const char *sqlite3PreferredTableName(const char*);
 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*);
 SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
-SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
-SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
-SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
+SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, const Token*);
+SQLITE_PRIVATE int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*,Expr*,int);
+SQLITE_PRIVATE int sqlite3ExprListCompare(const ExprList*,const ExprList*, int);
+SQLITE_PRIVATE int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int);
 SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
 SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
-SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
+SQLITE_PRIVATE int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*);
 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
 #ifndef SQLITE_UNTESTABLE
 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
@@ -19980,10 +19930,11 @@ SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
 SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
+SQLITE_PRIVATE int sqlite3ExprIsTableConstraint(Expr*,const SrcItem*);
 #ifdef SQLITE_ENABLE_CURSOR_HINTS
 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
 #endif
-SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
+SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*);
 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
@@ -20008,20 +19959,26 @@ SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
-SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
-SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
-SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
-SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
-SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
+SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,const Expr*,int);
+SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int);
+SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int);
+SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,const IdList*);
+SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,const Select*,int);
 SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
+SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum*,sqlite3_value*);
 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
+SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void);
 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
+SQLITE_PRIVATE   int sqlite3JsonTableFunctions(sqlite3*);
+#endif
 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
+SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p);
 
 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
@@ -20107,14 +20064,8 @@ SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
-#ifndef SQLITE_OMIT_VIRTUALTABLE
 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
-#endif
-#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
-    defined(SQLITE_ENABLE_STAT4) || \
-    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
-#endif
 SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
 SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
 SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
@@ -20149,7 +20100,7 @@ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
 SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
 SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
-SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
+SQLITE_PRIVATE char sqlite3TableColumnAffinity(const Table*,int);
 SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);
 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
@@ -20165,7 +20116,7 @@ SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
 SQLITE_PRIVATE const char *sqlite3ErrName(int);
 #endif
 
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
 SQLITE_PRIVATE int sqlite3MemdbInit(void);
 #endif
 
@@ -20178,14 +20129,14 @@ SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);
 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
 SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
 SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
-SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
-SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
+SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int);
+SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*);
 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
 SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
-SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
+SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, i64);
 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
@@ -20210,12 +20161,19 @@ SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
 #ifndef SQLITE_OMIT_UTF16
 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
 #endif
-SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
+SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **);
 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
 #ifndef SQLITE_AMALGAMATION
 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
 SQLITE_PRIVATE const char sqlite3StrBINARY[];
+SQLITE_PRIVATE const unsigned char sqlite3StdTypeLen[];
+SQLITE_PRIVATE const char sqlite3StdTypeAffinity[];
+SQLITE_PRIVATE const char sqlite3StdTypeMap[];
+SQLITE_PRIVATE const char *sqlite3StdType[];
 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
+SQLITE_PRIVATE const unsigned char *sqlite3aLTb;
+SQLITE_PRIVATE const unsigned char *sqlite3aEQb;
+SQLITE_PRIVATE const unsigned char *sqlite3aGTb;
 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
@@ -20255,9 +20213,9 @@ SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const
 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 sqlite3AlterDropColumn(Parse*, SrcList*, const Token*);
+SQLITE_PRIVATE const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*);
+SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom);
 SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
 SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
@@ -20294,15 +20252,20 @@ SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   FuncDestructor *pDestructor
 );
 SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
-SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
+SQLITE_PRIVATE void *sqlite3OomFault(sqlite3*);
 SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
 
 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
+SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum*, int);
 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
+SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8);
+SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
+SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
+SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
 
 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
@@ -20353,7 +20316,7 @@ SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
 #endif
 
 #ifdef SQLITE_OMIT_VIRTUALTABLE
-#  define sqlite3VtabClear(Y)
+#  define sqlite3VtabClear(D,T)
 #  define sqlite3VtabSync(X,Y) SQLITE_OK
 #  define sqlite3VtabRollback(X)
 #  define sqlite3VtabCommit(X)
@@ -20390,9 +20353,11 @@ SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 SQLITE_PRIVATE   int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
 SQLITE_PRIVATE   int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
+SQLITE_PRIVATE   void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*);
 #else
 # define sqlite3ShadowTableName(A,B) 0
 # define sqlite3IsShadowTableOf(A,B,C) 0
+# define sqlite3MarkAllShadowTablesOf(A,B)
 #endif
 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
@@ -20405,11 +20370,17 @@ SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
+
 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
+#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
+    && !defined(SQLITE_OMIT_VIRTUALTABLE)
+SQLITE_PRIVATE   void sqlite3VtabWriteAll(sqlite3_index_info*);
+#endif
 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
-SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
+SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse*,sqlite3*);
+SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse*);
 SQLITE_PRIVATE void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*);
 #ifdef SQLITE_ENABLE_NORMALIZE
 SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
@@ -20429,13 +20400,13 @@ 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);
+SQLITE_PRIVATE   With *sqlite3WithPush(Parse*, With*, u8);
 #else
 # 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)
+# define sqlite3WithPush(x,y,z) ((void*)0)
 #endif
 #ifndef SQLITE_OMIT_UPSERT
 SQLITE_PRIVATE   Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*);
@@ -20468,6 +20439,7 @@ SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int
 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
+SQLITE_PRIVATE   void sqlite3FkClearTriggerCache(sqlite3*,int);
 #else
   #define sqlite3FkActions(a,b,c,d,e,f)
   #define sqlite3FkCheck(a,b,c,d,e,f)
@@ -20475,6 +20447,7 @@ SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
   #define sqlite3FkOldmask(a,b)         0
   #define sqlite3FkRequired(a,b,c,d)    0
   #define sqlite3FkReferences(a)        0
+  #define sqlite3FkClearTriggerCache(a,b)
 #endif
 #ifndef SQLITE_OMIT_FOREIGN_KEY
 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
@@ -20532,7 +20505,7 @@ SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
 
 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
 #if SQLITE_MAX_EXPR_DEPTH>0
-SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
+SQLITE_PRIVATE   int sqlite3SelectExprHeight(const Select *);
 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
 #else
   #define sqlite3SelectExprHeight(x) 0
@@ -20603,8 +20576,8 @@ SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
 */
 #ifdef SQLITE_MEMDEBUG
 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
-SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
-SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
+SQLITE_PRIVATE   int sqlite3MemdebugHasType(const void*,u8);
+SQLITE_PRIVATE   int sqlite3MemdebugNoType(const void*,u8);
 #else
 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
 # define sqlite3MemdebugHasType(X,Y)  1
@@ -20629,10 +20602,10 @@ SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
 #endif
 
-SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
-SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
+SQLITE_PRIVATE int sqlite3ExprVectorSize(const Expr *pExpr);
+SQLITE_PRIVATE int sqlite3ExprIsVector(const Expr *pExpr);
 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
-SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
+SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int);
 SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
 
 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
@@ -20642,6 +20615,993 @@ SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
 #endif /* SQLITEINT_H */
 
 /************** End of sqliteInt.h *******************************************/
+/************** Begin file os_common.h ***************************************/
+/*
+** 2004 May 22
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains macros and a little bit of code that is common to
+** all of the platform-specific files (os_*.c) and is #included into those
+** files.
+**
+** This file should be #included by the os_*.c files only.  It is not a
+** general purpose header file.
+*/
+#ifndef _OS_COMMON_H_
+#define _OS_COMMON_H_
+
+/*
+** At least two bugs have slipped in because we changed the MEMORY_DEBUG
+** macro to SQLITE_DEBUG and some older makefiles have not yet made the
+** switch.  The following code should catch this problem at compile-time.
+*/
+#ifdef MEMORY_DEBUG
+# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
+#endif
+
+/*
+** Macros for performance tracing.  Normally turned off.  Only works
+** on i486 hardware.
+*/
+#ifdef SQLITE_PERFORMANCE_TRACE
+
+/*
+** hwtime.h contains inline assembler code for implementing
+** high-performance timing routines.
+*/
+/************** Include hwtime.h in the middle of os_common.h ****************/
+/************** Begin file hwtime.h ******************************************/
+/*
+** 2008 May 27
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This file contains inline asm code for retrieving "high-performance"
+** counters for x86 and x86_64 class CPUs.
+*/
+#ifndef SQLITE_HWTIME_H
+#define SQLITE_HWTIME_H
+
+/*
+** The following routine only works on pentium-class (or newer) processors.
+** It uses the RDTSC opcode to read the cycle count value out of the
+** processor and returns that value.  This can be used for high-res
+** profiling.
+*/
+#if !defined(__STRICT_ANSI__) && \
+    (defined(__GNUC__) || defined(_MSC_VER)) && \
+    (defined(i386) || defined(__i386__) || defined(_M_IX86))
+
+  #if defined(__GNUC__)
+
+  __inline__ sqlite_uint64 sqlite3Hwtime(void){
+     unsigned int lo, hi;
+     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
+     return (sqlite_uint64)hi << 32 | lo;
+  }
+
+  #elif defined(_MSC_VER)
+
+  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
+     __asm {
+        rdtsc
+        ret       ; return value at EDX:EAX
+     }
+  }
+
+  #endif
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
+
+  __inline__ sqlite_uint64 sqlite3Hwtime(void){
+      unsigned long val;
+      __asm__ __volatile__ ("rdtsc" : "=A" (val));
+      return val;
+  }
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
+
+  __inline__ sqlite_uint64 sqlite3Hwtime(void){
+      unsigned long long retval;
+      unsigned long junk;
+      __asm__ __volatile__ ("\n\
+          1:      mftbu   %1\n\
+                  mftb    %L0\n\
+                  mftbu   %0\n\
+                  cmpw    %0,%1\n\
+                  bne     1b"
+                  : "=r" (retval), "=r" (junk));
+      return retval;
+  }
+
+#else
+
+  /*
+  ** asm() is needed for hardware timing support.  Without asm(),
+  ** disable the sqlite3Hwtime() routine.
+  **
+  ** sqlite3Hwtime() is only used for some obscure debugging
+  ** and analysis configurations, not in any deliverable, so this
+  ** should not be a great loss.
+  */
+SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
+
+#endif
+
+#endif /* !defined(SQLITE_HWTIME_H) */
+
+/************** End of hwtime.h **********************************************/
+/************** Continuing where we left off in os_common.h ******************/
+
+static sqlite_uint64 g_start;
+static sqlite_uint64 g_elapsed;
+#define TIMER_START       g_start=sqlite3Hwtime()
+#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
+#define TIMER_ELAPSED     g_elapsed
+#else
+#define TIMER_START
+#define TIMER_END
+#define TIMER_ELAPSED     ((sqlite_uint64)0)
+#endif
+
+/*
+** If we compile with the SQLITE_TEST macro set, then the following block
+** of code will give us the ability to simulate a disk I/O error.  This
+** is used for testing the I/O recovery logic.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_io_error_hit;
+SQLITE_API extern int sqlite3_io_error_hardhit;
+SQLITE_API extern int sqlite3_io_error_pending;
+SQLITE_API extern int sqlite3_io_error_persist;
+SQLITE_API extern int sqlite3_io_error_benign;
+SQLITE_API extern int sqlite3_diskfull_pending;
+SQLITE_API extern int sqlite3_diskfull;
+#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
+#define SimulateIOError(CODE)  \
+  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
+       || sqlite3_io_error_pending-- == 1 )  \
+              { local_ioerr(); CODE; }
+static void local_ioerr(){
+  IOTRACE(("IOERR\n"));
+  sqlite3_io_error_hit++;
+  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
+}
+#define SimulateDiskfullError(CODE) \
+   if( sqlite3_diskfull_pending ){ \
+     if( sqlite3_diskfull_pending == 1 ){ \
+       local_ioerr(); \
+       sqlite3_diskfull = 1; \
+       sqlite3_io_error_hit = 1; \
+       CODE; \
+     }else{ \
+       sqlite3_diskfull_pending--; \
+     } \
+   }
+#else
+#define SimulateIOErrorBenign(X)
+#define SimulateIOError(A)
+#define SimulateDiskfullError(A)
+#endif /* defined(SQLITE_TEST) */
+
+/*
+** When testing, keep a count of the number of open files.
+*/
+#if defined(SQLITE_TEST)
+SQLITE_API extern int sqlite3_open_file_count;
+#define OpenCounter(X)  sqlite3_open_file_count+=(X)
+#else
+#define OpenCounter(X)
+#endif /* defined(SQLITE_TEST) */
+
+#endif /* !defined(_OS_COMMON_H_) */
+
+/************** End of os_common.h *******************************************/
+/************** Begin file ctime.c *******************************************/
+/* DO NOT EDIT!
+** This file is automatically generated by the script in the canonical
+** SQLite source tree at tool/mkctimec.tcl.
+**
+** To modify this header, edit any of the various lists in that script
+** which specify categories of generated conditionals in this file.
+*/
+
+/*
+** 2010 February 23
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file implements routines used to report what compile-time options
+** SQLite was built with.
+*/
+#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
+
+/*
+** Include the configuration header output by 'configure' if we're using the
+** autoconf-based build
+*/
+#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
+/* #include "config.h" */
+#define SQLITECONFIG_H 1
+#endif
+
+/* These macros are provided to "stringify" the value of the define
+** for those options in which the value is meaningful. */
+#define CTIMEOPT_VAL_(opt) #opt
+#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
+
+/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
+** option requires a separate macro because legal values contain a single
+** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
+#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
+#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
+/* #include "sqliteInt.h" */
+
+/*
+** An array of names of all compile-time options.  This array should
+** be sorted A-Z.
+**
+** This array looks large, but in a typical installation actually uses
+** only a handful of compile-time options, so most times this array is usually
+** rather short and uses little memory space.
+*/
+static const char * const sqlite3azCompileOpt[] = {
+
+#ifdef SQLITE_32BIT_ROWID
+  "32BIT_ROWID",
+#endif
+#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
+  "4_BYTE_ALIGNED_MALLOC",
+#endif
+#ifdef SQLITE_64BIT_STATS
+  "64BIT_STATS",
+#endif
+#ifdef SQLITE_ALLOW_COVERING_INDEX_SCAN
+# if SQLITE_ALLOW_COVERING_INDEX_SCAN != 1
+  "ALLOW_COVERING_INDEX_SCAN=" CTIMEOPT_VAL(SQLITE_ALLOW_COVERING_INDEX_SCAN),
+# endif
+#endif
+#ifdef SQLITE_ALLOW_URI_AUTHORITY
+  "ALLOW_URI_AUTHORITY",
+#endif
+#ifdef SQLITE_ATOMIC_INTRINSICS
+  "ATOMIC_INTRINSICS=" CTIMEOPT_VAL(SQLITE_ATOMIC_INTRINSICS),
+#endif
+#ifdef SQLITE_BITMASK_TYPE
+  "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
+#endif
+#ifdef SQLITE_BUG_COMPATIBLE_20160819
+  "BUG_COMPATIBLE_20160819",
+#endif
+#ifdef SQLITE_CASE_SENSITIVE_LIKE
+  "CASE_SENSITIVE_LIKE",
+#endif
+#ifdef SQLITE_CHECK_PAGES
+  "CHECK_PAGES",
+#endif
+#if defined(__clang__) && defined(__clang_major__)
+  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
+                    CTIMEOPT_VAL(__clang_minor__) "."
+                    CTIMEOPT_VAL(__clang_patchlevel__),
+#elif defined(_MSC_VER)
+  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
+#elif defined(__GNUC__) && defined(__VERSION__)
+  "COMPILER=gcc-" __VERSION__,
+#endif
+#ifdef SQLITE_COVERAGE_TEST
+  "COVERAGE_TEST",
+#endif
+#ifdef SQLITE_DEBUG
+  "DEBUG",
+#endif
+#ifdef SQLITE_DEFAULT_AUTOMATIC_INDEX
+  "DEFAULT_AUTOMATIC_INDEX",
+#endif
+#ifdef SQLITE_DEFAULT_AUTOVACUUM
+  "DEFAULT_AUTOVACUUM",
+#endif
+#ifdef SQLITE_DEFAULT_CACHE_SIZE
+  "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
+#endif
+#ifdef SQLITE_DEFAULT_CKPTFULLFSYNC
+  "DEFAULT_CKPTFULLFSYNC",
+#endif
+#ifdef SQLITE_DEFAULT_FILE_FORMAT
+  "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
+#endif
+#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
+  "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
+#endif
+#ifdef SQLITE_DEFAULT_FOREIGN_KEYS
+  "DEFAULT_FOREIGN_KEYS",
+#endif
+#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
+  "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
+#endif
+#ifdef SQLITE_DEFAULT_LOCKING_MODE
+  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
+#endif
+#ifdef SQLITE_DEFAULT_LOOKASIDE
+  "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
+#endif
+#ifdef SQLITE_DEFAULT_MEMSTATUS
+# if SQLITE_DEFAULT_MEMSTATUS != 1
+  "DEFAULT_MEMSTATUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_MEMSTATUS),
+# endif
+#endif
+#ifdef SQLITE_DEFAULT_MMAP_SIZE
+  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
+#endif
+#ifdef SQLITE_DEFAULT_PAGE_SIZE
+  "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
+#endif
+#ifdef SQLITE_DEFAULT_PCACHE_INITSZ
+  "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
+#endif
+#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
+  "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
+#endif
+#ifdef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
+  "DEFAULT_RECURSIVE_TRIGGERS",
+#endif
+#ifdef SQLITE_DEFAULT_ROWEST
+  "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
+#endif
+#ifdef SQLITE_DEFAULT_SECTOR_SIZE
+  "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
+#endif
+#ifdef SQLITE_DEFAULT_SYNCHRONOUS
+  "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
+#endif
+#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
+  "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
+#endif
+#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
+  "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
+#endif
+#ifdef SQLITE_DEFAULT_WORKER_THREADS
+  "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
+#endif
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+  "DIRECT_OVERFLOW_READ",
+#endif
+#ifdef SQLITE_DISABLE_DIRSYNC
+  "DISABLE_DIRSYNC",
+#endif
+#ifdef SQLITE_DISABLE_FTS3_UNICODE
+  "DISABLE_FTS3_UNICODE",
+#endif
+#ifdef SQLITE_DISABLE_FTS4_DEFERRED
+  "DISABLE_FTS4_DEFERRED",
+#endif
+#ifdef SQLITE_DISABLE_INTRINSIC
+  "DISABLE_INTRINSIC",
+#endif
+#ifdef SQLITE_DISABLE_LFS
+  "DISABLE_LFS",
+#endif
+#ifdef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
+  "DISABLE_PAGECACHE_OVERFLOW_STATS",
+#endif
+#ifdef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
+  "DISABLE_SKIPAHEAD_DISTINCT",
+#endif
+#ifdef SQLITE_ENABLE_8_3_NAMES
+  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
+#endif
+#ifdef SQLITE_ENABLE_API_ARMOR
+  "ENABLE_API_ARMOR",
+#endif
+#ifdef SQLITE_ENABLE_ATOMIC_WRITE
+  "ENABLE_ATOMIC_WRITE",
+#endif
+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
+  "ENABLE_BATCH_ATOMIC_WRITE",
+#endif
+#ifdef SQLITE_ENABLE_BYTECODE_VTAB
+  "ENABLE_BYTECODE_VTAB",
+#endif
+#ifdef SQLITE_ENABLE_CEROD
+  "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
+#endif
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
+  "ENABLE_COLUMN_METADATA",
+#endif
+#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
+  "ENABLE_COLUMN_USED_MASK",
+#endif
+#ifdef SQLITE_ENABLE_COSTMULT
+  "ENABLE_COSTMULT",
+#endif
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
+  "ENABLE_CURSOR_HINTS",
+#endif
+#ifdef SQLITE_ENABLE_DBPAGE_VTAB
+  "ENABLE_DBPAGE_VTAB",
+#endif
+#ifdef SQLITE_ENABLE_DBSTAT_VTAB
+  "ENABLE_DBSTAT_VTAB",
+#endif
+#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
+  "ENABLE_EXPENSIVE_ASSERT",
+#endif
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+  "ENABLE_EXPLAIN_COMMENTS",
+#endif
+#ifdef SQLITE_ENABLE_FTS3
+  "ENABLE_FTS3",
+#endif
+#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
+  "ENABLE_FTS3_PARENTHESIS",
+#endif
+#ifdef SQLITE_ENABLE_FTS3_TOKENIZER
+  "ENABLE_FTS3_TOKENIZER",
+#endif
+#ifdef SQLITE_ENABLE_FTS4
+  "ENABLE_FTS4",
+#endif
+#ifdef SQLITE_ENABLE_FTS5
+  "ENABLE_FTS5",
+#endif
+#ifdef SQLITE_ENABLE_GEOPOLY
+  "ENABLE_GEOPOLY",
+#endif
+#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
+  "ENABLE_HIDDEN_COLUMNS",
+#endif
+#ifdef SQLITE_ENABLE_ICU
+  "ENABLE_ICU",
+#endif
+#ifdef SQLITE_ENABLE_IOTRACE
+  "ENABLE_IOTRACE",
+#endif
+#ifdef SQLITE_ENABLE_LOAD_EXTENSION
+  "ENABLE_LOAD_EXTENSION",
+#endif
+#ifdef SQLITE_ENABLE_LOCKING_STYLE
+  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
+#endif
+#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
+  "ENABLE_MATH_FUNCTIONS",
+#endif
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
+  "ENABLE_MEMORY_MANAGEMENT",
+#endif
+#ifdef SQLITE_ENABLE_MEMSYS3
+  "ENABLE_MEMSYS3",
+#endif
+#ifdef SQLITE_ENABLE_MEMSYS5
+  "ENABLE_MEMSYS5",
+#endif
+#ifdef SQLITE_ENABLE_MULTIPLEX
+  "ENABLE_MULTIPLEX",
+#endif
+#ifdef SQLITE_ENABLE_NORMALIZE
+  "ENABLE_NORMALIZE",
+#endif
+#ifdef SQLITE_ENABLE_NULL_TRIM
+  "ENABLE_NULL_TRIM",
+#endif
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+  "ENABLE_OFFSET_SQL_FUNC",
+#endif
+#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
+  "ENABLE_OVERSIZE_CELL_CHECK",
+#endif
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+  "ENABLE_PREUPDATE_HOOK",
+#endif
+#ifdef SQLITE_ENABLE_QPSG
+  "ENABLE_QPSG",
+#endif
+#ifdef SQLITE_ENABLE_RBU
+  "ENABLE_RBU",
+#endif
+#ifdef SQLITE_ENABLE_RTREE
+  "ENABLE_RTREE",
+#endif
+#ifdef SQLITE_ENABLE_SELECTTRACE
+  "ENABLE_SELECTTRACE",
+#endif
+#ifdef SQLITE_ENABLE_SESSION
+  "ENABLE_SESSION",
+#endif
+#ifdef SQLITE_ENABLE_SNAPSHOT
+  "ENABLE_SNAPSHOT",
+#endif
+#ifdef SQLITE_ENABLE_SORTER_REFERENCES
+  "ENABLE_SORTER_REFERENCES",
+#endif
+#ifdef SQLITE_ENABLE_SQLLOG
+  "ENABLE_SQLLOG",
+#endif
+#ifdef SQLITE_ENABLE_STAT4
+  "ENABLE_STAT4",
+#endif
+#ifdef SQLITE_ENABLE_STMTVTAB
+  "ENABLE_STMTVTAB",
+#endif
+#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
+  "ENABLE_STMT_SCANSTATUS",
+#endif
+#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+  "ENABLE_UNKNOWN_SQL_FUNCTION",
+#endif
+#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
+  "ENABLE_UNLOCK_NOTIFY",
+#endif
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+  "ENABLE_UPDATE_DELETE_LIMIT",
+#endif
+#ifdef SQLITE_ENABLE_URI_00_ERROR
+  "ENABLE_URI_00_ERROR",
+#endif
+#ifdef SQLITE_ENABLE_VFSTRACE
+  "ENABLE_VFSTRACE",
+#endif
+#ifdef SQLITE_ENABLE_WHERETRACE
+  "ENABLE_WHERETRACE",
+#endif
+#ifdef SQLITE_ENABLE_ZIPVFS
+  "ENABLE_ZIPVFS",
+#endif
+#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
+  "EXPLAIN_ESTIMATED_ROWS",
+#endif
+#ifdef SQLITE_EXTRA_IFNULLROW
+  "EXTRA_IFNULLROW",
+#endif
+#ifdef SQLITE_EXTRA_INIT
+  "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
+#endif
+#ifdef SQLITE_EXTRA_SHUTDOWN
+  "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
+#endif
+#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
+  "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
+#endif
+#ifdef SQLITE_FTS5_ENABLE_TEST_MI
+  "FTS5_ENABLE_TEST_MI",
+#endif
+#ifdef SQLITE_FTS5_NO_WITHOUT_ROWID
+  "FTS5_NO_WITHOUT_ROWID",
+#endif
+#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
+  "HAVE_ISNAN",
+#endif
+#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
+# if SQLITE_HOMEGROWN_RECURSIVE_MUTEX != 1
+  "HOMEGROWN_RECURSIVE_MUTEX=" CTIMEOPT_VAL(SQLITE_HOMEGROWN_RECURSIVE_MUTEX),
+# endif
+#endif
+#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
+  "IGNORE_AFP_LOCK_ERRORS",
+#endif
+#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
+  "IGNORE_FLOCK_LOCK_ERRORS",
+#endif
+#ifdef SQLITE_INLINE_MEMCPY
+  "INLINE_MEMCPY",
+#endif
+#ifdef SQLITE_INT64_TYPE
+  "INT64_TYPE",
+#endif
+#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
+  "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
+#endif
+#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
+  "LIKE_DOESNT_MATCH_BLOBS",
+#endif
+#ifdef SQLITE_LOCK_TRACE
+  "LOCK_TRACE",
+#endif
+#ifdef SQLITE_LOG_CACHE_SPILL
+  "LOG_CACHE_SPILL",
+#endif
+#ifdef SQLITE_MALLOC_SOFT_LIMIT
+  "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
+#endif
+#ifdef SQLITE_MAX_ATTACHED
+  "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
+#endif
+#ifdef SQLITE_MAX_COLUMN
+  "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
+#endif
+#ifdef SQLITE_MAX_COMPOUND_SELECT
+  "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
+#endif
+#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
+  "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
+#endif
+#ifdef SQLITE_MAX_EXPR_DEPTH
+  "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
+#endif
+#ifdef SQLITE_MAX_FUNCTION_ARG
+  "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
+#endif
+#ifdef SQLITE_MAX_LENGTH
+  "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
+#endif
+#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
+  "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
+#endif
+#ifdef SQLITE_MAX_MEMORY
+  "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
+#endif
+#ifdef SQLITE_MAX_MMAP_SIZE
+  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
+#endif
+#ifdef SQLITE_MAX_MMAP_SIZE_
+  "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
+#endif
+#ifdef SQLITE_MAX_PAGE_COUNT
+  "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
+#endif
+#ifdef SQLITE_MAX_PAGE_SIZE
+  "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
+#endif
+#ifdef SQLITE_MAX_SCHEMA_RETRY
+  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
+#endif
+#ifdef SQLITE_MAX_SQL_LENGTH
+  "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
+#endif
+#ifdef SQLITE_MAX_TRIGGER_DEPTH
+  "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
+#endif
+#ifdef SQLITE_MAX_VARIABLE_NUMBER
+  "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
+#endif
+#ifdef SQLITE_MAX_VDBE_OP
+  "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
+#endif
+#ifdef SQLITE_MAX_WORKER_THREADS
+  "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
+#endif
+#ifdef SQLITE_MEMDEBUG
+  "MEMDEBUG",
+#endif
+#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
+  "MIXED_ENDIAN_64BIT_FLOAT",
+#endif
+#ifdef SQLITE_MMAP_READWRITE
+  "MMAP_READWRITE",
+#endif
+#ifdef SQLITE_MUTEX_NOOP
+  "MUTEX_NOOP",
+#endif
+#ifdef SQLITE_MUTEX_OMIT
+  "MUTEX_OMIT",
+#endif
+#ifdef SQLITE_MUTEX_PTHREADS
+  "MUTEX_PTHREADS",
+#endif
+#ifdef SQLITE_MUTEX_W32
+  "MUTEX_W32",
+#endif
+#ifdef SQLITE_NEED_ERR_NAME
+  "NEED_ERR_NAME",
+#endif
+#ifdef SQLITE_NO_SYNC
+  "NO_SYNC",
+#endif
+#ifdef SQLITE_OMIT_ALTERTABLE
+  "OMIT_ALTERTABLE",
+#endif
+#ifdef SQLITE_OMIT_ANALYZE
+  "OMIT_ANALYZE",
+#endif
+#ifdef SQLITE_OMIT_ATTACH
+  "OMIT_ATTACH",
+#endif
+#ifdef SQLITE_OMIT_AUTHORIZATION
+  "OMIT_AUTHORIZATION",
+#endif
+#ifdef SQLITE_OMIT_AUTOINCREMENT
+  "OMIT_AUTOINCREMENT",
+#endif
+#ifdef SQLITE_OMIT_AUTOINIT
+  "OMIT_AUTOINIT",
+#endif
+#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
+  "OMIT_AUTOMATIC_INDEX",
+#endif
+#ifdef SQLITE_OMIT_AUTORESET
+  "OMIT_AUTORESET",
+#endif
+#ifdef SQLITE_OMIT_AUTOVACUUM
+  "OMIT_AUTOVACUUM",
+#endif
+#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
+  "OMIT_BETWEEN_OPTIMIZATION",
+#endif
+#ifdef SQLITE_OMIT_BLOB_LITERAL
+  "OMIT_BLOB_LITERAL",
+#endif
+#ifdef SQLITE_OMIT_CAST
+  "OMIT_CAST",
+#endif
+#ifdef SQLITE_OMIT_CHECK
+  "OMIT_CHECK",
+#endif
+#ifdef SQLITE_OMIT_COMPLETE
+  "OMIT_COMPLETE",
+#endif
+#ifdef SQLITE_OMIT_COMPOUND_SELECT
+  "OMIT_COMPOUND_SELECT",
+#endif
+#ifdef SQLITE_OMIT_CONFLICT_CLAUSE
+  "OMIT_CONFLICT_CLAUSE",
+#endif
+#ifdef SQLITE_OMIT_CTE
+  "OMIT_CTE",
+#endif
+#if defined(SQLITE_OMIT_DATETIME_FUNCS) || defined(SQLITE_OMIT_FLOATING_POINT)
+  "OMIT_DATETIME_FUNCS",
+#endif
+#ifdef SQLITE_OMIT_DECLTYPE
+  "OMIT_DECLTYPE",
+#endif
+#ifdef SQLITE_OMIT_DEPRECATED
+  "OMIT_DEPRECATED",
+#endif
+#ifdef SQLITE_OMIT_DESERIALIZE
+  "OMIT_DESERIALIZE",
+#endif
+#ifdef SQLITE_OMIT_DISKIO
+  "OMIT_DISKIO",
+#endif
+#ifdef SQLITE_OMIT_EXPLAIN
+  "OMIT_EXPLAIN",
+#endif
+#ifdef SQLITE_OMIT_FLAG_PRAGMAS
+  "OMIT_FLAG_PRAGMAS",
+#endif
+#ifdef SQLITE_OMIT_FLOATING_POINT
+  "OMIT_FLOATING_POINT",
+#endif
+#ifdef SQLITE_OMIT_FOREIGN_KEY
+  "OMIT_FOREIGN_KEY",
+#endif
+#ifdef SQLITE_OMIT_GET_TABLE
+  "OMIT_GET_TABLE",
+#endif
+#ifdef SQLITE_OMIT_HEX_INTEGER
+  "OMIT_HEX_INTEGER",
+#endif
+#ifdef SQLITE_OMIT_INCRBLOB
+  "OMIT_INCRBLOB",
+#endif
+#ifdef SQLITE_OMIT_INTEGRITY_CHECK
+  "OMIT_INTEGRITY_CHECK",
+#endif
+#ifdef SQLITE_OMIT_INTROSPECTION_PRAGMAS
+  "OMIT_INTROSPECTION_PRAGMAS",
+#endif
+#ifdef SQLITE_OMIT_JSON
+  "OMIT_JSON",
+#endif
+#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
+  "OMIT_LIKE_OPTIMIZATION",
+#endif
+#ifdef SQLITE_OMIT_LOAD_EXTENSION
+  "OMIT_LOAD_EXTENSION",
+#endif
+#ifdef SQLITE_OMIT_LOCALTIME
+  "OMIT_LOCALTIME",
+#endif
+#ifdef SQLITE_OMIT_LOOKASIDE
+  "OMIT_LOOKASIDE",
+#endif
+#ifdef SQLITE_OMIT_MEMORYDB
+  "OMIT_MEMORYDB",
+#endif
+#ifdef SQLITE_OMIT_OR_OPTIMIZATION
+  "OMIT_OR_OPTIMIZATION",
+#endif
+#ifdef SQLITE_OMIT_PAGER_PRAGMAS
+  "OMIT_PAGER_PRAGMAS",
+#endif
+#ifdef SQLITE_OMIT_PARSER_TRACE
+  "OMIT_PARSER_TRACE",
+#endif
+#ifdef SQLITE_OMIT_POPEN
+  "OMIT_POPEN",
+#endif
+#ifdef SQLITE_OMIT_PRAGMA
+  "OMIT_PRAGMA",
+#endif
+#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
+  "OMIT_PROGRESS_CALLBACK",
+#endif
+#ifdef SQLITE_OMIT_QUICKBALANCE
+  "OMIT_QUICKBALANCE",
+#endif
+#ifdef SQLITE_OMIT_REINDEX
+  "OMIT_REINDEX",
+#endif
+#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
+  "OMIT_SCHEMA_PRAGMAS",
+#endif
+#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
+  "OMIT_SCHEMA_VERSION_PRAGMAS",
+#endif
+#ifdef SQLITE_OMIT_SHARED_CACHE
+  "OMIT_SHARED_CACHE",
+#endif
+#ifdef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
+  "OMIT_SHUTDOWN_DIRECTORIES",
+#endif
+#ifdef SQLITE_OMIT_SUBQUERY
+  "OMIT_SUBQUERY",
+#endif
+#ifdef SQLITE_OMIT_TCL_VARIABLE
+  "OMIT_TCL_VARIABLE",
+#endif
+#ifdef SQLITE_OMIT_TEMPDB
+  "OMIT_TEMPDB",
+#endif
+#ifdef SQLITE_OMIT_TEST_CONTROL
+  "OMIT_TEST_CONTROL",
+#endif
+#ifdef SQLITE_OMIT_TRACE
+# if SQLITE_OMIT_TRACE != 1
+  "OMIT_TRACE=" CTIMEOPT_VAL(SQLITE_OMIT_TRACE),
+# endif
+#endif
+#ifdef SQLITE_OMIT_TRIGGER
+  "OMIT_TRIGGER",
+#endif
+#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
+  "OMIT_TRUNCATE_OPTIMIZATION",
+#endif
+#ifdef SQLITE_OMIT_UTF16
+  "OMIT_UTF16",
+#endif
+#ifdef SQLITE_OMIT_VACUUM
+  "OMIT_VACUUM",
+#endif
+#ifdef SQLITE_OMIT_VIEW
+  "OMIT_VIEW",
+#endif
+#ifdef SQLITE_OMIT_VIRTUALTABLE
+  "OMIT_VIRTUALTABLE",
+#endif
+#ifdef SQLITE_OMIT_WAL
+  "OMIT_WAL",
+#endif
+#ifdef SQLITE_OMIT_WSD
+  "OMIT_WSD",
+#endif
+#ifdef SQLITE_OMIT_XFER_OPT
+  "OMIT_XFER_OPT",
+#endif
+#ifdef SQLITE_PCACHE_SEPARATE_HEADER
+  "PCACHE_SEPARATE_HEADER",
+#endif
+#ifdef SQLITE_PERFORMANCE_TRACE
+  "PERFORMANCE_TRACE",
+#endif
+#ifdef SQLITE_POWERSAFE_OVERWRITE
+# if SQLITE_POWERSAFE_OVERWRITE != 1
+  "POWERSAFE_OVERWRITE=" CTIMEOPT_VAL(SQLITE_POWERSAFE_OVERWRITE),
+# endif
+#endif
+#ifdef SQLITE_PREFER_PROXY_LOCKING
+  "PREFER_PROXY_LOCKING",
+#endif
+#ifdef SQLITE_PROXY_DEBUG
+  "PROXY_DEBUG",
+#endif
+#ifdef SQLITE_REVERSE_UNORDERED_SELECTS
+  "REVERSE_UNORDERED_SELECTS",
+#endif
+#ifdef SQLITE_RTREE_INT_ONLY
+  "RTREE_INT_ONLY",
+#endif
+#ifdef SQLITE_SECURE_DELETE
+  "SECURE_DELETE",
+#endif
+#ifdef SQLITE_SMALL_STACK
+  "SMALL_STACK",
+#endif
+#ifdef SQLITE_SORTER_PMASZ
+  "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
+#endif
+#ifdef SQLITE_SOUNDEX
+  "SOUNDEX",
+#endif
+#ifdef SQLITE_STAT4_SAMPLES
+  "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
+#endif
+#ifdef SQLITE_STMTJRNL_SPILL
+  "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
+#endif
+#ifdef SQLITE_SUBSTR_COMPATIBILITY
+  "SUBSTR_COMPATIBILITY",
+#endif
+#if (!defined(SQLITE_WIN32_MALLOC) \
+     && !defined(SQLITE_ZERO_MALLOC) \
+     && !defined(SQLITE_MEMDEBUG) \
+    ) || defined(SQLITE_SYSTEM_MALLOC)
+  "SYSTEM_MALLOC",
+#endif
+#ifdef SQLITE_TCL
+  "TCL",
+#endif
+#ifdef SQLITE_TEMP_STORE
+  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
+#endif
+#ifdef SQLITE_TEST
+  "TEST",
+#endif
+#if defined(SQLITE_THREADSAFE)
+  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
+#elif defined(THREADSAFE)
+  "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
+#else
+  "THREADSAFE=1",
+#endif
+#ifdef SQLITE_UNLINK_AFTER_CLOSE
+  "UNLINK_AFTER_CLOSE",
+#endif
+#ifdef SQLITE_UNTESTABLE
+  "UNTESTABLE",
+#endif
+#ifdef SQLITE_USER_AUTHENTICATION
+  "USER_AUTHENTICATION",
+#endif
+#ifdef SQLITE_USE_ALLOCA
+  "USE_ALLOCA",
+#endif
+#ifdef SQLITE_USE_FCNTL_TRACE
+  "USE_FCNTL_TRACE",
+#endif
+#ifdef SQLITE_USE_URI
+  "USE_URI",
+#endif
+#ifdef SQLITE_VDBE_COVERAGE
+  "VDBE_COVERAGE",
+#endif
+#ifdef SQLITE_WIN32_MALLOC
+  "WIN32_MALLOC",
+#endif
+#ifdef SQLITE_ZERO_MALLOC
+  "ZERO_MALLOC",
+#endif
+
+} ;
+
+SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
+  *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
+  return (const char**)sqlite3azCompileOpt;
+}
+
+#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
+
+/************** End of ctime.c ***********************************************/
 /************** Begin file global.c ******************************************/
 /*
 ** 2008 June 13
@@ -20682,7 +21642,7 @@ SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
-    252,253,254,255
+    252,253,254,255,
 #endif
 #ifdef SQLITE_EBCDIC
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
@@ -20702,7 +21662,35 @@ SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
     224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
     240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
 #endif
+/* All of the upper-to-lower conversion data is above.  The following
+** 18 integers are completely unrelated.  They are appended to the
+** sqlite3UpperToLower[] array to avoid UBSAN warnings.  Here's what is
+** going on:
+**
+** The SQL comparison operators (<>, =, >, <=, <, and >=) are implemented
+** by invoking sqlite3MemCompare(A,B) which compares values A and B and
+** returns negative, zero, or positive if A is less then, equal to, or
+** greater than B, respectively.  Then the true false results is found by
+** consulting sqlite3aLTb[opcode], sqlite3aEQb[opcode], or
+** sqlite3aGTb[opcode] depending on whether the result of compare(A,B)
+** is negative, zero, or positive, where opcode is the specific opcode.
+** The only works because the comparison opcodes are consecutive and in
+** this order: NE EQ GT LE LT GE.  Various assert()s throughout the code
+** ensure that is the case.
+**
+** These elements must be appended to another array.  Otherwise the
+** index (here shown as [256-OP_Ne]) would be out-of-bounds and thus
+** be undefined behavior.  That's goofy, but the C-standards people thought
+** it was a good idea, so here we are.
+*/
+/* NE  EQ  GT  LE  LT  GE  */
+   1,  0,  0,  1,  1,  0,  /* aLTb[]: Use when compare(A,B) less than zero */
+   0,  1,  0,  1,  0,  1,  /* aEQb[]: Use when compare(A,B) equals zero */
+   1,  0,  1,  0,  0,  1   /* aGTb[]: Use when compare(A,B) greater than zero*/
 };
+SQLITE_PRIVATE const unsigned char *sqlite3aLTb = &sqlite3UpperToLower[256-OP_Ne];
+SQLITE_PRIVATE const unsigned char *sqlite3aEQb = &sqlite3UpperToLower[256+6-OP_Ne];
+SQLITE_PRIVATE const unsigned char *sqlite3aGTb = &sqlite3UpperToLower[256+12-OP_Ne];
 
 /*
 ** The following 256 byte lookup table is used to support SQLites built-in
@@ -20896,13 +21884,14 @@ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
    0,                         /* xVdbeBranch */
    0,                         /* pVbeBranchArg */
 #endif
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
    SQLITE_MEMDB_DEFAULT_MAXSIZE,   /* mxMemdbSize */
 #endif
 #ifndef SQLITE_UNTESTABLE
    0,                         /* xTestCallback */
 #endif
    0,                         /* bLocaltimeFault */
+   0,                         /* xAltLocaltime */
    0x7ffffffe,                /* iOnceResetThreshold */
    SQLITE_DEFAULT_SORTERREF_SIZE,   /* szSorterRef */
    0,                         /* iPrngSeed */
@@ -20915,6 +21904,18 @@ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
 */
 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
+/*
+** Counter used for coverage testing.  Does not come into play for
+** release builds.
+**
+** Access to this global variable is not mutex protected.  This might
+** result in TSAN warnings.  But as the variable does not exist in
+** release builds, that should not be a concern.
+*/
+SQLITE_PRIVATE unsigned int sqlite3CoverageCounter;
+#endif /* SQLITE_COVERAGE_TEST || SQLITE_DEBUG */
+
 #ifdef VDBE_PROFILE
 /*
 ** The following performance counter can be used in place of
@@ -20965,6 +21966,48 @@ SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
 */
 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
 
+/*
+** Standard typenames.  These names must match the COLTYPE_* definitions.
+** Adjust the SQLITE_N_STDTYPE value if adding or removing entries.
+**
+**    sqlite3StdType[]            The actual names of the datatypes.
+**
+**    sqlite3StdTypeLen[]         The length (in bytes) of each entry
+**                                in sqlite3StdType[].
+**
+**    sqlite3StdTypeAffinity[]    The affinity associated with each entry
+**                                in sqlite3StdType[].
+**
+**    sqlite3StdTypeMap[]         The type value (as returned from
+**                                sqlite3_column_type() or sqlite3_value_type())
+**                                for each entry in sqlite3StdType[].
+*/
+SQLITE_PRIVATE const unsigned char sqlite3StdTypeLen[] = { 3, 4, 3, 7, 4, 4 };
+SQLITE_PRIVATE const char sqlite3StdTypeAffinity[] = {
+  SQLITE_AFF_NUMERIC,
+  SQLITE_AFF_BLOB,
+  SQLITE_AFF_INTEGER,
+  SQLITE_AFF_INTEGER,
+  SQLITE_AFF_REAL,
+  SQLITE_AFF_TEXT
+};
+SQLITE_PRIVATE const char sqlite3StdTypeMap[] = {
+  0,
+  SQLITE_BLOB,
+  SQLITE_INTEGER,
+  SQLITE_INTEGER,
+  SQLITE_FLOAT,
+  SQLITE_TEXT
+};
+SQLITE_PRIVATE const char *sqlite3StdType[] = {
+  "ANY",
+  "BLOB",
+  "INT",
+  "INTEGER",
+  "REAL",
+  "TEXT"
+};
+
 /************** End of global.c **********************************************/
 /************** Begin file status.c ******************************************/
 /*
@@ -21062,7 +22105,7 @@ typedef struct AuxData AuxData;
 typedef struct VdbeCursor VdbeCursor;
 struct VdbeCursor {
   u8 eCurType;            /* One of the CURTYPE_* values above */
-  i8 iDb;                 /* Index of cursor database in db->aDb[] (or -1) */
+  i8 iDb;                 /* Index of cursor database in db->aDb[] */
   u8 nullRow;             /* True if pointing to a row with no data */
   u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */
   u8 isTable;             /* True for rowid tables.  False for indexes */
@@ -21075,9 +22118,11 @@ struct VdbeCursor {
   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 */
+  union {                 /* pBtx for isEphermeral.  pAltMap otherwise */
+    Btree *pBtx;            /* Separate file holding temporary table */
+    u32 *aAltMap;           /* Mapping from table to index column numbers */
+  } ub;
   i64 seqCount;           /* Sequence counter */
-  u32 *aAltMap;           /* Mapping from table to index column numbers */
 
   /* Cached OP_Column parse information is only valid if cacheStatus matches
   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
@@ -21167,8 +22212,8 @@ struct VdbeFrame {
   int nMem;               /* Number of entries in aMem */
   int nChildMem;          /* Number of memory cells for child frame */
   int nChildCsr;          /* Number of cursors for child frame */
-  int nChange;            /* Statement changes (Vdbe.nChange)     */
-  int nDbChange;          /* Value of db->nChange */
+  i64 nChange;            /* Statement changes (Vdbe.nChange)     */
+  i64 nDbChange;          /* Value of db->nChange */
 };
 
 /* Magic number for sanity checking on VdbeFrame objects */
@@ -21375,7 +22420,7 @@ struct Vdbe {
   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
   int pc;                 /* The program counter */
   int rc;                 /* Value to return */
-  int nChange;            /* Number of db changes made since last reset */
+  i64 nChange;            /* Number of db changes made since last reset */
   int iStatement;         /* Statement number (or 0 if has no opened stmt) */
   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
@@ -21417,7 +22462,7 @@ struct Vdbe {
   bft bIsReader:1;        /* True for statements that read */
   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
-  u32 aCounter[7];        /* Counters used by sqlite3_stmt_status() */
+  u32 aCounter[9];        /* Counters used by sqlite3_stmt_status() */
   char *zSql;             /* Text of the SQL statement that generated this */
 #ifdef SQLITE_ENABLE_NORMALIZE
   char *zNormSql;         /* Normalization of the associated SQL statement */
@@ -21459,6 +22504,7 @@ struct PreUpdate {
   UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
   UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
   int iNewReg;                    /* Register for new.* values */
+  int iBlobWrite;                 /* Value returned by preupdate_blobwrite() */
   i64 iKey1;                      /* First key value passed to hook */
   i64 iKey2;                      /* Second key value passed to hook */
   Mem *aNew;                      /* Array of new.* values */
@@ -21466,6 +22512,24 @@ struct PreUpdate {
   Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
 };
 
+/*
+** An instance of this object is used to pass an vector of values into
+** OP_VFilter, the xFilter method of a virtual table.  The vector is the
+** set of values on the right-hand side of an IN constraint.
+**
+** The value as passed into xFilter is an sqlite3_value with a "pointer"
+** type, such as is generated by sqlite3_result_pointer() and read by
+** sqlite3_value_pointer.  Such values have MEM_Term|MEM_Subtype|MEM_Null
+** and a subtype of 'p'.  The sqlite3_vtab_in_first() and _next() interfaces
+** know how to use this object to step through all the values in the
+** right operand of the IN constraint.
+*/
+typedef struct ValueList ValueList;
+struct ValueList {
+  BtCursor *pCsr;          /* An ephemeral table holding all values */
+  sqlite3_value *pOut;     /* Register to hold each decoded output value */
+};
+
 /*
 ** Function prototypes
 */
@@ -21478,7 +22542,7 @@ SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
-SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
+SQLITE_PRIVATE void sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
 
 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
@@ -21502,7 +22566,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
+SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, i64, u8, void(*)(void*));
 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
 #ifdef SQLITE_OMIT_FLOATING_POINT
 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
@@ -21512,14 +22576,19 @@ SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
 SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
+#ifndef SQLITE_OMIT_INCRBLOB
 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
+#else
+SQLITE_PRIVATE int sqlite3VdbeMemSetZeroBlob(Mem*,int);
+#endif
 #ifdef SQLITE_DEBUG
 SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
 #endif
 SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
-SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
+SQLITE_PRIVATE int sqlite3IntFloatCompare(i64,double);
+SQLITE_PRIVATE i64 sqlite3VdbeIntValue(const Mem*);
 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
 SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
@@ -21547,7 +22616,8 @@ SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*);      /* Destructor on Mem */
 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
-SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
+SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
+    Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int,int);
 #endif
 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
 
@@ -22496,8 +23566,10 @@ static void clearYMD_HMS_TZ(DateTime *p){
 ** is available.  This routine returns 0 on success and
 ** non-zero on any kind of error.
 **
-** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
-** routine will always fail.
+** If the sqlite3GlobalConfig.bLocaltimeFault variable is non-zero then this
+** routine will always fail.  If bLocaltimeFault is nonzero and
+** sqlite3GlobalConfig.xAltLocaltime is not NULL, then xAltLocaltime() is
+** invoked in place of the OS-defined localtime() function.
 **
 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
 ** library function localtime_r() is used to assist in the calculation of
@@ -22513,14 +23585,30 @@ static int osLocaltime(time_t *t, struct tm *pTm){
   sqlite3_mutex_enter(mutex);
   pX = localtime(t);
 #ifndef SQLITE_UNTESTABLE
-  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
+  if( sqlite3GlobalConfig.bLocaltimeFault ){
+    if( sqlite3GlobalConfig.xAltLocaltime!=0
+     && 0==sqlite3GlobalConfig.xAltLocaltime((const void*)t,(void*)pTm)
+    ){
+      pX = pTm;
+    }else{
+      pX = 0;
+    }
+  }
 #endif
   if( pX ) *pTm = *pX;
+#if SQLITE_THREADSAFE>0
   sqlite3_mutex_leave(mutex);
+#endif
   rc = pX==0;
 #else
 #ifndef SQLITE_UNTESTABLE
-  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
+  if( sqlite3GlobalConfig.bLocaltimeFault ){
+    if( sqlite3GlobalConfig.xAltLocaltime!=0 ){
+      return sqlite3GlobalConfig.xAltLocaltime((const void*)t,(void*)pTm);
+    }else{
+      return 1;
+    }
+  }
 #endif
 #if HAVE_LOCALTIME_R
   rc = localtime_r(t, pTm)==0;
@@ -22535,67 +23623,56 @@ static int osLocaltime(time_t *t, struct tm *pTm){
 
 #ifndef SQLITE_OMIT_LOCALTIME
 /*
-** Compute the difference (in milliseconds) between localtime and UTC
-** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
-** return this value and set *pRc to SQLITE_OK.
-**
-** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
-** is undefined in this case.
+** Assuming the input DateTime is UTC, move it to its localtime equivalent.
 */
-static sqlite3_int64 localtimeOffset(
-  DateTime *p,                    /* Date at which to calculate offset */
-  sqlite3_context *pCtx,          /* Write error here if one occurs */
-  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
+static int toLocaltime(
+  DateTime *p,                   /* Date at which to calculate offset */
+  sqlite3_context *pCtx          /* Write error here if one occurs */
 ){
-  DateTime x, y;
   time_t t;
   struct tm sLocal;
+  int iYearDiff;
 
   /* Initialize the contents of sLocal to avoid a compiler warning. */
   memset(&sLocal, 0, sizeof(sLocal));
 
-  x = *p;
-  computeYMD_HMS(&x);
-  if( x.Y<1971 || x.Y>=2038 ){
+  computeJD(p);
+  if( p->iJD<2108667600*(i64)100000 /* 1970-01-01 */
+   || p->iJD>2130141456*(i64)100000 /* 2038-01-18 */
+  ){
     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
     ** works for years between 1970 and 2037. For dates outside this range,
     ** SQLite attempts to map the year into an equivalent year within this
     ** range, do the calculation, then map the year back.
     */
-    x.Y = 2000;
-    x.M = 1;
-    x.D = 1;
-    x.h = 0;
-    x.m = 0;
-    x.s = 0.0;
-  } else {
-    int s = (int)(x.s + 0.5);
-    x.s = s;
+    DateTime x = *p;
+    computeYMD_HMS(&x);
+    iYearDiff = (2000 + x.Y%4) - x.Y;
+    x.Y += iYearDiff;
+    x.validJD = 0;
+    computeJD(&x);
+    t = (time_t)(x.iJD/1000 -  21086676*(i64)10000);
+  }else{
+    iYearDiff = 0;
+    t = (time_t)(p->iJD/1000 -  21086676*(i64)10000);
   }
-  x.tz = 0;
-  x.validJD = 0;
-  computeJD(&x);
-  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
   if( osLocaltime(&t, &sLocal) ){
     sqlite3_result_error(pCtx, "local time unavailable", -1);
-    *pRc = SQLITE_ERROR;
-    return 0;
+    return SQLITE_ERROR;
   }
-  y.Y = sLocal.tm_year + 1900;
-  y.M = sLocal.tm_mon + 1;
-  y.D = sLocal.tm_mday;
-  y.h = sLocal.tm_hour;
-  y.m = sLocal.tm_min;
-  y.s = sLocal.tm_sec;
-  y.validYMD = 1;
-  y.validHMS = 1;
-  y.validJD = 0;
-  y.rawS = 0;
-  y.validTZ = 0;
-  y.isError = 0;
-  computeJD(&y);
-  *pRc = SQLITE_OK;
-  return y.iJD - x.iJD;
+  p->Y = sLocal.tm_year + 1900 - iYearDiff;
+  p->M = sLocal.tm_mon + 1;
+  p->D = sLocal.tm_mday;
+  p->h = sLocal.tm_hour;
+  p->m = sLocal.tm_min;
+  p->s = sLocal.tm_sec + (p->iJD%1000)*0.001;
+  p->validYMD = 1;
+  p->validHMS = 1;
+  p->validJD = 0;
+  p->rawS = 0;
+  p->validTZ = 0;
+  p->isError = 0;
+  return SQLITE_OK;
 }
 #endif /* SQLITE_OMIT_LOCALTIME */
 
@@ -22608,18 +23685,17 @@ static sqlite3_int64 localtimeOffset(
 ** of several units of time.
 */
 static const struct {
-  u8 eType;           /* Transformation type code */
-  u8 nName;           /* Length of th name */
-  char *zName;        /* Name of the transformation */
-  double rLimit;      /* Maximum NNN value for this transform */
-  double rXform;      /* Constant used for this transform */
+  u8 nName;           /* Length of the name */
+  char zName[7];      /* Name of the transformation */
+  float rLimit;       /* Maximum NNN value for this transform */
+  float rXform;       /* Constant used for this transform */
 } aXformType[] = {
-  { 0, 6, "second", 464269060800.0, 1000.0         },
-  { 0, 6, "minute", 7737817680.0,   60000.0        },
-  { 0, 4, "hour",   128963628.0,    3600000.0      },
-  { 0, 3, "day",    5373485.0,      86400000.0     },
-  { 1, 5, "month",  176546.0,       2592000000.0   },
-  { 2, 4, "year",   14713.0,        31536000000.0  },
+  { 6, "second", 4.6427e+14,       1.0  },
+  { 6, "minute", 7.7379e+12,      60.0  },
+  { 4, "hour",   1.2897e+11,    3600.0  },
+  { 3, "day",    5373485.0,    86400.0  },
+  { 5, "month",  176546.0,   2592000.0  },
+  { 4, "year",   14713.0,   31536000.0  },
 };
 
 /*
@@ -22650,11 +23726,55 @@ static int parseModifier(
   sqlite3_context *pCtx,      /* Function context */
   const char *z,              /* The text of the modifier */
   int n,                      /* Length of zMod in bytes */
-  DateTime *p                 /* The date/time value to be modified */
+  DateTime *p,                /* The date/time value to be modified */
+  int idx                     /* Parameter index of the modifier */
 ){
   int rc = 1;
   double r;
   switch(sqlite3UpperToLower[(u8)z[0]] ){
+    case 'a': {
+      /*
+      **    auto
+      **
+      ** If rawS is available, then interpret as a julian day number, or
+      ** a unix timestamp, depending on its magnitude.
+      */
+      if( sqlite3_stricmp(z, "auto")==0 ){
+        if( idx>1 ) return 1; /* IMP: R-33611-57934 */
+        if( !p->rawS || p->validJD ){
+          rc = 0;
+          p->rawS = 0;
+        }else if( p->s>=-21086676*(i64)10000        /* -4713-11-24 12:00:00 */
+               && p->s<=(25340230*(i64)10000)+799   /*  9999-12-31 23:59:59 */
+        ){
+          r = p->s*1000.0 + 210866760000000.0;
+          clearYMD_HMS_TZ(p);
+          p->iJD = (sqlite3_int64)(r + 0.5);
+          p->validJD = 1;
+          p->rawS = 0;
+          rc = 0;
+        }
+      }
+      break;
+    }
+    case 'j': {
+      /*
+      **    julianday
+      **
+      ** Always interpret the prior number as a julian-day value.  If this
+      ** is not the first modifier, or if the prior argument is not a numeric
+      ** value in the allowed range of julian day numbers understood by
+      ** SQLite (0..5373484.5) then the result will be NULL.
+      */
+      if( sqlite3_stricmp(z, "julianday")==0 ){
+        if( idx>1 ) return 1;  /* IMP: R-31176-64601 */
+        if( p->validJD && p->rawS ){
+          rc = 0;
+          p->rawS = 0;
+        }
+      }
+      break;
+    }
 #ifndef SQLITE_OMIT_LOCALTIME
     case 'l': {
       /*    localtime
@@ -22663,9 +23783,7 @@ static int parseModifier(
       ** show local time.
       */
       if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
-        computeJD(p);
-        p->iJD += localtimeOffset(p, pCtx, &rc);
-        clearYMD_HMS_TZ(p);
+        rc = toLocaltime(p, pCtx);
       }
       break;
     }
@@ -22678,6 +23796,7 @@ static int parseModifier(
       ** seconds since 1970.  Convert to a real julian day number.
       */
       if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
+        if( idx>1 ) return 1;  /* IMP: R-49255-55373 */
         r = p->s*1000.0 + 210866760000000.0;
         if( r>=0.0 && r<464269060800000.0 ){
           clearYMD_HMS_TZ(p);
@@ -22690,18 +23809,31 @@ static int parseModifier(
 #ifndef SQLITE_OMIT_LOCALTIME
       else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
         if( p->tzSet==0 ){
-          sqlite3_int64 c1;
+          i64 iOrigJD;              /* Original localtime */
+          i64 iGuess;               /* Guess at the corresponding utc time */
+          int cnt = 0;              /* Safety to prevent infinite loop */
+          int iErr;                 /* Guess is off by this much */
+
           computeJD(p);
-          c1 = localtimeOffset(p, pCtx, &rc);
-          if( rc==SQLITE_OK ){
-            p->iJD -= c1;
-            clearYMD_HMS_TZ(p);
-            p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
-          }
+          iGuess = iOrigJD = p->iJD;
+          iErr = 0;
+          do{
+            DateTime new;
+            memset(&new, 0, sizeof(new));
+            iGuess -= iErr;
+            new.iJD = iGuess;
+            new.validJD = 1;
+            rc = toLocaltime(&new, pCtx);
+            if( rc ) return rc;
+            computeJD(&new);
+            iErr = new.iJD - iOrigJD;
+          }while( iErr && cnt++<3 );
+          memset(p, 0, sizeof(*p));
+          p->iJD = iGuess;
+          p->validJD = 1;
           p->tzSet = 1;
-        }else{
-          rc = SQLITE_OK;
         }
+        rc = SQLITE_OK;
       }
 #endif
       break;
@@ -22817,9 +23949,10 @@ static int parseModifier(
          && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
          && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
         ){
-          switch( aXformType[i].eType ){
-            case 1: { /* Special processing to add months */
+          switch( i ){
+            case 4: { /* Special processing to add months */
               int x;
+              assert( strcmp(aXformType[i].zName,"month")==0 );
               computeYMD_HMS(p);
               p->M += (int)r;
               x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
@@ -22829,8 +23962,9 @@ static int parseModifier(
               r -= (int)r;
               break;
             }
-            case 2: { /* Special processing to add years */
+            case 5: { /* Special processing to add years */
               int y = (int)r;
+              assert( strcmp(aXformType[i].zName,"year")==0 );
               computeYMD_HMS(p);
               p->Y += y;
               p->validJD = 0;
@@ -22839,7 +23973,7 @@ static int parseModifier(
             }
           }
           computeJD(p);
-          p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
+          p->iJD += (sqlite3_int64)(r*1000.0*aXformType[i].rXform + rRounder);
           rc = 0;
           break;
         }
@@ -22889,7 +24023,7 @@ static int isDate(
   for(i=1; i<argc; i++){
     z = sqlite3_value_text(argv[i]);
     n = sqlite3_value_bytes(argv[i]);
-    if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
+    if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
   }
   computeJD(p);
   if( p->isError || !validJulianDay(p->iJD) ) return 1;
@@ -22919,6 +24053,24 @@ static void juliandayFunc(
   }
 }
 
+/*
+**    unixepoch( TIMESTRING, MOD, MOD, ...)
+**
+** Return the number of seconds (including fractional seconds) since
+** the unix epoch of 1970-01-01 00:00:00 GMT.
+*/
+static void unixepochFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  DateTime x;
+  if( isDate(context, argc, argv, &x)==0 ){
+    computeJD(&x);
+    sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000);
+  }
+}
+
 /*
 **    datetime( TIMESTRING, MOD, MOD, ...)
 **
@@ -22931,11 +24083,38 @@ static void datetimeFunc(
 ){
   DateTime x;
   if( isDate(context, argc, argv, &x)==0 ){
-    char zBuf[100];
+    int Y, s;
+    char zBuf[24];
     computeYMD_HMS(&x);
-    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
-                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
-    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+    Y = x.Y;
+    if( Y<0 ) Y = -Y;
+    zBuf[1] = '0' + (Y/1000)%10;
+    zBuf[2] = '0' + (Y/100)%10;
+    zBuf[3] = '0' + (Y/10)%10;
+    zBuf[4] = '0' + (Y)%10;
+    zBuf[5] = '-';
+    zBuf[6] = '0' + (x.M/10)%10;
+    zBuf[7] = '0' + (x.M)%10;
+    zBuf[8] = '-';
+    zBuf[9] = '0' + (x.D/10)%10;
+    zBuf[10] = '0' + (x.D)%10;
+    zBuf[11] = ' ';
+    zBuf[12] = '0' + (x.h/10)%10;
+    zBuf[13] = '0' + (x.h)%10;
+    zBuf[14] = ':';
+    zBuf[15] = '0' + (x.m/10)%10;
+    zBuf[16] = '0' + (x.m)%10;
+    zBuf[17] = ':';
+    s = (int)x.s;
+    zBuf[18] = '0' + (s/10)%10;
+    zBuf[19] = '0' + (s)%10;
+    zBuf[20] = 0;
+    if( x.Y<0 ){
+      zBuf[0] = '-';
+      sqlite3_result_text(context, zBuf, 20, SQLITE_TRANSIENT);
+    }else{
+      sqlite3_result_text(context, &zBuf[1], 19, SQLITE_TRANSIENT);
+    }
   }
 }
 
@@ -22951,10 +24130,20 @@ static void timeFunc(
 ){
   DateTime x;
   if( isDate(context, argc, argv, &x)==0 ){
-    char zBuf[100];
+    int s;
+    char zBuf[16];
     computeHMS(&x);
-    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
-    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+    zBuf[0] = '0' + (x.h/10)%10;
+    zBuf[1] = '0' + (x.h)%10;
+    zBuf[2] = ':';
+    zBuf[3] = '0' + (x.m/10)%10;
+    zBuf[4] = '0' + (x.m)%10;
+    zBuf[5] = ':';
+    s = (int)x.s;
+    zBuf[6] = '0' + (s/10)%10;
+    zBuf[7] = '0' + (s)%10;
+    zBuf[8] = 0;
+    sqlite3_result_text(context, zBuf, 8, SQLITE_TRANSIENT);
   }
 }
 
@@ -22970,10 +24159,28 @@ static void dateFunc(
 ){
   DateTime x;
   if( isDate(context, argc, argv, &x)==0 ){
-    char zBuf[100];
+    int Y;
+    char zBuf[16];
     computeYMD(&x);
-    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
-    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
+    Y = x.Y;
+    if( Y<0 ) Y = -Y;
+    zBuf[1] = '0' + (Y/1000)%10;
+    zBuf[2] = '0' + (Y/100)%10;
+    zBuf[3] = '0' + (Y/10)%10;
+    zBuf[4] = '0' + (Y)%10;
+    zBuf[5] = '-';
+    zBuf[6] = '0' + (x.M/10)%10;
+    zBuf[7] = '0' + (x.M)%10;
+    zBuf[8] = '-';
+    zBuf[9] = '0' + (x.D/10)%10;
+    zBuf[10] = '0' + (x.D)%10;
+    zBuf[11] = 0;
+    if( x.Y<0 ){
+      zBuf[0] = '-';
+      sqlite3_result_text(context, zBuf, 11, SQLITE_TRANSIENT);
+    }else{
+      sqlite3_result_text(context, &zBuf[1], 10, SQLITE_TRANSIENT);
+    }
   }
 }
 
@@ -23002,131 +24209,100 @@ static void strftimeFunc(
   sqlite3_value **argv
 ){
   DateTime x;
-  u64 n;
   size_t i,j;
-  char *z;
   sqlite3 *db;
   const char *zFmt;
-  char zBuf[100];
+  sqlite3_str sRes;
+
+
   if( argc==0 ) return;
   zFmt = (const char*)sqlite3_value_text(argv[0]);
   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
   db = sqlite3_context_db_handle(context);
-  for(i=0, n=1; zFmt[i]; i++, n++){
-    if( zFmt[i]=='%' ){
-      switch( zFmt[i+1] ){
-        case 'd':
-        case 'H':
-        case 'm':
-        case 'M':
-        case 'S':
-        case 'W':
-          n++;
-          /* fall thru */
-        case 'w':
-        case '%':
-          break;
-        case 'f':
-          n += 8;
-          break;
-        case 'j':
-          n += 3;
-          break;
-        case 'Y':
-          n += 8;
-          break;
-        case 's':
-        case 'J':
-          n += 50;
-          break;
-        default:
-          return;  /* ERROR.  return a NULL */
-      }
-      i++;
-    }
-  }
-  testcase( n==sizeof(zBuf)-1 );
-  testcase( n==sizeof(zBuf) );
-  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
-  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
-  if( n<sizeof(zBuf) ){
-    z = zBuf;
-  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
-    sqlite3_result_error_toobig(context);
-    return;
-  }else{
-    z = sqlite3DbMallocRawNN(db, (int)n);
-    if( z==0 ){
-      sqlite3_result_error_nomem(context);
-      return;
-    }
-  }
+  sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
+
   computeJD(&x);
   computeYMD_HMS(&x);
   for(i=j=0; zFmt[i]; i++){
-    if( zFmt[i]!='%' ){
-      z[j++] = zFmt[i];
-    }else{
-      i++;
-      switch( zFmt[i] ){
-        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
-        case 'f': {
-          double s = x.s;
-          if( s>59.999 ) s = 59.999;
-          sqlite3_snprintf(7, &z[j],"%06.3f", s);
-          j += sqlite3Strlen30(&z[j]);
-          break;
-        }
-        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
-        case 'W': /* Fall thru */
-        case 'j': {
-          int nDay;             /* Number of days since 1st day of year */
-          DateTime y = x;
-          y.validJD = 0;
-          y.M = 1;
-          y.D = 1;
-          computeJD(&y);
-          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
-          if( zFmt[i]=='W' ){
-            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
-            wd = (int)(((x.iJD+43200000)/86400000)%7);
-            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
-            j += 2;
-          }else{
-            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
-            j += 3;
-          }
-          break;
-        }
-        case 'J': {
-          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
-          j+=sqlite3Strlen30(&z[j]);
-          break;
-        }
-        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
-        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
-        case 's': {
-          i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
-          sqlite3Int64ToText(iS, &z[j]);
-          j += sqlite3Strlen30(&z[j]);
-          break;
-        }
-        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
-        case 'w': {
-          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
-          break;
-        }
-        case 'Y': {
-          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
-          break;
+    if( zFmt[i]!='%' ) continue;
+    if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
+    i++;
+    j = i + 1;
+    switch( zFmt[i] ){
+      case 'd': {
+        sqlite3_str_appendf(&sRes, "%02d", x.D);
+        break;
+      }
+      case 'f': {
+        double s = x.s;
+        if( s>59.999 ) s = 59.999;
+        sqlite3_str_appendf(&sRes, "%06.3f", s);
+        break;
+      }
+      case 'H': {
+        sqlite3_str_appendf(&sRes, "%02d", x.h);
+        break;
+      }
+      case 'W': /* Fall thru */
+      case 'j': {
+        int nDay;             /* Number of days since 1st day of year */
+        DateTime y = x;
+        y.validJD = 0;
+        y.M = 1;
+        y.D = 1;
+        computeJD(&y);
+        nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
+        if( zFmt[i]=='W' ){
+          int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
+          wd = (int)(((x.iJD+43200000)/86400000)%7);
+          sqlite3_str_appendf(&sRes,"%02d",(nDay+7-wd)/7);
+        }else{
+          sqlite3_str_appendf(&sRes,"%03d",nDay+1);
         }
-        default:   z[j++] = '%'; break;
+        break;
+      }
+      case 'J': {
+        sqlite3_str_appendf(&sRes,"%.16g",x.iJD/86400000.0);
+        break;
+      }
+      case 'm': {
+        sqlite3_str_appendf(&sRes,"%02d",x.M);
+        break;
+      }
+      case 'M': {
+        sqlite3_str_appendf(&sRes,"%02d",x.m);
+        break;
+      }
+      case 's': {
+        i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
+        sqlite3_str_appendf(&sRes,"%lld",iS);
+        break;
+      }
+      case 'S': {
+        sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
+        break;
+      }
+      case 'w': {
+        sqlite3_str_appendchar(&sRes, 1,
+                       (char)(((x.iJD+129600000)/86400000) % 7) + '0');
+        break;
+      }
+      case 'Y': {
+        sqlite3_str_appendf(&sRes,"%04d",x.Y);
+        break;
+      }
+      case '%': {
+        sqlite3_str_appendchar(&sRes, 1, '%');
+        break;
+      }
+      default: {
+        sqlite3_str_reset(&sRes);
+        return;
       }
     }
   }
-  z[j] = 0;
-  sqlite3_result_text(context, z, -1,
-                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
+  if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
+  sqlite3ResultStrAccum(context, &sRes);
 }
 
 /*
@@ -23226,6 +24402,7 @@ SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
   static FuncDef aDateTimeFuncs[] = {
 #ifndef SQLITE_OMIT_DATETIME_FUNCS
     PURE_DATE(julianday,        -1, 0, 0, juliandayFunc ),
+    PURE_DATE(unixepoch,        -1, 0, 0, unixepochFunc ),
     PURE_DATE(date,             -1, 0, 0, dateFunc      ),
     PURE_DATE(time,             -1, 0, 0, timeFunc      ),
     PURE_DATE(datetime,         -1, 0, 0, datetimeFunc  ),
@@ -23407,6 +24584,7 @@ SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
 }
 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
+  if( NEVER(id->pMethods==0) ) return 0;
   return id->pMethods->xDeviceCharacteristics(id);
 }
 #ifndef SQLITE_OMIT_WAL
@@ -23475,7 +24653,7 @@ SQLITE_PRIVATE int sqlite3OsOpen(
 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   DO_OS_MALLOC_TEST(0);
   assert( dirSync==0 || dirSync==1 );
-  return pVfs->xDelete(pVfs, zPath, dirSync);
+  return pVfs->xDelete!=0 ? pVfs->xDelete(pVfs, zPath, dirSync) : SQLITE_OK;
 }
 SQLITE_PRIVATE int sqlite3OsAccess(
   sqlite3_vfs *pVfs,
@@ -23498,6 +24676,8 @@ SQLITE_PRIVATE int sqlite3OsFullPathname(
 }
 #ifndef SQLITE_OMIT_LOAD_EXTENSION
 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
+  assert( zPath!=0 );
+  assert( strlen(zPath)<=SQLITE_MAX_PATHLEN );  /* tag-20210611-1 */
   return pVfs->xDlOpen(pVfs, zPath);
 }
 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
@@ -23559,12 +24739,15 @@ SQLITE_PRIVATE int sqlite3OsOpenMalloc(
     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
     if( rc!=SQLITE_OK ){
       sqlite3_free(pFile);
+      *ppFile = 0;
     }else{
       *ppFile = pFile;
     }
   }else{
+    *ppFile = 0;
     rc = SQLITE_NOMEM_BKPT;
   }
+  assert( *ppFile!=0 || rc!=SQLITE_OK );
   return rc;
 }
 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
@@ -24282,7 +25465,7 @@ static void adjustStats(int iSize, int increment){
 ** This routine checks the guards at either end of the allocation and
 ** if they are incorrect it asserts.
 */
-static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
+static struct MemBlockHdr *sqlite3MemsysGetHeader(const void *pAllocation){
   struct MemBlockHdr *p;
   int *pInt;
   u8 *pU8;
@@ -24529,7 +25712,7 @@ SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
 **
 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 */
-SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
+SQLITE_PRIVATE int sqlite3MemdebugHasType(const void *p, u8 eType){
   int rc = 1;
   if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
     struct MemBlockHdr *pHdr;
@@ -24551,7 +25734,7 @@ SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
 **
 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
 */
-SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
+SQLITE_PRIVATE int sqlite3MemdebugNoType(const void *p, u8 eType){
   int rc = 1;
   if( p && sqlite3GlobalConfig.m.xFree==sqlite3MemFree ){
     struct MemBlockHdr *pHdr;
@@ -26929,205 +28112,7 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 /*
 ** Include code that is common to all os_*.c files
 */
-/************** Include os_common.h in the middle of mutex_w32.c *************/
-/************** Begin file os_common.h ***************************************/
-/*
-** 2004 May 22
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This file contains macros and a little bit of code that is common to
-** all of the platform-specific files (os_*.c) and is #included into those
-** files.
-**
-** This file should be #included by the os_*.c files only.  It is not a
-** general purpose header file.
-*/
-#ifndef _OS_COMMON_H_
-#define _OS_COMMON_H_
-
-/*
-** At least two bugs have slipped in because we changed the MEMORY_DEBUG
-** macro to SQLITE_DEBUG and some older makefiles have not yet made the
-** switch.  The following code should catch this problem at compile-time.
-*/
-#ifdef MEMORY_DEBUG
-# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
-#endif
-
-/*
-** Macros for performance tracing.  Normally turned off.  Only works
-** on i486 hardware.
-*/
-#ifdef SQLITE_PERFORMANCE_TRACE
-
-/*
-** hwtime.h contains inline assembler code for implementing
-** high-performance timing routines.
-*/
-/************** Include hwtime.h in the middle of os_common.h ****************/
-/************** Begin file hwtime.h ******************************************/
-/*
-** 2008 May 27
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 and x86_64 class CPUs.
-*/
-#ifndef SQLITE_HWTIME_H
-#define SQLITE_HWTIME_H
-
-/*
-** The following routine only works on pentium-class (or newer) processors.
-** It uses the RDTSC opcode to read the cycle count value out of the
-** processor and returns that value.  This can be used for high-res
-** profiling.
-*/
-#if !defined(__STRICT_ANSI__) && \
-    (defined(__GNUC__) || defined(_MSC_VER)) && \
-    (defined(i386) || defined(__i386__) || defined(_M_IX86))
-
-  #if defined(__GNUC__)
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-     unsigned int lo, hi;
-     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
-     return (sqlite_uint64)hi << 32 | lo;
-  }
-
-  #elif defined(_MSC_VER)
-
-  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
-     __asm {
-        rdtsc
-        ret       ; return value at EDX:EAX
-     }
-  }
-
-  #endif
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long val;
-      __asm__ __volatile__ ("rdtsc" : "=A" (val));
-      return val;
-  }
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long long retval;
-      unsigned long junk;
-      __asm__ __volatile__ ("\n\
-          1:      mftbu   %1\n\
-                  mftb    %L0\n\
-                  mftbu   %0\n\
-                  cmpw    %0,%1\n\
-                  bne     1b"
-                  : "=r" (retval), "=r" (junk));
-      return retval;
-  }
-
-#else
-
-  /*
-  ** asm() is needed for hardware timing support.  Without asm(),
-  ** disable the sqlite3Hwtime() routine.
-  **
-  ** sqlite3Hwtime() is only used for some obscure debugging
-  ** and analysis configurations, not in any deliverable, so this
-  ** should not be a great loss.
-  */
-SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
-
-#endif
-
-#endif /* !defined(SQLITE_HWTIME_H) */
-
-/************** End of hwtime.h **********************************************/
-/************** Continuing where we left off in os_common.h ******************/
-
-static sqlite_uint64 g_start;
-static sqlite_uint64 g_elapsed;
-#define TIMER_START       g_start=sqlite3Hwtime()
-#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
-#define TIMER_ELAPSED     g_elapsed
-#else
-#define TIMER_START
-#define TIMER_END
-#define TIMER_ELAPSED     ((sqlite_uint64)0)
-#endif
-
-/*
-** If we compile with the SQLITE_TEST macro set, then the following block
-** of code will give us the ability to simulate a disk I/O error.  This
-** is used for testing the I/O recovery logic.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_io_error_hit;
-SQLITE_API extern int sqlite3_io_error_hardhit;
-SQLITE_API extern int sqlite3_io_error_pending;
-SQLITE_API extern int sqlite3_io_error_persist;
-SQLITE_API extern int sqlite3_io_error_benign;
-SQLITE_API extern int sqlite3_diskfull_pending;
-SQLITE_API extern int sqlite3_diskfull;
-#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
-#define SimulateIOError(CODE)  \
-  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
-       || sqlite3_io_error_pending-- == 1 )  \
-              { local_ioerr(); CODE; }
-static void local_ioerr(){
-  IOTRACE(("IOERR\n"));
-  sqlite3_io_error_hit++;
-  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
-}
-#define SimulateDiskfullError(CODE) \
-   if( sqlite3_diskfull_pending ){ \
-     if( sqlite3_diskfull_pending == 1 ){ \
-       local_ioerr(); \
-       sqlite3_diskfull = 1; \
-       sqlite3_io_error_hit = 1; \
-       CODE; \
-     }else{ \
-       sqlite3_diskfull_pending--; \
-     } \
-   }
-#else
-#define SimulateIOErrorBenign(X)
-#define SimulateIOError(A)
-#define SimulateDiskfullError(A)
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** When testing, keep a count of the number of open files.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_open_file_count;
-#define OpenCounter(X)  sqlite3_open_file_count+=(X)
-#else
-#define OpenCounter(X)
-#endif /* defined(SQLITE_TEST) */
-
-#endif /* !defined(_OS_COMMON_H_) */
-
-/************** End of os_common.h *******************************************/
-/************** Continuing where we left off in mutex_w32.c ******************/
+/* #include "os_common.h" */
 
 /*
 ** Include the header file for the Windows VFS.
@@ -27765,7 +28750,6 @@ SQLITE_PRIVATE int sqlite3MallocInit(void){
   if( sqlite3GlobalConfig.m.xMalloc==0 ){
     sqlite3MemSetDefault();
   }
-  memset(&mem0, 0, sizeof(mem0));
   mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
       || sqlite3GlobalConfig.nPage<=0 ){
@@ -27921,7 +28905,7 @@ SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
 ** TRUE if p is a lookaside memory allocation from db
 */
 #ifndef SQLITE_OMIT_LOOKASIDE
-static int isLookaside(sqlite3 *db, void *p){
+static int isLookaside(sqlite3 *db, const void *p){
   return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
 }
 #else
@@ -27932,18 +28916,18 @@ static int isLookaside(sqlite3 *db, void *p){
 ** Return the size of a memory allocation previously obtained from
 ** sqlite3Malloc() or sqlite3_malloc().
 */
-SQLITE_PRIVATE int sqlite3MallocSize(void *p){
+SQLITE_PRIVATE int sqlite3MallocSize(const void *p){
   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
-  return sqlite3GlobalConfig.m.xSize(p);
+  return sqlite3GlobalConfig.m.xSize((void*)p);
 }
-static int lookasideMallocSize(sqlite3 *db, void *p){
+static int lookasideMallocSize(sqlite3 *db, const void *p){
 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
   return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
 #else
   return db->lookaside.szTrue;
 #endif
 }
-SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
+SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, const void *p){
   assert( p!=0 );
 #ifdef SQLITE_DEBUG
   if( db==0 || !isLookaside(db,p) ){
@@ -27970,7 +28954,7 @@ SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
       }
     }
   }
-  return sqlite3GlobalConfig.m.xSize(p);
+  return sqlite3GlobalConfig.m.xSize((void*)p);
 }
 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
@@ -28355,8 +29339,9 @@ SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const cha
 ** Free any prior content in *pz and replace it with a copy of zNew.
 */
 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
+  char *z = sqlite3DbStrDup(db, zNew);
   sqlite3DbFree(db, *pz);
-  *pz = sqlite3DbStrDup(db, zNew);
+  *pz = z;
 }
 
 /*
@@ -28364,8 +29349,15 @@ SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
 ** has happened.  This routine will set db->mallocFailed, and also
 ** temporarily disable the lookaside memory allocator and interrupt
 ** any running VDBEs.
+**
+** Always return a NULL pointer so that this routine can be invoked using
+**
+**      return sqlite3OomFault(db);
+**
+** and thereby avoid unnecessary stack frame allocations for the overwhelmingly
+** common case where no OOM occurs.
 */
-SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
+SQLITE_PRIVATE void *sqlite3OomFault(sqlite3 *db){
   if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
     db->mallocFailed = 1;
     if( db->nVdbeExec>0 ){
@@ -28373,9 +29365,11 @@ SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
     }
     DisableLookaside;
     if( db->pParse ){
+      sqlite3ErrorMsg(db->pParse, "out of memory");
       db->pParse->rc = SQLITE_NOMEM_BKPT;
     }
   }
+  return 0;
 }
 
 /*
@@ -28464,7 +29458,7 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
                           NULL pointers replaced by SQL NULL.  %Q */
 #define etTOKEN      11 /* a pointer to a Token structure */
-#define etSRCLIST    12 /* a pointer to a SrcList */
+#define etSRCITEM    12 /* a pointer to a SrcItem */
 #define etPOINTER    13 /* The %p conversion */
 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
 #define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
@@ -28530,10 +29524,16 @@ static const et_info fmtinfo[] = {
 
   /* All the rest are undocumented and are for internal use only */
   {  'T',  0, 0, etTOKEN,      0,  0 },
-  {  'S',  0, 0, etSRCLIST,    0,  0 },
+  {  'S',  0, 0, etSRCITEM,    0,  0 },
   {  'r', 10, 1, etORDINAL,    0,  0 },
 };
 
+/* Notes:
+**
+**    %S    Takes a pointer to SrcItem.  Shows name or database.name
+**    %!S   Like %S but prefer the zName over the zAlias
+*/
+
 /* Floating point constants used for rounding */
 static const double arRound[] = {
   5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
@@ -28574,7 +29574,7 @@ static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
 /*
 ** Set the StrAccum object to an error mode.
 */
-static void setStrAccumError(StrAccum *p, u8 eError){
+SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum *p, u8 eError){
   assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
   p->accError = eError;
   if( p->mxAlloc ) sqlite3_str_reset(p);
@@ -28610,12 +29610,12 @@ static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
   char *z;
   if( pAccum->accError ) return 0;
   if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
-    setStrAccumError(pAccum, SQLITE_TOOBIG);
+    sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG);
     return 0;
   }
   z = sqlite3DbMallocRaw(pAccum->db, n);
   if( z==0 ){
-    setStrAccumError(pAccum, SQLITE_NOMEM);
+    sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM);
   }
   return z;
 }
@@ -29278,31 +30278,44 @@ SQLITE_API void sqlite3_str_vappendf(
         goto adjust_width_for_utf8;
       }
       case etTOKEN: {
-        Token *pToken;
         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
-        pToken = va_arg(ap, Token*);
-        assert( bArgList==0 );
-        if( pToken && pToken->n ){
-          sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
+        if( flag_alternateform ){
+          /* %#T means an Expr pointer that uses Expr.u.zToken */
+          Expr *pExpr = va_arg(ap,Expr*);
+          if( ALWAYS(pExpr) && ALWAYS(!ExprHasProperty(pExpr,EP_IntValue)) ){
+            sqlite3_str_appendall(pAccum, (const char*)pExpr->u.zToken);
+            sqlite3RecordErrorOffsetOfExpr(pAccum->db, pExpr);
+          }
+        }else{
+          /* %T means a Token pointer */
+          Token *pToken = va_arg(ap, Token*);
+          assert( bArgList==0 );
+          if( pToken && pToken->n ){
+            sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
+            sqlite3RecordErrorByteOffset(pAccum->db, pToken->z);
+          }
         }
         length = width = 0;
         break;
       }
-      case etSRCLIST: {
-        SrcList *pSrc;
-        int k;
+      case etSRCITEM: {
         SrcItem *pItem;
         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
-        pSrc = va_arg(ap, SrcList*);
-        k = va_arg(ap, int);
-        pItem = &pSrc->a[k];
+        pItem = va_arg(ap, SrcItem*);
         assert( bArgList==0 );
-        assert( k>=0 && k<pSrc->nSrc );
-        if( pItem->zDatabase ){
-          sqlite3_str_appendall(pAccum, pItem->zDatabase);
-          sqlite3_str_append(pAccum, ".", 1);
+        if( pItem->zAlias && !flag_altform2 ){
+          sqlite3_str_appendall(pAccum, pItem->zAlias);
+        }else if( pItem->zName ){
+          if( pItem->zDatabase ){
+            sqlite3_str_appendall(pAccum, pItem->zDatabase);
+            sqlite3_str_append(pAccum, ".", 1);
+          }
+          sqlite3_str_appendall(pAccum, pItem->zName);
+        }else if( pItem->zAlias ){
+          sqlite3_str_appendall(pAccum, pItem->zAlias);
+        }else if( ALWAYS(pItem->pSelect) ){
+          sqlite3_str_appendf(pAccum, "SUBQUERY %u", pItem->pSelect->selId);
         }
-        sqlite3_str_appendall(pAccum, pItem->zName);
         length = width = 0;
         break;
       }
@@ -29335,6 +30348,42 @@ SQLITE_API void sqlite3_str_vappendf(
   }/* End for loop over the format string */
 } /* End of function */
 
+
+/*
+** The z string points to the first character of a token that is
+** associated with an error.  If db does not already have an error
+** byte offset recorded, try to compute the error byte offset for
+** z and set the error byte offset in db.
+*/
+SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3 *db, const char *z){
+  const Parse *pParse;
+  const char *zText;
+  const char *zEnd;
+  assert( z!=0 );
+  if( NEVER(db==0) ) return;
+  if( db->errByteOffset!=(-2) ) return;
+  pParse = db->pParse;
+  if( NEVER(pParse==0) ) return;
+  zText =pParse->zTail;
+  if( NEVER(zText==0) ) return;
+  zEnd = &zText[strlen(zText)];
+  if( SQLITE_WITHIN(z,zText,zEnd) ){
+    db->errByteOffset = (int)(z-zText);
+  }
+}
+
+/*
+** If pExpr has a byte offset for the start of a token, record that as
+** as the error offset.
+*/
+SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3 *db, const Expr *pExpr){
+  while( pExpr && (ExprHasProperty(pExpr,EP_FromJoin) || pExpr->w.iOfst<=0) ){
+    pExpr = pExpr->pLeft;
+  }
+  if( pExpr==0 ) return;
+  db->errByteOffset = pExpr->w.iOfst;
+}
+
 /*
 ** Enlarge the memory allocation on a StrAccum object so that it is
 ** able to accept at least N more bytes of text.
@@ -29342,7 +30391,7 @@ SQLITE_API void sqlite3_str_vappendf(
 ** Return the number of bytes of text that StrAccum is able to accept
 ** after the attempted enlargement.  The value returned might be zero.
 */
-static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
+SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum *p, int N){
   char *zNew;
   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
   if( p->accError ){
@@ -29351,7 +30400,7 @@ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
     return 0;
   }
   if( p->mxAlloc==0 ){
-    setStrAccumError(p, SQLITE_TOOBIG);
+    sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
     return p->nAlloc - p->nChar - 1;
   }else{
     char *zOld = isMalloced(p) ? p->zText : 0;
@@ -29364,7 +30413,7 @@ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
     }
     if( szNew > p->mxAlloc ){
       sqlite3_str_reset(p);
-      setStrAccumError(p, SQLITE_TOOBIG);
+      sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
       return 0;
     }else{
       p->nAlloc = (int)szNew;
@@ -29382,7 +30431,7 @@ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
     }else{
       sqlite3_str_reset(p);
-      setStrAccumError(p, SQLITE_NOMEM);
+      sqlite3StrAccumSetError(p, SQLITE_NOMEM);
       return 0;
     }
   }
@@ -29455,7 +30504,7 @@ static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
     memcpy(zText, p->zText, p->nChar+1);
     p->printfFlags |= SQLITE_PRINTF_MALLOCED;
   }else{
-    setStrAccumError(p, SQLITE_NOMEM);
+    sqlite3StrAccumSetError(p, SQLITE_NOMEM);
   }
   p->zText = zText;
   return zText;
@@ -29470,6 +30519,22 @@ SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
   return p->zText;
 }
 
+/*
+** Use the content of the StrAccum passed as the second argument
+** as the result of an SQL function.
+*/
+SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){
+  if( p->accError ){
+    sqlite3_result_error_code(pCtx, p->accError);
+    sqlite3_str_reset(p);
+  }else if( isMalloced(p) ){
+    sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
+  }else{
+    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
+    sqlite3_str_reset(p);
+  }
+}
+
 /*
 ** This singleton is an sqlite3_str object that is returned if
 ** sqlite3_malloc() fails to provide space for a real one.  This
@@ -29882,21 +30947,16 @@ SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc)
     StrAccum x;
     char zLine[100];
     sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
-    sqlite3_str_appendf(&x, "{%d:*}", pItem->iCursor);
-    if( pItem->zDatabase ){
-      sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
-    }else if( pItem->zName ){
-      sqlite3_str_appendf(&x, " %s", pItem->zName);
-    }
+    x.printfFlags |= SQLITE_PRINTF_INTERNAL;
+    sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem);
     if( pItem->pTab ){
       sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx",
            pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);
     }
-    if( pItem->zAlias ){
-      sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
-    }
     if( pItem->fg.jointype & JT_LEFT ){
       sqlite3_str_appendf(&x, " LEFT-JOIN");
+    }else if( pItem->fg.jointype & JT_CROSS ){
+      sqlite3_str_appendf(&x, " CROSS-JOIN");
     }
     if( pItem->fg.fromDDL ){
       sqlite3_str_appendf(&x, " DDL");
@@ -30165,7 +31225,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     sqlite3_str_appendf(&x, " fg.af=%x.%c",
       pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
     if( ExprHasProperty(pExpr, EP_FromJoin) ){
-      sqlite3_str_appendf(&x, " iRJT=%d", pExpr->iRightJoinTable);
+      sqlite3_str_appendf(&x, " iRJT=%d", pExpr->w.iRightJoinTable);
     }
     if( ExprHasProperty(pExpr, EP_FromDDL) ){
       sqlite3_str_appendf(&x, " DDL");
@@ -30195,6 +31255,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
         sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s",
                                     pExpr->iColumn, zFlgs, zOp2);
       }else{
+        assert( ExprUseYTab(pExpr) );
         sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s",
                         pExpr->iTable, pExpr->iColumn,
                         pExpr->y.pTab, zFlgs);
@@ -30214,11 +31275,13 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     }
 #ifndef SQLITE_OMIT_FLOATING_POINT
     case TK_FLOAT: {
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
       break;
     }
 #endif
     case TK_STRING: {
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
       break;
     }
@@ -30227,17 +31290,19 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       break;
     }
     case TK_TRUEFALSE: {
-      sqlite3TreeViewLine(pView,
-         sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
+      sqlite3TreeViewLine(pView,"%s%s",
+         sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE", zFlgs);
       break;
     }
 #ifndef SQLITE_OMIT_BLOB_LITERAL
     case TK_BLOB: {
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
       break;
     }
 #endif
     case TK_VARIABLE: {
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
                           pExpr->u.zToken, pExpr->iColumn);
       break;
@@ -30247,12 +31312,14 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       break;
     }
     case TK_ID: {
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
       break;
     }
 #ifndef SQLITE_OMIT_CAST
     case TK_CAST: {
       /* Expressions of the form:   CAST(pLeft AS token) */
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
       break;
@@ -30302,6 +31369,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     }
 
     case TK_SPAN: {
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
       break;
@@ -30313,6 +31381,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       ** up in the treeview output as "SOFT-COLLATE".  Explicit COLLATE
       ** operators that appear in the original SQL always have the
       ** EP_Collate bit set and appear in treeview output as just "COLLATE" */
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView, "%sCOLLATE %Q%s",
         !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "",
         pExpr->u.zToken, zFlgs);
@@ -30328,6 +31397,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
         pFarg = 0;
         pWin = 0;
       }else{
+        assert( ExprUseXList(pExpr) );
         pFarg = pExpr->x.pList;
 #ifndef SQLITE_OMIT_WINDOWFUNC
         pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;
@@ -30335,6 +31405,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
         pWin = 0;
 #endif
       }
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       if( pExpr->op==TK_AGG_FUNCTION ){
         sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s agg=%d[%d]/%p",
                              pExpr->op2, pExpr->u.zToken, zFlgs,
@@ -30366,11 +31437,13 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     }
 #ifndef SQLITE_OMIT_SUBQUERY
     case TK_EXISTS: {
+      assert( ExprUseXSelect(pExpr) );
       sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
       break;
     }
     case TK_SELECT: {
+      assert( ExprUseXSelect(pExpr) );
       sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags);
       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
       break;
@@ -30378,7 +31451,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     case TK_IN: {
       sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
-      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+      if( ExprUseXSelect(pExpr) ){
         sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
       }else{
         sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
@@ -30399,9 +31472,12 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     ** Z is stored in pExpr->pList->a[1].pExpr.
     */
     case TK_BETWEEN: {
-      Expr *pX = pExpr->pLeft;
-      Expr *pY = pExpr->x.pList->a[0].pExpr;
-      Expr *pZ = pExpr->x.pList->a[1].pExpr;
+      const Expr *pX, *pY, *pZ;
+      pX = pExpr->pLeft;
+      assert( ExprUseXList(pExpr) );
+      assert( pExpr->x.pList->nExpr==2 );
+      pY = pExpr->x.pList->a[0].pExpr;
+      pZ = pExpr->x.pList->a[1].pExpr;
       sqlite3TreeViewLine(pView, "BETWEEN");
       sqlite3TreeViewExpr(pView, pX, 1);
       sqlite3TreeViewExpr(pView, pY, 1);
@@ -30423,6 +31499,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     case TK_CASE: {
       sqlite3TreeViewLine(pView, "CASE");
       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
+      assert( ExprUseXList(pExpr) );
       sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
       break;
     }
@@ -30435,6 +31512,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
         case OE_Fail:       zType = "fail";      break;
         case OE_Ignore:     zType = "ignore";    break;
       }
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
       break;
     }
@@ -30447,12 +31525,16 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     }
     case TK_VECTOR: {
       char *z = sqlite3_mprintf("VECTOR%s",zFlgs);
+      assert( ExprUseXList(pExpr) );
       sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);
       sqlite3_free(z);
       break;
     }
     case TK_SELECT_COLUMN: {
-      sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
+      sqlite3TreeViewLine(pView, "SELECT-COLUMN %d of [0..%d]%s",
+              pExpr->iColumn, pExpr->iTable-1,
+              pExpr->pRight==pExpr->pLeft ? " (SELECT-owner)" : "");
+      assert( ExprUseXSelect(pExpr->pLeft) );
       sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
       break;
     }
@@ -30461,6 +31543,23 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
       break;
     }
+    case TK_ERROR: {
+      Expr tmp;
+      sqlite3TreeViewLine(pView, "ERROR");
+      tmp = *pExpr;
+      tmp.op = pExpr->op2;
+      sqlite3TreeViewExpr(pView, &tmp, 0);
+      break;
+    }
+    case TK_ROW: {
+      if( pExpr->iColumn<=0 ){
+        sqlite3TreeViewLine(pView, "First FROM table rowid");
+      }else{
+        sqlite3TreeViewLine(pView, "First FROM table column %d",
+            pExpr->iColumn-1);
+      }
+      break;
+    }
     default: {
       sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
       break;
@@ -30610,11 +31709,16 @@ SQLITE_API void sqlite3_randomness(int N, void *pBuf){
   ** number generator) not as an encryption device.
   */
   if( !wsdPrng.isInit ){
+    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
     int i;
     char k[256];
     wsdPrng.j = 0;
     wsdPrng.i = 0;
-    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
+    if( NEVER(pVfs==0) ){
+      memset(k, 0, sizeof(k));
+    }else{
+      sqlite3OsRandomness(pVfs, 256, k);
+    }
     for(i=0; i<256; i++){
       wsdPrng.s[i] = (u8)i;
     }
@@ -31507,16 +32611,6 @@ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
 #include <math.h>
 #endif
 
-/*
-** Routine needed to support the testcase() macro.
-*/
-#ifdef SQLITE_COVERAGE_TEST
-SQLITE_PRIVATE void sqlite3Coverage(int x){
-  static unsigned dummy = 0;
-  dummy += (unsigned)x;
-}
-#endif
-
 /*
 ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
 ** or to bypass normal error detection during testing in order to let
@@ -31546,11 +32640,21 @@ SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
 #ifndef SQLITE_OMIT_FLOATING_POINT
 /*
 ** Return true if the floating point value is Not a Number (NaN).
+**
+** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
+** Otherwise, we have our own implementation that works on most systems.
 */
 SQLITE_PRIVATE int sqlite3IsNaN(double x){
+  int rc;   /* The value return */
+#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
   u64 y;
   memcpy(&y,&x,sizeof(y));
-  return IsNaN(y);
+  rc = IsNaN(y);
+#else
+  rc = isnan(x);
+#endif /* HAVE_ISNAN */
+  testcase( rc );
+  return rc;
 }
 #endif /* SQLITE_OMIT_FLOATING_POINT */
 
@@ -31575,8 +32679,14 @@ SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
 */
 SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
-  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
-  return pCol->zName + strlen(pCol->zName) + 1;
+  if( pCol->colFlags & COLFLAG_HASTYPE ){
+    return pCol->zCnName + strlen(pCol->zCnName) + 1;
+  }else if( pCol->eCType ){
+    assert( pCol->eCType<=SQLITE_N_STDTYPE );
+    return (char*)sqlite3StdType[pCol->eCType-1];
+  }else{
+    return zDflt;
+  }
 }
 
 /*
@@ -31597,7 +32707,11 @@ static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
   assert( db!=0 );
   db->errCode = err_code;
-  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
+  if( err_code || db->pErr ){
+    sqlite3ErrorFinish(db, err_code);
+  }else{
+    db->errByteOffset = -1;
+  }
 }
 
 /*
@@ -31607,6 +32721,7 @@ SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
 SQLITE_PRIVATE void sqlite3ErrorClear(sqlite3 *db){
   assert( db!=0 );
   db->errCode = SQLITE_OK;
+  db->errByteOffset = -1;
   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
 }
 
@@ -31627,17 +32742,8 @@ SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
 ** handle "db". The error code is set to "err_code".
 **
 ** If it is not NULL, string zFormat specifies the format of the
-** error string in the style of the printf functions: The following
-** format characters are allowed:
-**
-**      %s      Insert a string
-**      %z      A string that should be freed after use
-**      %d      Insert an integer
-**      %T      Insert a token
-**      %S      Insert the first element of a SrcList
-**
-** zFormat and any string tokens that follow it are assumed to be
-** encoded in UTF-8.
+** error string.  zFormat and any string tokens that follow it are
+** assumed to be encoded in UTF-8.
 **
 ** To clear the most recent error for sqlite handle "db", sqlite3Error
 ** should be called with err_code set to SQLITE_OK and zFormat set
@@ -31661,13 +32767,6 @@ SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *z
 
 /*
 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
-** The following formatting characters are allowed:
-**
-**      %s      Insert a string
-**      %z      A string that should be freed after use
-**      %d      Insert an integer
-**      %T      Insert a token
-**      %S      Insert the first element of a SrcList
 **
 ** This function should be used to report any error that occurs while
 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
@@ -31680,11 +32779,19 @@ SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
   char *zMsg;
   va_list ap;
   sqlite3 *db = pParse->db;
+  assert( db!=0 );
+  assert( db->pParse==pParse );
+  db->errByteOffset = -2;
   va_start(ap, zFormat);
   zMsg = sqlite3VMPrintf(db, zFormat, ap);
   va_end(ap);
+  if( db->errByteOffset<-1 ) db->errByteOffset = -1;
   if( db->suppressErr ){
     sqlite3DbFree(db, zMsg);
+    if( db->mallocFailed ){
+      pParse->nErr++;
+      pParse->rc = SQLITE_NOMEM;
+    }
   }else{
     pParse->nErr++;
     sqlite3DbFree(db, pParse->zErrMsg);
@@ -31747,11 +32854,34 @@ SQLITE_PRIVATE void sqlite3Dequote(char *z){
   z[j] = 0;
 }
 SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
+  assert( !ExprHasProperty(p, EP_IntValue) );
   assert( sqlite3Isquote(p->u.zToken[0]) );
   p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
   sqlite3Dequote(p->u.zToken);
 }
 
+/*
+** If the input token p is quoted, try to adjust the token to remove
+** the quotes.  This is not always possible:
+**
+**     "abc"     ->   abc
+**     "ab""cd"  ->   (not possible because of the interior "")
+**
+** Remove the quotes if possible.  This is a optimization.  The overall
+** system should still return the correct answer even if this routine
+** is always a no-op.
+*/
+SQLITE_PRIVATE void sqlite3DequoteToken(Token *p){
+  unsigned int i;
+  if( p->n<2 ) return;
+  if( !sqlite3Isquote(p->z[0]) ) return;
+  for(i=1; i<p->n-1; i++){
+    if( sqlite3Isquote(p->z[i]) ) return;
+  }
+  p->n -= 2;
+  p->z++;
+}
+
 /*
 ** Generate a Token object from a string
 */
@@ -32857,13 +33987,13 @@ static void logBadConnection(const char *zType){
 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
 */
 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
-  u32 magic;
+  u8 eOpenState;
   if( db==0 ){
     logBadConnection("NULL");
     return 0;
   }
-  magic = db->magic;
-  if( magic!=SQLITE_MAGIC_OPEN ){
+  eOpenState = db->eOpenState;
+  if( eOpenState!=SQLITE_STATE_OPEN ){
     if( sqlite3SafetyCheckSickOrOk(db) ){
       testcase( sqlite3GlobalConfig.xLog!=0 );
       logBadConnection("unopened");
@@ -32874,11 +34004,11 @@ SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
   }
 }
 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
-  u32 magic;
-  magic = db->magic;
-  if( magic!=SQLITE_MAGIC_SICK &&
-      magic!=SQLITE_MAGIC_OPEN &&
-      magic!=SQLITE_MAGIC_BUSY ){
+  u8 eOpenState;
+  eOpenState = db->eOpenState;
+  if( eOpenState!=SQLITE_STATE_SICK &&
+      eOpenState!=SQLITE_STATE_OPEN &&
+      eOpenState!=SQLITE_STATE_BUSY ){
     testcase( sqlite3GlobalConfig.xLog!=0 );
     logBadConnection("invalid");
     return 0;
@@ -33043,7 +34173,6 @@ SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
   return a[x&7] + y - 10;
 }
 
-#ifndef SQLITE_OMIT_VIRTUALTABLE
 /*
 ** Convert a double into a LogEst
 ** In other words, compute an approximation for 10*log2(x).
@@ -33058,16 +34187,9 @@ SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
   e = (a>>52) - 1022;
   return e*10;
 }
-#endif /* SQLITE_OMIT_VIRTUALTABLE */
 
-#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
-    defined(SQLITE_ENABLE_STAT4) || \
-    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 /*
 ** Convert a LogEst into an integer.
-**
-** Note that this routine is only used when one or more of various
-** non-standard compile-time options is enabled.
 */
 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
   u64 n;
@@ -33075,17 +34197,9 @@ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
   x /= 10;
   if( n>=5 ) n -= 2;
   else if( n>=1 ) n -= 1;
-#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
-    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
   if( x>60 ) return (u64)LARGEST_INT64;
-#else
-  /* If only SQLITE_ENABLE_STAT4 is on, then the largest input
-  ** possible to this routine is 310, resulting in a maximum x of 31 */
-  assert( x<=60 );
-#endif
   return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
 }
-#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
 
 /*
 ** Add a new name/number pair to a VList.  This might require that the
@@ -33497,35 +34611,35 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
     /*  18 */ "If"               OpHelp(""),
     /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
     /*  20 */ "IfNot"            OpHelp(""),
-    /*  21 */ "IfNullRow"        OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
-    /*  22 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
-    /*  23 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
-    /*  24 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
-    /*  25 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
-    /*  26 */ "IfNotOpen"        OpHelp("if( !csr[P1] ) goto P2"),
-    /*  27 */ "IfNoHope"         OpHelp("key=r[P3@P4]"),
-    /*  28 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
-    /*  29 */ "NotFound"         OpHelp("key=r[P3@P4]"),
-    /*  30 */ "Found"            OpHelp("key=r[P3@P4]"),
-    /*  31 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
-    /*  32 */ "NotExists"        OpHelp("intkey=r[P3]"),
-    /*  33 */ "Last"             OpHelp(""),
-    /*  34 */ "IfSmaller"        OpHelp(""),
-    /*  35 */ "SorterSort"       OpHelp(""),
-    /*  36 */ "Sort"             OpHelp(""),
-    /*  37 */ "Rewind"           OpHelp(""),
-    /*  38 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
-    /*  39 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
-    /*  40 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
-    /*  41 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
-    /*  42 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
+    /*  21 */ "IsNullOrType"     OpHelp("if typeof(r[P1]) IN (P3,5) goto P2"),
+    /*  22 */ "IfNullRow"        OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
+    /*  23 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
+    /*  24 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
+    /*  25 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
+    /*  26 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
+    /*  27 */ "IfNotOpen"        OpHelp("if( !csr[P1] ) goto P2"),
+    /*  28 */ "IfNoHope"         OpHelp("key=r[P3@P4]"),
+    /*  29 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
+    /*  30 */ "NotFound"         OpHelp("key=r[P3@P4]"),
+    /*  31 */ "Found"            OpHelp("key=r[P3@P4]"),
+    /*  32 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
+    /*  33 */ "NotExists"        OpHelp("intkey=r[P3]"),
+    /*  34 */ "Last"             OpHelp(""),
+    /*  35 */ "IfSmaller"        OpHelp(""),
+    /*  36 */ "SorterSort"       OpHelp(""),
+    /*  37 */ "Sort"             OpHelp(""),
+    /*  38 */ "Rewind"           OpHelp(""),
+    /*  39 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
+    /*  40 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
+    /*  41 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
+    /*  42 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
     /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
     /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
-    /*  45 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
-    /*  46 */ "Program"          OpHelp(""),
-    /*  47 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
-    /*  48 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
-    /*  49 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
+    /*  45 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
+    /*  46 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
+    /*  47 */ "Program"          OpHelp(""),
+    /*  48 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
+    /*  49 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
     /*  50 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
     /*  51 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
     /*  52 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
@@ -33534,50 +34648,50 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
     /*  55 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
     /*  56 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
     /*  57 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
-    /*  58 */ "ElseNotEq"        OpHelp(""),
-    /*  59 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
-    /*  60 */ "IncrVacuum"       OpHelp(""),
-    /*  61 */ "VNext"            OpHelp(""),
-    /*  62 */ "Init"             OpHelp("Start at P2"),
-    /*  63 */ "PureFunc"         OpHelp("r[P3]=func(r[P2@NP])"),
-    /*  64 */ "Function"         OpHelp("r[P3]=func(r[P2@NP])"),
-    /*  65 */ "Return"           OpHelp(""),
-    /*  66 */ "EndCoroutine"     OpHelp(""),
-    /*  67 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
-    /*  68 */ "Halt"             OpHelp(""),
-    /*  69 */ "Integer"          OpHelp("r[P2]=P1"),
-    /*  70 */ "Int64"            OpHelp("r[P2]=P4"),
-    /*  71 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
-    /*  72 */ "Null"             OpHelp("r[P2..P3]=NULL"),
-    /*  73 */ "SoftNull"         OpHelp("r[P1]=NULL"),
-    /*  74 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
-    /*  75 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
-    /*  76 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
-    /*  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 */ "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"),
+    /*  58 */ "ElseEq"           OpHelp(""),
+    /*  59 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
+    /*  60 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
+    /*  61 */ "IncrVacuum"       OpHelp(""),
+    /*  62 */ "VNext"            OpHelp(""),
+    /*  63 */ "Filter"           OpHelp("if key(P3@P4) not in filter(P1) goto P2"),
+    /*  64 */ "Init"             OpHelp("Start at P2"),
+    /*  65 */ "PureFunc"         OpHelp("r[P3]=func(r[P2@NP])"),
+    /*  66 */ "Function"         OpHelp("r[P3]=func(r[P2@NP])"),
+    /*  67 */ "Return"           OpHelp(""),
+    /*  68 */ "EndCoroutine"     OpHelp(""),
+    /*  69 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
+    /*  70 */ "Halt"             OpHelp(""),
+    /*  71 */ "Integer"          OpHelp("r[P2]=P1"),
+    /*  72 */ "Int64"            OpHelp("r[P2]=P4"),
+    /*  73 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
+    /*  74 */ "Null"             OpHelp("r[P2..P3]=NULL"),
+    /*  75 */ "SoftNull"         OpHelp("r[P1]=NULL"),
+    /*  76 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
+    /*  77 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
+    /*  78 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
+    /*  79 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
+    /*  80 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
+    /*  81 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
+    /*  82 */ "FkCheck"          OpHelp(""),
+    /*  83 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
+    /*  84 */ "CollSeq"          OpHelp(""),
+    /*  85 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
+    /*  86 */ "RealAffinity"     OpHelp(""),
+    /*  87 */ "Cast"             OpHelp("affinity(r[P1])"),
+    /*  88 */ "Permutation"      OpHelp(""),
+    /*  89 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
+    /*  90 */ "IsTrue"           OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
+    /*  91 */ "ZeroOrNull"       OpHelp("r[P2] = 0 OR NULL"),
+    /*  92 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
+    /*  93 */ "Column"           OpHelp("r[P3]=PX"),
+    /*  94 */ "TypeCheck"        OpHelp("typecheck(r[P1@P2])"),
+    /*  95 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
+    /*  96 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
+    /*  97 */ "Count"            OpHelp("r[P2]=count()"),
+    /*  98 */ "ReadCookie"       OpHelp(""),
+    /*  99 */ "SetCookie"        OpHelp(""),
+    /* 100 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
+    /* 101 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
     /* 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]"),
@@ -33588,73 +34702,79 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
     /* 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(""),
+    /* 112 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
+    /* 113 */ "OpenDup"          OpHelp(""),
+    /* 114 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
+    /* 115 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
+    /* 116 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
+    /* 117 */ "String8"          OpHelp("r[P2]='P4'"),
+    /* 118 */ "SorterOpen"       OpHelp(""),
+    /* 119 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
+    /* 120 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
+    /* 121 */ "Close"            OpHelp(""),
+    /* 122 */ "ColumnsUsed"      OpHelp(""),
+    /* 123 */ "SeekScan"         OpHelp("Scan-ahead up to P1 rows"),
+    /* 124 */ "SeekHit"          OpHelp("set P2<=seekHit<=P3"),
+    /* 125 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
+    /* 126 */ "NewRowid"         OpHelp("r[P2]=rowid"),
+    /* 127 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
+    /* 128 */ "RowCell"          OpHelp(""),
+    /* 129 */ "Delete"           OpHelp(""),
+    /* 130 */ "ResetCount"       OpHelp(""),
+    /* 131 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
+    /* 132 */ "SorterData"       OpHelp("r[P2]=data"),
+    /* 133 */ "RowData"          OpHelp("r[P2]=data"),
+    /* 134 */ "Rowid"            OpHelp("r[P2]=rowid"),
+    /* 135 */ "NullRow"          OpHelp(""),
+    /* 136 */ "SeekEnd"          OpHelp(""),
+    /* 137 */ "IdxInsert"        OpHelp("key=r[P2]"),
+    /* 138 */ "SorterInsert"     OpHelp("key=r[P2]"),
+    /* 139 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
+    /* 140 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
+    /* 141 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
+    /* 142 */ "FinishSeek"       OpHelp(""),
+    /* 143 */ "Destroy"          OpHelp(""),
+    /* 144 */ "Clear"            OpHelp(""),
+    /* 145 */ "ResetSorter"      OpHelp(""),
+    /* 146 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
+    /* 147 */ "SqlExec"          OpHelp(""),
+    /* 148 */ "ParseSchema"      OpHelp(""),
+    /* 149 */ "LoadAnalysis"     OpHelp(""),
+    /* 150 */ "DropTable"        OpHelp(""),
+    /* 151 */ "DropIndex"        OpHelp(""),
+    /* 152 */ "DropTrigger"      OpHelp(""),
+    /* 153 */ "Real"             OpHelp("r[P2]=P4"),
+    /* 154 */ "IntegrityCk"      OpHelp(""),
+    /* 155 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
+    /* 156 */ "Param"            OpHelp(""),
+    /* 157 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
+    /* 158 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
+    /* 159 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
+    /* 160 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
+    /* 161 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
+    /* 162 */ "AggStep1"         OpHelp("accum=r[P3] step(r[P2@P5])"),
+    /* 163 */ "AggValue"         OpHelp("r[P3]=value N=P2"),
+    /* 164 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
+    /* 165 */ "Expire"           OpHelp(""),
+    /* 166 */ "CursorLock"       OpHelp(""),
+    /* 167 */ "CursorUnlock"     OpHelp(""),
+    /* 168 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
+    /* 169 */ "VBegin"           OpHelp(""),
+    /* 170 */ "VCreate"          OpHelp(""),
+    /* 171 */ "VDestroy"         OpHelp(""),
+    /* 172 */ "VOpen"            OpHelp(""),
+    /* 173 */ "VInitIn"          OpHelp("r[P2]=ValueList(P1,P3)"),
+    /* 174 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
+    /* 175 */ "VRename"          OpHelp(""),
+    /* 176 */ "Pagecount"        OpHelp(""),
+    /* 177 */ "MaxPgcnt"         OpHelp(""),
+    /* 178 */ "FilterAdd"        OpHelp("filter(P1) += key(P3@P4)"),
+    /* 179 */ "Trace"            OpHelp(""),
+    /* 180 */ "CursorHint"       OpHelp(""),
+    /* 181 */ "ReleaseReg"       OpHelp("release r[P1@P2] mask P3"),
+    /* 182 */ "Noop"             OpHelp(""),
+    /* 183 */ "Explain"          OpHelp(""),
+    /* 184 */ "Abortable"        OpHelp(""),
   };
   return azName[i];
 }
@@ -33961,205 +35081,7 @@ static pid_t randomnessPid = 0;
 /*
 ** Include code that is common to all os_*.c files
 */
-/************** Include os_common.h in the middle of os_unix.c ***************/
-/************** Begin file os_common.h ***************************************/
-/*
-** 2004 May 22
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This file contains macros and a little bit of code that is common to
-** all of the platform-specific files (os_*.c) and is #included into those
-** files.
-**
-** This file should be #included by the os_*.c files only.  It is not a
-** general purpose header file.
-*/
-#ifndef _OS_COMMON_H_
-#define _OS_COMMON_H_
-
-/*
-** At least two bugs have slipped in because we changed the MEMORY_DEBUG
-** macro to SQLITE_DEBUG and some older makefiles have not yet made the
-** switch.  The following code should catch this problem at compile-time.
-*/
-#ifdef MEMORY_DEBUG
-# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
-#endif
-
-/*
-** Macros for performance tracing.  Normally turned off.  Only works
-** on i486 hardware.
-*/
-#ifdef SQLITE_PERFORMANCE_TRACE
-
-/*
-** hwtime.h contains inline assembler code for implementing
-** high-performance timing routines.
-*/
-/************** Include hwtime.h in the middle of os_common.h ****************/
-/************** Begin file hwtime.h ******************************************/
-/*
-** 2008 May 27
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 and x86_64 class CPUs.
-*/
-#ifndef SQLITE_HWTIME_H
-#define SQLITE_HWTIME_H
-
-/*
-** The following routine only works on pentium-class (or newer) processors.
-** It uses the RDTSC opcode to read the cycle count value out of the
-** processor and returns that value.  This can be used for high-res
-** profiling.
-*/
-#if !defined(__STRICT_ANSI__) && \
-    (defined(__GNUC__) || defined(_MSC_VER)) && \
-    (defined(i386) || defined(__i386__) || defined(_M_IX86))
-
-  #if defined(__GNUC__)
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-     unsigned int lo, hi;
-     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
-     return (sqlite_uint64)hi << 32 | lo;
-  }
-
-  #elif defined(_MSC_VER)
-
-  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
-     __asm {
-        rdtsc
-        ret       ; return value at EDX:EAX
-     }
-  }
-
-  #endif
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long val;
-      __asm__ __volatile__ ("rdtsc" : "=A" (val));
-      return val;
-  }
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long long retval;
-      unsigned long junk;
-      __asm__ __volatile__ ("\n\
-          1:      mftbu   %1\n\
-                  mftb    %L0\n\
-                  mftbu   %0\n\
-                  cmpw    %0,%1\n\
-                  bne     1b"
-                  : "=r" (retval), "=r" (junk));
-      return retval;
-  }
-
-#else
-
-  /*
-  ** asm() is needed for hardware timing support.  Without asm(),
-  ** disable the sqlite3Hwtime() routine.
-  **
-  ** sqlite3Hwtime() is only used for some obscure debugging
-  ** and analysis configurations, not in any deliverable, so this
-  ** should not be a great loss.
-  */
-SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
-
-#endif
-
-#endif /* !defined(SQLITE_HWTIME_H) */
-
-/************** End of hwtime.h **********************************************/
-/************** Continuing where we left off in os_common.h ******************/
-
-static sqlite_uint64 g_start;
-static sqlite_uint64 g_elapsed;
-#define TIMER_START       g_start=sqlite3Hwtime()
-#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
-#define TIMER_ELAPSED     g_elapsed
-#else
-#define TIMER_START
-#define TIMER_END
-#define TIMER_ELAPSED     ((sqlite_uint64)0)
-#endif
-
-/*
-** If we compile with the SQLITE_TEST macro set, then the following block
-** of code will give us the ability to simulate a disk I/O error.  This
-** is used for testing the I/O recovery logic.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_io_error_hit;
-SQLITE_API extern int sqlite3_io_error_hardhit;
-SQLITE_API extern int sqlite3_io_error_pending;
-SQLITE_API extern int sqlite3_io_error_persist;
-SQLITE_API extern int sqlite3_io_error_benign;
-SQLITE_API extern int sqlite3_diskfull_pending;
-SQLITE_API extern int sqlite3_diskfull;
-#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
-#define SimulateIOError(CODE)  \
-  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
-       || sqlite3_io_error_pending-- == 1 )  \
-              { local_ioerr(); CODE; }
-static void local_ioerr(){
-  IOTRACE(("IOERR\n"));
-  sqlite3_io_error_hit++;
-  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
-}
-#define SimulateDiskfullError(CODE) \
-   if( sqlite3_diskfull_pending ){ \
-     if( sqlite3_diskfull_pending == 1 ){ \
-       local_ioerr(); \
-       sqlite3_diskfull = 1; \
-       sqlite3_io_error_hit = 1; \
-       CODE; \
-     }else{ \
-       sqlite3_diskfull_pending--; \
-     } \
-   }
-#else
-#define SimulateIOErrorBenign(X)
-#define SimulateIOError(A)
-#define SimulateDiskfullError(A)
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** When testing, keep a count of the number of open files.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_open_file_count;
-#define OpenCounter(X)  sqlite3_open_file_count+=(X)
-#else
-#define OpenCounter(X)
-#endif /* defined(SQLITE_TEST) */
-
-#endif /* !defined(_OS_COMMON_H_) */
-
-/************** End of os_common.h *******************************************/
-/************** Continuing where we left off in os_unix.c ********************/
+/* #include "os_common.h" */
 
 /*
 ** Define various macros that are missing from some systems.
@@ -37813,6 +38735,9 @@ static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
 
 /* Forward declaration */
 static int unixGetTempname(int nBuf, char *zBuf);
+#ifndef SQLITE_OMIT_WAL
+ static int unixFcntlExternalReader(unixFile*, int*);
+#endif
 
 /*
 ** Information and control of an open file handle.
@@ -37929,6 +38854,15 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){
       return proxyFileControl(id,op,pArg);
     }
 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
+
+    case SQLITE_FCNTL_EXTERNAL_READER: {
+#ifndef SQLITE_OMIT_WAL
+      return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
+#else
+      *(int*)pArg = 0;
+      return SQLITE_OK;
+#endif
+    }
   }
   return SQLITE_NOTFOUND;
 }
@@ -38174,6 +39108,40 @@ struct unixShm {
 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
 
+/*
+** Use F_GETLK to check whether or not there are any readers with open
+** wal-mode transactions in other processes on database file pFile. If
+** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
+** such transactions, or 0 otherwise. If an error occurs, return an
+** SQLite error code. The final value of *piOut is undefined in this
+** case.
+*/
+static int unixFcntlExternalReader(unixFile *pFile, int *piOut){
+  int rc = SQLITE_OK;
+  *piOut = 0;
+  if( pFile->pShm){
+    unixShmNode *pShmNode = pFile->pShm->pShmNode;
+    struct flock f;
+
+    memset(&f, 0, sizeof(f));
+    f.l_type = F_WRLCK;
+    f.l_whence = SEEK_SET;
+    f.l_start = UNIX_SHM_BASE + 3;
+    f.l_len = SQLITE_SHM_NLOCK - 3;
+
+    sqlite3_mutex_enter(pShmNode->pShmMutex);
+    if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){
+      rc = SQLITE_IOERR_LOCK;
+    }else{
+      *piOut = (f.l_type!=F_UNLCK);
+    }
+    sqlite3_mutex_leave(pShmNode->pShmMutex);
+  }
+
+  return rc;
+}
+
+
 /*
 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
 **
@@ -38726,11 +39694,17 @@ static int unixShmLock(
   int flags                  /* What to do with the lock */
 ){
   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
-  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
-  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
+  unixShm *p;                           /* The shared memory being locked */
+  unixShmNode *pShmNode;                /* The underlying file iNode */
   int rc = SQLITE_OK;                   /* Result code */
   u16 mask;                             /* Mask of locks to take or release */
-  int *aLock = pShmNode->aLock;
+  int *aLock;
+
+  p = pDbFd->pShm;
+  if( p==0 ) return SQLITE_IOERR_SHMLOCK;
+  pShmNode = p->pShmNode;
+  if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
+  aLock = pShmNode->aLock;
 
   assert( pShmNode==pDbFd->pInode->pShmNode );
   assert( pShmNode->pInode==pDbFd->pInode );
@@ -39614,25 +40588,35 @@ static int fillInUnixFile(
   return rc;
 }
 
+/*
+** Directories to consider for temp files.
+*/
+static const char *azTempDirs[] = {
+  0,
+  0,
+  "/var/tmp",
+  "/usr/tmp",
+  "/tmp",
+  "."
+};
+
+/*
+** Initialize first two members of azTempDirs[] array.
+*/
+static void unixTempFileInit(void){
+  azTempDirs[0] = getenv("SQLITE_TMPDIR");
+  azTempDirs[1] = getenv("TMPDIR");
+}
+
 /*
 ** Return the name of a directory in which to put temporary files.
 ** If no suitable temporary file directory can be found, return NULL.
 */
 static const char *unixTempFileDir(void){
-  static const char *azDirs[] = {
-     0,
-     0,
-     "/var/tmp",
-     "/usr/tmp",
-     "/tmp",
-     "."
-  };
   unsigned int i = 0;
   struct stat buf;
   const char *zDir = sqlite3_temp_directory;
 
-  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
-  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   while(1){
     if( zDir!=0
      && osStat(zDir, &buf)==0
@@ -39641,8 +40625,8 @@ static const char *unixTempFileDir(void){
     ){
       return zDir;
     }
-    if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
-    zDir = azDirs[i++];
+    if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break;
+    zDir = azTempDirs[i++];
   }
   return 0;
 }
@@ -39948,6 +40932,11 @@ static int unixOpen(
   }
   memset(p, 0, sizeof(unixFile));
 
+#ifdef SQLITE_ASSERT_NO_FILES
+  /* Applications that never read or write a persistent disk files */
+  assert( zName==0 );
+#endif
+
   if( eType==SQLITE_OPEN_MAIN_DB ){
     UnixUnusedFd *pUnused;
     pUnused = findReusableFd(zName, flags);
@@ -41890,6 +42879,28 @@ SQLITE_API int sqlite3_os_init(void){
     sqlite3_vfs_register(&aVfs[i], i==0);
   }
   unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
+
+#ifndef SQLITE_OMIT_WAL
+  /* Validate lock assumptions */
+  assert( SQLITE_SHM_NLOCK==8 );  /* Number of available locks */
+  assert( UNIX_SHM_BASE==120  );  /* Start of locking area */
+  /* Locks:
+  **    WRITE       UNIX_SHM_BASE      120
+  **    CKPT        UNIX_SHM_BASE+1    121
+  **    RECOVER     UNIX_SHM_BASE+2    122
+  **    READ-0      UNIX_SHM_BASE+3    123
+  **    READ-1      UNIX_SHM_BASE+4    124
+  **    READ-2      UNIX_SHM_BASE+5    125
+  **    READ-3      UNIX_SHM_BASE+6    126
+  **    READ-4      UNIX_SHM_BASE+7    127
+  **    DMS         UNIX_SHM_BASE+8    128
+  */
+  assert( UNIX_SHM_DMS==128   );  /* Byte offset of the deadman-switch */
+#endif
+
+  /* Initialize temp file dir array. */
+  unixTempFileInit();
+
   return SQLITE_OK;
 }
 
@@ -41929,205 +42940,7 @@ SQLITE_API int sqlite3_os_end(void){
 /*
 ** Include code that is common to all os_*.c files
 */
-/************** Include os_common.h in the middle of os_win.c ****************/
-/************** Begin file os_common.h ***************************************/
-/*
-** 2004 May 22
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This file contains macros and a little bit of code that is common to
-** all of the platform-specific files (os_*.c) and is #included into those
-** files.
-**
-** This file should be #included by the os_*.c files only.  It is not a
-** general purpose header file.
-*/
-#ifndef _OS_COMMON_H_
-#define _OS_COMMON_H_
-
-/*
-** At least two bugs have slipped in because we changed the MEMORY_DEBUG
-** macro to SQLITE_DEBUG and some older makefiles have not yet made the
-** switch.  The following code should catch this problem at compile-time.
-*/
-#ifdef MEMORY_DEBUG
-# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
-#endif
-
-/*
-** Macros for performance tracing.  Normally turned off.  Only works
-** on i486 hardware.
-*/
-#ifdef SQLITE_PERFORMANCE_TRACE
-
-/*
-** hwtime.h contains inline assembler code for implementing
-** high-performance timing routines.
-*/
-/************** Include hwtime.h in the middle of os_common.h ****************/
-/************** Begin file hwtime.h ******************************************/
-/*
-** 2008 May 27
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 and x86_64 class CPUs.
-*/
-#ifndef SQLITE_HWTIME_H
-#define SQLITE_HWTIME_H
-
-/*
-** The following routine only works on pentium-class (or newer) processors.
-** It uses the RDTSC opcode to read the cycle count value out of the
-** processor and returns that value.  This can be used for high-res
-** profiling.
-*/
-#if !defined(__STRICT_ANSI__) && \
-    (defined(__GNUC__) || defined(_MSC_VER)) && \
-    (defined(i386) || defined(__i386__) || defined(_M_IX86))
-
-  #if defined(__GNUC__)
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-     unsigned int lo, hi;
-     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
-     return (sqlite_uint64)hi << 32 | lo;
-  }
-
-  #elif defined(_MSC_VER)
-
-  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
-     __asm {
-        rdtsc
-        ret       ; return value at EDX:EAX
-     }
-  }
-
-  #endif
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long val;
-      __asm__ __volatile__ ("rdtsc" : "=A" (val));
-      return val;
-  }
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long long retval;
-      unsigned long junk;
-      __asm__ __volatile__ ("\n\
-          1:      mftbu   %1\n\
-                  mftb    %L0\n\
-                  mftbu   %0\n\
-                  cmpw    %0,%1\n\
-                  bne     1b"
-                  : "=r" (retval), "=r" (junk));
-      return retval;
-  }
-
-#else
-
-  /*
-  ** asm() is needed for hardware timing support.  Without asm(),
-  ** disable the sqlite3Hwtime() routine.
-  **
-  ** sqlite3Hwtime() is only used for some obscure debugging
-  ** and analysis configurations, not in any deliverable, so this
-  ** should not be a great loss.
-  */
-SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
-
-#endif
-
-#endif /* !defined(SQLITE_HWTIME_H) */
-
-/************** End of hwtime.h **********************************************/
-/************** Continuing where we left off in os_common.h ******************/
-
-static sqlite_uint64 g_start;
-static sqlite_uint64 g_elapsed;
-#define TIMER_START       g_start=sqlite3Hwtime()
-#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
-#define TIMER_ELAPSED     g_elapsed
-#else
-#define TIMER_START
-#define TIMER_END
-#define TIMER_ELAPSED     ((sqlite_uint64)0)
-#endif
-
-/*
-** If we compile with the SQLITE_TEST macro set, then the following block
-** of code will give us the ability to simulate a disk I/O error.  This
-** is used for testing the I/O recovery logic.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_io_error_hit;
-SQLITE_API extern int sqlite3_io_error_hardhit;
-SQLITE_API extern int sqlite3_io_error_pending;
-SQLITE_API extern int sqlite3_io_error_persist;
-SQLITE_API extern int sqlite3_io_error_benign;
-SQLITE_API extern int sqlite3_diskfull_pending;
-SQLITE_API extern int sqlite3_diskfull;
-#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
-#define SimulateIOError(CODE)  \
-  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
-       || sqlite3_io_error_pending-- == 1 )  \
-              { local_ioerr(); CODE; }
-static void local_ioerr(){
-  IOTRACE(("IOERR\n"));
-  sqlite3_io_error_hit++;
-  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
-}
-#define SimulateDiskfullError(CODE) \
-   if( sqlite3_diskfull_pending ){ \
-     if( sqlite3_diskfull_pending == 1 ){ \
-       local_ioerr(); \
-       sqlite3_diskfull = 1; \
-       sqlite3_io_error_hit = 1; \
-       CODE; \
-     }else{ \
-       sqlite3_diskfull_pending--; \
-     } \
-   }
-#else
-#define SimulateIOErrorBenign(X)
-#define SimulateIOError(A)
-#define SimulateDiskfullError(A)
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** When testing, keep a count of the number of open files.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_open_file_count;
-#define OpenCounter(X)  sqlite3_open_file_count+=(X)
-#else
-#define OpenCounter(X)
-#endif /* defined(SQLITE_TEST) */
-
-#endif /* !defined(_OS_COMMON_H_) */
-
-/************** End of os_common.h *******************************************/
-/************** Continuing where we left off in os_win.c *********************/
+/* #include "os_common.h" */
 
 /*
 ** Include the header file for the Windows VFS.
@@ -46179,10 +46992,14 @@ static int winShmLock(
   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
   winShm *pX;                           /* For looping over all siblings */
-  winShmNode *pShmNode = p->pShmNode;
+  winShmNode *pShmNode;
   int rc = SQLITE_OK;                   /* Result code */
   u16 mask;                             /* Mask of locks to take or release */
 
+  if( p==0 ) return SQLITE_IOERR_SHMLOCK;
+  pShmNode = p->pShmNode;
+  if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
+
   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   assert( n>=1 );
   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
@@ -48283,31 +49100,88 @@ SQLITE_API int sqlite3_os_end(void){
 ** sqlite3_deserialize().
 */
 /* #include "sqliteInt.h" */
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
 
 /*
 ** Forward declaration of objects used by this utility
 */
 typedef struct sqlite3_vfs MemVfs;
 typedef struct MemFile MemFile;
+typedef struct MemStore MemStore;
 
 /* Access to a lower-level VFS that (might) implement dynamic loading,
 ** access to randomness, etc.
 */
 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
 
-/* An open file */
-struct MemFile {
-  sqlite3_file base;              /* IO methods */
+/* Storage for a memdb file.
+**
+** An memdb object can be shared or separate.  Shared memdb objects can be
+** used by more than one database connection.  Mutexes are used by shared
+** memdb objects to coordinate access.  Separate memdb objects are only
+** connected to a single database connection and do not require additional
+** mutexes.
+**
+** Shared memdb objects have .zFName!=0 and .pMutex!=0.  They are created
+** using "file:/name?vfs=memdb".  The first character of the name must be
+** "/" or else the object will be a separate memdb object.  All shared
+** memdb objects are stored in memdb_g.apMemStore[] in an arbitrary order.
+**
+** Separate memdb objects are created using a name that does not begin
+** with "/" or using sqlite3_deserialize().
+**
+** Access rules for shared MemStore objects:
+**
+**   *  .zFName is initialized when the object is created and afterwards
+**      is unchanged until the object is destroyed.  So it can be accessed
+**      at any time as long as we know the object is not being destroyed,
+**      which means while either the SQLITE_MUTEX_STATIC_VFS1 or
+**      .pMutex is held or the object is not part of memdb_g.apMemStore[].
+**
+**   *  Can .pMutex can only be changed while holding the
+**      SQLITE_MUTEX_STATIC_VFS1 mutex or while the object is not part
+**      of memdb_g.apMemStore[].
+**
+**   *  Other fields can only be changed while holding the .pMutex mutex
+**      or when the .nRef is less than zero and the object is not part of
+**      memdb_g.apMemStore[].
+**
+**   *  The .aData pointer has the added requirement that it can can only
+**      be changed (for resizing) when nMmap is zero.
+**
+*/
+struct MemStore {
   sqlite3_int64 sz;               /* Size of the file */
   sqlite3_int64 szAlloc;          /* Space allocated to aData */
   sqlite3_int64 szMax;            /* Maximum allowed size of the file */
   unsigned char *aData;           /* content of the file */
+  sqlite3_mutex *pMutex;          /* Used by shared stores only */
   int nMmap;                      /* Number of memory mapped pages */
   unsigned mFlags;                /* Flags */
+  int nRdLock;                    /* Number of readers */
+  int nWrLock;                    /* Number of writers.  (Always 0 or 1) */
+  int nRef;                       /* Number of users of this MemStore */
+  char *zFName;                   /* The filename for shared stores */
+};
+
+/* An open file */
+struct MemFile {
+  sqlite3_file base;              /* IO methods */
+  MemStore *pStore;               /* The storage */
   int eLock;                      /* Most recent lock against this file */
 };
 
+/*
+** File-scope variables for holding the memdb files that are accessible
+** to multiple database connections in separate threads.
+**
+** Must hold SQLITE_MUTEX_STATIC_VFS1 to access any part of this object.
+*/
+static struct MemFS {
+  int nMemStore;                  /* Number of shared MemStore objects */
+  MemStore **apMemStore;          /* Array of all shared MemStore objects */
+} memdb_g;
+
 /*
 ** Methods for MemFile
 */
@@ -48361,7 +49235,10 @@ static sqlite3_vfs memdb_vfs = {
   memdbSleep,                  /* xSleep */
   0, /* memdbCurrentTime, */   /* xCurrentTime */
   memdbGetLastError,           /* xGetLastError */
-  memdbCurrentTimeInt64        /* xCurrentTimeInt64 */
+  memdbCurrentTimeInt64,       /* xCurrentTimeInt64 */
+  0,                           /* xSetSystemCall */
+  0,                           /* xGetSystemCall */
+  0,                           /* xNextSystemCall */
 };
 
 static const sqlite3_io_methods memdb_io_methods = {
@@ -48386,19 +49263,67 @@ static const sqlite3_io_methods memdb_io_methods = {
   memdbUnfetch                     /* xUnfetch */
 };
 
+/*
+** Enter/leave the mutex on a MemStore
+*/
+#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
+static void memdbEnter(MemStore *p){
+  UNUSED_PARAMETER(p);
+}
+static void memdbLeave(MemStore *p){
+  UNUSED_PARAMETER(p);
+}
+#else
+static void memdbEnter(MemStore *p){
+  sqlite3_mutex_enter(p->pMutex);
+}
+static void memdbLeave(MemStore *p){
+  sqlite3_mutex_leave(p->pMutex);
+}
+#endif
+
 
 
 /*
 ** Close an memdb-file.
-**
-** The pData pointer is owned by the application, so there is nothing
-** to free.  Unless the SQLITE_DESERIALIZE_FREEONCLOSE flag is set,
-** in which case we own the pData pointer and need to free it.
+** Free the underlying MemStore object when its refcount drops to zero
+** or less.
 */
 static int memdbClose(sqlite3_file *pFile){
-  MemFile *p = (MemFile *)pFile;
-  if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ){
-    sqlite3_free(p->aData);
+  MemStore *p = ((MemFile*)pFile)->pStore;
+  if( p->zFName ){
+    int i;
+#ifndef SQLITE_MUTEX_OMIT
+    sqlite3_mutex *pVfsMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
+#endif
+    sqlite3_mutex_enter(pVfsMutex);
+    for(i=0; ALWAYS(i<memdb_g.nMemStore); i++){
+      if( memdb_g.apMemStore[i]==p ){
+        memdbEnter(p);
+        if( p->nRef==1 ){
+          memdb_g.apMemStore[i] = memdb_g.apMemStore[--memdb_g.nMemStore];
+          if( memdb_g.nMemStore==0 ){
+            sqlite3_free(memdb_g.apMemStore);
+            memdb_g.apMemStore = 0;
+          }
+        }
+        break;
+      }
+    }
+    sqlite3_mutex_leave(pVfsMutex);
+  }else{
+    memdbEnter(p);
+  }
+  p->nRef--;
+  if( p->nRef<=0 ){
+    if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ){
+      sqlite3_free(p->aData);
+    }
+    memdbLeave(p);
+    sqlite3_mutex_free(p->pMutex);
+    sqlite3_free(p);
+  }else{
+    memdbLeave(p);
   }
   return SQLITE_OK;
 }
@@ -48412,22 +49337,25 @@ static int memdbRead(
   int iAmt,
   sqlite_int64 iOfst
 ){
-  MemFile *p = (MemFile *)pFile;
+  MemStore *p = ((MemFile*)pFile)->pStore;
+  memdbEnter(p);
   if( iOfst+iAmt>p->sz ){
     memset(zBuf, 0, iAmt);
     if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
+    memdbLeave(p);
     return SQLITE_IOERR_SHORT_READ;
   }
   memcpy(zBuf, p->aData+iOfst, iAmt);
+  memdbLeave(p);
   return SQLITE_OK;
 }
 
 /*
 ** Try to enlarge the memory allocation to hold at least sz bytes
 */
-static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
+static int memdbEnlarge(MemStore *p, sqlite3_int64 newSz){
   unsigned char *pNew;
-  if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
+  if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || NEVER(p->nMmap>0) ){
     return SQLITE_FULL;
   }
   if( newSz>p->szMax ){
@@ -48436,7 +49364,7 @@ static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
   newSz *= 2;
   if( newSz>p->szMax ) newSz = p->szMax;
   pNew = sqlite3Realloc(p->aData, newSz);
-  if( pNew==0 ) return SQLITE_NOMEM;
+  if( pNew==0 ) return SQLITE_IOERR_NOMEM;
   p->aData = pNew;
   p->szAlloc = newSz;
   return SQLITE_OK;
@@ -48451,19 +49379,27 @@ static int memdbWrite(
   int iAmt,
   sqlite_int64 iOfst
 ){
-  MemFile *p = (MemFile *)pFile;
-  if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;
+  MemStore *p = ((MemFile*)pFile)->pStore;
+  memdbEnter(p);
+  if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ){
+    /* Can't happen: memdbLock() will return SQLITE_READONLY before
+    ** reaching this point */
+    memdbLeave(p);
+    return SQLITE_IOERR_WRITE;
+  }
   if( iOfst+iAmt>p->sz ){
     int rc;
     if( iOfst+iAmt>p->szAlloc
      && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
     ){
+      memdbLeave(p);
       return rc;
     }
     if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
     p->sz = iOfst+iAmt;
   }
   memcpy(p->aData+iOfst, z, iAmt);
+  memdbLeave(p);
   return SQLITE_OK;
 }
 
@@ -48475,16 +49411,25 @@ static int memdbWrite(
 ** the size of a file, never to increase the size.
 */
 static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
-  MemFile *p = (MemFile *)pFile;
-  if( NEVER(size>p->sz) ) return SQLITE_FULL;
-  p->sz = size;
-  return SQLITE_OK;
+  MemStore *p = ((MemFile*)pFile)->pStore;
+  int rc = SQLITE_OK;
+  memdbEnter(p);
+  if( size>p->sz ){
+    /* This can only happen with a corrupt wal mode db */
+    rc = SQLITE_CORRUPT;
+  }else{
+    p->sz = size;
+  }
+  memdbLeave(p);
+  return rc;
 }
 
 /*
 ** Sync an memdb-file.
 */
 static int memdbSync(sqlite3_file *pFile, int flags){
+  UNUSED_PARAMETER(pFile);
+  UNUSED_PARAMETER(flags);
   return SQLITE_OK;
 }
 
@@ -48492,8 +49437,10 @@ static int memdbSync(sqlite3_file *pFile, int flags){
 ** Return the current file-size of an memdb-file.
 */
 static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
-  MemFile *p = (MemFile *)pFile;
+  MemStore *p = ((MemFile*)pFile)->pStore;
+  memdbEnter(p);
   *pSize = p->sz;
+  memdbLeave(p);
   return SQLITE_OK;
 }
 
@@ -48501,19 +49448,48 @@ static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
 ** Lock an memdb-file.
 */
 static int memdbLock(sqlite3_file *pFile, int eLock){
-  MemFile *p = (MemFile *)pFile;
-  if( eLock>SQLITE_LOCK_SHARED
-   && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
-  ){
-    return SQLITE_READONLY;
+  MemFile *pThis = (MemFile*)pFile;
+  MemStore *p = pThis->pStore;
+  int rc = SQLITE_OK;
+  if( eLock==pThis->eLock ) return SQLITE_OK;
+  memdbEnter(p);
+  if( eLock>SQLITE_LOCK_SHARED ){
+    if( p->mFlags & SQLITE_DESERIALIZE_READONLY ){
+      rc = SQLITE_READONLY;
+    }else if( pThis->eLock<=SQLITE_LOCK_SHARED ){
+      if( p->nWrLock ){
+        rc = SQLITE_BUSY;
+      }else{
+        p->nWrLock = 1;
+      }
+    }
+  }else if( eLock==SQLITE_LOCK_SHARED ){
+    if( pThis->eLock > SQLITE_LOCK_SHARED ){
+      assert( p->nWrLock==1 );
+      p->nWrLock = 0;
+    }else if( p->nWrLock ){
+      rc = SQLITE_BUSY;
+    }else{
+      p->nRdLock++;
+    }
+  }else{
+    assert( eLock==SQLITE_LOCK_NONE );
+    if( pThis->eLock>SQLITE_LOCK_SHARED ){
+      assert( p->nWrLock==1 );
+      p->nWrLock = 0;
+    }
+    assert( p->nRdLock>0 );
+    p->nRdLock--;
   }
-  p->eLock = eLock;
-  return SQLITE_OK;
+  if( rc==SQLITE_OK ) pThis->eLock = eLock;
+  memdbLeave(p);
+  return rc;
 }
 
-#if 0 /* Never used because memdbAccess() always returns false */
+#if 0
 /*
-** Check if another file-handle holds a RESERVED lock on an memdb-file.
+** This interface is only used for crash recovery, which does not
+** occur on an in-memory database.
 */
 static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
   *pResOut = 0;
@@ -48521,12 +49497,14 @@ static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
 }
 #endif
 
+
 /*
 ** File control method. For custom operations on an memdb-file.
 */
 static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
-  MemFile *p = (MemFile *)pFile;
+  MemStore *p = ((MemFile*)pFile)->pStore;
   int rc = SQLITE_NOTFOUND;
+  memdbEnter(p);
   if( op==SQLITE_FCNTL_VFSNAME ){
     *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
     rc = SQLITE_OK;
@@ -48544,6 +49522,7 @@ static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
     *(sqlite3_int64*)pArg = iLimit;
     rc = SQLITE_OK;
   }
+  memdbLeave(p);
   return rc;
 }
 
@@ -48560,6 +49539,7 @@ static int memdbSectorSize(sqlite3_file *pFile){
 ** Return the device characteristic flags supported by an memdb-file.
 */
 static int memdbDeviceCharacteristics(sqlite3_file *pFile){
+  UNUSED_PARAMETER(pFile);
   return SQLITE_IOCAP_ATOMIC |
          SQLITE_IOCAP_POWERSAFE_OVERWRITE |
          SQLITE_IOCAP_SAFE_APPEND |
@@ -48573,20 +49553,26 @@ static int memdbFetch(
   int iAmt,
   void **pp
 ){
-  MemFile *p = (MemFile *)pFile;
-  if( iOfst+iAmt>p->sz ){
+  MemStore *p = ((MemFile*)pFile)->pStore;
+  memdbEnter(p);
+  if( iOfst+iAmt>p->sz || (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)!=0 ){
     *pp = 0;
   }else{
     p->nMmap++;
     *pp = (void*)(p->aData + iOfst);
   }
+  memdbLeave(p);
   return SQLITE_OK;
 }
 
 /* Release a memory-mapped page */
 static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
-  MemFile *p = (MemFile *)pFile;
+  MemStore *p = ((MemFile*)pFile)->pStore;
+  UNUSED_PARAMETER(iOfst);
+  UNUSED_PARAMETER(pPage);
+  memdbEnter(p);
   p->nMmap--;
+  memdbLeave(p);
   return SQLITE_OK;
 }
 
@@ -48596,20 +49582,79 @@ static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
 static int memdbOpen(
   sqlite3_vfs *pVfs,
   const char *zName,
-  sqlite3_file *pFile,
+  sqlite3_file *pFd,
   int flags,
   int *pOutFlags
 ){
-  MemFile *p = (MemFile*)pFile;
-  if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
-    return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
+  MemFile *pFile = (MemFile*)pFd;
+  MemStore *p = 0;
+  int szName;
+  UNUSED_PARAMETER(pVfs);
+
+  memset(pFile, 0, sizeof(*pFile));
+  szName = sqlite3Strlen30(zName);
+  if( szName>1 && zName[0]=='/' ){
+    int i;
+#ifndef SQLITE_MUTEX_OMIT
+    sqlite3_mutex *pVfsMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
+#endif
+    sqlite3_mutex_enter(pVfsMutex);
+    for(i=0; i<memdb_g.nMemStore; i++){
+      if( strcmp(memdb_g.apMemStore[i]->zFName,zName)==0 ){
+        p = memdb_g.apMemStore[i];
+        break;
+      }
+    }
+    if( p==0 ){
+      MemStore **apNew;
+      p = sqlite3Malloc( sizeof(*p) + szName + 3 );
+      if( p==0 ){
+        sqlite3_mutex_leave(pVfsMutex);
+        return SQLITE_NOMEM;
+      }
+      apNew = sqlite3Realloc(memdb_g.apMemStore,
+                             sizeof(apNew[0])*(memdb_g.nMemStore+1) );
+      if( apNew==0 ){
+        sqlite3_free(p);
+        sqlite3_mutex_leave(pVfsMutex);
+        return SQLITE_NOMEM;
+      }
+      apNew[memdb_g.nMemStore++] = p;
+      memdb_g.apMemStore = apNew;
+      memset(p, 0, sizeof(*p));
+      p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE|SQLITE_DESERIALIZE_FREEONCLOSE;
+      p->szMax = sqlite3GlobalConfig.mxMemdbSize;
+      p->zFName = (char*)&p[1];
+      memcpy(p->zFName, zName, szName+1);
+      p->pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
+      if( p->pMutex==0 ){
+        memdb_g.nMemStore--;
+        sqlite3_free(p);
+        sqlite3_mutex_leave(pVfsMutex);
+        return SQLITE_NOMEM;
+      }
+      p->nRef = 1;
+      memdbEnter(p);
+    }else{
+      memdbEnter(p);
+      p->nRef++;
+    }
+    sqlite3_mutex_leave(pVfsMutex);
+  }else{
+    p = sqlite3Malloc( sizeof(*p) );
+    if( p==0 ){
+      return SQLITE_NOMEM;
+    }
+    memset(p, 0, sizeof(*p));
+    p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
+    p->szMax = sqlite3GlobalConfig.mxMemdbSize;
   }
-  memset(p, 0, sizeof(*p));
-  p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
-  assert( pOutFlags!=0 );  /* True because flags==SQLITE_OPEN_MAIN_DB */
-  *pOutFlags = flags | SQLITE_OPEN_MEMORY;
-  pFile->pMethods = &memdb_io_methods;
-  p->szMax = sqlite3GlobalConfig.mxMemdbSize;
+  pFile->pStore = p;
+  if( pOutFlags!=0 ){
+    *pOutFlags = flags | SQLITE_OPEN_MEMORY;
+  }
+  pFd->pMethods = &memdb_io_methods;
+  memdbLeave(p);
   return SQLITE_OK;
 }
 
@@ -48637,6 +49682,9 @@ static int memdbAccess(
   int flags,
   int *pResOut
 ){
+  UNUSED_PARAMETER(pVfs);
+  UNUSED_PARAMETER(zPath);
+  UNUSED_PARAMETER(flags);
   *pResOut = 0;
   return SQLITE_OK;
 }
@@ -48652,6 +49700,7 @@ static int memdbFullPathname(
   int nOut,
   char *zOut
 ){
+  UNUSED_PARAMETER(pVfs);
   sqlite3_snprintf(nOut, zOut, "%s", zPath);
   return SQLITE_OK;
 }
@@ -48724,9 +49773,14 @@ static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
 */
 static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
   MemFile *p = 0;
+  MemStore *pStore;
   int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
   if( rc ) return 0;
   if( p->base.pMethods!=&memdb_io_methods ) return 0;
+  pStore = p->pStore;
+  memdbEnter(pStore);
+  if( pStore->zFName!=0 ) p = 0;
+  memdbLeave(pStore);
   return p;
 }
 
@@ -48762,12 +49816,14 @@ SQLITE_API unsigned char *sqlite3_serialize(
   if( piSize ) *piSize = -1;
   if( iDb<0 ) return 0;
   if( p ){
-    if( piSize ) *piSize = p->sz;
+    MemStore *pStore = p->pStore;
+    assert( pStore->pMutex==0 );
+    if( piSize ) *piSize = pStore->sz;
     if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
-      pOut = p->aData;
+      pOut = pStore->aData;
     }else{
-      pOut = sqlite3_malloc64( p->sz );
-      if( pOut ) memcpy(pOut, p->aData, p->sz);
+      pOut = sqlite3_malloc64( pStore->sz );
+      if( pOut ) memcpy(pOut, pStore->aData, pStore->sz);
     }
     return pOut;
   }
@@ -48837,7 +49893,8 @@ SQLITE_API int sqlite3_deserialize(
   sqlite3_mutex_enter(db->mutex);
   if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
   iDb = sqlite3FindDbName(db, zSchema);
-  if( iDb<0 ){
+  testcase( iDb==1 );
+  if( iDb<2 && iDb!=0 ){
     rc = SQLITE_ERROR;
     goto end_deserialize;
   }
@@ -48861,15 +49918,16 @@ SQLITE_API int sqlite3_deserialize(
   if( p==0 ){
     rc = SQLITE_ERROR;
   }else{
-    p->aData = pData;
+    MemStore *pStore = p->pStore;
+    pStore->aData = pData;
     pData = 0;
-    p->sz = szDb;
-    p->szAlloc = szBuf;
-    p->szMax = szBuf;
-    if( p->szMax<sqlite3GlobalConfig.mxMemdbSize ){
-      p->szMax = sqlite3GlobalConfig.mxMemdbSize;
+    pStore->sz = szDb;
+    pStore->szAlloc = szBuf;
+    pStore->szMax = szBuf;
+    if( pStore->szMax<sqlite3GlobalConfig.mxMemdbSize ){
+      pStore->szMax = sqlite3GlobalConfig.mxMemdbSize;
     }
-    p->mFlags = mFlags;
+    pStore->mFlags = mFlags;
     rc = SQLITE_OK;
   }
 
@@ -48888,7 +49946,9 @@ end_deserialize:
 */
 SQLITE_PRIVATE int sqlite3MemdbInit(void){
   sqlite3_vfs *pLower = sqlite3_vfs_find(0);
-  int sz = pLower->szOsFile;
+  unsigned int sz;
+  if( NEVER(pLower==0) ) return SQLITE_ERROR;
+  sz = pLower->szOsFile;
   memdb_vfs.pAppData = pLower;
   /* The following conditional can only be true when compiled for
   ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0.  We always leave
@@ -48898,7 +49958,7 @@ SQLITE_PRIVATE int sqlite3MemdbInit(void){
   memdb_vfs.szOsFile = sz;
   return sqlite3_vfs_register(&memdb_vfs, 0);
 }
-#endif /* SQLITE_ENABLE_DESERIALIZE */
+#endif /* SQLITE_OMIT_DESERIALIZE */
 
 /************** End of memdb.c ***********************************************/
 /************** Begin file bitvec.c ******************************************/
@@ -49257,7 +50317,7 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   sqlite3BitvecClear(0, 1, pTmpSpace);
 
   /* Run the program */
-  pc = 0;
+  pc = i = 0;
   while( (op = aOp[pc])!=0 ){
     switch( op ){
       case 1:
@@ -49561,11 +50621,14 @@ static int numberOfCachePages(PCache *p){
     ** suggested cache size is set to N. */
     return p->szCache;
   }else{
+    i64 n;
     /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the
     ** number of cache pages is adjusted to be a number of pages that would
     ** use approximately abs(N*1024) bytes of memory based on the current
     ** page size. */
-    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
+    n = ((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
+    if( n>1000000000 ) n = 1000000000;
+    return (int)n;
   }
 }
 
@@ -49866,7 +50929,8 @@ SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
 ** make it so.
 */
 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
-  assert( p->nRef>0 );
+  assert( p->nRef>0 || p->pCache->bPurgeable==0 );
+  testcase( p->nRef==0 );
   assert( sqlite3PcachePageSanity(p) );
   if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
     p->flags &= ~PGHDR_DONT_WRITE;
@@ -51020,12 +52084,18 @@ static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
 */
 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   PCache1 *pCache = (PCache1 *)p;
+  u32 n;
+  assert( nMax>=0 );
   if( pCache->bPurgeable ){
     PGroup *pGroup = pCache->pGroup;
     pcache1EnterMutex(pGroup);
-    pGroup->nMaxPage += (nMax - pCache->nMax);
+    n = (u32)nMax;
+    if( n > 0x7fff0000 - pGroup->nMaxPage + pCache->nMax ){
+      n = 0x7fff0000 - pGroup->nMaxPage + pCache->nMax;
+    }
+    pGroup->nMaxPage += (n - pCache->nMax);
     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
-    pCache->nMax = nMax;
+    pCache->nMax = n;
     pCache->n90pct = pCache->nMax*9/10;
     pcache1EnforceMaxPage(pCache);
     pcache1LeaveMutex(pGroup);
@@ -51041,7 +52111,7 @@ static void pcache1Shrink(sqlite3_pcache *p){
   PCache1 *pCache = (PCache1*)p;
   if( pCache->bPurgeable ){
     PGroup *pGroup = pCache->pGroup;
-    int savedMaxPage;
+    unsigned int savedMaxPage;
     pcache1EnterMutex(pGroup);
     savedMaxPage = pGroup->nMaxPage;
     pGroup->nMaxPage = 0;
@@ -52778,6 +53848,7 @@ struct Pager {
   u8 noLock;                  /* Do not lock (except in WAL mode) */
   u8 readOnly;                /* True for a read-only database */
   u8 memDb;                   /* True to inhibit all file I/O */
+  u8 memVfs;                  /* VFS-implemented memory database */
 
   /**************************************************************************
   ** The following block contains those class members that change during
@@ -52827,8 +53898,8 @@ struct Pager {
   i16 nReserve;               /* Number of unused bytes at end of each page */
   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   u32 sectorSize;             /* Assumed sector size during rollback */
-  int pageSize;               /* Number of bytes in a page */
   Pgno mxPgno;                /* Maximum allowed size of the database */
+  i64 pageSize;               /* Number of bytes in a page */
   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   char *zFilename;            /* Name of the database file */
   char *zJournal;             /* Name of the journal file */
@@ -54991,6 +56062,9 @@ static int pager_playback(Pager *pPager, int isHot){
         goto end_playback;
       }
       pPager->dbSize = mxPg;
+      if( pPager->mxPgno<mxPg ){
+        pPager->mxPgno = mxPg;
+      }
     }
 
     /* Copy original pages out of the journal and back into the
@@ -55172,6 +56246,7 @@ static int readDbPage(PgHdr *pPg){
 */
 static void pager_write_changecounter(PgHdr *pPg){
   u32 change_counter;
+  if( NEVER(pPg==0) ) return;
 
   /* Increment the value just read and write it back to byte 24. */
   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
@@ -56046,8 +57121,7 @@ static int pager_wait_on_lock(Pager *pPager, int locktype){
 **      current database image, in pages, OR
 **
 **   b) if the page content were written at this time, it would not
-**      be necessary to write the current content out to the sub-journal
-**      (as determined by function subjRequiresPage()).
+**      be necessary to write the current content out to the sub-journal.
 **
 ** If the condition asserted by this function were not true, and the
 ** dirty page were to be discarded from the cache via the pagerStress()
@@ -56062,8 +57136,16 @@ static int pager_wait_on_lock(Pager *pPager, int locktype){
 */
 #if defined(SQLITE_DEBUG)
 static void assertTruncateConstraintCb(PgHdr *pPg){
+  Pager *pPager = pPg->pPager;
   assert( pPg->flags&PGHDR_DIRTY );
-  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
+  if( pPg->pgno>pPager->dbSize ){      /* if (a) is false */
+    Pgno pgno = pPg->pgno;
+    int i;
+    for(i=0; i<pPg->pPager->nSavepoint; i++){
+      PagerSavepoint *p = &pPager->aSavepoint[i];
+      assert( p->nOrig<pgno || sqlite3BitvecTestNotNull(p->pInSavepoint,pgno) );
+    }
+  }
 }
 static void assertTruncateConstraint(Pager *pPager){
   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
@@ -56084,7 +57166,7 @@ static void assertTruncateConstraint(Pager *pPager){
 ** then continue writing to the database.
 */
 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
-  assert( pPager->dbSize>=nPage );
+  assert( pPager->dbSize>=nPage || CORRUPT_DB );
   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   pPager->dbSize = nPage;
 
@@ -56812,7 +57894,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
   int rc = SQLITE_OK;      /* Return code */
   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   int memDb = 0;           /* True if this is an in-memory file */
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
   int memJM = 0;           /* Memory journal mode */
 #else
 # define memJM 0
@@ -57005,6 +58087,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
     pPager->zWal = 0;
   }
 #endif
+  (void)pPtr;  /* Suppress warning about unused pPtr value */
 
   if( nPathname ) sqlite3DbFree(0, zPathname);
   pPager->pVfs = pVfs;
@@ -57016,8 +58099,8 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
     int fout = 0;                    /* VFS flags returned by xOpen() */
     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
     assert( !memDb );
-#ifdef SQLITE_ENABLE_DESERIALIZE
-    memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
+#ifndef SQLITE_OMIT_DESERIALIZE
+    pPager->memVfs = memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
 #endif
     readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
 
@@ -57402,7 +58485,7 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
       ** may mean that the pager was in the error-state when this
       ** function was called and the journal file does not exist.
       */
-      if( !isOpen(pPager->jfd) ){
+      if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
         sqlite3_vfs * const pVfs = pPager->pVfs;
         int bExists;              /* True if journal file exists */
         rc = sqlite3OsAccess(
@@ -57804,6 +58887,7 @@ SQLITE_PRIVATE int sqlite3PagerGet(
   DbPage **ppPage,    /* Write a pointer to the page here */
   int flags           /* PAGER_GET_XXX flags */
 ){
+  /* printf("PAGE %u\n", pgno); fflush(stdout); */
   return pPager->xGet(pPager, pgno, ppPage, flags);
 }
 
@@ -57984,7 +59068,7 @@ SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory
   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
   pPager->subjInMemory = (u8)subjInMemory;
 
-  if( ALWAYS(pPager->eState==PAGER_READER) ){
+  if( pPager->eState==PAGER_READER ){
     assert( pPager->pInJournal==0 );
 
     if( pagerUseWal(pPager) ){
@@ -58884,8 +59968,8 @@ SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
 ** used by the pager and its associated cache.
 */
 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
-  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
-                                     + 5*sizeof(void*);
+  int perPageSize = pPager->pageSize + pPager->nExtra
+    + (int)(sizeof(PgHdr) + 5*sizeof(void*));
   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
            + sqlite3MallocSize(pPager)
            + pPager->pageSize;
@@ -58954,7 +60038,7 @@ SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, i
 ** Return true if this is an in-memory or temp-file backed pager.
 */
 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
-  return pPager->tempFile;
+  return pPager->tempFile || pPager->memVfs;
 }
 
 /*
@@ -59079,14 +60163,14 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
     }
     pPager->nSavepoint = nNew;
 
-    /* If this is a release of the outermost savepoint, truncate
-    ** the sub-journal to zero bytes in size. */
+    /* Truncate the sub-journal so that it only includes the parts
+    ** that are still in use. */
     if( op==SAVEPOINT_RELEASE ){
       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) ){
-          i64 sz = (pPager->pageSize+4)*pRel->iSubRec;
+          i64 sz = (pPager->pageSize+4)*(i64)pRel->iSubRec;
           rc = sqlite3OsTruncate(pPager->sjfd, sz);
           assert( rc==SQLITE_OK );
         }
@@ -59274,7 +60358,7 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i
   pPgOld = sqlite3PagerLookup(pPager, pgno);
   assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
   if( pPgOld ){
-    if( pPgOld->nRef>1 ){
+    if( NEVER(pPgOld->nRef>1) ){
       sqlite3PagerUnrefNotNull(pPgOld);
       return SQLITE_CORRUPT_BKPT;
     }
@@ -59409,12 +60493,12 @@ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   u8 eOld = pPager->journalMode;    /* Prior journalmode */
 
   /* The eMode parameter is always valid */
-  assert(      eMode==PAGER_JOURNALMODE_DELETE
-            || eMode==PAGER_JOURNALMODE_TRUNCATE
-            || eMode==PAGER_JOURNALMODE_PERSIST
-            || eMode==PAGER_JOURNALMODE_OFF
-            || eMode==PAGER_JOURNALMODE_WAL
-            || eMode==PAGER_JOURNALMODE_MEMORY );
+  assert(      eMode==PAGER_JOURNALMODE_DELETE    /* 0 */
+            || eMode==PAGER_JOURNALMODE_PERSIST   /* 1 */
+            || eMode==PAGER_JOURNALMODE_OFF       /* 2 */
+            || eMode==PAGER_JOURNALMODE_TRUNCATE  /* 3 */
+            || eMode==PAGER_JOURNALMODE_MEMORY    /* 4 */
+            || eMode==PAGER_JOURNALMODE_WAL       /* 5 */ );
 
   /* This routine is only called from the OP_JournalMode opcode, and
   ** the logic there will never allow a temporary file to be changed
@@ -59451,7 +60535,6 @@ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
 
     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
-
       /* In this case we would like to delete the journal file. If it is
       ** not possible, then that is not a problem. Deleting the journal file
       ** here is an optimization only.
@@ -59563,6 +60646,18 @@ SQLITE_PRIVATE int sqlite3PagerCheckpoint(
   int *pnCkpt                     /* OUT: Final number of checkpointed frames */
 ){
   int rc = SQLITE_OK;
+  if( pPager->pWal==0 && pPager->journalMode==PAGER_JOURNALMODE_WAL ){
+    /* This only happens when a database file is zero bytes in size opened and
+    ** then "PRAGMA journal_mode=WAL" is run and then sqlite3_wal_checkpoint()
+    ** is invoked without any intervening transactions.  We need to start
+    ** a transaction to initialize pWal.  The PRAGMA table_list statement is
+    ** used for this since it starts transactions on every database file,
+    ** including all ATTACHed databases.  This seems expensive for a single
+    ** sqlite3_wal_checkpoint() call, but it happens very rarely.
+    ** https://sqlite.org/forum/forumpost/fd0f19d229156939
+    */
+    sqlite3_exec(db, "PRAGMA table_list",0,0,0);
+  }
   if( pPager->pWal ){
     rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
         (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
@@ -60020,7 +61115,10 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
 ** first index block are the same size as all other index blocks in the
-** wal-index.
+** wal-index.  The values are:
+**
+**   HASHTABLE_NPAGE      4096
+**   HASHTABLE_NPAGE_ONE  4062
 **
 ** Each index block contains two sections, a page-mapping that contains the
 ** database page number associated with each wal frame, and a hash-table
@@ -60256,6 +61354,70 @@ struct WalCkptInfo {
 };
 #define READMARK_NOT_USED  0xffffffff
 
+/*
+** This is a schematic view of the complete 136-byte header of the
+** wal-index file (also known as the -shm file):
+**
+**      +-----------------------------+
+**   0: | iVersion                    | \
+**      +-----------------------------+  |
+**   4: | (unused padding)            |  |
+**      +-----------------------------+  |
+**   8: | iChange                     |  |
+**      +-------+-------+-------------+  |
+**  12: | bInit |  bBig |   szPage    |  |
+**      +-------+-------+-------------+  |
+**  16: | mxFrame                     |  |  First copy of the
+**      +-----------------------------+  |  WalIndexHdr object
+**  20: | nPage                       |  |
+**      +-----------------------------+  |
+**  24: | aFrameCksum                 |  |
+**      |                             |  |
+**      +-----------------------------+  |
+**  32: | aSalt                       |  |
+**      |                             |  |
+**      +-----------------------------+  |
+**  40: | aCksum                      |  |
+**      |                             | /
+**      +-----------------------------+
+**  48: | iVersion                    | \
+**      +-----------------------------+  |
+**  52: | (unused padding)            |  |
+**      +-----------------------------+  |
+**  56: | iChange                     |  |
+**      +-------+-------+-------------+  |
+**  60: | bInit |  bBig |   szPage    |  |
+**      +-------+-------+-------------+  |  Second copy of the
+**  64: | mxFrame                     |  |  WalIndexHdr
+**      +-----------------------------+  |
+**  68: | nPage                       |  |
+**      +-----------------------------+  |
+**  72: | aFrameCksum                 |  |
+**      |                             |  |
+**      +-----------------------------+  |
+**  80: | aSalt                       |  |
+**      |                             |  |
+**      +-----------------------------+  |
+**  88: | aCksum                      |  |
+**      |                             | /
+**      +-----------------------------+
+**  96: | nBackfill                   |
+**      +-----------------------------+
+** 100: | 5 read marks                |
+**      |                             |
+**      |                             |
+**      |                             |
+**      |                             |
+**      +-------+-------+------+------+
+** 120: | Write | Ckpt  | Rcvr | Rd0  | \
+**      +-------+-------+------+------+  ) 8 lock bytes
+**      | Read1 | Read2 | Rd3  | Rd4  | /
+**      +-------+-------+------+------+
+** 128: | nBackfillAttempted          |
+**      +-----------------------------+
+** 132: | (unused padding)            |
+**      +-----------------------------+
+*/
 
 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
@@ -60412,9 +61574,13 @@ struct WalIterator {
 ** so.  It is safe to enlarge the wal-index if pWal->writeLock is true
 ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
 **
-** If this call is successful, *ppPage is set to point to the wal-index
-** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
-** then an SQLite error code is returned and *ppPage is set to 0.
+** Three possible result scenarios:
+**
+**   (1)  rc==SQLITE_OK    and *ppPage==Requested-Wal-Index-Page
+**   (2)  rc>=SQLITE_ERROR and *ppPage==NULL
+**   (3)  rc==SQLITE_OK    and *ppPage==NULL  // only if iPage==0
+**
+** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
 */
 static SQLITE_NOINLINE int walIndexPageRealloc(
   Wal *pWal,               /* The WAL context */
@@ -60447,7 +61613,9 @@ static SQLITE_NOINLINE int walIndexPageRealloc(
     rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
         pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
     );
-    assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
+    assert( pWal->apWiData[iPage]!=0
+         || rc!=SQLITE_OK
+         || (pWal->writeLock==0 && iPage==0) );
     testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
     if( rc==SQLITE_OK ){
       if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
@@ -60786,8 +61954,8 @@ struct WalHashLoc {
 ** slot in the hash table is set to N, it refers to frame number
 ** (pLoc->iZero+N) in the log.
 **
-** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
-** first frame indexed by the hash table, frame (pLoc->iZero+1).
+** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
+** first frame indexed by the hash table, frame (pLoc->iZero).
 */
 static int walHashGet(
   Wal *pWal,                      /* WAL handle */
@@ -60799,7 +61967,7 @@ static int walHashGet(
   rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
   assert( rc==SQLITE_OK || iHash>0 );
 
-  if( rc==SQLITE_OK ){
+  if( pLoc->aPgno ){
     pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
     if( iHash==0 ){
       pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
@@ -60807,7 +61975,8 @@ static int walHashGet(
     }else{
       pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
     }
-    pLoc->aPgno = &pLoc->aPgno[-1];
+  }else if( NEVER(rc==SQLITE_OK) ){
+    rc = SQLITE_ERROR;
   }
   return rc;
 }
@@ -60858,7 +62027,6 @@ static void walCleanupHash(Wal *pWal){
   int iLimit = 0;                 /* Zero values greater than this */
   int nByte;                      /* Number of bytes to zero in aPgno[] */
   int i;                          /* Used to iterate through aHash[] */
-  int rc;                         /* Return code form walHashGet() */
 
   assert( pWal->writeLock );
   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
@@ -60873,8 +62041,8 @@ static void walCleanupHash(Wal *pWal){
   */
   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
-  rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
-  if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */
+  i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
+  if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
 
   /* Zero all hash-table entries that correspond to frame numbers greater
   ** than pWal->hdr.mxFrame.
@@ -60890,8 +62058,9 @@ static void walCleanupHash(Wal *pWal){
   /* Zero the entries in the aPgno array that correspond to frames with
   ** frame numbers greater than pWal->hdr.mxFrame.
   */
-  nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
-  memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
+  nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
+  assert( nByte>=0 );
+  memset((void *)&sLoc.aPgno[iLimit], 0, nByte);
 
 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   /* Verify that the every entry in the mapping region is still reachable
@@ -60900,11 +62069,11 @@ static void walCleanupHash(Wal *pWal){
   if( iLimit ){
     int j;           /* Loop counter */
     int iKey;        /* Hash key */
-    for(j=1; j<=iLimit; j++){
+    for(j=0; j<iLimit; j++){
       for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
-        if( sLoc.aHash[iKey]==j ) break;
+        if( sLoc.aHash[iKey]==j+1 ) break;
       }
-      assert( sLoc.aHash[iKey]==j );
+      assert( sLoc.aHash[iKey]==j+1 );
     }
   }
 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
@@ -60936,9 +62105,9 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
     ** entire hash table and aPgno[] array before proceeding.
     */
     if( idx==1 ){
-      int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
-                               - (u8 *)&sLoc.aPgno[1]);
-      memset((void*)&sLoc.aPgno[1], 0, nByte);
+      int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
+      assert( nByte>=0 );
+      memset((void*)sLoc.aPgno, 0, nByte);
     }
 
     /* If the entry in aPgno[] is already set, then the previous writer
@@ -60947,9 +62116,9 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
     ** Remove the remnants of that writers uncommitted transaction from
     ** the hash-table before writing any new entries.
     */
-    if( sLoc.aPgno[idx] ){
+    if( sLoc.aPgno[idx-1] ){
       walCleanupHash(pWal);
-      assert( !sLoc.aPgno[idx] );
+      assert( !sLoc.aPgno[idx-1] );
     }
 
     /* Write the aPgno[] array entry and the hash-table slot. */
@@ -60957,7 +62126,7 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
     for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
     }
-    sLoc.aPgno[idx] = iPage;
+    sLoc.aPgno[idx-1] = iPage;
     AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
 
 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
@@ -60978,19 +62147,18 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
     */
     if( (idx&0x3ff)==0 ){
       int i;           /* Loop counter */
-      for(i=1; i<=idx; i++){
+      for(i=0; i<idx; i++){
         for(iKey=walHash(sLoc.aPgno[i]);
             sLoc.aHash[iKey];
             iKey=walNextHash(iKey)){
-          if( sLoc.aHash[iKey]==i ) break;
+          if( sLoc.aHash[iKey]==i+1 ) break;
         }
-        assert( sLoc.aHash[iKey]==i );
+        assert( sLoc.aHash[iKey]==i+1 );
       }
     }
 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   }
 
-
   return rc;
 }
 
@@ -61111,7 +62279,8 @@ static int walIndexRecover(Wal *pWal){
       u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
       u32 nHdr, nHdr32;
       rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
-      if( rc ) break;
+      assert( aShare!=0 || rc!=SQLITE_OK );
+      if( aShare==0 ) break;
       pWal->apWiData[iPg] = aPrivate;
 
       for(iFrame=iFirst; iFrame<=iLast; iFrame++){
@@ -61270,14 +62439,43 @@ SQLITE_PRIVATE int sqlite3WalOpen(
   assert( zWalName && zWalName[0] );
   assert( pDbFd );
 
+  /* Verify the values of various constants.  Any changes to the values
+  ** of these constants would result in an incompatible on-disk format
+  ** for the -shm file.  Any change that causes one of these asserts to
+  ** fail is a backward compatibility problem, even if the change otherwise
+  ** works.
+  **
+  ** This table also serves as a helpful cross-reference when trying to
+  ** interpret hex dumps of the -shm file.
+  */
+  assert(    48 ==  sizeof(WalIndexHdr)  );
+  assert(    40 ==  sizeof(WalCkptInfo)  );
+  assert(   120 ==  WALINDEX_LOCK_OFFSET );
+  assert(   136 ==  WALINDEX_HDR_SIZE    );
+  assert(  4096 ==  HASHTABLE_NPAGE      );
+  assert(  4062 ==  HASHTABLE_NPAGE_ONE  );
+  assert(  8192 ==  HASHTABLE_NSLOT      );
+  assert(   383 ==  HASHTABLE_HASH_1     );
+  assert( 32768 ==  WALINDEX_PGSZ        );
+  assert(     8 ==  SQLITE_SHM_NLOCK     );
+  assert(     5 ==  WAL_NREADER          );
+  assert(    24 ==  WAL_FRAME_HDRSIZE    );
+  assert(    32 ==  WAL_HDRSIZE          );
+  assert(   120 ==  WALINDEX_LOCK_OFFSET + WAL_WRITE_LOCK   );
+  assert(   121 ==  WALINDEX_LOCK_OFFSET + WAL_CKPT_LOCK    );
+  assert(   122 ==  WALINDEX_LOCK_OFFSET + WAL_RECOVER_LOCK );
+  assert(   123 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(0) );
+  assert(   124 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(1) );
+  assert(   125 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(2) );
+  assert(   126 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(3) );
+  assert(   127 ==  WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(4) );
+
   /* In the amalgamation, the os_unix.c and os_win.c source files come before
   ** this source file.  Verify that the #defines of the locking byte offsets
   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
   ** For that matter, if the lock offset ever changes from its initial design
   ** value of 120, we need to know that so there is an assert() to check it.
   */
-  assert( 120==WALINDEX_LOCK_OFFSET );
-  assert( 136==WALINDEX_HDR_SIZE );
 #ifdef WIN_SHM_BASE
   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
 #endif
@@ -61579,7 +62777,6 @@ static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
       int nEntry;                 /* Number of entries in this segment */
       ht_slot *aIndex;            /* Sorted index for this segment */
 
-      sLoc.aPgno++;
       if( (i+1)==nSegment ){
         nEntry = (int)(iLast - sLoc.iZero);
       }else{
@@ -62360,7 +63557,9 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
   }
 
   /* Allocate a buffer to read frames into */
-  szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
+  assert( (pWal->szPage & (pWal->szPage-1))==0 );
+  assert( pWal->szPage>=512 && pWal->szPage<=65536 );
+  szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
   aFrame = (u8 *)sqlite3_malloc64(szFrame);
   if( aFrame==0 ){
     rc = SQLITE_NOMEM_BKPT;
@@ -62374,7 +63573,7 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
   ** the caller.  */
   aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
   aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
-  for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
+  for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
       iOffset+szFrame<=szWal;
       iOffset+=szFrame
   ){
@@ -62718,7 +63917,8 @@ SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
 
           rc = walHashGet(pWal, walFramePage(i), &sLoc);
           if( rc!=SQLITE_OK ) break;
-          pgno = sLoc.aPgno[i-sLoc.iZero];
+          assert( i - sLoc.iZero - 1 >=0 );
+          pgno = sLoc.aPgno[i-sLoc.iZero-1];
           iDbOff = (i64)(pgno-1) * szPage;
 
           if( iDbOff+szPage<=szDb ){
@@ -62951,7 +64151,7 @@ SQLITE_PRIVATE int sqlite3WalFindFrame(
     iKey = walHash(pgno);
     while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
       u32 iFrame = iH + sLoc.iZero;
-      if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){
+      if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
         assert( iFrame>iRead || CORRUPT_DB );
         iRead = iFrame;
       }
@@ -64203,7 +65403,6 @@ typedef struct CellInfo CellInfo;
 */
 struct MemPage {
   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
-  u8 bBusy;            /* Prevent endless loops on corrupt database files */
   u8 intKey;           /* True if table b-trees.  False for index b-trees */
   u8 intKeyLeaf;       /* True if the leaf of an intKey table */
   Pgno pgno;           /* Page number for this page */
@@ -64225,7 +65424,9 @@ struct MemPage {
   u8 *apOvfl[4];       /* Pointers to the body of overflow cells */
   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   u8 *aData;           /* Pointer to disk image of the page data */
-  u8 *aDataEnd;        /* One byte past the end of usable data */
+  u8 *aDataEnd;        /* One byte past the end of the entire page - not just
+                       ** the usable space, the entire page.  Used to prevent
+                       ** corruption-induced of buffer overflow. */
   u8 *aCellIdx;        /* The cell index area */
   u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
   DbPage *pDbPage;     /* Pager page handle */
@@ -65504,7 +66705,7 @@ static void invalidateIncrblobCursors(
   int isClearTable        /* True if all rows are being deleted */
 ){
   BtCursor *p;
-  if( pBtree->hasIncrblobCur==0 ) return;
+  assert( pBtree->hasIncrblobCur );
   assert( sqlite3BtreeHoldsMutex(pBtree) );
   pBtree->hasIncrblobCur = 0;
   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
@@ -65784,15 +66985,13 @@ static int btreeMoveto(
     sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
     if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
       rc = SQLITE_CORRUPT_BKPT;
-      goto moveto_done;
+    }else{
+      rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
     }
+    sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
   }else{
     pIdxKey = 0;
-  }
-  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
-moveto_done:
-  if( pIdxKey ){
-    sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
+    rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
   }
   return rc;
 }
@@ -66184,18 +67383,32 @@ static void btreeParseCellPtr(
   **
   **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
   **
-  ** The code is inlined to avoid a function call.
+  ** The code is inlined and the loop is unrolled for performance.
+  ** This routine is a high-runner.
   */
   iKey = *pIter;
   if( iKey>=0x80 ){
-    u8 *pEnd = &pIter[7];
-    iKey &= 0x7f;
-    while(1){
-      iKey = (iKey<<7) | (*++pIter & 0x7f);
-      if( (*pIter)<0x80 ) break;
-      if( pIter>=pEnd ){
-        iKey = (iKey<<8) | *++pIter;
-        break;
+    u8 x;
+    iKey = ((iKey&0x7f)<<7) | ((x = *++pIter) & 0x7f);
+    if( x>=0x80 ){
+      iKey = (iKey<<7) | ((x =*++pIter) & 0x7f);
+      if( x>=0x80 ){
+        iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
+        if( x>=0x80 ){
+          iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
+          if( x>=0x80 ){
+            iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
+            if( x>=0x80 ){
+              iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
+              if( x>=0x80 ){
+                iKey = (iKey<<7) | ((x = *++pIter) & 0x7f);
+                if( x>=0x80 ){
+                  iKey = (iKey<<8) | (*++pIter);
+                }
+              }
+            }
+          }
+        }
       }
     }
   }
@@ -66205,7 +67418,7 @@ static void btreeParseCellPtr(
   pInfo->nPayload = nPayload;
   pInfo->pPayload = pIter;
   testcase( nPayload==pPage->maxLocal );
-  testcase( nPayload==pPage->maxLocal+1 );
+  testcase( nPayload==(u32)pPage->maxLocal+1 );
   if( nPayload<=pPage->maxLocal ){
     /* This is the (easy) common case where the entire payload fits
     ** on the local page.  No overflow is required.
@@ -66242,7 +67455,7 @@ static void btreeParseCellPtrIndex(
   pInfo->nPayload = nPayload;
   pInfo->pPayload = pIter;
   testcase( nPayload==pPage->maxLocal );
-  testcase( nPayload==pPage->maxLocal+1 );
+  testcase( nPayload==(u32)pPage->maxLocal+1 );
   if( nPayload<=pPage->maxLocal ){
     /* This is the (easy) common case where the entire payload fits
     ** on the local page.  No overflow is required.
@@ -66305,7 +67518,7 @@ static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
     while( (*pIter++)&0x80 && pIter<pEnd );
   }
   testcase( nSize==pPage->maxLocal );
-  testcase( nSize==pPage->maxLocal+1 );
+  testcase( nSize==(u32)pPage->maxLocal+1 );
   if( nSize<=pPage->maxLocal ){
     nSize += (u32)(pIter - pCell);
     if( nSize<4 ) nSize = 4;
@@ -66313,7 +67526,7 @@ static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
     int minLocal = pPage->minLocal;
     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
     testcase( nSize==pPage->maxLocal );
-    testcase( nSize==pPage->maxLocal+1 );
+    testcase( nSize==(u32)pPage->maxLocal+1 );
     if( nSize>pPage->maxLocal ){
       nSize = minLocal;
     }
@@ -66405,6 +67618,7 @@ static int defragmentPage(MemPage *pPage, int nMaxFrag){
   unsigned char *src;        /* Source of content */
   int iCellFirst;            /* First allowable cell index */
   int iCellLast;             /* Last possible cell index */
+  int iCellStart;            /* First cell offset in input */
 
   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   assert( pPage->pBt!=0 );
@@ -66465,6 +67679,7 @@ static int defragmentPage(MemPage *pPage, int nMaxFrag){
 
   cbrk = usableSize;
   iCellLast = usableSize - 4;
+  iCellStart = get2byte(&data[hdr+5]);
   for(i=0; i<nCell; i++){
     u8 *pAddr;     /* The i-th cell pointer */
     pAddr = &data[cellOffset + i*2];
@@ -66474,25 +67689,23 @@ static int defragmentPage(MemPage *pPage, int nMaxFrag){
     /* These conditions have already been verified in btreeInitPage()
     ** if PRAGMA cell_size_check=ON.
     */
-    if( pc<iCellFirst || pc>iCellLast ){
+    if( pc<iCellStart || pc>iCellLast ){
       return SQLITE_CORRUPT_PAGE(pPage);
     }
-    assert( pc>=iCellFirst && pc<=iCellLast );
+    assert( pc>=iCellStart && pc<=iCellLast );
     size = pPage->xCellSize(pPage, &src[pc]);
     cbrk -= size;
-    if( cbrk<iCellFirst || pc+size>usableSize ){
+    if( cbrk<iCellStart || pc+size>usableSize ){
       return SQLITE_CORRUPT_PAGE(pPage);
     }
-    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
+    assert( cbrk+size<=usableSize && cbrk>=iCellStart );
     testcase( cbrk+size==usableSize );
     testcase( pc+size==usableSize );
     put2byte(pAddr, cbrk);
     if( temp==0 ){
-      int x;
       if( cbrk==pc ) continue;
       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
-      x = get2byte(&data[hdr+5]);
-      memcpy(&temp[x], &data[x], (cbrk+size) - x);
+      memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
       src = temp;
     }
     memcpy(&data[cbrk], &src[pc], size);
@@ -66554,6 +67767,8 @@ static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
         ** fragmented bytes within the page. */
         memcpy(&aData[iAddr], &aData[pc], 2);
         aData[hdr+7] += (u8)x;
+        testcase( pc+x>maxPC );
+        return &aData[pc];
       }else if( x+pc > maxPC ){
         /* This slot extends off the end of the usable part of the page */
         *pRc = SQLITE_CORRUPT_PAGE(pPg);
@@ -66641,7 +67856,7 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
       int g2;
       assert( pSpace+nByte<=data+pPage->pBt->usableSize );
       *pIdx = g2 = (int)(pSpace-data);
-      if( NEVER(g2<=gap) ){
+      if( g2<=gap ){
         return SQLITE_CORRUPT_PAGE(pPage);
       }else{
         return SQLITE_OK;
@@ -66727,7 +67942,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
     if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
       return SQLITE_CORRUPT_PAGE(pPage);
     }
-    assert( iFreeBlk>iPtr || iFreeBlk==0 );
+    assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );
 
     /* At this point:
     **    iFreeBlk:   First freeblock after iStart, or zero if none
@@ -66998,7 +68213,7 @@ static int btreeInitPage(MemPage *pPage){
   pPage->nOverflow = 0;
   pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
   pPage->aCellIdx = data + pPage->childPtrSize + 8;
-  pPage->aDataEnd = pPage->aData + pBt->usableSize;
+  pPage->aDataEnd = pPage->aData + pBt->pageSize;
   pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
   ** number of cells on the page. */
@@ -67033,7 +68248,7 @@ static void zeroPage(MemPage *pPage, int flags){
   u8 hdr = pPage->hdrOffset;
   u16 first;
 
-  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
+  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
@@ -67049,7 +68264,7 @@ static void zeroPage(MemPage *pPage, int flags){
   pPage->nFree = (u16)(pBt->usableSize - first);
   decodeFlags(pPage, flags);
   pPage->cellOffset = first;
-  pPage->aDataEnd = &data[pBt->usableSize];
+  pPage->aDataEnd = &data[pBt->pageSize];
   pPage->aCellIdx = &data[first];
   pPage->aDataOfst = &data[pPage->childPtrSize];
   pPage->nOverflow = 0;
@@ -67175,7 +68390,7 @@ static int getAndInitPage(
       goto getAndInitPage_error2;
     }
   }
-  assert( (*ppPage)->pgno==pgno );
+  assert( (*ppPage)->pgno==pgno || CORRUPT_DB );
   assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
 
   /* If obtaining a child page for a cursor, we must verify that the page is
@@ -67652,30 +68867,38 @@ static int removeFromSharingList(BtShared *pBt){
 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
 ** pointer.
 */
-static void allocateTempSpace(BtShared *pBt){
-  if( !pBt->pTmpSpace ){
-    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
-
-    /* One of the uses of pBt->pTmpSpace is to format cells before
-    ** inserting them into a leaf page (function fillInCell()). If
-    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
-    ** by the various routines that manipulate binary cells. Which
-    ** can mean that fillInCell() only initializes the first 2 or 3
-    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
-    ** it into a database page. This is not actually a problem, but it
-    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
-    ** data is passed to system call write(). So to avoid this error,
-    ** zero the first 4 bytes of temp space here.
-    **
-    ** Also:  Provide four bytes of initialized space before the
-    ** beginning of pTmpSpace as an area available to prepend the
-    ** left-child pointer to the beginning of a cell.
-    */
-    if( pBt->pTmpSpace ){
-      memset(pBt->pTmpSpace, 0, 8);
-      pBt->pTmpSpace += 4;
-    }
+static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
+  assert( pBt!=0 );
+  assert( pBt->pTmpSpace==0 );
+  /* This routine is called only by btreeCursor() when allocating the
+  ** first write cursor for the BtShared object */
+  assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
+  pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
+  if( pBt->pTmpSpace==0 ){
+    BtCursor *pCur = pBt->pCursor;
+    pBt->pCursor = pCur->pNext;  /* Unlink the cursor */
+    memset(pCur, 0, sizeof(*pCur));
+    return SQLITE_NOMEM_BKPT;
   }
+
+  /* One of the uses of pBt->pTmpSpace is to format cells before
+  ** inserting them into a leaf page (function fillInCell()). If
+  ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
+  ** by the various routines that manipulate binary cells. Which
+  ** can mean that fillInCell() only initializes the first 2 or 3
+  ** bytes of pTmpSpace, but that the first 4 bytes are copied from
+  ** it into a database page. This is not actually a problem, but it
+  ** does cause a valgrind error when the 1 or 2 bytes of unitialized
+  ** data is passed to system call write(). So to avoid this error,
+  ** zero the first 4 bytes of temp space here.
+  **
+  ** Also:  Provide four bytes of initialized space before the
+  ** beginning of pTmpSpace as an area available to prepend the
+  ** left-child pointer to the beginning of a cell.
+  */
+  memset(pBt->pTmpSpace, 0, 8);
+  pBt->pTmpSpace += 4;
+  return SQLITE_OK;
 }
 
 /*
@@ -68054,7 +69277,6 @@ static int lockBtree(BtShared *pBt){
   MemPage *pPage1;     /* Page 1 of the database file */
   u32 nPage;           /* Number of pages in the database */
   u32 nPageFile = 0;   /* Number of pages in the database file */
-  u32 nPageHeader;     /* Number of pages in the database according to hdr */
 
   assert( sqlite3_mutex_held(pBt->mutex) );
   assert( pBt->pPage1==0 );
@@ -68066,7 +69288,7 @@ static int lockBtree(BtShared *pBt){
   /* Do some checking to help insure the file we opened really is
   ** a valid database file.
   */
-  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
+  nPage = get4byte(28+(u8*)pPage1->aData);
   sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
     nPage = nPageFile;
@@ -68101,7 +69323,7 @@ static int lockBtree(BtShared *pBt){
       goto page1_init_failed;
     }
 
-    /* If the write version is set to 2, this database should be accessed
+    /* If the read version is set to 2, this database should be accessed
     ** in WAL mode. If the log is not already open, open it now. Then
     ** return SQLITE_OK and return without populating BtShared.pPage1.
     ** The caller detects this and calls this function again. This is
@@ -68173,9 +69395,13 @@ static int lockBtree(BtShared *pBt){
                                    pageSize-usableSize);
       return rc;
     }
-    if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
-      rc = SQLITE_CORRUPT_BKPT;
-      goto page1_init_failed;
+    if( nPage>nPageFile ){
+      if( sqlite3WritableSchema(pBt->db)==0 ){
+        rc = SQLITE_CORRUPT_BKPT;
+        goto page1_init_failed;
+      }else{
+        nPage = nPageFile;
+      }
     }
     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
     ** be less than 480. In other words, if the page size is 512, then the
@@ -68899,16 +70125,18 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
 /*
 ** This routine is called prior to sqlite3PagerCommit when a transaction
 ** is committed for an auto-vacuum database.
-**
-** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
-** the database file should be truncated to during the commit process.
-** i.e. the database has been reorganized so that only the first *pnTrunc
-** pages are in use.
 */
-static int autoVacuumCommit(BtShared *pBt){
+static int autoVacuumCommit(Btree *p){
   int rc = SQLITE_OK;
-  Pager *pPager = pBt->pPager;
-  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
+  Pager *pPager;
+  BtShared *pBt;
+  sqlite3 *db;
+  VVA_ONLY( int nRef );
+
+  assert( p!=0 );
+  pBt = p->pBt;
+  pPager = pBt->pPager;
+  VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
 
   assert( sqlite3_mutex_held(pBt->mutex) );
   invalidateAllOverflowCache(pBt);
@@ -68916,6 +70144,7 @@ static int autoVacuumCommit(BtShared *pBt){
   if( !pBt->incrVacuum ){
     Pgno nFin;         /* Number of pages in database after autovacuuming */
     Pgno nFree;        /* Number of pages on the freelist initially */
+    Pgno nVac;         /* Number of pages to vacuum */
     Pgno iFree;        /* The next page to be freed */
     Pgno nOrig;        /* Database size before freeing */
 
@@ -68929,18 +70158,42 @@ static int autoVacuumCommit(BtShared *pBt){
     }
 
     nFree = get4byte(&pBt->pPage1->aData[36]);
-    nFin = finalDbSize(pBt, nOrig, nFree);
+    db = p->db;
+    if( db->xAutovacPages ){
+      int iDb;
+      for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
+        if( db->aDb[iDb].pBt==p ) break;
+      }
+      nVac = db->xAutovacPages(
+        db->pAutovacPagesArg,
+        db->aDb[iDb].zDbSName,
+        nOrig,
+        nFree,
+        pBt->pageSize
+      );
+      if( nVac>nFree ){
+        nVac = nFree;
+      }
+      if( nVac==0 ){
+        return SQLITE_OK;
+      }
+    }else{
+      nVac = nFree;
+    }
+    nFin = finalDbSize(pBt, nOrig, nVac);
     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
     if( nFin<nOrig ){
       rc = saveAllCursors(pBt, 0, 0);
     }
     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
-      rc = incrVacuumStep(pBt, nFin, iFree, 1);
+      rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
     }
     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
-      put4byte(&pBt->pPage1->aData[32], 0);
-      put4byte(&pBt->pPage1->aData[36], 0);
+      if( nVac==nFree ){
+        put4byte(&pBt->pPage1->aData[32], 0);
+        put4byte(&pBt->pPage1->aData[36], 0);
+      }
       put4byte(&pBt->pPage1->aData[28], nFin);
       pBt->bDoTruncate = 1;
       pBt->nPage = nFin;
@@ -68991,7 +70244,7 @@ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
     sqlite3BtreeEnter(p);
 #ifndef SQLITE_OMIT_AUTOVACUUM
     if( pBt->autoVacuum ){
-      rc = autoVacuumCommit(pBt);
+      rc = autoVacuumCommit(p);
       if( rc!=SQLITE_OK ){
         sqlite3BtreeLeave(p);
         return rc;
@@ -69178,7 +70431,7 @@ static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
   int nPage = get4byte(&pPage1->aData[28]);
   testcase( nPage==0 );
   if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
-  testcase( pBt->nPage!=nPage );
+  testcase( pBt->nPage!=(u32)nPage );
   pBt->nPage = nPage;
 }
 
@@ -69390,10 +70643,6 @@ static int btreeCursor(
   assert( pBt->pPage1 && pBt->pPage1->aData );
   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
 
-  if( wrFlag ){
-    allocateTempSpace(pBt);
-    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
-  }
   if( iTable<=1 ){
     if( iTable<1 ){
       return SQLITE_CORRUPT_BKPT;
@@ -69410,19 +70659,25 @@ static int btreeCursor(
   pCur->pKeyInfo = pKeyInfo;
   pCur->pBtree = p;
   pCur->pBt = pBt;
-  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
-  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
+  pCur->curFlags = 0;
   /* If there are two or more cursors on the same btree, then all such
   ** cursors *must* have the BTCF_Multiple flag set. */
   for(pX=pBt->pCursor; pX; pX=pX->pNext){
     if( pX->pgnoRoot==iTable ){
       pX->curFlags |= BTCF_Multiple;
-      pCur->curFlags |= BTCF_Multiple;
+      pCur->curFlags = BTCF_Multiple;
     }
   }
+  pCur->eState = CURSOR_INVALID;
   pCur->pNext = pBt->pCursor;
   pBt->pCursor = pCur;
-  pCur->eState = CURSOR_INVALID;
+  if( wrFlag ){
+    pCur->curFlags |= BTCF_WriteFlag;
+    pCur->curPagerFlags = 0;
+    if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
+  }else{
+    pCur->curPagerFlags = PAGER_GET_READONLY;
+  }
   return SQLITE_OK;
 }
 static int btreeCursorWithLock(
@@ -69796,7 +71051,9 @@ static int accessPayload(
   assert( pPage );
   assert( eOp==0 || eOp==1 );
   assert( pCur->eState==CURSOR_VALID );
-  assert( pCur->ix<pPage->nCell );
+  if( pCur->ix>=pPage->nCell ){
+    return SQLITE_CORRUPT_PAGE(pPage);
+  }
   assert( cursorHoldsMutex(pCur) );
 
   getCellInfo(pCur);
@@ -69983,7 +71240,6 @@ SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void
   assert( cursorHoldsMutex(pCur) );
   assert( pCur->eState==CURSOR_VALID );
   assert( pCur->iPage>=0 && pCur->pPage );
-  assert( pCur->ix<pCur->pPage->nCell );
   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
 }
 
@@ -70045,7 +71301,7 @@ static const void *fetchPayload(
   assert( pCur->eState==CURSOR_VALID );
   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   assert( cursorOwnsBtShared(pCur) );
-  assert( pCur->ix<pCur->pPage->nCell );
+  assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
   assert( pCur->info.nSize>0 );
   assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
   assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
@@ -70196,7 +71452,7 @@ static int moveToRoot(BtCursor *pCur){
       while( --pCur->iPage ){
         releasePageNotNull(pCur->apPage[pCur->iPage]);
       }
-      pCur->pPage = pCur->apPage[0];
+      pRoot = pCur->pPage = pCur->apPage[0];
       goto skip_init;
     }
   }else if( pCur->pgnoRoot==0 ){
@@ -70221,7 +71477,7 @@ static int moveToRoot(BtCursor *pCur){
     pCur->curIntKey = pCur->pPage->intKey;
   }
   pRoot = pCur->pPage;
-  assert( pRoot->pgno==pCur->pgnoRoot );
+  assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
 
   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
@@ -70243,7 +71499,6 @@ skip_init:
   pCur->info.nSize = 0;
   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
 
-  pRoot = pCur->pPage;
   if( pRoot->nCell>0 ){
     pCur->eState = CURSOR_VALID;
   }else if( !pRoot->leaf ){
@@ -70351,7 +71606,9 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
     for(ii=0; ii<pCur->iPage; ii++){
       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
     }
-    assert( pCur->ix==pCur->pPage->nCell-1 );
+    assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
+    testcase( pCur->ix!=pCur->pPage->nCell-1 );
+    /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
     assert( pCur->pPage->leaf );
 #endif
     *pRes = 0;
@@ -70376,12 +71633,8 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   return rc;
 }
 
-/* Move the cursor so that it points to an entry near the key
-** specified by pIdxKey or intKey.   Return a success code.
-**
-** For INTKEY tables, the intKey parameter is used.  pIdxKey
-** must be NULL.  For index tables, pIdxKey is used and intKey
-** is ignored.
+/* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
+** table near the key intKey.   Return a success code.
 **
 ** If an exact match is not found, then the cursor is always
 ** left pointing at a leaf page which would hold the entry if it
@@ -70394,39 +71647,32 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
 ** *pRes is as follows:
 **
 **     *pRes<0      The cursor is left pointing at an entry that
-**                  is smaller than intKey/pIdxKey or if the table is empty
+**                  is smaller than intKey or if the table is empty
 **                  and the cursor is therefore left point to nothing.
 **
 **     *pRes==0     The cursor is left pointing at an entry that
-**                  exactly matches intKey/pIdxKey.
+**                  exactly matches intKey.
 **
 **     *pRes>0      The cursor is left pointing at an entry that
-**                  is larger than intKey/pIdxKey.
-**
-** For index tables, the pIdxKey->eqSeen field is set to 1 if there
-** exists an entry in the table that exactly matches pIdxKey.
+**                  is larger than intKey.
 */
-SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
+SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
   BtCursor *pCur,          /* The cursor to be moved */
-  UnpackedRecord *pIdxKey, /* Unpacked index key */
   i64 intKey,              /* The table key */
   int biasRight,           /* If true, bias the search to the high end */
   int *pRes                /* Write search results here */
 ){
   int rc;
-  RecordCompare xRecordCompare;
 
   assert( cursorOwnsBtShared(pCur) );
   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   assert( pRes );
-  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
-  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
+  assert( pCur->pKeyInfo==0 );
+  assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
 
   /* If the cursor is already positioned at the point we are trying
   ** to move to, then just return without doing any work */
-  if( pIdxKey==0
-   && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
-  ){
+  if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
     if( pCur->info.nKey==intKey ){
       *pRes = 0;
       return SQLITE_OK;
@@ -70448,9 +71694,7 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
           if( pCur->info.nKey==intKey ){
             return SQLITE_OK;
           }
-        }else if( rc==SQLITE_DONE ){
-          rc = SQLITE_OK;
-        }else{
+        }else if( rc!=SQLITE_DONE ){
           return rc;
         }
       }
@@ -70461,17 +71705,6 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   pCur->pBtree->nSeek++;   /* Performance measurement during testing */
 #endif
 
-  if( pIdxKey ){
-    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
-    pIdxKey->errCode = 0;
-    assert( pIdxKey->default_rc==1
-         || pIdxKey->default_rc==0
-         || pIdxKey->default_rc==-1
-    );
-  }else{
-    xRecordCompare = 0; /* All keys are integers */
-  }
-
   rc = moveToRoot(pCur);
   if( rc ){
     if( rc==SQLITE_EMPTY ){
@@ -70486,7 +71719,8 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   assert( pCur->eState==CURSOR_VALID );
   assert( pCur->pPage->nCell > 0 );
   assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
-  assert( pCur->curIntKey || pIdxKey );
+  assert( pCur->curIntKey );
+
   for(;;){
     int lwr, upr, idx, c;
     Pgno chldPg;
@@ -70500,144 +71734,246 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
     ** be the right kind (index or table) of b-tree page. Otherwise
     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
     assert( pPage->nCell>0 );
-    assert( pPage->intKey==(pIdxKey==0) );
+    assert( pPage->intKey );
     lwr = 0;
     upr = pPage->nCell-1;
     assert( biasRight==0 || biasRight==1 );
     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
-    pCur->ix = (u16)idx;
-    if( xRecordCompare==0 ){
-      for(;;){
-        i64 nCellKey;
-        pCell = findCellPastPtr(pPage, idx);
-        if( pPage->intKeyLeaf ){
-          while( 0x80 <= *(pCell++) ){
-            if( pCell>=pPage->aDataEnd ){
-              return SQLITE_CORRUPT_PAGE(pPage);
-            }
+    for(;;){
+      i64 nCellKey;
+      pCell = findCellPastPtr(pPage, idx);
+      if( pPage->intKeyLeaf ){
+        while( 0x80 <= *(pCell++) ){
+          if( pCell>=pPage->aDataEnd ){
+            return SQLITE_CORRUPT_PAGE(pPage);
           }
         }
-        getVarint(pCell, (u64*)&nCellKey);
-        if( nCellKey<intKey ){
-          lwr = idx+1;
-          if( lwr>upr ){ c = -1; break; }
-        }else if( nCellKey>intKey ){
-          upr = idx-1;
-          if( lwr>upr ){ c = +1; break; }
+      }
+      getVarint(pCell, (u64*)&nCellKey);
+      if( nCellKey<intKey ){
+        lwr = idx+1;
+        if( lwr>upr ){ c = -1; break; }
+      }else if( nCellKey>intKey ){
+        upr = idx-1;
+        if( lwr>upr ){ c = +1; break; }
+      }else{
+        assert( nCellKey==intKey );
+        pCur->ix = (u16)idx;
+        if( !pPage->leaf ){
+          lwr = idx;
+          goto moveto_table_next_layer;
         }else{
-          assert( nCellKey==intKey );
-          pCur->ix = (u16)idx;
-          if( !pPage->leaf ){
-            lwr = idx;
-            goto moveto_next_layer;
-          }else{
-            pCur->curFlags |= BTCF_ValidNKey;
-            pCur->info.nKey = nCellKey;
-            pCur->info.nSize = 0;
-            *pRes = 0;
-            return SQLITE_OK;
-          }
+          pCur->curFlags |= BTCF_ValidNKey;
+          pCur->info.nKey = nCellKey;
+          pCur->info.nSize = 0;
+          *pRes = 0;
+          return SQLITE_OK;
         }
-        assert( lwr+upr>=0 );
-        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
       }
+      assert( lwr+upr>=0 );
+      idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
+    }
+    assert( lwr==upr+1 || !pPage->leaf );
+    assert( pPage->isInit );
+    if( pPage->leaf ){
+      assert( pCur->ix<pCur->pPage->nCell );
+      pCur->ix = (u16)idx;
+      *pRes = c;
+      rc = SQLITE_OK;
+      goto moveto_table_finish;
+    }
+moveto_table_next_layer:
+    if( lwr>=pPage->nCell ){
+      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
     }else{
-      for(;;){
-        int nCell;  /* Size of the pCell cell in bytes */
-        pCell = findCellPastPtr(pPage, idx);
-
-        /* The maximum supported page-size is 65536 bytes. This means that
-        ** the maximum number of record bytes stored on an index B-Tree
-        ** page is less than 16384 bytes and may be stored as a 2-byte
-        ** varint. This information is used to attempt to avoid parsing
-        ** the entire cell by checking for the cases where the record is
-        ** stored entirely within the b-tree page by inspecting the first
-        ** 2 bytes of the cell.
-        */
-        nCell = pCell[0];
-        if( nCell<=pPage->max1bytePayload ){
-          /* This branch runs if the record-size field of the cell is a
-          ** single byte varint and the record fits entirely on the main
-          ** b-tree page.  */
-          testcase( pCell+nCell+1==pPage->aDataEnd );
-          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
-        }else if( !(pCell[1] & 0x80)
-          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
-        ){
-          /* The record-size field is a 2 byte varint and the record
-          ** fits entirely on the main b-tree page.  */
-          testcase( pCell+nCell+2==pPage->aDataEnd );
-          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
-        }else{
-          /* The record flows over onto one or more overflow pages. In
-          ** this case the whole cell needs to be parsed, a buffer allocated
-          ** and accessPayload() used to retrieve the record into the
-          ** buffer before VdbeRecordCompare() can be called.
-          **
-          ** If the record is corrupt, the xRecordCompare routine may read
-          ** up to two varints past the end of the buffer. An extra 18
-          ** bytes of padding is allocated at the end of the buffer in
-          ** case this happens.  */
-          void *pCellKey;
-          u8 * const pCellBody = pCell - pPage->childPtrSize;
-          const int nOverrun = 18;  /* Size of the overrun padding */
-          pPage->xParseCell(pPage, pCellBody, &pCur->info);
-          nCell = (int)pCur->info.nKey;
-          testcase( nCell<0 );   /* True if key size is 2^32 or more */
-          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
-          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
-          testcase( nCell==2 );  /* Minimum legal index key size */
-          if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
-            rc = SQLITE_CORRUPT_PAGE(pPage);
-            goto moveto_finish;
-          }
-          pCellKey = sqlite3Malloc( nCell+nOverrun );
-          if( pCellKey==0 ){
-            rc = SQLITE_NOMEM_BKPT;
-            goto moveto_finish;
-          }
-          pCur->ix = (u16)idx;
-          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
-          memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
-          pCur->curFlags &= ~BTCF_ValidOvfl;
-          if( rc ){
-            sqlite3_free(pCellKey);
-            goto moveto_finish;
-          }
-          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
-          sqlite3_free(pCellKey);
+      chldPg = get4byte(findCell(pPage, lwr));
+    }
+    pCur->ix = (u16)lwr;
+    rc = moveToChild(pCur, chldPg);
+    if( rc ) break;
+  }
+moveto_table_finish:
+  pCur->info.nSize = 0;
+  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
+  return rc;
+}
+
+/* Move the cursor so that it points to an entry in an index table
+** near the key pIdxKey.   Return a success code.
+**
+** If an exact match is not found, then the cursor is always
+** left pointing at a leaf page which would hold the entry if it
+** were present.  The cursor might point to an entry that comes
+** before or after the key.
+**
+** An integer is written into *pRes which is the result of
+** comparing the key with the entry to which the cursor is
+** pointing.  The meaning of the integer written into
+** *pRes is as follows:
+**
+**     *pRes<0      The cursor is left pointing at an entry that
+**                  is smaller than pIdxKey or if the table is empty
+**                  and the cursor is therefore left point to nothing.
+**
+**     *pRes==0     The cursor is left pointing at an entry that
+**                  exactly matches pIdxKey.
+**
+**     *pRes>0      The cursor is left pointing at an entry that
+**                  is larger than pIdxKey.
+**
+** The pIdxKey->eqSeen field is set to 1 if there
+** exists an entry in the table that exactly matches pIdxKey.
+*/
+SQLITE_PRIVATE int sqlite3BtreeIndexMoveto(
+  BtCursor *pCur,          /* The cursor to be moved */
+  UnpackedRecord *pIdxKey, /* Unpacked index key */
+  int *pRes                /* Write search results here */
+){
+  int rc;
+  RecordCompare xRecordCompare;
+
+  assert( cursorOwnsBtShared(pCur) );
+  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
+  assert( pRes );
+  assert( pCur->pKeyInfo!=0 );
+
+#ifdef SQLITE_DEBUG
+  pCur->pBtree->nSeek++;   /* Performance measurement during testing */
+#endif
+
+  xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
+  pIdxKey->errCode = 0;
+  assert( pIdxKey->default_rc==1
+       || pIdxKey->default_rc==0
+       || pIdxKey->default_rc==-1
+  );
+
+  rc = moveToRoot(pCur);
+  if( rc ){
+    if( rc==SQLITE_EMPTY ){
+      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
+      *pRes = -1;
+      return SQLITE_OK;
+    }
+    return rc;
+  }
+  assert( pCur->pPage );
+  assert( pCur->pPage->isInit );
+  assert( pCur->eState==CURSOR_VALID );
+  assert( pCur->pPage->nCell > 0 );
+  assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
+  assert( pCur->curIntKey || pIdxKey );
+  for(;;){
+    int lwr, upr, idx, c;
+    Pgno chldPg;
+    MemPage *pPage = pCur->pPage;
+    u8 *pCell;                          /* Pointer to current cell in pPage */
+
+    /* pPage->nCell must be greater than zero. If this is the root-page
+    ** the cursor would have been INVALID above and this for(;;) loop
+    ** not run. If this is not the root-page, then the moveToChild() routine
+    ** would have already detected db corruption. Similarly, pPage must
+    ** be the right kind (index or table) of b-tree page. Otherwise
+    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
+    assert( pPage->nCell>0 );
+    assert( pPage->intKey==(pIdxKey==0) );
+    lwr = 0;
+    upr = pPage->nCell-1;
+    idx = upr>>1; /* idx = (lwr+upr)/2; */
+    for(;;){
+      int nCell;  /* Size of the pCell cell in bytes */
+      pCell = findCellPastPtr(pPage, idx);
+
+      /* The maximum supported page-size is 65536 bytes. This means that
+      ** the maximum number of record bytes stored on an index B-Tree
+      ** page is less than 16384 bytes and may be stored as a 2-byte
+      ** varint. This information is used to attempt to avoid parsing
+      ** the entire cell by checking for the cases where the record is
+      ** stored entirely within the b-tree page by inspecting the first
+      ** 2 bytes of the cell.
+      */
+      nCell = pCell[0];
+      if( nCell<=pPage->max1bytePayload ){
+        /* This branch runs if the record-size field of the cell is a
+        ** single byte varint and the record fits entirely on the main
+        ** b-tree page.  */
+        testcase( pCell+nCell+1==pPage->aDataEnd );
+        c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
+      }else if( !(pCell[1] & 0x80)
+        && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
+      ){
+        /* The record-size field is a 2 byte varint and the record
+        ** fits entirely on the main b-tree page.  */
+        testcase( pCell+nCell+2==pPage->aDataEnd );
+        c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
+      }else{
+        /* The record flows over onto one or more overflow pages. In
+        ** this case the whole cell needs to be parsed, a buffer allocated
+        ** and accessPayload() used to retrieve the record into the
+        ** buffer before VdbeRecordCompare() can be called.
+        **
+        ** If the record is corrupt, the xRecordCompare routine may read
+        ** up to two varints past the end of the buffer. An extra 18
+        ** bytes of padding is allocated at the end of the buffer in
+        ** case this happens.  */
+        void *pCellKey;
+        u8 * const pCellBody = pCell - pPage->childPtrSize;
+        const int nOverrun = 18;  /* Size of the overrun padding */
+        pPage->xParseCell(pPage, pCellBody, &pCur->info);
+        nCell = (int)pCur->info.nKey;
+        testcase( nCell<0 );   /* True if key size is 2^32 or more */
+        testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
+        testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
+        testcase( nCell==2 );  /* Minimum legal index key size */
+        if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
+          rc = SQLITE_CORRUPT_PAGE(pPage);
+          goto moveto_index_finish;
+        }
+        pCellKey = sqlite3Malloc( nCell+nOverrun );
+        if( pCellKey==0 ){
+          rc = SQLITE_NOMEM_BKPT;
+          goto moveto_index_finish;
         }
-        assert(
-            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
-         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
-        );
-        if( c<0 ){
-          lwr = idx+1;
-        }else if( c>0 ){
-          upr = idx-1;
-        }else{
-          assert( c==0 );
-          *pRes = 0;
-          rc = SQLITE_OK;
-          pCur->ix = (u16)idx;
-          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
-          goto moveto_finish;
+        pCur->ix = (u16)idx;
+        rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
+        memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
+        pCur->curFlags &= ~BTCF_ValidOvfl;
+        if( rc ){
+          sqlite3_free(pCellKey);
+          goto moveto_index_finish;
         }
-        if( lwr>upr ) break;
-        assert( lwr+upr>=0 );
-        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
+        c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
+        sqlite3_free(pCellKey);
+      }
+      assert(
+          (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
+       && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
+      );
+      if( c<0 ){
+        lwr = idx+1;
+      }else if( c>0 ){
+        upr = idx-1;
+      }else{
+        assert( c==0 );
+        *pRes = 0;
+        rc = SQLITE_OK;
+        pCur->ix = (u16)idx;
+        if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
+        goto moveto_index_finish;
       }
+      if( lwr>upr ) break;
+      assert( lwr+upr>=0 );
+      idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
     }
     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
     assert( pPage->isInit );
     if( pPage->leaf ){
-      assert( pCur->ix<pCur->pPage->nCell );
+      assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
       pCur->ix = (u16)idx;
       *pRes = c;
       rc = SQLITE_OK;
-      goto moveto_finish;
+      goto moveto_index_finish;
     }
-moveto_next_layer:
     if( lwr>=pPage->nCell ){
       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
     }else{
@@ -70647,7 +71983,7 @@ moveto_next_layer:
     rc = moveToChild(pCur, chldPg);
     if( rc ) break;
   }
-moveto_finish:
+moveto_index_finish:
   pCur->info.nSize = 0;
   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
   return rc;
@@ -70748,16 +72084,6 @@ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
     return SQLITE_CORRUPT_BKPT;
   }
 
-  /* If the database file is corrupt, it is possible for the value of idx
-  ** to be invalid here. This can only occur if a second cursor modifies
-  ** the page while cursor pCur is holding a reference to it. Which can
-  ** only happen if the database is corrupt in such a way as to link the
-  ** page into more than one b-tree structure.
-  **
-  ** Update 2019-12-23: appears to long longer be possible after the
-  ** addition of anotherValidCursor() condition on balance_deeper().  */
-  harmless( idx>pPage->nCell );
-
   if( idx>=pPage->nCell ){
     if( !pPage->leaf ){
       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
@@ -71118,7 +72444,7 @@ static int allocateBtreePage(
 
         iPage = get4byte(&aData[8+closest*4]);
         testcase( iPage==mxPage );
-        if( iPage>mxPage ){
+        if( iPage>mxPage || iPage<2 ){
           rc = SQLITE_CORRUPT_PGNO(iTrunk);
           goto end_allocate_page;
         }
@@ -71374,10 +72700,9 @@ static void freePage(MemPage *pPage, int *pRC){
 }
 
 /*
-** Free any overflow pages associated with the given Cell.  Store
-** size information about the cell in pInfo.
+** Free the overflow pages associated with the given Cell.
 */
-static int clearCell(
+static SQLITE_NOINLINE int clearCellOverflow(
   MemPage *pPage,          /* The page that contains the Cell */
   unsigned char *pCell,    /* First byte of the Cell */
   CellInfo *pInfo          /* Size information about the cell */
@@ -71389,10 +72714,7 @@ static int clearCell(
   u32 ovflPageSize;
 
   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
-  pPage->xParseCell(pPage, pCell, pInfo);
-  if( pInfo->nLocal==pInfo->nPayload ){
-    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
-  }
+  assert( pInfo->nLocal!=pInfo->nPayload );
   testcase( pCell + pInfo->nSize == pPage->aDataEnd );
   testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
   if( pCell + pInfo->nSize > pPage->aDataEnd ){
@@ -71448,6 +72770,21 @@ static int clearCell(
   return SQLITE_OK;
 }
 
+/* Call xParseCell to compute the size of a cell.  If the cell contains
+** overflow, then invoke cellClearOverflow to clear out that overflow.
+** STore the result code (SQLITE_OK or some error code) in rc.
+**
+** Implemented as macro to force inlining for performance.
+*/
+#define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo)   \
+  pPage->xParseCell(pPage, pCell, &sInfo);          \
+  if( sInfo.nLocal!=sInfo.nPayload ){               \
+    rc = clearCellOverflow(pPage, pCell, &sInfo);   \
+  }else{                                            \
+    rc = SQLITE_OK;                                 \
+  }
+
+
 /*
 ** Create the byte sequence used to represent a cell on page pPage
 ** and write that byte sequence into pCell[].  Overflow pages are
@@ -71658,16 +72995,24 @@ static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
 
   if( *pRC ) return;
-  assert( idx>=0 && idx<pPage->nCell );
+  assert( idx>=0 );
+  assert( idx<pPage->nCell );
   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   assert( pPage->nFree>=0 );
   data = pPage->aData;
   ptr = &pPage->aCellIdx[2*idx];
+  assert( pPage->pBt->usableSize > (u32)(ptr-data) );
   pc = get2byte(ptr);
   hdr = pPage->hdrOffset;
-  testcase( pc==get2byte(&data[hdr+5]) );
+#if 0  /* Not required.  Omit for efficiency */
+  if( pc<hdr+pPage->nCell*2 ){
+    *pRC = SQLITE_CORRUPT_BKPT;
+    return;
+  }
+#endif
+  testcase( pc==(u32)get2byte(&data[hdr+5]) );
   testcase( pc+sz==pPage->pBt->usableSize );
   if( pc+sz > pPage->pBt->usableSize ){
     *pRC = SQLITE_CORRUPT_BKPT;
@@ -71959,7 +73304,7 @@ static int rebuildPage(
 
   assert( i<iEnd );
   j = get2byte(&aData[hdr+5]);
-  if( NEVER(j>(u32)usableSize) ){ j = 0; }
+  if( j>(u32)usableSize ){ j = 0; }
   memcpy(&pTmp[j], &aData[j], usableSize - j);
 
   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
@@ -71970,7 +73315,7 @@ static int rebuildPage(
     u8 *pCell = pCArray->apCell[i];
     u16 sz = pCArray->szCell[i];
     assert( sz>0 );
-    if( SQLITE_WITHIN(pCell,aData,pEnd) ){
+    if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
       if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
       pCell = &pTmp[pCell - aData];
     }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
@@ -71983,9 +73328,8 @@ static int rebuildPage(
     put2byte(pCellptr, (pData - aData));
     pCellptr += 2;
     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
-    memcpy(pData, pCell, sz);
+    memmove(pData, pCell, sz);
     assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
-    testcase( sz!=pPg->xCellSize(pPg,pCell) )
     i++;
     if( i>=iEnd ) break;
     if( pCArray->ixNx[k]<=i ){
@@ -72124,7 +73468,9 @@ static int pageFreeArray(
         }
         pFree = pCell;
         szFree = sz;
-        if( pFree+sz>pEnd ) return 0;
+        if( pFree+sz>pEnd ){
+          return 0;
+        }
       }else{
         pFree = pCell;
         szFree += sz;
@@ -72189,6 +73535,7 @@ static int editPage(
 
   pData = &aData[get2byteNotZero(&aData[hdr+5])];
   if( pData<pBegin ) goto editpage_fail;
+  if( pData>pPg->aDataEnd ) goto editpage_fail;
 
   /* Add cells to the start of the page */
   if( iNew<iOld ){
@@ -72550,11 +73897,10 @@ static int balance_nonroot(
   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
-  CellArray b;                  /* Parsed information on cells being balanced */
+  CellArray b;                 /* Parsed information on cells being balanced */
 
   memset(abDone, 0, sizeof(abDone));
-  b.nCell = 0;
-  b.apCell = 0;
+  memset(&b, 0, sizeof(b));
   pBt = pParent->pBt;
   assert( sqlite3_mutex_held(pBt->mutex) );
   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
@@ -72619,6 +73965,7 @@ static int balance_nonroot(
         goto balance_cleanup;
       }
     }
+    nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
     if( (i--)==0 ) break;
 
     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
@@ -72660,7 +74007,6 @@ static int balance_nonroot(
 
   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   ** alignment */
-  nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
   nMaxCells = (nMaxCells + 3)&~3;
 
   /*
@@ -72777,7 +74123,7 @@ static int balance_nonroot(
       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
       if( !pOld->leaf ){
         assert( leafCorrection==0 );
-        assert( pOld->hdrOffset==0 );
+        assert( pOld->hdrOffset==0 || CORRUPT_DB );
         /* The right pointer of the child page pOld becomes the left
         ** pointer of the divider cell */
         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
@@ -72943,7 +74289,9 @@ static int balance_nonroot(
       apOld[i] = 0;
       rc = sqlite3PagerWrite(pNew->pDbPage);
       nNew++;
-      if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv)) ){
+      if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
+       && rc==SQLITE_OK
+      ){
         rc = SQLITE_CORRUPT_BKPT;
       }
       if( rc ) goto balance_cleanup;
@@ -73100,6 +74448,7 @@ static int balance_nonroot(
     u8 *pCell;
     u8 *pTemp;
     int sz;
+    u8 *pSrcEnd;
     MemPage *pNew = apNew[i];
     j = cntNew[i];
 
@@ -73143,6 +74492,12 @@ static int balance_nonroot(
     iOvflSpace += sz;
     assert( sz<=pBt->maxLocal+23 );
     assert( iOvflSpace <= (int)pBt->pageSize );
+    for(k=0; b.ixNx[k]<=j && ALWAYS(k<NB*2); k++){}
+    pSrcEnd = b.apEnd[k];
+    if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
+      rc = SQLITE_CORRUPT_BKPT;
+      goto balance_cleanup;
+    }
     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
     if( rc!=SQLITE_OK ) goto balance_cleanup;
     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
@@ -73356,7 +74711,7 @@ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
 ** on the same B-tree as pCur.
 **
-** This can if a database is corrupt with two or more SQL tables
+** This can occur if a database is corrupt with two or more SQL tables
 ** pointing to the same b-tree.  If an insert occurs on one SQL table
 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
 ** table linked to the same b-tree.  If the secondary insert causes a
@@ -73585,7 +74940,7 @@ static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
   do{
     rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
     if( rc ) return rc;
-    if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
+    if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
       rc = SQLITE_CORRUPT_BKPT;
     }else{
       if( iOffset+ovflPageSize<(u32)nTotal ){
@@ -73653,24 +75008,6 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
   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 );
-    return pCur->skipNext;
-  }
-
-  assert( cursorOwnsBtShared(pCur) );
-  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
-              && pBt->inTransaction==TRANS_WRITE
-              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
-  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
-
-  /* Assert that the caller has been consistent. If this cursor was opened
-  ** expecting an index b-tree, then the caller should be inserting blob
-  ** 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( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
-
   /* Save the positions of any other cursors open on this table.
   **
   ** In some cases, the call to btreeMoveto() below is a no-op. For
@@ -73685,13 +75022,41 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
   if( pCur->curFlags & BTCF_Multiple ){
     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
     if( rc ) return rc;
+    if( loc && pCur->iPage<0 ){
+      /* This can only happen if the schema is corrupt such that there is more
+      ** than one table or index with the same root page as used by the cursor.
+      ** Which can only happen if the SQLITE_NoSchemaError flag was set when
+      ** the schema was loaded. This cannot be asserted though, as a user might
+      ** set the flag, load the schema, and then unset the flag.  */
+      return SQLITE_CORRUPT_BKPT;
+    }
   }
 
+  if( pCur->eState>=CURSOR_REQUIRESEEK ){
+    rc = moveToRoot(pCur);
+    if( rc && rc!=SQLITE_EMPTY ) return rc;
+  }
+
+  assert( cursorOwnsBtShared(pCur) );
+  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
+              && pBt->inTransaction==TRANS_WRITE
+              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
+  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
+
+  /* Assert that the caller has been consistent. If this cursor was opened
+  ** expecting an index b-tree, then the caller should be inserting blob
+  ** 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( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
+
   if( pCur->pKeyInfo==0 ){
     assert( pX->pKey==0 );
     /* If this is an insert into a table b-tree, invalidate any incrblob
     ** cursors open on the row being replaced */
-    invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
+    if( p->hasIncrblobCur ){
+      invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
+    }
 
     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
     ** to a row with the same key as the new entry being inserted.
@@ -73724,7 +75089,8 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
       ** to an adjacent cell.  Move the cursor so that it is pointing either
       ** to the cell to be overwritten or an adjacent cell.
       */
-      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
+      rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
+               (flags & BTREE_APPEND)!=0, &loc);
       if( rc ) return rc;
     }
   }else{
@@ -73747,13 +75113,11 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
         r.aMem = pX->aMem;
         r.nField = pX->nMem;
         r.default_rc = 0;
-        r.errCode = 0;
-        r.r1 = 0;
-        r.r2 = 0;
         r.eqSeen = 0;
-        rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
+        rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
       }else{
-        rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
+        rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
+                    (flags & BTREE_APPEND)!=0, &loc);
       }
       if( rc ) return rc;
     }
@@ -73772,11 +75136,9 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
         return btreeOverwriteCell(pCur, &x2);
       }
     }
-
   }
   assert( pCur->eState==CURSOR_VALID
-       || (pCur->eState==CURSOR_INVALID && loc)
-       || CORRUPT_DB );
+       || (pCur->eState==CURSOR_INVALID && loc) );
 
   pPage = pCur->pPage;
   assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
@@ -73817,7 +75179,10 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
   idx = pCur->ix;
   if( loc==0 ){
     CellInfo info;
-    assert( idx<pPage->nCell );
+    assert( idx>=0 );
+    if( idx>=pPage->nCell ){
+      return SQLITE_CORRUPT_BKPT;
+    }
     rc = sqlite3PagerWrite(pPage->pDbPage);
     if( rc ){
       goto end_insert;
@@ -73826,7 +75191,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
     if( !pPage->leaf ){
       memcpy(newCell, oldCell, 4);
     }
-    rc = clearCell(pPage, oldCell, &info);
+    BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
     testcase( pCur->curFlags & BTCF_ValidOvfl );
     invalidateOverflowCache(pCur);
     if( info.nSize==szNew && info.nLocal==info.nPayload
@@ -73999,7 +75364,7 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64
         }
       }while( rc==SQLITE_OK && nOut>0 );
 
-      if( rc==SQLITE_OK && nRem>0 ){
+      if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
         Pgno pgnoNew;
         MemPage *pNew = 0;
         rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
@@ -74045,14 +75410,13 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64
 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   Btree *p = pCur->pBtree;
   BtShared *pBt = p->pBt;
-  int rc;                              /* Return code */
-  MemPage *pPage;                      /* Page to delete cell from */
-  unsigned char *pCell;                /* Pointer to cell to delete */
-  int iCellIdx;                        /* Index of cell to delete */
-  int iCellDepth;                      /* Depth of node containing pCell */
-  CellInfo info;                       /* Size of the cell being deleted */
-  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
-  u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
+  int rc;                    /* Return code */
+  MemPage *pPage;            /* Page to delete cell from */
+  unsigned char *pCell;      /* Pointer to cell to delete */
+  int iCellIdx;              /* Index of cell to delete */
+  int iCellDepth;            /* Depth of node containing pCell */
+  CellInfo info;             /* Size of the cell being deleted */
+  u8 bPreserve;              /* Keep cursor valid.  2 for CURSOR_SKIPNEXT */
 
   assert( cursorOwnsBtShared(pCur) );
   assert( pBt->inTransaction==TRANS_WRITE );
@@ -74061,27 +75425,45 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
-  if( pCur->eState==CURSOR_REQUIRESEEK ){
-    rc = btreeRestoreCursorPosition(pCur);
-    if( rc ) return rc;
+  if( pCur->eState!=CURSOR_VALID ){
+    if( pCur->eState>=CURSOR_REQUIRESEEK ){
+      rc = btreeRestoreCursorPosition(pCur);
+      assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
+      if( rc || pCur->eState!=CURSOR_VALID ) return rc;
+    }else{
+      return SQLITE_CORRUPT_BKPT;
+    }
   }
   assert( pCur->eState==CURSOR_VALID );
 
   iCellDepth = pCur->iPage;
   iCellIdx = pCur->ix;
   pPage = pCur->pPage;
+  if( pPage->nCell<=iCellIdx ){
+    return SQLITE_CORRUPT_BKPT;
+  }
   pCell = findCell(pPage, iCellIdx);
-  if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
+  if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
+    return SQLITE_CORRUPT_BKPT;
+  }
 
-  /* If the bPreserve flag is set to true, then the cursor position must
+  /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
   ** be preserved following this delete operation. If the current delete
   ** will cause a b-tree rebalance, then this is done by saving the cursor
   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
   ** returning.
   **
-  ** Or, if the current delete will not cause a rebalance, then the cursor
+  ** If the current delete will not cause a rebalance, then the cursor
   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
-  ** before or after the deleted entry. In this case set bSkipnext to true.  */
+  ** before or after the deleted entry.
+  **
+  ** The bPreserve value records which path is required:
+  **
+  **    bPreserve==0         Not necessary to save the cursor position
+  **    bPreserve==1         Use CURSOR_REQUIRESEEK to save the cursor position
+  **    bPreserve==2         Cursor won't move.  Set CURSOR_SKIPNEXT.
+  */
+  bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
   if( bPreserve ){
     if( !pPage->leaf
      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
@@ -74092,7 +75474,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
       rc = saveCursorKey(pCur);
       if( rc ) return rc;
     }else{
-      bSkipnext = 1;
+      bPreserve = 2;
     }
   }
 
@@ -74118,7 +75500,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
 
   /* If this is a delete operation to remove a row from a table b-tree,
   ** invalidate any incrblob cursors open on the row being deleted.  */
-  if( pCur->pKeyInfo==0 ){
+  if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
   }
 
@@ -74127,7 +75509,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   ** itself from within the page.  */
   rc = sqlite3PagerWrite(pPage->pDbPage);
   if( rc ) return rc;
-  rc = clearCell(pPage, pCell, &info);
+  BTREE_CLEAR_CELL(rc, pPage, pCell, info);
   dropCell(pPage, iCellIdx, info.nSize, &rc);
   if( rc ) return rc;
 
@@ -74192,8 +75574,8 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   }
 
   if( rc==SQLITE_OK ){
-    if( bSkipnext ){
-      assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
+    if( bPreserve>1 ){
+      assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
       assert( pPage==pCur->pPage || CORRUPT_DB );
       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
       pCur->eState = CURSOR_SKIPNEXT;
@@ -74387,7 +75769,7 @@ static int clearDatabasePage(
   BtShared *pBt,           /* The BTree that contains the table */
   Pgno pgno,               /* Page number to clear */
   int freePageFlag,        /* Deallocate page if true */
-  int *pnChange            /* Add number of Cells freed to this counter */
+  i64 *pnChange            /* Add number of Cells freed to this counter */
 ){
   MemPage *pPage;
   int rc;
@@ -74402,11 +75784,12 @@ static int clearDatabasePage(
   }
   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
   if( rc ) return rc;
-  if( pPage->bBusy ){
+  if( (pBt->openFlags & BTREE_SINGLE)==0
+   && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
+  ){
     rc = SQLITE_CORRUPT_BKPT;
     goto cleardatabasepage_out;
   }
-  pPage->bBusy = 1;
   hdr = pPage->hdrOffset;
   for(i=0; i<pPage->nCell; i++){
     pCell = findCell(pPage, i);
@@ -74414,14 +75797,15 @@ static int clearDatabasePage(
       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
       if( rc ) goto cleardatabasepage_out;
     }
-    rc = clearCell(pPage, pCell, &info);
+    BTREE_CLEAR_CELL(rc, pPage, pCell, info);
     if( rc ) goto cleardatabasepage_out;
   }
   if( !pPage->leaf ){
     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
     if( rc ) goto cleardatabasepage_out;
-  }else if( pnChange ){
-    assert( pPage->intKey || CORRUPT_DB );
+    if( pPage->intKey ) pnChange = 0;
+  }
+  if( pnChange ){
     testcase( !pPage->intKey );
     *pnChange += pPage->nCell;
   }
@@ -74432,7 +75816,6 @@ static int clearDatabasePage(
   }
 
 cleardatabasepage_out:
-  pPage->bBusy = 0;
   releasePage(pPage);
   return rc;
 }
@@ -74446,11 +75829,10 @@ cleardatabasepage_out:
 ** read cursors on the table.  Open write cursors are moved to the
 ** root of the table.
 **
-** If pnChange is not NULL, then table iTable must be an intkey table. The
-** integer value pointed to by pnChange is incremented by the number of
-** entries in the table.
+** If pnChange is not NULL, then the integer value pointed to by pnChange
+** is incremented by the number of entries in the table.
 */
-SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
+SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
   int rc;
   BtShared *pBt = p->pBt;
   sqlite3BtreeEnter(p);
@@ -74462,7 +75844,9 @@ SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
     ** is the root of a table b-tree - if it is not, the following call is
     ** a no-op).  */
-    invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
+    if( p->hasIncrblobCur ){
+      invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
+    }
     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   }
   sqlite3BtreeLeave(p);
@@ -74510,10 +75894,10 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
     return SQLITE_CORRUPT_BKPT;
   }
 
-  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
-  if( rc ) return rc;
   rc = sqlite3BtreeClearTable(p, iTable, 0);
-  if( rc ){
+  if( rc ) return rc;
+  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
+  if( NEVER(rc) ){
     releasePage(pPage);
     return rc;
   }
@@ -75781,14 +77165,13 @@ static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   if( i==1 ){
     Parse sParse;
     int rc = 0;
-    memset(&sParse, 0, sizeof(sParse));
-    sParse.db = pDb;
+    sqlite3ParseObjectInit(&sParse,pDb);
     if( sqlite3OpenTempDatabase(&sParse) ){
       sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
       rc = SQLITE_ERROR;
     }
     sqlite3DbFree(pErrorDb, sParse.zErrMsg);
-    sqlite3ParserReset(&sParse);
+    sqlite3ParseObjectReset(&sParse);
     if( rc ){
       return 0;
     }
@@ -76545,7 +77928,9 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
 
   /* The szMalloc field holds the correct memory allocation size */
   assert( p->szMalloc==0
-       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
+       || (p->flags==MEM_Undefined
+           && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
+       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
 
   /* If p holds a string or blob, the Mem.z must point to exactly
   ** one of the following:
@@ -76668,10 +78053,15 @@ SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
 #ifndef SQLITE_OMIT_UTF16
   int rc;
 #endif
+  assert( pMem!=0 );
   assert( !sqlite3VdbeMemIsRowSet(pMem) );
   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
            || desiredEnc==SQLITE_UTF16BE );
-  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
+  if( !(pMem->flags&MEM_Str) ){
+    pMem->enc = desiredEnc;
+    return SQLITE_OK;
+  }
+  if( pMem->enc==desiredEnc ){
     return SQLITE_OK;
   }
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
@@ -76709,7 +78099,9 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPre
   testcase( bPreserve && pMem->z==0 );
 
   assert( pMem->szMalloc==0
-       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
+       || (pMem->flags==MEM_Undefined
+           && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
+       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
   if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
     if( pMem->db ){
       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
@@ -76798,6 +78190,7 @@ static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
 */
 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   assert( !sqlite3VdbeMemIsRowSet(pMem) );
   if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
@@ -76822,6 +78215,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
 #ifndef SQLITE_OMIT_INCRBLOB
 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   int nByte;
+  assert( pMem!=0 );
   assert( pMem->flags & MEM_Zero );
   assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
   testcase( sqlite3_value_nochange(pMem) );
@@ -76837,6 +78231,8 @@ SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
     return SQLITE_NOMEM_BKPT;
   }
+  assert( pMem->z!=0 );
+  assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
 
   memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   pMem->n += pMem->u.nZero;
@@ -76849,6 +78245,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
 ** Make sure the given Mem is \u0000 terminated.
 */
 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
@@ -76876,6 +78273,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
   const int nByte = 32;
 
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   assert( !(pMem->flags&MEM_Zero) );
   assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
@@ -76911,6 +78309,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   sqlite3_context ctx;
   Mem t;
   assert( pFunc!=0 );
+  assert( pMem!=0 );
   assert( pFunc->xFinalize!=0 );
   assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
@@ -77054,13 +78453,14 @@ static SQLITE_NOINLINE i64 doubleToInt64(double r){
 **
 ** If pMem represents a string value, its encoding might be changed.
 */
-static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
+static SQLITE_NOINLINE i64 memIntValue(const Mem *pMem){
   i64 value = 0;
   sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
   return value;
 }
-SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
+SQLITE_PRIVATE i64 sqlite3VdbeIntValue(const Mem *pMem){
   int flags;
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   flags = pMem->flags;
@@ -77089,6 +78489,7 @@ static SQLITE_NOINLINE double memRealValue(Mem *pMem){
   return val;
 }
 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   if( pMem->flags & MEM_Real ){
@@ -77121,6 +78522,7 @@ SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
 */
 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   i64 ix;
+  assert( pMem!=0 );
   assert( pMem->flags & MEM_Real );
   assert( !sqlite3VdbeMemIsRowSet(pMem) );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
@@ -77148,6 +78550,7 @@ SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
 ** Convert pMem to type integer.  Invalidate any prior representations.
 */
 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   assert( !sqlite3VdbeMemIsRowSet(pMem) );
   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
@@ -77162,6 +78565,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
 ** Invalidate any prior representations.
 */
 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 
@@ -77195,6 +78599,7 @@ SQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
 ** as much of the string as we can and ignore the rest.
 */
 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
+  assert( pMem!=0 );
   testcase( pMem->flags & MEM_Int );
   testcase( pMem->flags & MEM_Real );
   testcase( pMem->flags & MEM_IntReal );
@@ -77304,6 +78709,7 @@ SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
 ** Delete any previous value and set the value to be a BLOB of length
 ** n containing all zeros.
 */
+#ifndef SQLITE_OMIT_INCRBLOB
 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   sqlite3VdbeMemRelease(pMem);
   pMem->flags = MEM_Blob|MEM_Zero;
@@ -77313,6 +78719,21 @@ SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   pMem->enc = SQLITE_UTF8;
   pMem->z = 0;
 }
+#else
+SQLITE_PRIVATE int sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
+  int nByte = n>0?n:1;
+  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
+    return SQLITE_NOMEM_BKPT;
+  }
+  assert( pMem->z!=0 );
+  assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
+  memset(pMem->z, 0, nByte);
+  pMem->n = n>0?n:0;
+  pMem->flags = MEM_Blob;
+  pMem->enc = SQLITE_UTF8;
+  return SQLITE_OK;
+}
+#endif
 
 /*
 ** The pMem is known to contain content that needs to be destroyed prior
@@ -77352,6 +78773,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
   void (*xDestructor)(void*)
 ){
   assert( pMem->flags==MEM_Null );
+  vdbeMemClear(pMem);
   pMem->u.zPType = zPType ? zPType : "";
   pMem->z = pPtr;
   pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
@@ -77538,14 +78960,15 @@ SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   Mem *pMem,          /* Memory cell to set to string value */
   const char *z,      /* String pointer */
-  int n,              /* Bytes in string, or negative */
+  i64 n,              /* Bytes in string, or negative */
   u8 enc,             /* Encoding of z.  0 for BLOBs */
   void (*xDel)(void*) /* Destructor function */
 ){
-  int nByte = n;      /* New value for pMem->n */
+  i64 nByte = n;      /* New value for pMem->n */
   int iLimit;         /* Maximum allowed string or blob size */
   u16 flags = 0;      /* New value for pMem->flags */
 
+  assert( pMem!=0 );
   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   assert( !sqlite3VdbeMemIsRowSet(pMem) );
 
@@ -77564,7 +78987,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   if( nByte<0 ){
     assert( enc!=0 );
     if( enc==SQLITE_UTF8 ){
-      nByte = 0x7fffffff & (int)strlen(z);
+      nByte = strlen(z);
     }else{
       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
     }
@@ -77576,7 +78999,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   ** management (one of MEM_Dyn or MEM_Static).
   */
   if( xDel==SQLITE_TRANSIENT ){
-    u32 nAlloc = nByte;
+    i64 nAlloc = nByte;
     if( flags&MEM_Term ){
       nAlloc += (enc==SQLITE_UTF8?1:2);
     }
@@ -77602,7 +79025,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
     }
   }
 
-  pMem->n = nByte;
+  pMem->n = (int)(nByte & 0x7fffffff);
   pMem->flags = flags;
   if( enc ){
     pMem->enc = enc;
@@ -77622,7 +79045,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
 #endif
 
   if( nByte>iLimit ){
-    return SQLITE_TOOBIG;
+    return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
   }
 
   return SQLITE_OK;
@@ -77854,7 +79277,7 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
 #ifdef SQLITE_ENABLE_STAT4
 static int valueFromFunction(
   sqlite3 *db,                    /* The database connection */
-  Expr *p,                        /* The expression to evaluate */
+  const Expr *p,                  /* The expression to evaluate */
   u8 enc,                         /* Encoding to use */
   u8 aff,                         /* Affinity to use */
   sqlite3_value **ppVal,          /* Write the new value here */
@@ -77871,8 +79294,10 @@ static int valueFromFunction(
 
   assert( pCtx!=0 );
   assert( (p->flags & EP_TokenOnly)==0 );
+  assert( ExprUseXList(p) );
   pList = p->x.pList;
   if( pList ) nVal = pList->nExpr;
+  assert( !ExprHasProperty(p, EP_IntValue) );
   pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
   assert( pFunc );
   if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
@@ -77948,7 +79373,7 @@ static int valueFromFunction(
 */
 static int valueFromExpr(
   sqlite3 *db,                    /* The database connection */
-  Expr *pExpr,                    /* The expression to evaluate */
+  const Expr *pExpr,              /* The expression to evaluate */
   u8 enc,                         /* Encoding to use */
   u8 affinity,                    /* Affinity to use */
   sqlite3_value **ppVal,          /* Write the new value here */
@@ -77963,11 +79388,7 @@ static int valueFromExpr(
 
   assert( pExpr!=0 );
   while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
-#if defined(SQLITE_ENABLE_STAT4)
   if( op==TK_REGISTER ) op = pExpr->op2;
-#else
-  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
-#endif
 
   /* Compressed expressions only appear when parsing the DEFAULT clause
   ** on a table column definition, and hence only when pCtx==0.  This
@@ -77976,7 +79397,9 @@ static int valueFromExpr(
   assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
 
   if( op==TK_CAST ){
-    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
+    u8 aff;
+    assert( !ExprHasProperty(pExpr, EP_IntValue) );
+    aff = sqlite3AffinityType(pExpr->u.zToken,0);
     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
     testcase( rc!=SQLITE_OK );
     if( *ppVal ){
@@ -78049,6 +79472,7 @@ static int valueFromExpr(
 #ifndef SQLITE_OMIT_BLOB_LITERAL
   else if( op==TK_BLOB ){
     int nVal;
+    assert( !ExprHasProperty(pExpr, EP_IntValue) );
     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
     assert( pExpr->u.zToken[1]=='\'' );
     pVal = valueNew(db, pCtx);
@@ -78066,6 +79490,7 @@ static int valueFromExpr(
   }
 #endif
   else if( op==TK_TRUEFALSE ){
+    assert( !ExprHasProperty(pExpr, EP_IntValue) );
     pVal = valueNew(db, pCtx);
     if( pVal ){
       pVal->flags = MEM_Int;
@@ -78078,7 +79503,7 @@ static int valueFromExpr(
 
 no_mem:
 #ifdef SQLITE_ENABLE_STAT4
-  if( pCtx==0 || pCtx->pParse->nErr==0 )
+  if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
 #endif
     sqlite3OomFault(db);
   sqlite3DbFree(db, zVal);
@@ -78103,7 +79528,7 @@ no_mem:
 */
 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   sqlite3 *db,              /* The database connection */
-  Expr *pExpr,              /* The expression to evaluate */
+  const Expr *pExpr,        /* The expression to evaluate */
   u8 enc,                   /* Encoding to use */
   u8 affinity,              /* Affinity to use */
   sqlite3_value **ppVal     /* Write the new value here */
@@ -78619,8 +80044,10 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   if( p->nOpAlloc<=i ){
     return growOp3(p, op, p1, p2, p3);
   }
+  assert( p->aOp!=0 );
   p->nOp++;
   pOp = &p->aOp[i];
+  assert( pOp!=0 );
   pOp->opcode = (u8)op;
   pOp->p5 = 0;
   pOp->p1 = p1;
@@ -79754,8 +81181,7 @@ SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
 */
 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
   assert( p->nOp>0 || p->aOp==0 );
-  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed
-          || p->pParse->nErr>0 );
+  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
   if( p->nOp ){
     assert( p->aOp );
     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
@@ -79863,13 +81289,9 @@ SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(
   if( zOpName[nOpName+1] ){
     int seenCom = 0;
     char c;
-    zSynopsis = zOpName += nOpName + 1;
+    zSynopsis = zOpName + nOpName + 1;
     if( strncmp(zSynopsis,"IF ",3)==0 ){
-      if( pOp->p5 & SQLITE_STOREP2 ){
-        sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
-      }else{
-        sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
-      }
+      sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
       zSynopsis = zAlt;
     }
     for(ii=0; (c = zSynopsis[ii])!=0; ii++){
@@ -79940,6 +81362,7 @@ static void displayP4Expr(StrAccum *p, Expr *pExpr){
   const char *zOp = 0;
   switch( pExpr->op ){
     case TK_STRING:
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
       break;
     case TK_INTEGER:
@@ -80042,7 +81465,7 @@ SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
     case P4_COLLSEQ: {
       static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
       CollSeq *pColl = pOp->p4.pColl;
-      assert( pColl->enc>=0 && pColl->enc<4 );
+      assert( pColl->enc<4 );
       sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
                           encnames[pColl->enc]);
       break;
@@ -80286,8 +81709,8 @@ static void releaseMemArray(Mem *p, int N){
       */
       testcase( p->flags & MEM_Agg );
       testcase( p->flags & MEM_Dyn );
-      testcase( p->xDel==sqlite3VdbeFrameMemDel );
       if( p->flags&(MEM_Agg|MEM_Dyn) ){
+        testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
         sqlite3VdbeMemRelease(p);
       }else if( p->szMalloc ){
         sqlite3DbFreeNN(db, p->zMalloc);
@@ -80849,8 +82272,6 @@ SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   if( pCx==0 ){
     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);
@@ -81387,9 +82808,9 @@ SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
 ** has made changes and is in autocommit mode, then commit those
 ** changes.  If a rollback is needed, then do the rollback.
 **
-** This routine is the only way to move the state of a VM from
-** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
-** call this on a VM that is in the SQLITE_MAGIC_HALT state.
+** This routine is the only way to move the sqlite3eOpenState of a VM from
+** SQLITE_STATE_RUN to SQLITE_STATE_HALT.  It is harmless to
+** call this on a VM that is in the SQLITE_STATE_HALT state.
 **
 ** Return an error code.  If the commit could not complete because of
 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
@@ -81435,9 +82856,15 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
     sqlite3VdbeEnter(p);
 
     /* Check for one of the special errors */
-    mrc = p->rc & 0xff;
-    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
-                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
+    if( p->rc ){
+      mrc = p->rc & 0xff;
+      isSpecialError = mrc==SQLITE_NOMEM
+                    || mrc==SQLITE_IOERR
+                    || mrc==SQLITE_INTERRUPT
+                    || mrc==SQLITE_FULL;
+    }else{
+      mrc = isSpecialError = 0;
+    }
     if( isSpecialError ){
       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
       ** no rollback is necessary. Otherwise, at least a savepoint
@@ -81489,6 +82916,9 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
             return SQLITE_ERROR;
           }
           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
+        }else if( db->flags & SQLITE_CorruptRdOnly ){
+          rc = SQLITE_CORRUPT;
+          db->flags &= ~SQLITE_CorruptRdOnly;
         }else{
           /* The auto-commit flag is true, the vdbe program was successful
           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
@@ -81622,6 +83052,7 @@ SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
     sqlite3ValueSetNull(db->pErr);
   }
   db->errCode = rc;
+  db->errByteOffset = -1;
   return rc;
 }
 
@@ -81883,7 +83314,7 @@ SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
   assert( p->deferredMoveto );
   assert( p->isTable );
   assert( p->eCurType==CURTYPE_BTREE );
-  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
+  rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
   if( rc ) return rc;
   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
 #ifdef SQLITE_TEST
@@ -81943,7 +83374,7 @@ SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, u32 *piCol){
   if( p->deferredMoveto ){
     u32 iMap;
     assert( !p->isEphemeral );
-    if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 && !p->nullRow ){
+    if( p->ub.aAltMap && (iMap = p->ub.aAltMap[1+*piCol])>0 && !p->nullRow ){
       *pp = p->pAltCursor;
       *piCol = iMap - 1;
       return SQLITE_OK;
@@ -82221,14 +83652,14 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
 
 /*
 ** Deserialize the data blob pointed to by buf as serial type serial_type
-** and store the result in pMem.  Return the number of bytes read.
+** and store the result in pMem.
 **
 ** This function is implemented as two separate routines for performance.
 ** The few cases that require local variables are broken out into a separate
 ** routine so that in most cases the overhead of moving the stack pointer
 ** is avoided.
 */
-static u32 serialGet(
+static void serialGet(
   const unsigned char *buf,     /* Buffer to deserialize from */
   u32 serial_type,              /* Serial type to deserialize */
   Mem *pMem                     /* Memory cell to write value into */
@@ -82262,9 +83693,8 @@ static u32 serialGet(
     memcpy(&pMem->u.r, &x, sizeof(x));
     pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
   }
-  return 8;
 }
-SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
+SQLITE_PRIVATE void sqlite3VdbeSerialGet(
   const unsigned char *buf,     /* Buffer to deserialize from */
   u32 serial_type,              /* Serial type to deserialize */
   Mem *pMem                     /* Memory cell to write value into */
@@ -82275,13 +83705,13 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       pMem->flags = MEM_Null|MEM_Zero;
       pMem->n = 0;
       pMem->u.nZero = 0;
-      break;
+      return;
     }
     case 11:   /* Reserved for future use */
     case 0: {  /* Null */
       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
       pMem->flags = MEM_Null;
-      break;
+      return;
     }
     case 1: {
       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
@@ -82289,7 +83719,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       pMem->u.i = ONE_BYTE_INT(buf);
       pMem->flags = MEM_Int;
       testcase( pMem->u.i<0 );
-      return 1;
+      return;
     }
     case 2: { /* 2-byte signed integer */
       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
@@ -82297,7 +83727,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       pMem->u.i = TWO_BYTE_INT(buf);
       pMem->flags = MEM_Int;
       testcase( pMem->u.i<0 );
-      return 2;
+      return;
     }
     case 3: { /* 3-byte signed integer */
       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
@@ -82305,7 +83735,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       pMem->u.i = THREE_BYTE_INT(buf);
       pMem->flags = MEM_Int;
       testcase( pMem->u.i<0 );
-      return 3;
+      return;
     }
     case 4: { /* 4-byte signed integer */
       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
@@ -82317,7 +83747,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
 #endif
       pMem->flags = MEM_Int;
       testcase( pMem->u.i<0 );
-      return 4;
+      return;
     }
     case 5: { /* 6-byte signed integer */
       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
@@ -82325,13 +83755,14 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
       pMem->flags = MEM_Int;
       testcase( pMem->u.i<0 );
-      return 6;
+      return;
     }
     case 6:   /* 8-byte signed integer */
     case 7: { /* IEEE floating point */
       /* These use local variables, so do them in a separate routine
       ** to avoid having to move the frame pointer in the common case */
-      return serialGet(buf,serial_type,pMem);
+      serialGet(buf,serial_type,pMem);
+      return;
     }
     case 8:    /* Integer 0 */
     case 9: {  /* Integer 1 */
@@ -82339,7 +83770,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
       pMem->u.i = serial_type-8;
       pMem->flags = MEM_Int;
-      return 0;
+      return;
     }
     default: {
       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
@@ -82350,10 +83781,10 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       pMem->z = (char *)buf;
       pMem->n = (serial_type-12)/2;
       pMem->flags = aFlag[serial_type&1];
-      return pMem->n;
+      return;
     }
   }
-  return 0;
+  return;
 }
 /*
 ** This routine is used to allocate sufficient space for an UnpackedRecord
@@ -82416,7 +83847,8 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
     pMem->szMalloc = 0;
     pMem->z = 0;
-    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
+    sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
+    d += sqlite3VdbeSerialTypeLen(serial_type);
     pMem++;
     if( (++u)>=p->nField ) break;
   }
@@ -82500,7 +83932,8 @@ static int vdbeRecordCompareDebug(
 
     /* Extract the values to be compared.
     */
-    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
+    sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
+    d1 += sqlite3VdbeSerialTypeLen(serial_type1);
 
     /* Do the comparison
     */
@@ -82667,7 +84100,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem
 ** number.  Return negative, zero, or positive if the first (i64) is less than,
 ** equal to, or greater than the second (double).
 */
-static int sqlite3IntFloatCompare(i64 i, double r){
+SQLITE_PRIVATE int sqlite3IntFloatCompare(i64 i, double r){
   if( sizeof(LONGDOUBLE_TYPE)>8 ){
     LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
     testcase( x<r );
@@ -83304,7 +84737,7 @@ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   /* The index entry must begin with a header size */
   getVarint32NR((u8*)m.z, szHdr);
   testcase( szHdr==3 );
-  testcase( szHdr==m.n );
+  testcase( szHdr==(u32)m.n );
   testcase( szHdr>0x7fffffff );
   assert( m.n>=0 );
   if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
@@ -83391,7 +84824,7 @@ SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
 ** This routine sets the value to be returned by subsequent calls to
 ** sqlite3_changes() on the database handle 'db'.
 */
-SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
+SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, i64 nChange){
   assert( sqlite3_mutex_held(db->mutex) );
   db->nChange = nChange;
   db->nTotalChange += nChange;
@@ -83571,7 +85004,8 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
   const char *zDb,                /* Database name */
   Table *pTab,                    /* Modified table */
   i64 iKey1,                      /* Initial key value */
-  int iReg                        /* Register for new.* record */
+  int iReg,                       /* Register for new.* record */
+  int iBlobWrite
 ){
   sqlite3 *db = v->db;
   i64 iKey2;
@@ -83592,6 +85026,8 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
     }
   }
 
+  assert( pCsr!=0 );
+  assert( pCsr->eCurType==CURTYPE_BTREE );
   assert( pCsr->nField==pTab->nCol
        || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
   );
@@ -83607,6 +85043,7 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
   preupdate.iKey1 = iKey1;
   preupdate.iKey2 = iKey2;
   preupdate.pTab = pTab;
+  preupdate.iBlobWrite = iBlobWrite;
 
   db->pPreUpdate = &preupdate;
   db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
@@ -83990,8 +85427,8 @@ SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
 ** the function result.
 **
 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
-** result as a string or blob but if the string or blob is too large, it
-** then sets the error code to SQLITE_TOOBIG
+** result as a string or blob.  Appropriate errors are set if the string/blob
+** is too big or if an OOM occurs.
 **
 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
 ** on value P is not going to be used and need to be destroyed.
@@ -84003,8 +85440,16 @@ static void setResultStrOrError(
   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   void (*xDel)(void*)     /* Destructor function */
 ){
-  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
-    sqlite3_result_error_toobig(pCtx);
+  int rc = sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel);
+  if( rc ){
+    if( rc==SQLITE_TOOBIG ){
+      sqlite3_result_error_toobig(pCtx);
+    }else{
+      /* The only errors possible from sqlite3VdbeMemSetStr are
+      ** SQLITE_TOOBIG and SQLITE_NOMEM */
+      assert( rc==SQLITE_NOMEM );
+      sqlite3_result_error_nomem(pCtx);
+    }
   }
 }
 static int invokeValueDestructor(
@@ -84020,7 +85465,7 @@ static int invokeValueDestructor(
   }else{
     xDel((void*)p);
   }
-  if( pCtx ) sqlite3_result_error_toobig(pCtx);
+  sqlite3_result_error_toobig(pCtx);
   return SQLITE_TOOBIG;
 }
 SQLITE_API void sqlite3_result_blob(
@@ -84161,8 +85606,12 @@ SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
   if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
     return SQLITE_TOOBIG;
   }
+#ifndef SQLITE_OMIT_INCRBLOB
   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
   return SQLITE_OK;
+#else
+  return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
+#endif
 }
 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   pCtx->isError = errCode ? errCode : -1;
@@ -84462,6 +85911,70 @@ SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
   return sqlite3_value_nochange(p->pOut);
 }
 
+/*
+** Implementation of sqlite3_vtab_in_first() (if bNext==0) and
+** sqlite3_vtab_in_next() (if bNext!=0).
+*/
+static int valueFromValueList(
+  sqlite3_value *pVal,        /* Pointer to the ValueList object */
+  sqlite3_value **ppOut,      /* Store the next value from the list here */
+  int bNext                   /* 1 for _next(). 0 for _first() */
+){
+  int rc;
+  ValueList *pRhs;
+
+  *ppOut = 0;
+  if( pVal==0 ) return SQLITE_MISUSE;
+  pRhs = (ValueList*)sqlite3_value_pointer(pVal, "ValueList");
+  if( pRhs==0 ) return SQLITE_MISUSE;
+  if( bNext ){
+    rc = sqlite3BtreeNext(pRhs->pCsr, 0);
+  }else{
+    int dummy = 0;
+    rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
+    assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
+    if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
+  }
+  if( rc==SQLITE_OK ){
+    u32 sz;       /* Size of current row in bytes */
+    Mem sMem;     /* Raw content of current row */
+    memset(&sMem, 0, sizeof(sMem));
+    sz = sqlite3BtreePayloadSize(pRhs->pCsr);
+    rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
+    if( rc==SQLITE_OK ){
+      u8 *zBuf = (u8*)sMem.z;
+      u32 iSerial;
+      sqlite3_value *pOut = pRhs->pOut;
+      int iOff = 1 + getVarint32(&zBuf[1], iSerial);
+      sqlite3VdbeSerialGet(&zBuf[iOff], iSerial, pOut);
+      pOut->enc = ENC(pOut->db);
+      if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
+        rc = SQLITE_NOMEM;
+      }else{
+        *ppOut = pOut;
+      }
+    }
+    sqlite3VdbeMemRelease(&sMem);
+  }
+  return rc;
+}
+
+/*
+** Set the iterator value pVal to point to the first value in the set.
+** Set (*ppOut) to point to this value before returning.
+*/
+SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut){
+  return valueFromValueList(pVal, ppOut, 0);
+}
+
+/*
+** Set the iterator value pVal to point to the next value in the set.
+** Set (*ppOut) to point to this value before returning.
+*/
+SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut){
+  return valueFromValueList(pVal, ppOut, 1);
+}
+
 /*
 ** Return the current time for a statement.  If the current time
 ** is requested more than once within the same run of a single prepared
@@ -85002,7 +86515,7 @@ static int bindText(
   sqlite3_stmt *pStmt,   /* The statement to bind against */
   int i,                 /* Index of the parameter to bind */
   const void *zData,     /* Pointer to the data to be bound */
-  int nData,             /* Number of bytes of data to be bound */
+  i64 nData,             /* Number of bytes of data to be bound */
   void (*xDel)(void*),   /* Destructor for the data */
   u8 encoding            /* Encoding for the data */
 ){
@@ -85054,11 +86567,7 @@ SQLITE_API int sqlite3_bind_blob64(
   void (*xDel)(void*)
 ){
   assert( xDel!=SQLITE_DYNAMIC );
-  if( nData>0x7fffffff ){
-    return invokeValueDestructor(zData, xDel, 0);
-  }else{
-    return bindText(pStmt, i, zData, (int)nData, xDel, 0);
-  }
+  return bindText(pStmt, i, zData, nData, xDel, 0);
 }
 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   int rc;
@@ -85128,12 +86637,8 @@ SQLITE_API int sqlite3_bind_text64(
   unsigned char enc
 ){
   assert( xDel!=SQLITE_DYNAMIC );
-  if( nData>0x7fffffff ){
-    return invokeValueDestructor(zData, xDel, 0);
-  }else{
-    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
-    return bindText(pStmt, i, zData, (int)nData, xDel, enc);
-  }
+  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
+  return bindText(pStmt, i, zData, nData, xDel, enc);
 }
 #ifndef SQLITE_OMIT_UTF16
 SQLITE_API int sqlite3_bind_text16(
@@ -85154,7 +86659,10 @@ SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_valu
       break;
     }
     case SQLITE_FLOAT: {
-      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
+      assert( pValue->flags & (MEM_Real|MEM_IntReal) );
+      rc = sqlite3_bind_double(pStmt, i,
+          (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
+      );
       break;
     }
     case SQLITE_BLOB: {
@@ -85182,7 +86690,11 @@ SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   Vdbe *p = (Vdbe *)pStmt;
   rc = vdbeUnbind(p, i);
   if( rc==SQLITE_OK ){
+#ifndef SQLITE_OMIT_INCRBLOB
     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
+#else
+    rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
+#endif
     sqlite3_mutex_leave(p->db->mutex);
   }
   return rc;
@@ -85470,6 +86982,7 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa
     u32 nRec;
     u8 *aRec;
 
+    assert( p->pCsr->eCurType==CURTYPE_BTREE );
     nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
     aRec = sqlite3DbMallocRaw(db, nRec);
     if( !aRec ) goto preupdate_old_out;
@@ -85533,6 +87046,17 @@ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
 }
 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
+/*
+** This function is designed to be called from within a pre-update callback
+** only.
+*/
+SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *db){
+  PreUpdate *p = db->pPreUpdate;
+  return (p ? p->iBlobWrite : -1);
+}
+#endif
+
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 /*
 ** This function is called from within a pre-update callback to retrieve
@@ -85766,11 +87290,9 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
 #ifndef SQLITE_OMIT_UTF16
   Mem utf8;                /* Used to convert UTF16 into UTF8 for display */
 #endif
-  char zBase[100];         /* Initial working space */
 
   db = p->db;
-  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
-                      db->aLimit[SQLITE_LIMIT_LENGTH]);
+  sqlite3StrAccumInit(&out, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
   if( db->nVdbeExec>1 ){
     while( *zRawSql ){
       const char *zStart = zRawSql;
@@ -86120,7 +87642,6 @@ static VdbeCursor *allocateCursor(
   Vdbe *p,              /* The virtual machine */
   int iCur,             /* Index of the new VdbeCursor */
   int nField,           /* Number of fields in the table or index */
-  int iDb,              /* Database the cursor belongs to, or -1 */
   u8 eCurType           /* Type of the new cursor */
 ){
   /* Find the memory cell that will be used to store the blob of memory
@@ -86154,18 +87675,35 @@ static VdbeCursor *allocateCursor(
     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
     p->apCsr[iCur] = 0;
   }
-  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
-    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
-    memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
-    pCx->eCurType = eCurType;
-    pCx->iDb = iDb;
-    pCx->nField = nField;
-    pCx->aOffset = &pCx->aType[nField];
-    if( eCurType==CURTYPE_BTREE ){
-      pCx->uc.pCursor = (BtCursor*)
-          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
-      sqlite3BtreeCursorZero(pCx->uc.pCursor);
+
+  /* There used to be a call to sqlite3VdbeMemClearAndResize() to make sure
+  ** the pMem used to hold space for the cursor has enough storage available
+  ** in pMem->zMalloc.  But for the special case of the aMem[] entries used
+  ** to hold cursors, it is faster to in-line the logic. */
+  assert( pMem->flags==MEM_Undefined );
+  assert( (pMem->flags & MEM_Dyn)==0 );
+  assert( pMem->szMalloc==0 || pMem->z==pMem->zMalloc );
+  if( pMem->szMalloc<nByte ){
+    if( pMem->szMalloc>0 ){
+      sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
+    }
+    pMem->z = pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, nByte);
+    if( pMem->zMalloc==0 ){
+      pMem->szMalloc = 0;
+      return 0;
     }
+    pMem->szMalloc = nByte;
+  }
+
+  p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc;
+  memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
+  pCx->eCurType = eCurType;
+  pCx->nField = nField;
+  pCx->aOffset = &pCx->aType[nField];
+  if( eCurType==CURTYPE_BTREE ){
+    pCx->uc.pCursor = (BtCursor*)
+        &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
+    sqlite3BtreeCursorZero(pCx->uc.pCursor);
   }
   return pCx;
 }
@@ -86312,7 +87850,10 @@ static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
   sqlite3_int64 ix;
   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
   assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
-  ExpandBlob(pMem);
+  if( ExpandBlob(pMem) ){
+    pMem->u.i = 0;
+    return MEM_Int;
+  }
   rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
   if( rc<=0 ){
     if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
@@ -86450,6 +87991,11 @@ static void registerTrace(int iReg, Mem *p){
   printf("\n");
   sqlite3VdbeCheckMemInvariants(p);
 }
+/**/ void sqlite3PrintMem(Mem *pMem){
+  memTracePrint(pMem);
+  printf("\n");
+  fflush(stdout);
+}
 #endif
 
 #ifdef SQLITE_DEBUG
@@ -86477,96 +88023,7 @@ SQLITE_PRIVATE void sqlite3VdbeRegisterDump(Vdbe *v){
 ** hwtime.h contains inline assembler code for implementing
 ** high-performance timing routines.
 */
-/************** Include hwtime.h in the middle of vdbe.c *********************/
-/************** Begin file hwtime.h ******************************************/
-/*
-** 2008 May 27
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-******************************************************************************
-**
-** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 and x86_64 class CPUs.
-*/
-#ifndef SQLITE_HWTIME_H
-#define SQLITE_HWTIME_H
-
-/*
-** The following routine only works on pentium-class (or newer) processors.
-** It uses the RDTSC opcode to read the cycle count value out of the
-** processor and returns that value.  This can be used for high-res
-** profiling.
-*/
-#if !defined(__STRICT_ANSI__) && \
-    (defined(__GNUC__) || defined(_MSC_VER)) && \
-    (defined(i386) || defined(__i386__) || defined(_M_IX86))
-
-  #if defined(__GNUC__)
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-     unsigned int lo, hi;
-     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
-     return (sqlite_uint64)hi << 32 | lo;
-  }
-
-  #elif defined(_MSC_VER)
-
-  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
-     __asm {
-        rdtsc
-        ret       ; return value at EDX:EAX
-     }
-  }
-
-  #endif
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long val;
-      __asm__ __volatile__ ("rdtsc" : "=A" (val));
-      return val;
-  }
-
-#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
-
-  __inline__ sqlite_uint64 sqlite3Hwtime(void){
-      unsigned long long retval;
-      unsigned long junk;
-      __asm__ __volatile__ ("\n\
-          1:      mftbu   %1\n\
-                  mftb    %L0\n\
-                  mftbu   %0\n\
-                  cmpw    %0,%1\n\
-                  bne     1b"
-                  : "=r" (retval), "=r" (junk));
-      return retval;
-  }
-
-#else
-
-  /*
-  ** asm() is needed for hardware timing support.  Without asm(),
-  ** disable the sqlite3Hwtime() routine.
-  **
-  ** sqlite3Hwtime() is only used for some obscure debugging
-  ** and analysis configurations, not in any deliverable, so this
-  ** should not be a great loss.
-  */
-SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
-
-#endif
-
-#endif /* !defined(SQLITE_HWTIME_H) */
-
-/************** End of hwtime.h **********************************************/
-/************** Continuing where we left off in vdbe.c ***********************/
+/* #include "hwtime.h" */
 
 #endif
 
@@ -86613,6 +88070,42 @@ static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
   }
 }
 
+/*
+** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
+** with pOp->p3.  Return the hash.
+*/
+static u64 filterHash(const Mem *aMem, const Op *pOp){
+  int i, mx;
+  u64 h = 0;
+
+  assert( pOp->p4type==P4_INT32 );
+  for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
+    const Mem *p = &aMem[i];
+    if( p->flags & (MEM_Int|MEM_IntReal) ){
+      h += p->u.i;
+    }else if( p->flags & MEM_Real ){
+      h += sqlite3VdbeIntValue(p);
+    }else if( p->flags & (MEM_Str|MEM_Blob) ){
+      h += p->n;
+      if( p->flags & MEM_Zero ) h += p->u.nZero;
+    }
+  }
+  return h;
+}
+
+/*
+** Return the symbolic name for the data type of a pMem
+*/
+static const char *vdbeMemTypeName(Mem *pMem){
+  static const char *azTypes[] = {
+      /* SQLITE_INTEGER */ "INT",
+      /* SQLITE_FLOAT   */ "REAL",
+      /* SQLITE_TEXT    */ "TEXT",
+      /* SQLITE_BLOB    */ "BLOB",
+      /* SQLITE_NULL    */ "NULL"
+  };
+  return azTypes[sqlite3_value_type(pMem)-1];
+}
 
 /*
 ** Execute as much of a VDBE program as we can.
@@ -86895,6 +88388,8 @@ case OP_Gosub: {            /* jump */
   /* Most jump operations do a goto to this spot in order to update
   ** the pOp pointer. */
 jump_to_p2:
+  assert( pOp->p2>0 );       /* There are never any jumps to instruction 0 */
+  assert( pOp->p2<p->nOp );  /* Jumps must be in range */
   pOp = &aOp[pOp->p2 - 1];
   break;
 }
@@ -87254,12 +88749,18 @@ case OP_SoftNull: {
 ** Synopsis: r[P2]=P4 (len=P1)
 **
 ** P4 points to a blob of data P1 bytes long.  Store this
-** blob in register P2.
+** blob in register P2.  If P4 is a NULL pointer, then construct
+** a zero-filled blob that is P1 bytes long in P2.
 */
 case OP_Blob: {                /* out2 */
   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   pOut = out2Prerelease(p, pOp);
-  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
+  if( pOp->p4.z==0 ){
+    sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
+    if( sqlite3VdbeMemExpandBlob(pOut) ) goto no_mem;
+  }else{
+    sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
+  }
   pOut->enc = encoding;
   UPDATE_MAX_BLOBSIZE(pOut);
   break;
@@ -87408,24 +88909,22 @@ case OP_IntCopy: {            /* out2 */
   break;
 }
 
-/* Opcode: ChngCntRow P1 P2 * * *
-** Synopsis: output=r[P1]
+/* Opcode: FkCheck * * * * *
 **
-** 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.
+** Halt with an SQLITE_CONSTRAINT error if there are any unresolved
+** foreign key constraint violations.  If there are no foreign key
+** constraint violations, this is a no-op.
 **
-** 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.
+** FK constraint violations are also checked when the prepared statement
+** exits.  This opcode is used to raise foreign key constraint errors prior
+** to returning results such as a row change count or the result of a
+** RETURNING clause.
 */
-case OP_ChngCntRow: {
-  assert( pOp->p2==1 );
+case OP_FkCheck: {
   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
+  break;
 }
 
 /* Opcode: ResultRow P1 P2 * * *
@@ -87441,7 +88940,7 @@ case OP_ResultRow: {
   Mem *pMem;
   int i;
   assert( p->nResColumn==pOp->p2 );
-  assert( pOp->p1>0 );
+  assert( pOp->p1>0 || CORRUPT_DB );
   assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
 
   /* Invalidate all ephemeral cursor row caches */
@@ -87883,8 +89382,7 @@ case OP_Cast: {                  /* in1 */
 ** Synopsis: IF r[P3]==r[P1]
 **
 ** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
-** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then
-** store the result of comparison in register P2.
+** jump to address P2.
 **
 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
@@ -87910,9 +89408,8 @@ case OP_Cast: {                  /* in1 */
 ** If neither operand is NULL the result is the same as it would be if
 ** the SQLITE_NULLEQ flag were omitted from P5.
 **
-** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
-** content of r[P2] is only changed if the new value is NULL or 0 (false).
-** In other words, a prior r[P2] value will not be overwritten by 1 (true).
+** This opcode saves the result of comparison for use by the new
+** OP_Jump opcode.
 */
 /* Opcode: Ne P1 P2 P3 P4 P5
 ** Synopsis: IF r[P3]!=r[P1]
@@ -87920,17 +89417,12 @@ case OP_Cast: {                  /* in1 */
 ** This works just like the Eq opcode except that the jump is taken if
 ** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
 ** additional information.
-**
-** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
-** content of r[P2] is only changed if the new value is NULL or 1 (true).
-** In other words, a prior r[P2] value will not be overwritten by 0 (false).
 */
 /* Opcode: Lt P1 P2 P3 P4 P5
 ** Synopsis: IF r[P3]<r[P1]
 **
 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
-** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store
-** the result of comparison (0 or 1 or NULL) into register P2.
+** jump to address P2.
 **
 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
 ** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL
@@ -87953,6 +89445,9 @@ case OP_Cast: {                  /* in1 */
 ** numeric, then a numeric comparison is used. If the two values
 ** are of different types, then numbers are considered less than
 ** strings and strings are considered less than blobs.
+**
+** This opcode saves the result of comparison for use by the new
+** OP_Jump opcode.
 */
 /* Opcode: Le P1 P2 P3 P4 P5
 ** Synopsis: IF r[P3]<=r[P1]
@@ -87990,6 +89485,31 @@ case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   pIn3 = &aMem[pOp->p3];
   flags1 = pIn1->flags;
   flags3 = pIn3->flags;
+  if( (flags1 & flags3 & MEM_Int)!=0 ){
+    assert( (pOp->p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_TEXT || CORRUPT_DB );
+    /* Common case of comparison of two integers */
+    if( pIn3->u.i > pIn1->u.i ){
+      iCompare = +1;
+      if( sqlite3aGTb[pOp->opcode] ){
+        VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
+        goto jump_to_p2;
+      }
+    }else if( pIn3->u.i < pIn1->u.i ){
+      iCompare = -1;
+      if( sqlite3aLTb[pOp->opcode] ){
+        VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
+        goto jump_to_p2;
+      }
+    }else{
+      iCompare = 0;
+      if( sqlite3aEQb[pOp->opcode] ){
+        VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
+        goto jump_to_p2;
+      }
+    }
+    VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
+    break;
+  }
   if( (flags1 | flags3)&MEM_Null ){
     /* One or both operands are NULL */
     if( pOp->p5 & SQLITE_NULLEQ ){
@@ -88012,22 +89532,16 @@ case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
       ** then the result is always NULL.
       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
       */
-      if( pOp->p5 & SQLITE_STOREP2 ){
-        pOut = &aMem[pOp->p2];
-        iCompare = 1;    /* Operands are not equal */
-        memAboutToChange(p, pOut);
-        MemSetTypeFlag(pOut, MEM_Null);
-        REGISTER_TRACE(pOp->p2, pOut);
-      }else{
-        VdbeBranchTaken(2,3);
-        if( pOp->p5 & SQLITE_JUMPIFNULL ){
-          goto jump_to_p2;
-        }
+      iCompare = 1;    /* Operands are not equal */
+      VdbeBranchTaken(2,3);
+      if( pOp->p5 & SQLITE_JUMPIFNULL ){
+        goto jump_to_p2;
       }
       break;
     }
   }else{
-    /* Neither operand is NULL.  Do a comparison. */
+    /* Neither operand is NULL and we couldn't do the special high-speed
+    ** integer comparison case.  So do a general-case comparison. */
     affinity = pOp->p5 & SQLITE_AFF_MASK;
     if( affinity>=SQLITE_AFF_NUMERIC ){
       if( (flags1 | flags3)&MEM_Str ){
@@ -88040,14 +89554,6 @@ case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
           applyNumericAffinity(pIn3,0);
         }
       }
-      /* Handle the common case of integer comparison here, as an
-      ** optimization, to avoid a call to sqlite3MemCompare() */
-      if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
-        if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
-        if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
-        res = 0;
-        goto compare_op;
-      }
     }else if( affinity==SQLITE_AFF_TEXT ){
       if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
         testcase( pIn1->flags & MEM_Int );
@@ -88056,7 +89562,7 @@ case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
         sqlite3VdbeMemStringify(pIn1, encoding, 1);
         testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
         flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
-        if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
+        if( pIn1==pIn3 ) flags3 = flags1 | MEM_Str;
       }
       if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
         testcase( pIn3->flags & MEM_Int );
@@ -88070,7 +89576,7 @@ case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   }
-compare_op:
+
   /* At this point, res is negative, zero, or positive if reg[P1] is
   ** less than, equal to, or greater than reg[P3], respectively.  Compute
   ** the answer to this operator in res2, depending on what the comparison
@@ -88079,16 +89585,14 @@ compare_op:
   ** order:  NE, EQ, GT, LE, LT, GE */
   assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
   assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
-  if( res<0 ){                        /* ne, eq, gt, le, lt, ge */
-    static const unsigned char aLTb[] = { 1,  0,  0,  1,  1,  0 };
-    res2 = aLTb[pOp->opcode - OP_Ne];
+  if( res<0 ){
+    res2 = sqlite3aLTb[pOp->opcode];
   }else if( res==0 ){
-    static const unsigned char aEQb[] = { 0,  1,  0,  1,  0,  1 };
-    res2 = aEQb[pOp->opcode - OP_Ne];
+    res2 = sqlite3aEQb[pOp->opcode];
   }else{
-    static const unsigned char aGTb[] = { 1,  0,  1,  0,  0,  1 };
-    res2 = aGTb[pOp->opcode - OP_Ne];
+    res2 = sqlite3aGTb[pOp->opcode];
   }
+  iCompare = res;
 
   /* Undo any changes made by applyAffinity() to the input registers. */
   assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
@@ -88096,67 +89600,39 @@ compare_op:
   assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
   pIn1->flags = flags1;
 
-  if( pOp->p5 & SQLITE_STOREP2 ){
-    pOut = &aMem[pOp->p2];
-    iCompare = res;
-    if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
-      /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
-      ** and prevents OP_Ne from overwriting NULL with 0.  This flag
-      ** is only used in contexts where either:
-      **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
-      **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
-      ** Therefore it is not necessary to check the content of r[P2] for
-      ** NULL. */
-      assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
-      assert( res2==0 || res2==1 );
-      testcase( res2==0 && pOp->opcode==OP_Eq );
-      testcase( res2==1 && pOp->opcode==OP_Eq );
-      testcase( res2==0 && pOp->opcode==OP_Ne );
-      testcase( res2==1 && pOp->opcode==OP_Ne );
-      if( (pOp->opcode==OP_Eq)==res2 ) break;
-    }
-    memAboutToChange(p, pOut);
-    MemSetTypeFlag(pOut, MEM_Int);
-    pOut->u.i = res2;
-    REGISTER_TRACE(pOp->p2, pOut);
-  }else{
-    VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
-    if( res2 ){
-      goto jump_to_p2;
-    }
+  VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
+  if( res2 ){
+    goto jump_to_p2;
   }
   break;
 }
 
-/* Opcode: ElseNotEq * P2 * * *
+/* Opcode: ElseEq * P2 * * *
 **
 ** This opcode must follow an OP_Lt or OP_Gt comparison operator.  There
 ** can be zero or more OP_ReleaseReg opcodes intervening, but no other
 ** opcodes are allowed to occur between this instruction and the previous
-** OP_Lt or OP_Gt.  Furthermore, the prior OP_Lt or OP_Gt must have the
-** SQLITE_STOREP2 bit set in the P5 field.
+** OP_Lt or OP_Gt.
 **
 ** If result of an OP_Eq comparison on the same two operands as the
-** prior OP_Lt or OP_Gt would have been NULL or false (0), then then
-** jump to P2.  If the result of an OP_Eq comparison on the two previous
-** operands would have been true (1), then fall through.
+** prior OP_Lt or OP_Gt would have been true, then jump to P2.
+** If the result of an OP_Eq comparison on the two previous
+** operands would have been false or NULL, then fall through.
 */
-case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
+case OP_ElseEq: {       /* same as TK_ESCAPE, jump */
 
 #ifdef SQLITE_DEBUG
   /* Verify the preconditions of this opcode - that it follows an OP_Lt or
-  ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening
-  ** OP_ReleaseReg opcodes */
+  ** OP_Gt with zero or more intervening OP_ReleaseReg opcodes */
   int iAddr;
   for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
     if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
     assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
-    assert( aOp[iAddr].p5 & SQLITE_STOREP2 );
     break;
   }
 #endif /* SQLITE_DEBUG */
-  VdbeBranchTaken(iCompare!=0, 2);
-  if( iCompare!=0 ) goto jump_to_p2;
+  VdbeBranchTaken(iCompare==0, 2);
+  if( iCompare==0 ) goto jump_to_p2;
   break;
 }
 
@@ -88467,6 +89943,40 @@ case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   break;
 }
 
+/* Opcode: IsNullOrType P1 P2 P3 * *
+** Synopsis: if typeof(r[P1]) IN (P3,5) goto P2
+**
+** Jump to P2 if the value in register P1 is NULL or has a datatype P3.
+** P3 is an integer which should be one of SQLITE_INTEGER, SQLITE_FLOAT,
+** SQLITE_BLOB, SQLITE_NULL, or SQLITE_TEXT.
+*/
+case OP_IsNullOrType: {      /* jump, in1 */
+  int doTheJump;
+  pIn1 = &aMem[pOp->p1];
+  doTheJump = (pIn1->flags & MEM_Null)!=0 || sqlite3_value_type(pIn1)==pOp->p3;
+  VdbeBranchTaken( doTheJump, 2);
+  if( doTheJump ) goto jump_to_p2;
+  break;
+}
+
+/* Opcode: ZeroOrNull P1 P2 P3 * *
+** Synopsis: r[P2] = 0 OR NULL
+**
+** If all both registers P1 and P3 are NOT NULL, then store a zero in
+** register P2.  If either registers P1 or P3 are NULL then put
+** a NULL in register P2.
+*/
+case OP_ZeroOrNull: {            /* in1, in2, out2, in3 */
+  if( (aMem[pOp->p1].flags & MEM_Null)!=0
+   || (aMem[pOp->p3].flags & MEM_Null)!=0
+  ){
+    sqlite3VdbeMemSetNull(aMem + pOp->p2);
+  }else{
+    sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
+  }
+  break;
+}
+
 /* Opcode: NotNull P1 P2 * * *
 ** Synopsis: if r[P1]!=NULL goto P2
 **
@@ -88520,10 +90030,18 @@ case OP_Offset: {          /* out3 */
   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   pC = p->apCsr[pOp->p1];
   pOut = &p->aMem[pOp->p3];
-  if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
+  if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
     sqlite3VdbeMemSetNull(pOut);
   }else{
-    sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
+    if( pC->deferredMoveto ){
+      rc = sqlite3VdbeFinishMoveto(pC);
+      if( rc ) goto abort_due_to_error;
+    }
+    if( sqlite3BtreeEof(pC->uc.pCursor) ){
+      sqlite3VdbeMemSetNull(pOut);
+    }else{
+      sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
+    }
   }
   break;
 }
@@ -88582,6 +90100,7 @@ case OP_Column: {
   assert( pC!=0 );
   assert( p2<(u32)pC->nField );
   aOffset = pC->aOffset;
+  assert( aOffset==pC->aType+pC->nField );
   assert( pC->eCurType!=CURTYPE_VTAB );
   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
   assert( pC->eCurType!=CURTYPE_SORTER );
@@ -88817,6 +90336,110 @@ op_column_corrupt:
   }
 }
 
+/* Opcode: TypeCheck P1 P2 P3 P4 *
+** Synopsis: typecheck(r[P1@P2])
+**
+** Apply affinities to the range of P2 registers beginning with P1.
+** Take the affinities from the Table object in P4.  If any value
+** cannot be coerced into the correct type, then raise an error.
+**
+** This opcode is similar to OP_Affinity except that this opcode
+** forces the register type to the Table column type.  This is used
+** to implement "strict affinity".
+**
+** GENERATED ALWAYS AS ... STATIC columns are only checked if P3
+** is zero.  When P3 is non-zero, no type checking occurs for
+** static generated columns.  Virtual columns are computed at query time
+** and so they are never checked.
+**
+** Preconditions:
+**
+** <ul>
+** <li> P2 should be the number of non-virtual columns in the
+**      table of P4.
+** <li> Table P4 should be a STRICT table.
+** </ul>
+**
+** If any precondition is false, an assertion fault occurs.
+*/
+case OP_TypeCheck: {
+  Table *pTab;
+  Column *aCol;
+  int i;
+
+  assert( pOp->p4type==P4_TABLE );
+  pTab = pOp->p4.pTab;
+  assert( pTab->tabFlags & TF_Strict );
+  assert( pTab->nNVCol==pOp->p2 );
+  aCol = pTab->aCol;
+  pIn1 = &aMem[pOp->p1];
+  for(i=0; i<pTab->nCol; i++){
+    if( aCol[i].colFlags & COLFLAG_GENERATED ){
+      if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;
+      if( pOp->p3 ){ pIn1++; continue; }
+    }
+    assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
+    applyAffinity(pIn1, aCol[i].affinity, encoding);
+    if( (pIn1->flags & MEM_Null)==0 ){
+      switch( aCol[i].eCType ){
+        case COLTYPE_BLOB: {
+          if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
+          break;
+        }
+        case COLTYPE_INTEGER:
+        case COLTYPE_INT: {
+          if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
+          break;
+        }
+        case COLTYPE_TEXT: {
+          if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
+          break;
+        }
+        case COLTYPE_REAL: {
+          testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
+          testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_IntReal );
+          if( pIn1->flags & MEM_Int ){
+            /* When applying REAL affinity, if the result is still an MEM_Int
+            ** that will fit in 6 bytes, then change the type to MEM_IntReal
+            ** so that we keep the high-resolution integer value but know that
+            ** the type really wants to be REAL. */
+            testcase( pIn1->u.i==140737488355328LL );
+            testcase( pIn1->u.i==140737488355327LL );
+            testcase( pIn1->u.i==-140737488355328LL );
+            testcase( pIn1->u.i==-140737488355329LL );
+            if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
+              pIn1->flags |= MEM_IntReal;
+              pIn1->flags &= ~MEM_Int;
+            }else{
+              pIn1->u.r = (double)pIn1->u.i;
+              pIn1->flags |= MEM_Real;
+              pIn1->flags &= ~MEM_Int;
+            }
+          }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
+            goto vdbe_type_error;
+          }
+          break;
+        }
+        default: {
+          /* COLTYPE_ANY.  Accept anything. */
+          break;
+        }
+      }
+    }
+    REGISTER_TRACE((int)(pIn1-aMem), pIn1);
+    pIn1++;
+  }
+  assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
+  break;
+
+vdbe_type_error:
+  sqlite3VdbeError(p, "cannot store %s value in %s column %s.%s",
+     vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
+     pTab->zName, aCol[i].zCnName);
+  rc = SQLITE_CONSTRAINT_DATATYPE;
+  goto abort_due_to_error;
+}
+
 /* Opcode: Affinity P1 P2 * P4 *
 ** Synopsis: affinity(r[P1@P2])
 **
@@ -89031,7 +90654,7 @@ case OP_MakeRecord: {
       testcase( uu==127 );               testcase( uu==128 );
       testcase( uu==32767 );             testcase( uu==32768 );
       testcase( uu==8388607 );           testcase( uu==8388608 );
-      testcase( uu==2147483647 );        testcase( uu==2147483648 );
+      testcase( uu==2147483647 );        testcase( uu==2147483648LL );
       testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
       if( uu<=127 ){
         if( (i&1)==i && file_format>=4 ){
@@ -89159,7 +90782,7 @@ case OP_MakeRecord: {
   break;
 }
 
-/* Opcode: Count P1 P2 p3 * *
+/* Opcode: Count P1 P2 P3 * *
 ** Synopsis: r[P2]=count()
 **
 ** Store the number of entries (an integer value) in the table or index
@@ -89480,8 +91103,16 @@ case OP_Transaction: {
   assert( pOp->p2>=0 && pOp->p2<=2 );
   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   assert( DbMaskTest(p->btreeMask, pOp->p1) );
-  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
-    rc = SQLITE_READONLY;
+  assert( rc==SQLITE_OK );
+  if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
+    if( db->flags & SQLITE_QueryOnly ){
+      /* Writes prohibited by the "PRAGMA query_only=TRUE" statement */
+      rc = SQLITE_READONLY;
+    }else{
+      /* Writes prohibited due to a prior SQLITE_CORRUPT in the current
+      ** transaction */
+      rc = SQLITE_CORRUPT;
+    }
     goto abort_due_to_error;
   }
   pBt = db->aDb[pOp->p1].pBt;
@@ -89523,7 +91154,8 @@ case OP_Transaction: {
     }
   }
   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
-  if( pOp->p5
+  if( rc==SQLITE_OK
+   && pOp->p5
    && (iMeta!=pOp->p3
       || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
   ){
@@ -89620,6 +91252,7 @@ case OP_SetCookie: {
     /* When the schema cookie changes, record the new cookie internally */
     pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5;
     db->mDbFlags |= DBFLAG_SchemaChange;
+    sqlite3FkClearTriggerCache(db, pOp->p1);
   }else if( pOp->p2==BTREE_FILE_FORMAT ){
     /* Record changes in the file format */
     pDb->pSchema->file_format = pOp->p3;
@@ -89733,6 +91366,8 @@ case OP_ReopenIdx: {
   pCur = p->apCsr[pOp->p1];
   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
+    assert( pCur->eCurType==CURTYPE_BTREE );
+    sqlite3BtreeClearCursor(pCur->uc.pCursor);
     goto open_cursor_set_hints;
   }
   /* If the cursor is not currently open or is open on a different
@@ -89795,8 +91430,9 @@ case OP_OpenWrite:
   assert( pOp->p1>=0 );
   assert( nField>=0 );
   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
-  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
+  pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
   if( pCur==0 ) goto no_mem;
+  pCur->iDb = iDb;
   pCur->nullRow = 1;
   pCur->isOrdered = 1;
   pCur->pgnoRoot = p2;
@@ -89838,7 +91474,7 @@ case OP_OpenDup: {
   assert( pOrig );
   assert( pOrig->isEphemeral );  /* Only ephemeral cursors can be duplicated */
 
-  pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
+  pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
   if( pCx==0 ) goto no_mem;
   pCx->nullRow = 1;
   pCx->isEphemeral = 1;
@@ -89846,10 +91482,10 @@ case OP_OpenDup: {
   pCx->isTable = pOrig->isTable;
   pCx->pgnoRoot = pOrig->pgnoRoot;
   pCx->isOrdered = pOrig->isOrdered;
-  pCx->pBtx = pOrig->pBtx;
+  pCx->ub.pBtx = pOrig->ub.pBtx;
   pCx->hasBeenDuped = 1;
   pOrig->hasBeenDuped = 1;
-  rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
+  rc = sqlite3BtreeCursor(pCx->ub.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
@@ -89915,23 +91551,23 @@ case OP_OpenEphemeral: {
     aMem[pOp->p3].z = "";
   }
   pCx = p->apCsr[pOp->p1];
-  if( pCx && !pCx->hasBeenDuped ){
+  if( pCx && !pCx->hasBeenDuped &&  ALWAYS(pOp->p2<=pCx->nField) ){
     /* 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;
-    rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
+    rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
   }else{
-    pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
+    pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
     if( pCx==0 ) goto no_mem;
     pCx->isEphemeral = 1;
-    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
+    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
                           BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
                           vfsFlags);
     if( rc==SQLITE_OK ){
-      rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
+      rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
       if( rc==SQLITE_OK ){
         /* If a transient index is required, create it by calling
         ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
@@ -89940,26 +91576,26 @@ case OP_OpenEphemeral: {
         */
         if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
           assert( pOp->p4type==P4_KEYINFO );
-          rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
+          rc = sqlite3BtreeCreateTable(pCx->ub.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,
+            rc = sqlite3BtreeCursor(pCx->ub.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,
+          rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
               0, pCx->uc.pCursor);
           pCx->isTable = 1;
         }
       }
       pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
       if( rc ){
-        sqlite3BtreeClose(pCx->pBtx);
+        sqlite3BtreeClose(pCx->ub.pBtx);
       }
     }
   }
@@ -89983,7 +91619,7 @@ case OP_SorterOpen: {
 
   assert( pOp->p1>=0 );
   assert( pOp->p2>=0 );
-  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
+  pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
   if( pCx==0 ) goto no_mem;
   pCx->pKeyInfo = pOp->p4.pKeyInfo;
   assert( pCx->pKeyInfo->db==db );
@@ -90032,7 +91668,7 @@ case OP_OpenPseudo: {
 
   assert( pOp->p1>=0 );
   assert( pOp->p3>=0 );
-  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
+  pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
   if( pCx==0 ) goto no_mem;
   pCx->nullRow = 1;
   pCx->seekResult = pOp->p2;
@@ -90220,6 +91856,7 @@ case OP_SeekGT: {       /* jump, in3, group */
     /* If the P3 value could not be converted into an integer without
     ** loss of information, then special processing is required... */
     if( (newType & (MEM_Int|MEM_IntReal))==0 ){
+      int c;
       if( (newType & MEM_Real)==0 ){
         if( (newType & MEM_Null) || oc>=OP_SeekGE ){
           VdbeBranchTaken(1,2);
@@ -90229,7 +91866,8 @@ case OP_SeekGT: {       /* jump, in3, group */
           if( rc!=SQLITE_OK ) goto abort_due_to_error;
           goto seek_not_found;
         }
-      }else
+      }
+      c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
 
       /* If the approximation iKey is larger than the actual real search
       ** term, substitute >= for > and < for <=. e.g. if the search term
@@ -90238,7 +91876,7 @@ case OP_SeekGT: {       /* jump, in3, group */
       **        (x >  4.9)    ->     (x >= 5)
       **        (x <= 4.9)    ->     (x <  5)
       */
-      if( pIn3->u.r<(double)iKey ){
+      if( c>0 ){
         assert( OP_SeekGE==(OP_SeekGT-1) );
         assert( OP_SeekLT==(OP_SeekLE-1) );
         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
@@ -90247,14 +91885,14 @@ case OP_SeekGT: {       /* jump, in3, group */
 
       /* If the approximation iKey is smaller than the actual real search
       ** term, substitute <= for < and > for >=.  */
-      else if( pIn3->u.r>(double)iKey ){
+      else if( c<0 ){
         assert( OP_SeekLE==(OP_SeekLT+1) );
         assert( OP_SeekGT==(OP_SeekGE+1) );
         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
       }
     }
-    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
+    rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
     pC->movetoTarget = iKey;  /* Used by OP_Delete */
     if( rc!=SQLITE_OK ){
       goto abort_due_to_error;
@@ -90301,7 +91939,7 @@ case OP_SeekGT: {       /* jump, in3, group */
     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
 #endif
     r.eqSeen = 0;
-    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
+    rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
     if( rc!=SQLITE_OK ){
       goto abort_due_to_error;
     }
@@ -90523,8 +92161,18 @@ case OP_SeekHit: {
   assert( pC!=0 );
   assert( pOp->p3>=pOp->p2 );
   if( pC->seekHit<pOp->p2 ){
+#ifdef SQLITE_DEBUG
+    if( db->flags&SQLITE_VdbeTrace ){
+      printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
+    }
+#endif
     pC->seekHit = pOp->p2;
   }else if( pC->seekHit>pOp->p3 ){
+#ifdef SQLITE_DEBUG
+    if( db->flags&SQLITE_VdbeTrace ){
+      printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
+    }
+#endif
     pC->seekHit = pOp->p3;
   }
   break;
@@ -90639,6 +92287,11 @@ case OP_IfNoHope: {     /* jump, in3 */
   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   pC = p->apCsr[pOp->p1];
   assert( pC!=0 );
+#ifdef SQLITE_DEBUG
+  if( db->flags&SQLITE_VdbeTrace ){
+    printf("seekHit is %d\n", pC->seekHit);
+  }
+#endif
   if( pC->seekHit>=pOp->p4.i ) break;
   /* Fall through into OP_NotFound */
   /* no break */ deliberate_fall_through
@@ -90705,7 +92358,7 @@ case OP_Found: {        /* jump, in3 */
       }
     }
   }
-  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
+  rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &res);
   if( pFree ) sqlite3DbFreeNN(db, pFree);
   if( rc!=SQLITE_OK ){
     goto abort_due_to_error;
@@ -90814,7 +92467,7 @@ notExistsWithKey:
   pCrsr = pC->uc.pCursor;
   assert( pCrsr!=0 );
   res = 0;
-  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
+  rc = sqlite3BtreeTableMoveto(pCrsr, iKey, 0, &res);
   assert( rc==SQLITE_OK || res==0 );
   pC->movetoTarget = iKey;  /* Used by OP_Delete */
   pC->nullRow = 0;
@@ -90971,7 +92624,7 @@ case OP_NewRowid: {           /* out2 */
       do{
         sqlite3_randomness(sizeof(v), &v);
         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
-      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
+      }while(  ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
                                                  0, &res))==SQLITE_OK)
             && (res==0)
             && (++cnt<100));
@@ -91061,14 +92714,14 @@ case OP_Insert: {
     assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
   }else{
     pTab = 0;
-    zDb = 0;  /* Not needed.  Silence a compiler warning. */
+    zDb = 0;
   }
 
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   /* Invoke the pre-update hook, if any */
   if( pTab ){
     if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
-      sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
+      sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
     }
     if( db->xUpdateCallback==0 || pTab->aCol==0 ){
       /* Prevent post-update hook from running in cases when it should not */
@@ -91214,13 +92867,14 @@ case OP_Delete: {
       pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
     }
   }else{
-    zDb = 0;   /* Not needed.  Silence a compiler warning. */
-    pTab = 0;  /* Not needed.  Silence a compiler warning. */
+    zDb = 0;
+    pTab = 0;
   }
 
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   /* Invoke the pre-update-hook if required. */
-  if( db->xPreUpdateCallback && pOp->p4.pTab ){
+  assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
+  if( db->xPreUpdateCallback && pTab ){
     assert( !(opflags & OPFLAG_ISUPDATE)
          || HasRowid(pTab)==0
          || (aMem[pOp->p3].flags & MEM_Int)
@@ -91228,7 +92882,7 @@ case OP_Delete: {
     sqlite3VdbePreUpdateHook(p, pC,
         (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
         zDb, pTab, pC->movetoTarget,
-        pOp->p3
+        pOp->p3, -1
     );
   }
   if( opflags & OPFLAG_ISNOOP ) break;
@@ -91261,7 +92915,7 @@ case OP_Delete: {
   /* Invoke the update-hook if required. */
   if( opflags & OPFLAG_NCHANGE ){
     p->nChange++;
-    if( db->xUpdateCallback && HasRowid(pTab) ){
+    if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
           pC->movetoTarget);
       assert( pC->iDb>=0 );
@@ -91466,6 +93120,10 @@ case OP_Rowid: {                 /* out2 */
 ** Move the cursor P1 to a null row.  Any OP_Column operations
 ** that occur while the cursor is on the null row will always
 ** write a NULL.
+**
+** Or, if P1 is a Pseudo-Cursor (a cursor opened using OP_OpenPseudo)
+** just reset the cache for that cursor.  This causes the row of
+** content held by the pseudo-cursor to be reparsed.
 */
 case OP_NullRow: {
   VdbeCursor *pC;
@@ -91848,7 +93506,8 @@ case OP_SorterInsert: {     /* in2 */
 ** an UPDATE or DELETE statement and the index entry to be updated
 ** or deleted is not found.  For some uses of IdxDelete
 ** (example:  the EXCEPT operator) it does not matter that no matching
-** entry is found.  For those cases, P5 is zero.
+** entry is found.  For those cases, P5 is zero.  Also, do not raise
+** this (self-correcting and non-critical) error if in writable_schema mode.
 */
 case OP_IdxDelete: {
   VdbeCursor *pC;
@@ -91869,12 +93528,12 @@ case OP_IdxDelete: {
   r.nField = (u16)pOp->p3;
   r.default_rc = 0;
   r.aMem = &aMem[pOp->p2];
-  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
+  rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res);
   if( rc ) goto abort_due_to_error;
   if( res==0 ){
     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
     if( rc ) goto abort_due_to_error;
-  }else if( pOp->p5 ){
+  }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
     rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
     goto abort_due_to_error;
   }
@@ -91953,9 +93612,9 @@ case OP_IdxRowid: {           /* out2 */
       pTabCur->movetoTarget = rowid;
       pTabCur->deferredMoveto = 1;
       assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
-      pTabCur->aAltMap = pOp->p4.ai;
-      assert( !pC->isEphemeral );
       assert( !pTabCur->isEphemeral );
+      pTabCur->ub.aAltMap = pOp->p4.ai;
+      assert( !pC->isEphemeral );
       pTabCur->pAltCursor = pC;
     }else{
       pOut = out2Prerelease(p, pOp);
@@ -92174,24 +93833,21 @@ case OP_Destroy: {     /* out2 */
 ** P2==1 then the table to be clear is in the auxiliary database file
 ** that is used to store tables create using CREATE TEMPORARY TABLE.
 **
-** If the P3 value is non-zero, then the table referred to must be an
-** intkey table (an SQL table, not an index). In this case the row change
-** count is incremented by the number of rows in the table being cleared.
-** If P3 is greater than zero, then the value stored in register P3 is
-** also incremented by the number of rows in the table being cleared.
+** If the P3 value is non-zero, then the row change count is incremented
+** by the number of rows in the table being cleared. If P3 is greater
+** than zero, then the value stored in register P3 is also incremented
+** by the number of rows in the table being cleared.
 **
 ** See also: Destroy
 */
 case OP_Clear: {
-  int nChange;
+  i64 nChange;
 
   sqlite3VdbeIncrWriteCounter(p, 0);
   nChange = 0;
   assert( p->readOnly==0 );
   assert( DbMaskTest(p->btreeMask, pOp->p2) );
-  rc = sqlite3BtreeClearTable(
-      db->aDb[pOp->p2].pBt, (u32)pOp->p1, (pOp->p3 ? &nChange : 0)
-  );
+  rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
   if( pOp->p3 ){
     p->nChange += nChange;
     if( pOp->p3>0 ){
@@ -92297,7 +93953,9 @@ case OP_ParseSchema: {
 
   iDb = pOp->p1;
   assert( iDb>=0 && iDb<db->nDb );
-  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
+  assert( DbHasProperty(db, iDb, DB_SchemaLoaded)
+           || db->mallocFailed
+           || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
 
 #ifndef SQLITE_OMIT_ALTERTABLE
   if( pOp->p4.z==0 ){
@@ -92309,7 +93967,7 @@ case OP_ParseSchema: {
   }else
 #endif
   {
-    zSchema = DFLT_SCHEMA_TABLE;
+    zSchema = LEGACY_SCHEMA_TABLE;
     initData.db = db;
     initData.iDb = iDb;
     initData.pzErrMsg = &p->zErrMsg;
@@ -93179,6 +94837,7 @@ case OP_JournalMode: {    /* out2 */
   pPager = sqlite3BtreePager(pBt);
   eOld = sqlite3PagerGetJournalMode(pPager);
   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
+  assert( sqlite3BtreeHoldsMutex(pBt) );
   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
 
 #ifndef SQLITE_OMIT_WAL
@@ -93477,7 +95136,7 @@ case OP_VOpen: {
   pVCur->pVtab = pVtab;
 
   /* Initialize vdbe cursor object */
-  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
+  pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
   if( pCur ){
     pCur->uc.pVCur = pVCur;
     pVtab->nRef++;
@@ -93490,6 +95149,34 @@ case OP_VOpen: {
 }
 #endif /* SQLITE_OMIT_VIRTUALTABLE */
 
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/* Opcode: VInitIn P1 P2 P3 * *
+** Synopsis: r[P2]=ValueList(P1,P3)
+**
+** Set register P2 to be a pointer to a ValueList object for cursor P1
+** with cache register P3 and output register P3+1.  This ValueList object
+** can be used as the first argument to sqlite3_vtab_in_first() and
+** sqlite3_vtab_in_next() to extract all of the values stored in the P1
+** cursor.  Register P3 is used to hold the values returned by
+** sqlite3_vtab_in_first() and sqlite3_vtab_in_next().
+*/
+case OP_VInitIn: {        /* out2 */
+  VdbeCursor *pC;         /* The cursor containing the RHS values */
+  ValueList *pRhs;        /* New ValueList object to put in reg[P2] */
+
+  pC = p->apCsr[pOp->p1];
+  pRhs = sqlite3_malloc64( sizeof(*pRhs) );
+  if( pRhs==0 ) goto no_mem;
+  pRhs->pCsr = pC->uc.pCursor;
+  pRhs->pOut = &aMem[pOp->p3];
+  pOut = out2Prerelease(p, pOp);
+  pOut->flags = MEM_Null;
+  sqlite3VdbeMemSetPointer(pOut, pRhs, "ValueList", sqlite3_free);
+  break;
+}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 /* Opcode: VFilter P1 P2 P3 P4 *
 ** Synopsis: iplan=r[P3] zplan='P4'
@@ -93528,6 +95215,7 @@ case OP_VFilter: {   /* jump */
   pCur = p->apCsr[pOp->p1];
   assert( memIsValid(pQuery) );
   REGISTER_TRACE(pOp->p3, pQuery);
+  assert( pCur!=0 );
   assert( pCur->eCurType==CURTYPE_VTAB );
   pVCur = pCur->uc.pVCur;
   pVtab = pVCur->pVtab;
@@ -93539,7 +95227,6 @@ case OP_VFilter: {   /* jump */
   iQuery = (int)pQuery->u.i;
 
   /* Invoke the xFilter method */
-  res = 0;
   apArg = p->apArg;
   for(i = 0; i<nArg; i++){
     apArg[i] = &pArgc[i+1];
@@ -93577,6 +95264,7 @@ case OP_VColumn: {
   sqlite3_context sContext;
 
   VdbeCursor *pCur = p->apCsr[pOp->p1];
+  assert( pCur!=0 );
   assert( pCur->eCurType==CURTYPE_VTAB );
   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   pDest = &aMem[pOp->p3];
@@ -93629,8 +95317,8 @@ case OP_VNext: {   /* jump */
   int res;
   VdbeCursor *pCur;
 
-  res = 0;
   pCur = p->apCsr[pOp->p1];
+  assert( pCur!=0 );
   assert( pCur->eCurType==CURTYPE_VTAB );
   if( pCur->nullRow ){
     break;
@@ -93726,7 +95414,7 @@ case OP_VUpdate: {
   const sqlite3_module *pModule;
   int nArg;
   int i;
-  sqlite_int64 rowid;
+  sqlite_int64 rowid = 0;
   Mem **apArg;
   Mem *pX;
 
@@ -93914,6 +95602,77 @@ case OP_Function: {            /* group */
   break;
 }
 
+/* Opcode: FilterAdd P1 * P3 P4 *
+** Synopsis: filter(P1) += key(P3@P4)
+**
+** Compute a hash on the P4 registers starting with r[P3] and
+** add that hash to the bloom filter contained in r[P1].
+*/
+case OP_FilterAdd: {
+  u64 h;
+
+  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
+  pIn1 = &aMem[pOp->p1];
+  assert( pIn1->flags & MEM_Blob );
+  assert( pIn1->n>0 );
+  h = filterHash(aMem, pOp);
+#ifdef SQLITE_DEBUG
+  if( db->flags&SQLITE_VdbeTrace ){
+    int ii;
+    for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
+      registerTrace(ii, &aMem[ii]);
+    }
+    printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
+  }
+#endif
+  h %= pIn1->n;
+  pIn1->z[h/8] |= 1<<(h&7);
+  break;
+}
+
+/* Opcode: Filter P1 P2 P3 P4 *
+** Synopsis: if key(P3@P4) not in filter(P1) goto P2
+**
+** Compute a hash on the key contained in the P4 registers starting
+** with r[P3].  Check to see if that hash is found in the
+** bloom filter hosted by register P1.  If it is not present then
+** maybe jump to P2.  Otherwise fall through.
+**
+** False negatives are harmless.  It is always safe to fall through,
+** even if the value is in the bloom filter.  A false negative causes
+** more CPU cycles to be used, but it should still yield the correct
+** answer.  However, an incorrect answer may well arise from a
+** false positive - if the jump is taken when it should fall through.
+*/
+case OP_Filter: {          /* jump */
+  u64 h;
+
+  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
+  pIn1 = &aMem[pOp->p1];
+  assert( (pIn1->flags & MEM_Blob)!=0 );
+  assert( pIn1->n >= 1 );
+  h = filterHash(aMem, pOp);
+#ifdef SQLITE_DEBUG
+  if( db->flags&SQLITE_VdbeTrace ){
+    int ii;
+    for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
+      registerTrace(ii, &aMem[ii]);
+    }
+    printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
+  }
+#endif
+  h %= pIn1->n;
+  if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
+    VdbeBranchTaken(1, 2);
+    p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
+    goto jump_to_p2;
+  }else{
+    p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
+    VdbeBranchTaken(0, 2);
+  }
+  break;
+}
+
 /* Opcode: Trace P1 P2 * P4 *
 **
 ** Write P4 on the statement trace output if statement tracing is
@@ -94171,6 +95930,18 @@ abort_due_to_error:
     rc = SQLITE_CORRUPT_BKPT;
   }
   assert( rc );
+#ifdef SQLITE_DEBUG
+  if( db->flags & SQLITE_VdbeTrace ){
+    const char *zTrace = p->zSql;
+    if( zTrace==0 ){
+      if( aOp[0].opcode==OP_Trace ){
+        zTrace = aOp[0].p4.z;
+      }
+      if( zTrace==0 ) zTrace = "???";
+    }
+    printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
+  }
+#endif
   if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
   }
@@ -94181,6 +95952,9 @@ abort_due_to_error:
                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
   sqlite3VdbeHalt(p);
   if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
+  if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
+    db->flags |= SQLITE_CorruptRdOnly;
+  }
   rc = SQLITE_ERROR;
   if( resetSchemaOnFault>0 ){
     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
@@ -94312,7 +96086,10 @@ static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   }
   if( rc==SQLITE_ROW ){
     VdbeCursor *pC = v->apCsr[0];
-    u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
+    u32 type;
+    assert( pC!=0 );
+    assert( pC->eCurType==CURTYPE_BTREE );
+    type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
     testcase( pC->nHdrParsed==p->iCol );
     testcase( pC->nHdrParsed==p->iCol+1 );
     if( type<12 ){
@@ -94386,10 +96163,9 @@ SQLITE_API int sqlite3_blob_open(
   sqlite3_mutex_enter(db->mutex);
 
   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
-  do {
-    memset(&sParse, 0, sizeof(Parse));
+  while(1){
+    sqlite3ParseObjectInit(&sParse,db);
     if( !pBlob ) goto blob_open_out;
-    sParse.db = db;
     sqlite3DbFree(db, zErr);
     zErr = 0;
 
@@ -94404,7 +96180,7 @@ SQLITE_API int sqlite3_blob_open(
       sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
     }
 #ifndef SQLITE_OMIT_VIEW
-    if( pTab && pTab->pSelect ){
+    if( pTab && IsView(pTab) ){
       pTab = 0;
       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
     }
@@ -94424,7 +96200,7 @@ SQLITE_API int sqlite3_blob_open(
 
     /* Now search pTab for the exact column. */
     for(iCol=0; iCol<pTab->nCol; iCol++) {
-      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
+      if( sqlite3StrICmp(pTab->aCol[iCol].zCnName, zColumn)==0 ){
         break;
       }
     }
@@ -94449,7 +96225,8 @@ SQLITE_API int sqlite3_blob_open(
         ** key columns must be indexed. The check below will pick up this
         ** case.  */
         FKey *pFKey;
-        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+        assert( IsOrdinaryTable(pTab) );
+        for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
           int j;
           for(j=0; j<pFKey->nCol; j++){
             if( pFKey->aCol[j].iFrom==iCol ){
@@ -94565,7 +96342,9 @@ SQLITE_API int sqlite3_blob_open(
       goto blob_open_out;
     }
     rc = blobSeekToRow(pBlob, iRow, &zErr);
-  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
+    if( (++nAttempt)>=SQLITE_MAX_SCHEMA_RETRY || rc!=SQLITE_SCHEMA ) break;
+    sqlite3ParseObjectReset(&sParse);
+  }
 
 blob_open_out:
   if( rc==SQLITE_OK && db->mallocFailed==0 ){
@@ -94576,7 +96355,7 @@ blob_open_out:
   }
   sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
   sqlite3DbFree(db, zErr);
-  sqlite3ParserReset(&sParse);
+  sqlite3ParseObjectReset(&sParse);
   rc = sqlite3ApiExit(db, rc);
   sqlite3_mutex_leave(db->mutex);
   return rc;
@@ -94656,8 +96435,10 @@ static int blobReadWrite(
       */
       sqlite3_int64 iKey;
       iKey = sqlite3BtreeIntegerKey(p->pCsr);
+      assert( v->apCsr[0]!=0 );
+      assert( v->apCsr[0]->eCurType==CURTYPE_BTREE );
       sqlite3VdbePreUpdateHook(
-          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
+          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol
       );
     }
 #endif
@@ -94728,6 +96509,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
     rc = SQLITE_ABORT;
   }else{
     char *zErr;
+    ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
     rc = blobSeekToRow(p, iRow, &zErr);
     if( rc!=SQLITE_OK ){
       sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
@@ -95708,7 +97490,8 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit(
   }
 #endif
 
-  assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
+  assert( pCsr->pKeyInfo );
+  assert( !pCsr->isEphemeral );
   assert( pCsr->eCurType==CURTYPE_SORTER );
   szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
   sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
@@ -95821,8 +97604,9 @@ static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
   fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
 }
 static void vdbeSorterRewindDebug(const char *zEvent){
-  i64 t;
-  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
+  i64 t = 0;
+  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
+  if( ALWAYS(pVfs) ) sqlite3OsCurrentTimeInt64(pVfs, &t);
   fprintf(stderr, "%lld:X %s\n", t, zEvent);
 }
 static void vdbeSorterPopulateDebug(
@@ -96036,7 +97820,7 @@ static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
     sqlite3OsFetch(pFd, 0, (int)nByte, &p);
-    sqlite3OsUnfetch(pFd, 0, p);
+    if( p ) sqlite3OsUnfetch(pFd, 0, p);
   }
 }
 #else
@@ -96754,6 +98538,7 @@ static int vdbeIncrMergerNew(
     vdbeMergeEngineFree(pMerger);
     rc = SQLITE_NOMEM_BKPT;
   }
+  assert( *ppOut!=0 || rc!=SQLITE_OK );
   return rc;
 }
 
@@ -98119,6 +99904,9 @@ static int memjrnlCreateFile(MemJournal *p){
 }
 
 
+/* Forward reference */
+static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size);
+
 /*
 ** Write data to the file.
 */
@@ -98149,22 +99937,20 @@ static int memjrnlWrite(
     ** the in-memory journal is being used by a connection using the
     ** atomic-write optimization. In this case the first 28 bytes of the
     ** journal file may be written as part of committing the transaction. */
-    assert( iOfst==p->endpoint.iOffset || iOfst==0 );
-#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
- || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
+    assert( iOfst<=p->endpoint.iOffset );
+    if( iOfst>0 && iOfst!=p->endpoint.iOffset ){
+      memjrnlTruncate(pJfd, iOfst);
+    }
     if( iOfst==0 && p->pFirst ){
       assert( p->nChunkSize>iAmt );
       memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
-    }else
-#else
-    assert( iOfst>0 || p->pFirst==0 );
-#endif
-    {
+    }else{
       while( nWrite>0 ){
         FileChunk *pChunk = p->endpoint.pChunk;
         int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
         int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
 
+        assert( pChunk!=0 || iChunkOffset==0 );
         if( iChunkOffset==0 ){
           /* New chunk is required to extend the file. */
           FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
@@ -98179,10 +99965,11 @@ static int memjrnlWrite(
             assert( !p->pFirst );
             p->pFirst = pNew;
           }
-          p->endpoint.pChunk = pNew;
+          pChunk = p->endpoint.pChunk = pNew;
         }
 
-        memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
+        assert( pChunk!=0 );
+        memcpy((u8*)pChunk->zChunk + iChunkOffset, zWrite, iSpace);
         zWrite += iSpace;
         nWrite -= iSpace;
         p->endpoint.iOffset += iSpace;
@@ -98198,26 +99985,28 @@ static int memjrnlWrite(
 */
 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   MemJournal *p = (MemJournal *)pJfd;
-  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;
+  assert( p->endpoint.pChunk==0 || p->endpoint.pChunk->pNext==0 );
+  if( size<p->endpoint.iOffset ){
+    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;
+    p->endpoint.pChunk = pIter;
+    p->endpoint.iOffset = size;
+    p->readpoint.pChunk = 0;
+    p->readpoint.iOffset = 0;
+  }
   return SQLITE_OK;
 }
 
@@ -98410,15 +100199,10 @@ static int walkWindowList(Walker *pWalker, Window *pList, int bOneOnly){
     if( rc ) return WRC_Abort;
     rc = sqlite3WalkExpr(pWalker, pWin->pFilter);
     if( rc ) return WRC_Abort;
-
-    /* The next two are purely for calls to sqlite3RenameExprUnmap()
-    ** within sqlite3WindowOffsetExpr().  Because of constraints imposed
-    ** by sqlite3WindowOffsetExpr(), they can never fail.  The results do
-    ** not matter anyhow. */
     rc = sqlite3WalkExpr(pWalker, pWin->pStart);
-    if( NEVER(rc) ) return WRC_Abort;
+    if( rc ) return WRC_Abort;
     rc = sqlite3WalkExpr(pWalker, pWin->pEnd);
-    if( NEVER(rc) ) return WRC_Abort;
+    if( rc ) return WRC_Abort;
     if( bOneOnly ) break;
   }
   return WRC_Continue;
@@ -98458,7 +100242,7 @@ static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
         assert( !ExprHasProperty(pExpr, EP_WinFunc) );
         pExpr = pExpr->pRight;
         continue;
-      }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+      }else if( ExprUseXSelect(pExpr) ){
         assert( !ExprHasProperty(pExpr, EP_WinFunc) );
         if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
       }else{
@@ -98495,6 +100279,16 @@ SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   return WRC_Continue;
 }
 
+/*
+** This is a no-op callback for Walker->xSelectCallback2.  If this
+** callback is set, then the Select->pWinDefn list is traversed.
+*/
+SQLITE_PRIVATE void sqlite3WalkWinDefnDummyCallback(Walker *pWalker, Select *p){
+  UNUSED_PARAMETER(pWalker);
+  UNUSED_PARAMETER(p);
+  /* No-op */
+}
+
 /*
 ** Walk all expressions associated with SELECT statement p.  Do
 ** not invoke the SELECT callback on p, but do (of course) invoke
@@ -98508,10 +100302,15 @@ SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
-#if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE)
-  {
-    Parse *pParse = pWalker->pParse;
-    if( pParse && IN_RENAME_OBJECT ){
+#if !defined(SQLITE_OMIT_WINDOWFUNC)
+  if( p->pWinDefn ){
+    Parse *pParse;
+    if( pWalker->xSelectCallback2==sqlite3WalkWinDefnDummyCallback
+     || ((pParse = pWalker->pParse)!=0 && IN_RENAME_OBJECT)
+#ifndef SQLITE_OMIT_CTE
+     || pWalker->xSelectCallback2==sqlite3SelectPopWith
+#endif
+    ){
       /* The following may return WRC_Abort if there are unresolvable
       ** symbols (e.g. a table that does not exist) in a window definition. */
       int rc = walkWindowList(pWalker, p->pWinDefn, 0);
@@ -98535,7 +100334,7 @@ SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   SrcItem *pItem;
 
   pSrc = p->pSrc;
-  if( pSrc ){
+  if( ALWAYS(pSrc) ){
     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
       if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
         return WRC_Abort;
@@ -98709,9 +100508,13 @@ static void resolveAlias(
   assert( pOrig!=0 );
   db = pParse->db;
   pDup = sqlite3ExprDup(db, pOrig, 0);
-  if( pDup!=0 ){
+  if( db->mallocFailed ){
+    sqlite3ExprDelete(db, pDup);
+    pDup = 0;
+  }else{
     incrAggFunctionDepth(pDup, nSubquery);
     if( pExpr->op==TK_COLLATE ){
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
     }
 
@@ -98731,10 +100534,8 @@ static void resolveAlias(
       pExpr->flags |= EP_MemToken;
     }
     if( ExprHasProperty(pExpr, EP_WinFunc) ){
-      if( pExpr->y.pWin!=0 ){
+      if( ALWAYS(pExpr->y.pWin!=0) ){
         pExpr->y.pWin->pOwner = pExpr;
-      }else{
-        assert( db->mallocFailed );
       }
     }
     sqlite3DbFree(db, pDup);
@@ -98817,6 +100618,7 @@ SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr *pExpr){
   Table *pExTab;
 
   n = pExpr->iColumn;
+  assert( ExprUseYTab(pExpr) );
   pExTab = pExpr->y.pTab;
   assert( pExTab!=0 );
   if( (pExTab->tabFlags & TF_HasGenerated)!=0
@@ -98930,7 +100732,7 @@ static int lookupName(
         u8 hCol;
         pTab = pItem->pTab;
         assert( pTab!=0 && pTab->zName!=0 );
-        assert( pTab->nCol>0 );
+        assert( pTab->nCol>0 || pParse->nErr );
         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
           int hit = 0;
           pEList = pItem->pSelect->pEList;
@@ -98945,8 +100747,9 @@ static int lookupName(
           }
           if( hit || zTab==0 ) continue;
         }
-        if( zDb && pTab->pSchema!=pSchema ){
-          continue;
+        if( zDb ){
+          if( pTab->pSchema!=pSchema ) continue;
+          if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
         }
         if( zTab ){
           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
@@ -98954,16 +100757,16 @@ static int lookupName(
           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
             continue;
           }
+          assert( ExprUseYTab(pExpr) );
           if( IN_RENAME_OBJECT && pItem->zAlias ){
             sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
           }
         }
-        if( 0==(cntTab++) ){
-          pMatch = pItem;
-        }
         hCol = sqlite3StrIHash(zCol);
         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
-          if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
+          if( pCol->hName==hCol
+           && sqlite3StrICmp(pCol->zCnName, zCol)==0
+          ){
             /* If there has been exactly one prior match and this match
             ** is for the right-hand table of a NATURAL JOIN or is in a
             ** USING clause, then skip this match.
@@ -98979,9 +100782,14 @@ static int lookupName(
             break;
           }
         }
+        if( 0==cnt && VisibleRowid(pTab) ){
+          cntTab++;
+          pMatch = pItem;
+        }
       }
       if( pMatch ){
         pExpr->iTable = pMatch->iCursor;
+        assert( ExprUseYTab(pExpr) );
         pExpr->y.pTab = pMatch->pTab;
         /* RIGHT JOIN not (yet) supported */
         assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
@@ -99036,7 +100844,9 @@ static int lookupName(
         pSchema = pTab->pSchema;
         cntTab++;
         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
-          if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
+          if( pCol->hName==hCol
+           && sqlite3StrICmp(pCol->zCnName, zCol)==0
+          ){
             if( iCol==pTab->iPKey ){
               iCol = -1;
             }
@@ -99053,6 +100863,7 @@ static int lookupName(
 #ifndef SQLITE_OMIT_UPSERT
           if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
             testcase( iCol==(-1) );
+            assert( ExprUseYTab(pExpr) );
             if( IN_RENAME_OBJECT ){
               pExpr->iColumn = iCol;
               pExpr->y.pTab = pTab;
@@ -99065,9 +100876,11 @@ static int lookupName(
           }else
 #endif /* SQLITE_OMIT_UPSERT */
           {
+            assert( ExprUseYTab(pExpr) );
             pExpr->y.pTab = pTab;
             if( pParse->bReturning ){
               eNewExprOp = TK_REGISTER;
+              pExpr->op2 = TK_COLUMN;
               pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
                  sqlite3TableColumnToStorage(pTab, iCol) + 1;
             }else{
@@ -99101,7 +100914,7 @@ static int lookupName(
      && pMatch
      && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
      && sqlite3IsRowid(zCol)
-     && VisibleRowid(pMatch->pTab)
+     && ALWAYS(VisibleRowid(pMatch->pTab))
     ){
       cnt = 1;
       pExpr->iColumn = -1;
@@ -99126,8 +100939,8 @@ static int lookupName(
     ** is supported for backwards compatibility only. Hence, we issue a warning
     ** on sqlite3_log() whenever the capability is used.
     */
-    if( (pNC->ncFlags & NC_UEList)!=0
-     && cnt==0
+    if( cnt==0
+     && (pNC->ncFlags & NC_UEList)!=0
      && zTab==0
     ){
       pEList = pNC->uNC.pEList;
@@ -99139,8 +100952,8 @@ static int lookupName(
         ){
           Expr *pOrig;
           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
-          assert( pExpr->x.pList==0 );
-          assert( pExpr->x.pSelect==0 );
+          assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
+          assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
           pOrig = pEList->a[j].pExpr;
           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
@@ -99191,7 +101004,6 @@ static int lookupName(
     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.
@@ -99206,11 +101018,6 @@ static int lookupName(
       ** 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);
@@ -99218,7 +101025,7 @@ static int lookupName(
       sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
 #endif
       pExpr->op = TK_STRING;
-      pExpr->y.pTab = 0;
+      memset(&pExpr->y, 0, sizeof(pExpr->y));
       return WRC_Prune;
     }
     if( sqlite3ExprIdToTrueFalse(pExpr) ){
@@ -99240,8 +101047,9 @@ static int lookupName(
     }else{
       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
     }
+    sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
     pParse->checkSchema = 1;
-    pTopNC->nErr++;
+    pTopNC->nNcErr++;
   }
 
   /* If a column from a table in pSrcList is referenced, then record
@@ -99304,7 +101112,9 @@ SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSr
   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   if( p ){
     SrcItem *pItem = &pSrc->a[iSrc];
-    Table *pTab = p->y.pTab = pItem->pTab;
+    Table *pTab;
+    assert( ExprUseYTab(p) );
+    pTab = p->y.pTab = pItem->pTab;
     p->iTable = pItem->iCursor;
     if( p->y.pTab->iPKey==iCol ){
       p->iColumn = -1;
@@ -99346,7 +101156,8 @@ static void notValidImpl(
    Parse *pParse,       /* Leave error message here */
    NameContext *pNC,    /* The name context */
    const char *zMsg,    /* Type of error */
-   Expr *pExpr          /* Invalidate this expression on error */
+   Expr *pExpr,         /* Invalidate this expression on error */
+   Expr *pError         /* Associate error with this expression */
 ){
   const char *zIn = "partial index WHERE clauses";
   if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
@@ -99358,10 +101169,11 @@ static void notValidImpl(
 #endif
   sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
   if( pExpr ) pExpr->op = TK_NULL;
+  sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
 }
-#define sqlite3ResolveNotValid(P,N,M,X,E) \
+#define sqlite3ResolveNotValid(P,N,M,X,E,R) \
   assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
-  if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E);
+  if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
 
 /*
 ** Expression p should encode a floating point value between 1.0 and 0.0.
@@ -99371,6 +101183,7 @@ static void notValidImpl(
 static int exprProbability(Expr *p){
   double r = -1.0;
   if( p->op!=TK_FLOAT ) return -1;
+  assert( !ExprHasProperty(p, EP_IntValue) );
   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
   assert( r>=0.0 );
   if( r>1.0 ) return -1;
@@ -99419,6 +101232,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       assert( pSrcList && pSrcList->nSrc>=1 );
       pItem = pSrcList->a;
       pExpr->op = TK_COLUMN;
+      assert( ExprUseYTab(pExpr) );
       pExpr->y.pTab = pItem->pTab;
       pExpr->iTable = pItem->iCursor;
       pExpr->iColumn--;
@@ -99450,6 +101264,8 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       }
       sqlite3WalkExpr(pWalker, pExpr->pLeft);
       if( 0==sqlite3ExprCanBeNull(pExpr->pLeft) && !IN_RENAME_OBJECT ){
+        testcase( ExprHasProperty(pExpr, EP_FromJoin) );
+        assert( !ExprHasProperty(pExpr, EP_IntValue) );
         if( pExpr->op==TK_NOTNULL ){
           pExpr->u.zToken = "true";
           ExprSetProperty(pExpr, EP_IsTrue);
@@ -99485,24 +101301,28 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       if( pExpr->op==TK_ID ){
         zDb = 0;
         zTable = 0;
+        assert( !ExprHasProperty(pExpr, EP_IntValue) );
         zColumn = pExpr->u.zToken;
       }else{
         Expr *pLeft = pExpr->pLeft;
         testcase( pNC->ncFlags & NC_IdxExpr );
         testcase( pNC->ncFlags & NC_GenCol );
         sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
-                               NC_IdxExpr|NC_GenCol, 0);
+                               NC_IdxExpr|NC_GenCol, 0, pExpr);
         pRight = pExpr->pRight;
         if( pRight->op==TK_ID ){
           zDb = 0;
         }else{
           assert( pRight->op==TK_DOT );
+          assert( !ExprHasProperty(pRight, EP_IntValue) );
           zDb = pLeft->u.zToken;
           pLeft = pRight->pLeft;
           pRight = pRight->pRight;
         }
+        assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
         zTable = pLeft->u.zToken;
         zColumn = pRight->u.zToken;
+        assert( ExprUseYTab(pExpr) );
         if( IN_RENAME_OBJECT ){
           sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
           sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
@@ -99519,7 +101339,6 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       int no_such_func = 0;       /* True if no such function exists */
       int wrong_num_args = 0;     /* True if wrong number of arguments */
       int is_agg = 0;             /* True if is an aggregate function */
-      int nId;                    /* Number of characters in function name */
       const char *zId;            /* The function name. */
       FuncDef *pDef;              /* Information about the function */
       u8 enc = ENC(pParse->db);   /* The database encoding */
@@ -99527,9 +101346,8 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
 #ifndef SQLITE_OMIT_WINDOWFUNC
       Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
 #endif
-      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+      assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
       zId = pExpr->u.zToken;
-      nId = sqlite3Strlen30(zId);
       pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
       if( pDef==0 ){
         pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
@@ -99546,9 +101364,9 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
             pExpr->iTable = exprProbability(pList->a[1].pExpr);
             if( pExpr->iTable<0 ){
               sqlite3ErrorMsg(pParse,
-                "second argument to likelihood() must be a "
-                "constant between 0.0 and 1.0");
-              pNC->nErr++;
+                "second argument to %#T() must be a "
+                "constant between 0.0 and 1.0", pExpr);
+              pNC->nNcErr++;
             }
           }else{
             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
@@ -99568,9 +101386,9 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
           int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
           if( auth!=SQLITE_OK ){
             if( auth==SQLITE_DENY ){
-              sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
-                                      pDef->zName);
-              pNC->nErr++;
+              sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
+                                      pExpr);
+              pNC->nNcErr++;
             }
             pExpr->op = TK_NULL;
             return WRC_Prune;
@@ -99592,7 +101410,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
           ** in a CHECK constraint.  SQLServer, MySQL, and PostgreSQL all
           ** all this. */
           sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
-                                 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0);
+                                 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
         }else{
           assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
           pExpr->op2 = pNC->ncFlags & NC_SelfRef;
@@ -99605,7 +101423,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
           /* Internal-use-only functions are disallowed unless the
           ** SQL is being compiled using sqlite3NestedParse() or
           ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
-          ** used to activate internal functionsn for testing purposes */
+          ** used to activate internal functions for testing purposes */
           no_such_func = 1;
           pDef = 0;
         }else
@@ -99624,9 +101442,9 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         );
         if( pDef && pDef->xValue==0 && pWin ){
           sqlite3ErrorMsg(pParse,
-              "%.*s() may not be used as a window function", nId, zId
+              "%#T() may not be used as a window function", pExpr
           );
-          pNC->nErr++;
+          pNC->nNcErr++;
         }else if(
               (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
            || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
@@ -99638,14 +101456,14 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
           }else{
             zType = "aggregate";
           }
-          sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
-          pNC->nErr++;
+          sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
+          pNC->nNcErr++;
           is_agg = 0;
         }
 #else
         if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
-          sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
-          pNC->nErr++;
+          sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
+          pNC->nNcErr++;
           is_agg = 0;
         }
 #endif
@@ -99654,20 +101472,20 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
                   && pParse->explain==0
 #endif
         ){
-          sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
-          pNC->nErr++;
+          sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
+          pNC->nNcErr++;
         }else if( wrong_num_args ){
-          sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
-               nId, zId);
-          pNC->nErr++;
+          sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
+               pExpr);
+          pNC->nNcErr++;
         }
 #ifndef SQLITE_OMIT_WINDOWFUNC
         else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
           sqlite3ErrorMsg(pParse,
-              "FILTER may not be used with non-aggregate %.*s()",
-              nId, zId
+              "FILTER may not be used with non-aggregate %#T()",
+              pExpr
           );
-          pNC->nErr++;
+          pNC->nNcErr++;
         }
 #endif
         if( is_agg ){
@@ -99691,7 +101509,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
 #ifndef SQLITE_OMIT_WINDOWFUNC
         if( pWin ){
           Select *pSel = pNC->pWinSelect;
-          assert( pWin==pExpr->y.pWin );
+          assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
           if( IN_RENAME_OBJECT==0 ){
             sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
             if( pParse->db->mallocFailed ) break;
@@ -99704,7 +101522,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         }else
 #endif /* SQLITE_OMIT_WINDOWFUNC */
         {
-          NameContext *pNC2 = pNC;
+          NameContext *pNC2;          /* For looping up thru outer contexts */
           pExpr->op = TK_AGG_FUNCTION;
           pExpr->op2 = 0;
 #ifndef SQLITE_OMIT_WINDOWFUNC
@@ -99712,16 +101530,22 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
             sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
           }
 #endif
-          while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
+          pNC2 = pNC;
+          while( pNC2
+              && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
+          ){
             pExpr->op2++;
             pNC2 = pNC2->pNext;
           }
           assert( pDef!=0 || IN_RENAME_OBJECT );
           if( pNC2 && pDef ){
             assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
+            assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
             testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
-            pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
-
+            testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
+            pNC2->ncFlags |= NC_HasAgg
+              | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
+                  & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
           }
         }
         pNC->ncFlags |= savedAllowFlags;
@@ -99737,15 +101561,17 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
 #endif
     case TK_IN: {
       testcase( pExpr->op==TK_IN );
-      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+      if( ExprUseXSelect(pExpr) ){
         int nRef = pNC->nRef;
         testcase( pNC->ncFlags & NC_IsCheck );
         testcase( pNC->ncFlags & NC_PartIdx );
         testcase( pNC->ncFlags & NC_IdxExpr );
         testcase( pNC->ncFlags & NC_GenCol );
-        sqlite3ResolveNotValid(pParse, pNC, "subqueries",
-                 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
-        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
+        if( pNC->ncFlags & NC_SelfRef ){
+          notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
+        }else{
+          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
+        }
         assert( pNC->nRef>=nRef );
         if( nRef!=pNC->nRef ){
           ExprSetProperty(pExpr, EP_VarSelect);
@@ -99760,7 +101586,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       testcase( pNC->ncFlags & NC_IdxExpr );
       testcase( pNC->ncFlags & NC_GenCol );
       sqlite3ResolveNotValid(pParse, pNC, "parameters",
-               NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
+               NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
       break;
     }
     case TK_IS:
@@ -99792,6 +101618,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       assert( pExpr->pLeft!=0 );
       nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
       if( pExpr->op==TK_BETWEEN ){
+        assert( ExprUseXList(pExpr) );
         nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
         if( nRight==nLeft ){
           nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
@@ -99811,11 +101638,13 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         testcase( pExpr->op==TK_ISNOT );
         testcase( pExpr->op==TK_BETWEEN );
         sqlite3ErrorMsg(pParse, "row value misused");
+        sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
       }
       break;
     }
   }
-  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
+  assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
+  return pParse->nErr ? WRC_Abort : WRC_Continue;
 }
 
 /*
@@ -99840,7 +101669,9 @@ static int resolveAsName(
   UNUSED_PARAMETER(pParse);
 
   if( pE->op==TK_ID ){
-    char *zCol = pE->u.zToken;
+    const char *zCol;
+    assert( !ExprHasProperty(pE, EP_IntValue) );
+    zCol = pE->u.zToken;
     for(i=0; i<pEList->nExpr; i++){
       if( pEList->a[i].eEName==ENAME_NAME
        && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
@@ -99891,11 +101722,11 @@ static int resolveOrderByTermToExprList(
   nc.pParse = pParse;
   nc.pSrcList = pSelect->pSrc;
   nc.uNC.pEList = pEList;
-  nc.ncFlags = NC_AllowAgg|NC_UEList;
-  nc.nErr = 0;
+  nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
+  nc.nNcErr = 0;
   db = pParse->db;
   savedSuppErr = db->suppressErr;
-  if( IN_RENAME_OBJECT==0 ) db->suppressErr = 1;
+  db->suppressErr = 1;
   rc = sqlite3ResolveExprNames(&nc, pE);
   db->suppressErr = savedSuppErr;
   if( rc ) return 0;
@@ -99921,11 +101752,13 @@ static void resolveOutOfRangeError(
   Parse *pParse,         /* The error context into which to write the error */
   const char *zType,     /* "ORDER" or "GROUP" */
   int i,                 /* The index (1-based) of the term out of range */
-  int mx                 /* Largest permissible value of i */
+  int mx,                /* Largest permissible value of i */
+  Expr *pError           /* Associate the error with the expression */
 ){
   sqlite3ErrorMsg(pParse,
     "%r %s BY term out of range - should be "
     "between 1 and %d", i, zType, mx);
+  sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
 }
 
 /*
@@ -99981,7 +101814,7 @@ static int resolveCompoundOrderBy(
       if( NEVER(pE==0) ) continue;
       if( sqlite3ExprIsInteger(pE, &iCol) ){
         if( iCol<=0 || iCol>pEList->nExpr ){
-          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
+          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
           return 1;
         }
       }else{
@@ -99994,29 +101827,24 @@ static int resolveCompoundOrderBy(
           ** Once the comparisons are finished, the duplicate expression
           ** is deleted.
           **
-          ** Or, if this is running as part of an ALTER TABLE operation,
-          ** resolve the symbols in the actual expression, not a duplicate.
-          ** And, if one of the comparisons is successful, leave the expression
-          ** as is instead of transforming it to an integer as in the usual
-          ** case. This allows the code in alter.c to modify column
-          ** refererences within the ORDER BY expression as required.  */
-          if( IN_RENAME_OBJECT ){
-            pDup = pE;
-          }else{
-            pDup = sqlite3ExprDup(db, pE, 0);
-          }
+          ** If this is running as part of an ALTER TABLE operation and
+          ** the symbols resolve successfully, also resolve the symbols in the
+          ** actual expression. This allows the code in alter.c to modify
+          ** column references within the ORDER BY expression as required.  */
+          pDup = sqlite3ExprDup(db, pE, 0);
           if( !db->mallocFailed ){
             assert(pDup);
             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
+            if( IN_RENAME_OBJECT && iCol>0 ){
+              resolveOrderByTermToExprList(pParse, pSelect, pE);
+            }
           }
-          if( !IN_RENAME_OBJECT ){
-            sqlite3ExprDelete(db, pDup);
-          }
+          sqlite3ExprDelete(db, pDup);
         }
       }
       if( iCol>0 ){
         /* Convert the ORDER BY term into an integer column number iCol,
-        ** taking care to preserve the COLLATE clause if it exists */
+        ** taking care to preserve the COLLATE clause if it exists. */
         if( !IN_RENAME_OBJECT ){
           Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
           if( pNew==0 ) return 1;
@@ -100082,7 +101910,7 @@ SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
     if( pItem->u.x.iOrderByCol ){
       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
-        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
+        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
         return 1;
       }
       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
@@ -100151,7 +101979,7 @@ static int resolveOrderGroupBy(
   Parse *pParse;                 /* Parsing context */
   int nResult;                   /* Number of terms in the result set */
 
-  if( pOrderBy==0 ) return 0;
+  assert( pOrderBy!=0 );
   nResult = pSelect->pEList->nExpr;
   pParse = pNC->pParse;
   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
@@ -100174,7 +102002,7 @@ static int resolveOrderGroupBy(
       ** number so that sqlite3ResolveOrderGroupBy() will convert the
       ** order-by term to a copy of the result-set expression */
       if( iCol<1 || iCol>0xffff ){
-        resolveOutOfRangeError(pParse, zType, i+1, nResult);
+        resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
         return 1;
       }
       pItem->u.x.iOrderByCol = (u16)iCol;
@@ -100232,7 +102060,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
   */
   if( (p->selFlags & SF_Expanded)==0 ){
     sqlite3SelectPrep(pParse, p, pOuterNC);
-    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
+    return pParse->nErr ? WRC_Abort : WRC_Prune;
   }
 
   isCompound = p->pPrior!=0;
@@ -100241,8 +102069,10 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
   while( p ){
     assert( (p->selFlags & SF_Expanded)!=0 );
     assert( (p->selFlags & SF_Resolved)==0 );
+    assert( db->suppressErr==0 ); /* SF_Resolved not set if errors suppressed */
     p->selFlags |= SF_Resolved;
 
+
     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
     ** are not allowed to refer to any names, so pass an empty NameContext.
     */
@@ -100267,7 +102097,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
       p->pOrderBy = 0;
     }
 
-    /* Recursively resolve names in all subqueries
+    /* Recursively resolve names in all subqueries in the FROM clause
     */
     for(i=0; i<p->pSrc->nSrc; i++){
       SrcItem *pItem = &p->pSrc->a[i];
@@ -100278,7 +102108,8 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
         pParse->zAuthContext = zSavedContext;
-        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
+        if( pParse->nErr ) return WRC_Abort;
+        assert( db->mallocFailed==0 );
 
         /* If the number of references to the outer context changed when
         ** expressions in the sub-select were resolved, the sub-select
@@ -100311,18 +102142,12 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
     pGroupBy = p->pGroupBy;
     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
       assert( NC_MinMaxAgg==SF_MinMaxAgg );
-      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
+      assert( NC_OrderAgg==SF_OrderByReqd );
+      p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
     }else{
       sNC.ncFlags &= ~NC_AllowAgg;
     }
 
-    /* If a HAVING clause is present, then there must be a GROUP BY clause.
-    */
-    if( p->pHaving && !pGroupBy ){
-      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
-      return WRC_Abort;
-    }
-
     /* Add the output column list to the name-context before parsing the
     ** other expressions in the SELECT statement. This is so that
     ** expressions in the WHERE clause (etc.) can refer to expressions by
@@ -100334,7 +102159,13 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
     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;
+    if( p->pHaving ){
+      if( !pGroupBy ){
+        sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
+        return WRC_Abort;
+      }
+      if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
+    }
     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
 
     /* Resolve names in table-valued-function arguments */
@@ -100347,6 +102178,19 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
       }
     }
 
+#ifndef SQLITE_OMIT_WINDOWFUNC
+    if( IN_RENAME_OBJECT ){
+      Window *pWin;
+      for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
+        if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
+         || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
+        ){
+          return WRC_Abort;
+        }
+      }
+    }
+#endif
+
     /* The ORDER BY and GROUP BY clauses may not refer to terms in
     ** outer queries
     */
@@ -100374,7 +102218,8 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
     ** is not detected until much later, and so we need to go ahead and
     ** resolve those symbols on the incorrect ORDER BY for consistency.
     */
-    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
+    if( p->pOrderBy!=0
+     && isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
     ){
       return WRC_Abort;
@@ -100402,19 +102247,6 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
       }
     }
 
-#ifndef SQLITE_OMIT_WINDOWFUNC
-    if( IN_RENAME_OBJECT ){
-      Window *pWin;
-      for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
-        if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
-         || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
-        ){
-          return WRC_Abort;
-        }
-      }
-    }
-#endif
-
     /* If this is part of a compound SELECT, check that it has the right
     ** number of expressions in the select list. */
     if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
@@ -100494,11 +102326,11 @@ SQLITE_PRIVATE int sqlite3ResolveExprNames(
   Walker w;
 
   if( pExpr==0 ) return SQLITE_OK;
-  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
-  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
+  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
   w.pParse = pNC->pParse;
   w.xExprCallback = resolveExprStep;
-  w.xSelectCallback = resolveSelectStep;
+  w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
   w.xSelectCallback2 = 0;
   w.u.pNC = pNC;
 #if SQLITE_MAX_EXPR_DEPTH>0
@@ -100517,7 +102349,7 @@ SQLITE_PRIVATE int sqlite3ResolveExprNames(
   testcase( pNC->ncFlags & NC_HasWin );
   ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
   pNC->ncFlags |= savedHasAgg;
-  return pNC->nErr>0 || w.pParse->nErr>0;
+  return pNC->nNcErr>0 || w.pParse->nErr>0;
 }
 
 /*
@@ -100538,8 +102370,8 @@ SQLITE_PRIVATE int sqlite3ResolveExprListNames(
   w.xSelectCallback = resolveSelectStep;
   w.xSelectCallback2 = 0;
   w.u.pNC = pNC;
-  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
-  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
+  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
   for(i=0; i<pList->nExpr; i++){
     Expr *pExpr = pList->a[i].pExpr;
     if( pExpr==0 ) continue;
@@ -100557,12 +102389,13 @@ SQLITE_PRIVATE int sqlite3ResolveExprListNames(
     assert( EP_Win==NC_HasWin );
     testcase( pNC->ncFlags & NC_HasAgg );
     testcase( pNC->ncFlags & NC_HasWin );
-    if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin) ){
+    if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
       ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
-      savedHasAgg |= pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
-      pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+      savedHasAgg |= pNC->ncFlags &
+                          (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
+      pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
     }
-    if( pNC->nErr>0 || w.pParse->nErr>0 ) return WRC_Abort;
+    if( w.pParse->nErr>0 ) return WRC_Abort;
   }
   pNC->ncFlags |= savedHasAgg;
   return WRC_Continue;
@@ -100674,9 +102507,9 @@ static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
 /*
 ** Return the affinity character for a single column of a table.
 */
-SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
-  assert( iCol<pTab->nCol );
-  return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
+SQLITE_PRIVATE char sqlite3TableColumnAffinity(const Table *pTab, int iCol){
+  if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;
+  return pTab->aCol[iCol].affinity;
 }
 
 /*
@@ -100705,30 +102538,36 @@ SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){
     assert( pExpr!=0 );
   }
   op = pExpr->op;
+  if( op==TK_REGISTER ) op = pExpr->op2;
+  if( op==TK_COLUMN || op==TK_AGG_COLUMN ){
+    assert( ExprUseYTab(pExpr) );
+    if( pExpr->y.pTab ){
+      return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
+    }
+  }
   if( op==TK_SELECT ){
-    assert( pExpr->flags&EP_xIsSelect );
+    assert( ExprUseXSelect(pExpr) );
     assert( pExpr->x.pSelect!=0 );
     assert( pExpr->x.pSelect->pEList!=0 );
     assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   }
-  if( op==TK_REGISTER ) op = pExpr->op2;
 #ifndef SQLITE_OMIT_CAST
   if( op==TK_CAST ){
     assert( !ExprHasProperty(pExpr, EP_IntValue) );
     return sqlite3AffinityType(pExpr->u.zToken, 0);
   }
 #endif
-  if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
-    return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
-  }
   if( op==TK_SELECT_COLUMN ){
-    assert( pExpr->pLeft->flags&EP_xIsSelect );
+    assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );
+    assert( pExpr->iColumn < pExpr->iTable );
+    assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
     return sqlite3ExprAffinity(
         pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
     );
   }
   if( op==TK_VECTOR ){
+    assert( ExprUseXList(pExpr) );
     return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
   }
   return pExpr->affExpr;
@@ -100743,23 +102582,12 @@ SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){
 ** and the pExpr parameter is returned unchanged.
 */
 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
-  Parse *pParse,           /* Parsing context */
+  const Parse *pParse,     /* Parsing context */
   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
   const Token *pCollName,  /* Name of collating sequence */
   int dequote              /* True to dequote pCollName */
 ){
-  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 ){
+  if( pCollName->n>0 ){
     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
     if( pNew ){
       pNew->pLeft = pExpr;
@@ -100769,7 +102597,11 @@ SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
   }
   return pExpr;
 }
-SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
+SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(
+  const Parse *pParse,  /* Parsing context */
+  Expr *pExpr,          /* Add the "COLLATE" clause to this expression */
+  const char *zC        /* The collating sequence name */
+){
   Token s;
   assert( zC!=0 );
   sqlite3TokenInit(&s, (char*)zC);
@@ -100795,7 +102627,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
   while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
     if( ExprHasProperty(pExpr, EP_Unlikely) ){
-      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+      assert( ExprUseXList(pExpr) );
       assert( pExpr->x.pList->nExpr>0 );
       assert( pExpr->op==TK_FUNCTION );
       pExpr = pExpr->x.pList->a[0].pExpr;
@@ -100828,27 +102660,30 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
   while( p ){
     int op = p->op;
     if( op==TK_REGISTER ) op = p->op2;
-    if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
-     && p->y.pTab!=0
-    ){
-      /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
-      ** a TK_COLUMN but was previously evaluated and cached in a register */
-      int j = p->iColumn;
-      if( j>=0 ){
-        const char *zColl = p->y.pTab->aCol[j].zColl;
-        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
+    if( op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER ){
+      assert( ExprUseYTab(p) );
+      if( p->y.pTab!=0 ){
+        /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
+        ** a TK_COLUMN but was previously evaluated and cached in a register */
+        int j = p->iColumn;
+        if( j>=0 ){
+          const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
+          pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
+        }
+        break;
       }
-      break;
     }
     if( op==TK_CAST || op==TK_UPLUS ){
       p = p->pLeft;
       continue;
     }
     if( op==TK_VECTOR ){
+      assert( ExprUseXList(p) );
       p = p->x.pList->a[0].pExpr;
       continue;
     }
     if( op==TK_COLLATE ){
+      assert( !ExprHasProperty(p, EP_IntValue) );
       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
       break;
     }
@@ -100858,11 +102693,9 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
       }else{
         Expr *pNext  = p->pRight;
         /* The Expr.x union is never used at the same time as Expr.pRight */
+        assert( ExprUseXList(p) );
         assert( p->x.pList==0 || p->pRight==0 );
-        if( p->x.pList!=0
-         && !db->mallocFailed
-         && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
-        ){
+        if( p->x.pList!=0 && !db->mallocFailed ){
           int i;
           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
@@ -100945,7 +102778,7 @@ static char comparisonAffinity(const Expr *pExpr){
   aff = sqlite3ExprAffinity(pExpr->pLeft);
   if( pExpr->pRight ){
     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
-  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+  }else if( ExprUseXSelect(pExpr) ){
     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   }else if( aff==0 ){
     aff = SQLITE_AFF_BLOB;
@@ -101071,7 +102904,7 @@ static int codeCompare(
 ** But a TK_SELECT might be either a vector or a scalar. It is only
 ** considered a vector if it has two or more result columns.
 */
-SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
+SQLITE_PRIVATE int sqlite3ExprIsVector(const Expr *pExpr){
   return sqlite3ExprVectorSize(pExpr)>1;
 }
 
@@ -101081,12 +102914,14 @@ SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
 ** is a sub-select, return the number of columns in the sub-select. For
 ** any other type of expression, return 1.
 */
-SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
+SQLITE_PRIVATE int sqlite3ExprVectorSize(const Expr *pExpr){
   u8 op = pExpr->op;
   if( op==TK_REGISTER ) op = pExpr->op2;
   if( op==TK_VECTOR ){
+    assert( ExprUseXList(pExpr) );
     return pExpr->x.pList->nExpr;
   }else if( op==TK_SELECT ){
+    assert( ExprUseXSelect(pExpr) );
     return pExpr->x.pSelect->pEList->nExpr;
   }else{
     return 1;
@@ -101109,12 +102944,14 @@ SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
 ** been positioned.
 */
 SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
-  assert( i<sqlite3ExprVectorSize(pVector) );
+  assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
   if( sqlite3ExprIsVector(pVector) ){
     assert( pVector->op2==0 || pVector->op==TK_REGISTER );
     if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
+      assert( ExprUseXSelect(pVector) );
       return pVector->x.pSelect->pEList->a[i].pExpr;
     }else{
+      assert( ExprUseXList(pVector) );
       return pVector->x.pList->a[i].pExpr;
     }
   }
@@ -101145,11 +102982,12 @@ SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
 SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
   Parse *pParse,       /* Parsing context */
   Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
-  int iField           /* Which column of the vector to return */
+  int iField,          /* Which column of the vector to return */
+  int nField           /* Total number of columns in the vector */
 ){
   Expr *pRet;
   if( pVector->op==TK_SELECT ){
-    assert( pVector->flags & EP_xIsSelect );
+    assert( ExprUseXSelect(pVector) );
     /* The TK_SELECT_COLUMN Expr node:
     **
     ** pLeft:           pVector containing TK_SELECT.  Not deleted.
@@ -101168,14 +103006,23 @@ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
     */
     pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
     if( pRet ){
+      pRet->iTable = nField;
       pRet->iColumn = iField;
       pRet->pLeft = pVector;
     }
-    assert( pRet==0 || pRet->iTable==0 );
   }else{
-    if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
+    if( pVector->op==TK_VECTOR ){
+      Expr **ppVector;
+      assert( ExprUseXList(pVector) );
+      ppVector = &pVector->x.pList->a[iField].pExpr;
+      pVector = *ppVector;
+      if( IN_RENAME_OBJECT ){
+        /* This must be a vector UPDATE inside a trigger */
+        *ppVector = 0;
+        return pVector;
+      }
+    }
     pRet = sqlite3ExprDup(pParse->db, pVector, 0);
-    sqlite3RenameTokenRemap(pParse, pRet, pVector);
   }
   return pRet;
 }
@@ -101225,17 +103072,22 @@ static int exprVectorRegister(
   int *pRegFree                   /* OUT: Temp register to free */
 ){
   u8 op = pVector->op;
-  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
+  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
   if( op==TK_REGISTER ){
     *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
     return pVector->iTable+iField;
   }
   if( op==TK_SELECT ){
+    assert( ExprUseXSelect(pVector) );
     *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
      return regSelect+iField;
   }
-  *ppExpr = pVector->x.pList->a[iField].pExpr;
-  return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
+  if( op==TK_VECTOR ){
+    assert( ExprUseXList(pVector) );
+    *ppExpr = pVector->x.pList->a[iField].pExpr;
+    return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
+  }
+  return 0;
 }
 
 /*
@@ -101264,6 +103116,7 @@ static void codeVectorCompare(
   int regLeft = 0;
   int regRight = 0;
   u8 opx = op;
+  int addrCmp = 0;
   int addrDone = sqlite3VdbeMakeLabel(pParse);
   int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
 
@@ -101283,21 +103136,24 @@ static void codeVectorCompare(
   assert( p5==0 || pExpr->op!=op );
   assert( p5==SQLITE_NULLEQ || pExpr->op==op );
 
-  p5 |= SQLITE_STOREP2;
-  if( opx==TK_LE ) opx = TK_LT;
-  if( opx==TK_GE ) opx = TK_GT;
+  if( op==TK_LE ) opx = TK_LT;
+  if( op==TK_GE ) opx = TK_GT;
+  if( op==TK_NE ) opx = TK_EQ;
 
   regLeft = exprCodeSubselect(pParse, pLeft);
   regRight = exprCodeSubselect(pParse, pRight);
 
+  sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
   for(i=0; 1 /*Loop exits by "break"*/; i++){
     int regFree1 = 0, regFree2 = 0;
-    Expr *pL, *pR;
+    Expr *pL = 0, *pR = 0;
     int r1, r2;
     assert( i>=0 && i<nLeft );
+    if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
     r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
     r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
-    codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
+    addrCmp = sqlite3VdbeCurrentAddr(v);
+    codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
     testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
     testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
     testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
@@ -101306,26 +103162,32 @@ static void codeVectorCompare(
     testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
     sqlite3ReleaseTempReg(pParse, regFree1);
     sqlite3ReleaseTempReg(pParse, regFree2);
+    if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
+      addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
+      testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
+      testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
+    }
+    if( p5==SQLITE_NULLEQ ){
+      sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
+    }else{
+      sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
+    }
     if( i==nLeft-1 ){
       break;
     }
     if( opx==TK_EQ ){
-      sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
-      p5 |= SQLITE_KEEPNULL;
-    }else if( opx==TK_NE ){
-      sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
-      p5 |= SQLITE_KEEPNULL;
+      sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
     }else{
       assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
-      sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
-      VdbeCoverageIf(v, op==TK_LT);
-      VdbeCoverageIf(v, op==TK_GT);
-      VdbeCoverageIf(v, op==TK_LE);
-      VdbeCoverageIf(v, op==TK_GE);
+      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
       if( i==nLeft-2 ) opx = op;
     }
   }
+  sqlite3VdbeJumpHere(v, addrCmp);
   sqlite3VdbeResolveLabel(v, addrDone);
+  if( op==TK_NE ){
+    sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
+  }
 }
 
 #if SQLITE_MAX_EXPR_DEPTH>0
@@ -101355,14 +103217,14 @@ SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
 ** to by pnHeight, the second parameter, then set *pnHeight to that
 ** value.
 */
-static void heightOfExpr(Expr *p, int *pnHeight){
+static void heightOfExpr(const Expr *p, int *pnHeight){
   if( p ){
     if( p->nHeight>*pnHeight ){
       *pnHeight = p->nHeight;
     }
   }
 }
-static void heightOfExprList(ExprList *p, int *pnHeight){
+static void heightOfExprList(const ExprList *p, int *pnHeight){
   if( p ){
     int i;
     for(i=0; i<p->nExpr; i++){
@@ -101370,8 +103232,8 @@ static void heightOfExprList(ExprList *p, int *pnHeight){
     }
   }
 }
-static void heightOfSelect(Select *pSelect, int *pnHeight){
-  Select *p;
+static void heightOfSelect(const Select *pSelect, int *pnHeight){
+  const Select *p;
   for(p=pSelect; p; p=p->pPrior){
     heightOfExpr(p->pWhere, pnHeight);
     heightOfExpr(p->pHaving, pnHeight);
@@ -101393,10 +103255,9 @@ static void heightOfSelect(Select *pSelect, int *pnHeight){
 ** if appropriate.
 */
 static void exprSetHeight(Expr *p){
-  int nHeight = 0;
-  heightOfExpr(p->pLeft, &nHeight);
-  heightOfExpr(p->pRight, &nHeight);
-  if( ExprHasProperty(p, EP_xIsSelect) ){
+  int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
+  if( p->pRight && p->pRight->nHeight>nHeight ) nHeight = p->pRight->nHeight;
+  if( ExprUseXSelect(p) ){
     heightOfSelect(p->x.pSelect, &nHeight);
   }else if( p->x.pList ){
     heightOfExprList(p->x.pList, &nHeight);
@@ -101423,7 +103284,7 @@ SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
 ** Return the maximum height of any expression tree referenced
 ** by the select statement passed as an argument.
 */
-SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
+SQLITE_PRIVATE int sqlite3SelectExprHeight(const Select *p){
   int nHeight = 0;
   heightOfSelect(p, &nHeight);
   return nHeight;
@@ -101435,7 +103296,7 @@ SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
 */
 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
   if( pParse->nErr ) return;
-  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
+  if( p && ExprUseXList(p) && p->x.pList ){
     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
   }
 }
@@ -101593,6 +103454,63 @@ SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pS
   }
 }
 
+/*
+** Expression list pEList is a list of vector values. This function
+** converts the contents of pEList to a VALUES(...) Select statement
+** returning 1 row for each element of the list. For example, the
+** expression list:
+**
+**   ( (1,2), (3,4) (5,6) )
+**
+** is translated to the equivalent of:
+**
+**   VALUES(1,2), (3,4), (5,6)
+**
+** Each of the vector values in pEList must contain exactly nElem terms.
+** If a list element that is not a vector or does not contain nElem terms,
+** an error message is left in pParse.
+**
+** This is used as part of processing IN(...) expressions with a list
+** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
+*/
+SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){
+  int ii;
+  Select *pRet = 0;
+  assert( nElem>1 );
+  for(ii=0; ii<pEList->nExpr; ii++){
+    Select *pSel;
+    Expr *pExpr = pEList->a[ii].pExpr;
+    int nExprElem;
+    if( pExpr->op==TK_VECTOR ){
+      assert( ExprUseXList(pExpr) );
+      nExprElem = pExpr->x.pList->nExpr;
+    }else{
+      nExprElem = 1;
+    }
+    if( nExprElem!=nElem ){
+      sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
+          nExprElem, nExprElem>1?"s":"", nElem
+      );
+      break;
+    }
+    assert( ExprUseXList(pExpr) );
+    pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
+    pExpr->x.pList = 0;
+    if( pSel ){
+      if( pRet ){
+        pSel->op = TK_ALL;
+        pSel->pPrior = pRet;
+      }
+      pRet = pSel;
+    }
+  }
+
+  if( pRet && pRet->pPrior ){
+    pRet->selFlags |= SF_MultiValue;
+  }
+  sqlite3ExprListDelete(pParse->db, pEList);
+  return pRet;
+}
 
 /*
 ** Join two expressions using an AND operator.  If either expression is
@@ -101626,7 +103544,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
 SQLITE_PRIVATE Expr *sqlite3ExprFunction(
   Parse *pParse,        /* Parsing context */
   ExprList *pList,      /* Argument list */
-  Token *pToken,        /* Name of the function */
+  const Token *pToken,  /* Name of the function */
   int eDistinct         /* SF_Distinct or SF_ALL or 0 */
 ){
   Expr *pNew;
@@ -101637,12 +103555,16 @@ SQLITE_PRIVATE Expr *sqlite3ExprFunction(
     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
     return 0;
   }
-  if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
+  pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
+  if( pList
+   && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
+   && !pParse->nested
+  ){
     sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
   }
   pNew->x.pList = pList;
   ExprSetProperty(pNew, EP_HasFunc);
-  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
+  assert( ExprUseXList(pNew) );
   sqlite3ExprSetHeightAndFlags(pParse, pNew);
   if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
   return pNew;
@@ -101661,8 +103583,8 @@ SQLITE_PRIVATE Expr *sqlite3ExprFunction(
 */
 SQLITE_PRIVATE void sqlite3ExprFunctionUsable(
   Parse *pParse,         /* Parsing and code generating context */
-  Expr *pExpr,           /* The function invocation */
-  FuncDef *pDef          /* The function being invoked */
+  const Expr *pExpr,     /* The function invocation */
+  const FuncDef *pDef    /* The function being invoked */
 ){
   assert( !IN_RENAME_OBJECT );
   assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
@@ -101677,7 +103599,7 @@ SQLITE_PRIVATE void sqlite3ExprFunctionUsable(
       **         SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
       **         that the schema is possibly tainted).
       */
-      sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName);
+      sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr);
     }
   }
 }
@@ -101733,6 +103655,7 @@ SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n
       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
+        sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
         return;
       }
       x = (ynVar)i;
@@ -101760,6 +103683,7 @@ SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n
   pExpr->iColumn = x;
   if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
     sqlite3ErrorMsg(pParse, "too many SQL variables");
+    sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
   }
 }
 
@@ -101768,27 +103692,26 @@ SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n
 */
 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
   assert( p!=0 );
-  /* Sanity check: Assert that the IntValue is non-negative if it exists */
-  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
-
-  assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
-  assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
-          || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
+  assert( !ExprUseUValue(p) || p->u.iValue>=0 );
+  assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
+  assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
+  assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
 #ifdef SQLITE_DEBUG
   if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
     assert( p->pLeft==0 );
     assert( p->pRight==0 );
-    assert( p->x.pSelect==0 );
+    assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
+    assert( !ExprUseXList(p) || p->x.pList==0 );
   }
 #endif
   if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
     /* The Expr.x union is never used at the same time as Expr.pRight */
-    assert( p->x.pList==0 || p->pRight==0 );
+    assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
     if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
     if( p->pRight ){
       assert( !ExprHasProperty(p, EP_WinFunc) );
       sqlite3ExprDeleteNN(db, p->pRight);
-    }else if( ExprHasProperty(p, EP_xIsSelect) ){
+    }else if( ExprUseXSelect(p) ){
       assert( !ExprHasProperty(p, EP_WinFunc) );
       sqlite3SelectDelete(db, p->x.pSelect);
     }else{
@@ -101800,7 +103723,10 @@ static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
 #endif
     }
   }
-  if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
+  if( ExprHasProperty(p, EP_MemToken) ){
+    assert( !ExprHasProperty(p, EP_IntValue) );
+    sqlite3DbFree(db, p->u.zToken);
+  }
   if( !ExprHasProperty(p, EP_Static) ){
     sqlite3DbFreeNN(db, p);
   }
@@ -101842,7 +103768,7 @@ SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
 */
-static int exprStructSize(Expr *p){
+static int exprStructSize(const Expr *p){
   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   return EXPR_FULLSIZE;
@@ -101882,7 +103808,7 @@ static int exprStructSize(Expr *p){
 ** of dupedExprStructSize() contain multiple assert() statements that attempt
 ** to enforce this constraint.
 */
-static int dupedExprStructSize(Expr *p, int flags){
+static int dupedExprStructSize(const Expr *p, int flags){
   int nSize;
   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   assert( EXPR_FULLSIZE<=0xfff );
@@ -101913,7 +103839,7 @@ static int dupedExprStructSize(Expr *p, int flags){
 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
 ** string is defined.)
 */
-static int dupedExprNodeSize(Expr *p, int flags){
+static int dupedExprNodeSize(const Expr *p, int flags){
   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
     nByte += sqlite3Strlen30NN(p->u.zToken)+1;
@@ -101934,7 +103860,7 @@ static int dupedExprNodeSize(Expr *p, int flags){
 ** and Expr.pRight variables (but not for any structures pointed to or
 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
 */
-static int dupedExprSize(Expr *p, int flags){
+static int dupedExprSize(const Expr *p, int flags){
   int nByte = 0;
   if( p ){
     nByte = dupedExprNodeSize(p, flags);
@@ -101953,7 +103879,7 @@ static int dupedExprSize(Expr *p, int flags){
 ** if any. Before returning, *pzBuffer is set to the first byte past the
 ** portion of the buffer copied into by this function.
 */
-static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
+static Expr *exprDup(sqlite3 *db, const Expr *p, int dupFlags, u8 **pzBuffer){
   Expr *pNew;           /* Value to return */
   u8 *zAlloc;           /* Memory space from which to build Expr object */
   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
@@ -101967,6 +103893,7 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
   if( pzBuffer ){
     zAlloc = *pzBuffer;
     staticFlag = EP_Static;
+    assert( zAlloc!=0 );
   }else{
     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
     staticFlag = 0;
@@ -102015,7 +103942,7 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
 
     if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
-      if( ExprHasProperty(p, EP_xIsSelect) ){
+      if( ExprUseXSelect(p) ){
         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
       }else{
         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
@@ -102044,8 +103971,8 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
       if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
         if( pNew->op==TK_SELECT_COLUMN ){
           pNew->pLeft = p->pLeft;
-          assert( p->iColumn==0 || p->pRight==0 );
-          assert( p->pRight==0  || p->pRight==p->pLeft );
+          assert( p->pRight==0  || p->pRight==p->pLeft
+                                || ExprHasProperty(p->pLeft, EP_Subquery) );
         }else{
           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
         }
@@ -102062,7 +103989,7 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
 ** and the db->mallocFailed flag set.
 */
 #ifndef SQLITE_OMIT_CTE
-static With *withDup(sqlite3 *db, With *p){
+SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p){
   With *pRet = 0;
   if( p ){
     sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
@@ -102080,7 +104007,7 @@ static With *withDup(sqlite3 *db, With *p){
   return pRet;
 }
 #else
-# define withDup(x,y) 0
+# define sqlite3WithDup(x,y) 0
 #endif
 
 #ifndef SQLITE_OMIT_WINDOWFUNC
@@ -102133,20 +104060,23 @@ static void gatherSelectWindows(Select *p){
 ** truncated version of the usual Expr structure that will be stored as
 ** part of the in-memory representation of the database schema.
 */
-SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
+SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){
   assert( flags==0 || flags==EXPRDUP_REDUCE );
   return p ? exprDup(db, p, flags, 0) : 0;
 }
-SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
+SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){
   ExprList *pNew;
-  struct ExprList_item *pItem, *pOldItem;
+  struct ExprList_item *pItem;
+  const struct ExprList_item *pOldItem;
   int i;
-  Expr *pPriorSelectCol = 0;
+  Expr *pPriorSelectColOld = 0;
+  Expr *pPriorSelectColNew = 0;
   assert( db!=0 );
   if( p==0 ) return 0;
   pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
   if( pNew==0 ) return 0;
   pNew->nExpr = p->nExpr;
+  pNew->nAlloc = p->nAlloc;
   pItem = pNew->a;
   pOldItem = p->a;
   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
@@ -102157,16 +104087,17 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags)
      && pOldExpr->op==TK_SELECT_COLUMN
      && (pNewExpr = pItem->pExpr)!=0
     ){
-      assert( pNewExpr->iColumn==0 || i>0 );
-      if( pNewExpr->iColumn==0 ){
-        assert( pOldExpr->pLeft==pOldExpr->pRight );
-        pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
+      if( pNewExpr->pRight ){
+        pPriorSelectColOld = pOldExpr->pRight;
+        pPriorSelectColNew = pNewExpr->pRight;
+        pNewExpr->pLeft = pNewExpr->pRight;
       }else{
-        assert( i>0 );
-        assert( pItem[-1].pExpr!=0 );
-        assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
-        assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
-        pNewExpr->pLeft = pPriorSelectCol;
+        if( pOldExpr->pLeft!=pPriorSelectColOld ){
+          pPriorSelectColOld = pOldExpr->pLeft;
+          pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
+          pNewExpr->pRight = pPriorSelectColNew;
+        }
+        pNewExpr->pLeft = pPriorSelectColNew;
       }
     }
     pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
@@ -102188,7 +104119,7 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags)
 */
 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  || !defined(SQLITE_OMIT_SUBQUERY)
-SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
+SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){
   SrcList *pNew;
   int i;
   int nByte;
@@ -102200,7 +104131,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   pNew->nSrc = pNew->nAlloc = p->nSrc;
   for(i=0; i<p->nSrc; i++){
     SrcItem *pNewItem = &pNew->a[i];
-    SrcItem *pOldItem = &p->a[i];
+    const SrcItem *pOldItem = &p->a[i];
     Table *pTab;
     pNewItem->pSchema = pOldItem->pSchema;
     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
@@ -102232,7 +104163,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   }
   return pNew;
 }
-SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
+SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){
   IdList *pNew;
   int i;
   assert( db!=0 );
@@ -102256,11 +104187,11 @@ SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   }
   return pNew;
 }
-SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
+SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){
   Select *pRet = 0;
   Select *pNext = 0;
   Select **pp = &pRet;
-  Select *p;
+  const Select *p;
 
   assert( db!=0 );
   for(p=pDup; p; p=p->pPrior){
@@ -102282,13 +104213,21 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
     pNew->addrOpenEphm[0] = -1;
     pNew->addrOpenEphm[1] = -1;
     pNew->nSelectRow = p->nSelectRow;
-    pNew->pWith = withDup(db, p->pWith);
+    pNew->pWith = sqlite3WithDup(db, p->pWith);
 #ifndef SQLITE_OMIT_WINDOWFUNC
     pNew->pWin = 0;
     pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
     if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
 #endif
     pNew->selId = p->selId;
+    if( db->mallocFailed ){
+      /* Any prior OOM might have left the Select object incomplete.
+      ** Delete the whole thing rather than allow an incomplete Select
+      ** to be used by the code generator. */
+      pNew->pNext = 0;
+      sqlite3SelectDelete(db, pNew);
+      break;
+    }
     *pp = pNew;
     pp = &pNew->pPrior;
     pNext = pNew;
@@ -102297,7 +104236,7 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
   return pRet;
 }
 #else
-SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
+SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){
   assert( p==0 );
   return 0;
 }
@@ -102319,41 +104258,64 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
 ** that the new entry was successfully appended.
 */
+static const struct ExprList_item zeroItem = {0};
+SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
+  sqlite3 *db,            /* Database handle.  Used for memory allocation */
+  Expr *pExpr             /* Expression to be appended. Might be NULL */
+){
+  struct ExprList_item *pItem;
+  ExprList *pList;
+
+  pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
+  if( pList==0 ){
+    sqlite3ExprDelete(db, pExpr);
+    return 0;
+  }
+  pList->nAlloc = 4;
+  pList->nExpr = 1;
+  pItem = &pList->a[0];
+  *pItem = zeroItem;
+  pItem->pExpr = pExpr;
+  return pList;
+}
+SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
+  sqlite3 *db,            /* Database handle.  Used for memory allocation */
+  ExprList *pList,        /* List to which to append. Might be NULL */
+  Expr *pExpr             /* Expression to be appended. Might be NULL */
+){
+  struct ExprList_item *pItem;
+  ExprList *pNew;
+  pList->nAlloc *= 2;
+  pNew = sqlite3DbRealloc(db, pList,
+       sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
+  if( pNew==0 ){
+    sqlite3ExprListDelete(db, pList);
+    sqlite3ExprDelete(db, pExpr);
+    return 0;
+  }else{
+    pList = pNew;
+  }
+  pItem = &pList->a[pList->nExpr++];
+  *pItem = zeroItem;
+  pItem->pExpr = pExpr;
+  return pList;
+}
 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   Parse *pParse,          /* Parsing context */
   ExprList *pList,        /* List to which to append. Might be NULL */
   Expr *pExpr             /* Expression to be appended. Might be NULL */
 ){
   struct ExprList_item *pItem;
-  sqlite3 *db = pParse->db;
-  assert( db!=0 );
   if( pList==0 ){
-    pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
-    if( pList==0 ){
-      goto no_mem;
-    }
-    pList->nExpr = 0;
-  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
-    ExprList *pNew;
-    pNew = sqlite3DbRealloc(db, pList,
-         sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
-    if( pNew==0 ){
-      goto no_mem;
-    }
-    pList = pNew;
+    return sqlite3ExprListAppendNew(pParse->db,pExpr);
+  }
+  if( pList->nAlloc<pList->nExpr+1 ){
+    return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
   }
   pItem = &pList->a[pList->nExpr++];
-  assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) );
-  assert( offsetof(struct ExprList_item,pExpr)==0 );
-  memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName));
+  *pItem = zeroItem;
   pItem->pExpr = pExpr;
   return pList;
-
-no_mem:
-  /* Avoid leaking memory if malloc has failed. */
-  sqlite3ExprDelete(db, pExpr);
-  sqlite3ExprListDelete(db, pList);
-  return 0;
 }
 
 /*
@@ -102394,11 +104356,9 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
   }
 
   for(i=0; i<pColumns->nId; i++){
-    Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
+    Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
     assert( pSubExpr!=0 || db->mallocFailed );
-    assert( pSubExpr==0 || pSubExpr->iTable==0 );
     if( pSubExpr==0 ) continue;
-    pSubExpr->iTable = pColumns->nId;
     pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
     if( pList ){
       assert( pList->nExpr==iFirst+i+1 );
@@ -102472,7 +104432,7 @@ SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int
 SQLITE_PRIVATE void sqlite3ExprListSetName(
   Parse *pParse,          /* Parsing context */
   ExprList *pList,        /* List to which to add the span. */
-  Token *pName,           /* Name to be added */
+  const Token *pName,     /* Name to be added */
   int dequote             /* True to cause the name to be dequoted */
 ){
   assert( pList!=0 || pParse->db->mallocFailed!=0 );
@@ -102490,7 +104450,7 @@ SQLITE_PRIVATE void sqlite3ExprListSetName(
       ** to the token-map.  */
       sqlite3Dequote(pItem->zEName);
       if( IN_RENAME_OBJECT ){
-        sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);
+        sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
       }
     }
   }
@@ -102609,7 +104569,7 @@ SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char *zIn){
 SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
   u32 v;
   assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
-  if( !ExprHasProperty(pExpr, EP_Quoted)
+  if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue)
    && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
   ){
     pExpr->op = TK_TRUEFALSE;
@@ -102626,6 +104586,7 @@ SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
 SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
   pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
   assert( pExpr->op==TK_TRUEFALSE );
+  assert( !ExprHasProperty(pExpr, EP_IntValue) );
   assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
        || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
   return pExpr->u.zToken[4]==0;
@@ -102809,6 +104770,38 @@ SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
   return exprIsConst(p, 3, iCur);
 }
 
+/*
+** Check pExpr to see if it is an invariant constraint on data source pSrc.
+** This is an optimization.  False negatives will perhaps cause slower
+** queries, but false positives will yield incorrect answers.  So when in
+** double, return 0.
+**
+** To be an invariant constraint, the following must be true:
+**
+**   (1)  pExpr cannot refer to any table other than pSrc->iCursor.
+**
+**   (2)  pExpr cannot use subqueries or non-deterministic functions.
+**
+**   (*)  ** Not applicable to this branch **
+**
+**   (4)  If pSrc is the right operand of a LEFT JOIN, then...
+**         (4a)  pExpr must come from an ON clause..
+**         (4b)  and specifically the ON clause associated with the LEFT JOIN.
+**
+**   (5)  If pSrc is not the right operand of a LEFT JOIN or the left
+**        operand of a RIGHT JOIN, then pExpr must be from the WHERE
+**        clause, not an ON clause.
+*/
+SQLITE_PRIVATE int sqlite3ExprIsTableConstraint(Expr *pExpr, const SrcItem *pSrc){
+  if( pSrc->fg.jointype & JT_LEFT ){
+    if( !ExprHasProperty(pExpr, EP_FromJoin) ) return 0;    /* rule (4a) */
+    if( pExpr->w.iRightJoinTable!=pSrc->iCursor ) return 0; /* rule (4b) */
+  }else{
+    if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;     /* rule (5) */
+  }
+  return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor);  /* rules (1), (2) */
+}
+
 
 /*
 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
@@ -102830,7 +104823,7 @@ static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
   }
 
   /* Check if pExpr is a sub-select. If so, consider it variable. */
-  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+  if( ExprUseXSelect(pExpr) ){
     pWalker->eCode = 0;
     return WRC_Abort;
   }
@@ -102918,7 +104911,7 @@ SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
 ** in *pValue.  If the expression is not an integer or if it is too big
 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
 */
-SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
+SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr *p, int *pValue){
   int rc = 0;
   if( NEVER(p==0) ) return 0;  /* Used to only happen following on OOM */
 
@@ -102937,9 +104930,9 @@ SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
       break;
     }
     case TK_UMINUS: {
-      int v;
+      int v = 0;
       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
-        assert( v!=(-2147483647-1) );
+        assert( ((unsigned int)v)!=0x80000000 );
         *pValue = -v;
         rc = 1;
       }
@@ -102966,8 +104959,10 @@ SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
 */
 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   u8 op;
+  assert( p!=0 );
   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
     p = p->pLeft;
+    assert( p!=0 );
   }
   op = p->op;
   if( op==TK_REGISTER ) op = p->op2;
@@ -102978,10 +104973,11 @@ SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
     case TK_BLOB:
       return 0;
     case TK_COLUMN:
+      assert( ExprUseYTab(p) );
       return ExprHasProperty(p, EP_CanBeNull) ||
              p->y.pTab==0 ||  /* Reference to column of index on expression */
              (p->iColumn>=0
-              && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
+              && p->y.pTab->aCol!=0 /* Possible due to prior error */
               && p->y.pTab->aCol[p->iColumn].notNull==0);
     default:
       return 1;
@@ -103049,13 +105045,13 @@ SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
 ** table, then return NULL.
 */
 #ifndef SQLITE_OMIT_SUBQUERY
-static Select *isCandidateForInOpt(Expr *pX){
+static Select *isCandidateForInOpt(const Expr *pX){
   Select *p;
   SrcList *pSrc;
   ExprList *pEList;
   Table *pTab;
   int i;
-  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
+  if( !ExprUseXSelect(pX) ) return 0;                 /* Not a subquery */
   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
   p = pX->x.pSelect;
   if( p->pPrior ) return 0;              /* Not a compound SELECT */
@@ -103073,7 +105069,7 @@ static Select *isCandidateForInOpt(Expr *pX){
   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   pTab = pSrc->a[0].pTab;
   assert( pTab!=0 );
-  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
+  assert( !IsView(pTab)  );              /* FROM clause is not a view */
   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   pEList = p->pEList;
   assert( pEList!=0 );
@@ -103226,7 +105222,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
   ** or not NULL is actually possible (it may not be, for example, due
   ** to NOT NULL constraints in the schema). If no NULL values are possible,
   ** set prRhsHasNull to 0 before continuing.  */
-  if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
+  if( prRhsHasNull && ExprUseXSelect(pX) ){
     int i;
     ExprList *pEList = pX->x.pSelect->pEList;
     for(i=0; i<pEList->nExpr; i++){
@@ -103382,7 +105378,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
   */
   if( eType==0
    && (inFlags & IN_INDEX_NOOP_OK)
-   && !ExprHasProperty(pX, EP_xIsSelect)
+   && ExprUseXList(pX)
    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
   ){
     eType = IN_INDEX_NOOP;
@@ -103427,10 +105423,10 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
 ** It is the responsibility of the caller to ensure that the returned
 ** string is eventually freed using sqlite3DbFree().
 */
-static char *exprINAffinity(Parse *pParse, Expr *pExpr){
+static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
   Expr *pLeft = pExpr->pLeft;
   int nVal = sqlite3ExprVectorSize(pLeft);
-  Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
+  Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
   char *zRet;
 
   assert( pExpr->op==TK_IN );
@@ -103480,7 +105476,7 @@ SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpec
 */
 SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
 #ifndef SQLITE_OMIT_SUBQUERY
-  if( pExpr->flags & EP_xIsSelect ){
+  if( ExprUseXSelect(pExpr) ){
     sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
   }else
 #endif
@@ -103544,10 +105540,11 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
     */
     if( ExprHasProperty(pExpr, EP_Subrtn) ){
       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
-      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+      if( ExprUseXSelect(pExpr) ){
         ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
               pExpr->x.pSelect->selId));
       }
+      assert( ExprUseYSub(pExpr) );
       sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
                         pExpr->y.sub.iAddr);
       sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
@@ -103556,6 +105553,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
     }
 
     /* Begin coding the subroutine */
+    assert( !ExprUseYWin(pExpr) );
     ExprSetProperty(pExpr, EP_Subrtn);
     assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
     pExpr->y.sub.regReturn = ++pParse->nMem;
@@ -103576,7 +105574,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
   pExpr->iTable = iTab;
   addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
-  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+  if( ExprUseXSelect(pExpr) ){
     VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
   }else{
     VdbeComment((v, "RHS of IN operator"));
@@ -103584,7 +105582,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
 #endif
   pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
 
-  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+  if( ExprUseXSelect(pExpr) ){
     /* Case 1:     expr IN (SELECT ...)
     **
     ** Generate code to write the results of the select into the temporary
@@ -103599,19 +105597,23 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
     /* If the LHS and RHS of the IN operator do not match, that
     ** error will have been caught long before we reach this point. */
     if( ALWAYS(pEList->nExpr==nVal) ){
+      Select *pCopy;
       SelectDest dest;
       int i;
+      int rc;
       sqlite3SelectDestInit(&dest, SRT_Set, iTab);
       dest.zAffSdst = exprINAffinity(pParse, pExpr);
       pSelect->iLimit = 0;
       testcase( pSelect->selFlags & SF_Distinct );
       testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
-      if( sqlite3Select(pParse, pSelect, &dest) ){
-        sqlite3DbFree(pParse->db, dest.zAffSdst);
+      pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
+      rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
+      sqlite3SelectDelete(pParse->db, pCopy);
+      sqlite3DbFree(pParse->db, dest.zAffSdst);
+      if( rc ){
         sqlite3KeyInfoUnref(pKeyInfo);
         return;
       }
-      sqlite3DbFree(pParse->db, dest.zAffSdst);
       assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
       assert( pEList!=0 );
       assert( pEList->nExpr>0 );
@@ -103678,6 +105680,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
   if( addrOnce ){
     sqlite3VdbeJumpHere(v, addrOnce);
     /* Subroutine return */
+    assert( ExprUseYSub(pExpr) );
     sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
     sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
     sqlite3ClearTempRegCache(pParse);
@@ -103710,12 +105713,33 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
 
   Vdbe *v = pParse->pVdbe;
   assert( v!=0 );
+  if( pParse->nErr ) return 0;
   testcase( pExpr->op==TK_EXISTS );
   testcase( pExpr->op==TK_SELECT );
   assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
-  assert( ExprHasProperty(pExpr, EP_xIsSelect) );
+  assert( ExprUseXSelect(pExpr) );
   pSel = pExpr->x.pSelect;
 
+  /* If this routine has already been coded, then invoke it as a
+  ** subroutine. */
+  if( ExprHasProperty(pExpr, EP_Subrtn) ){
+    ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
+    assert( ExprUseYSub(pExpr) );
+    sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
+                      pExpr->y.sub.iAddr);
+    return pExpr->iTable;
+  }
+
+  /* Begin coding the subroutine */
+  assert( !ExprUseYWin(pExpr) );
+  assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
+  ExprSetProperty(pExpr, EP_Subrtn);
+  pExpr->y.sub.regReturn = ++pParse->nMem;
+  pExpr->y.sub.iAddr =
+    sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
+  VdbeComment((v, "return address"));
+
+
   /* The evaluation of the EXISTS/SELECT must be repeated every time it
   ** is encountered if any of the following is true:
   **
@@ -103727,22 +105751,6 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
   ** save the results, and reuse the same result on subsequent invocations.
   */
   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
-    /* If this routine has already been coded, then invoke it as a
-    ** subroutine. */
-    if( ExprHasProperty(pExpr, EP_Subrtn) ){
-      ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
-      sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
-                        pExpr->y.sub.iAddr);
-      return pExpr->iTable;
-    }
-
-    /* Begin coding the subroutine */
-    ExprSetProperty(pExpr, EP_Subrtn);
-    pExpr->y.sub.regReturn = ++pParse->nMem;
-    pExpr->y.sub.iAddr =
-      sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
-    VdbeComment((v, "return address"));
-
     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   }
 
@@ -103791,19 +105799,21 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
   }
   pSel->iLimit = 0;
   if( sqlite3Select(pParse, pSel, &dest) ){
+    pExpr->op2 = pExpr->op;
+    pExpr->op = TK_ERROR;
     return 0;
   }
   pExpr->iTable = rReg = dest.iSDParm;
   ExprSetVVAProperty(pExpr, EP_NoReduce);
   if( addrOnce ){
     sqlite3VdbeJumpHere(v, addrOnce);
-
-    /* Subroutine return */
-    sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
-    sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
-    sqlite3ClearTempRegCache(pParse);
   }
 
+  /* Subroutine return */
+  assert( ExprUseYSub(pExpr) );
+  sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
+  sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
+  sqlite3ClearTempRegCache(pParse);
   return rReg;
 }
 #endif /* SQLITE_OMIT_SUBQUERY */
@@ -103817,7 +105827,7 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
 */
 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
   int nVector = sqlite3ExprVectorSize(pIn->pLeft);
-  if( (pIn->flags & EP_xIsSelect) ){
+  if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
     if( nVector!=pIn->x.pSelect->pEList->nExpr ){
       sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
       return 1;
@@ -103951,13 +105961,15 @@ static void sqlite3ExprCodeIN(
   ** This is step (1) in the in-operator.md optimized algorithm.
   */
   if( eType==IN_INDEX_NOOP ){
-    ExprList *pList = pExpr->x.pList;
-    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
+    ExprList *pList;
+    CollSeq *pColl;
     int labelOk = sqlite3VdbeMakeLabel(pParse);
     int r2, regToFree;
     int regCkNull = 0;
     int ii;
-    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+    assert( ExprUseXList(pExpr) );
+    pList = pExpr->x.pList;
+    pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
     if( destIfNull!=destIfFalse ){
       regCkNull = sqlite3GetTempReg(pParse);
       sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
@@ -104005,9 +106017,9 @@ static void sqlite3ExprCodeIN(
   }else{
     destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
   }
-  if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
   for(i=0; i<nVector; i++){
     Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
+    if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
     if( sqlite3ExprCanBeNull(p) ){
       sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
       VdbeCoverage(v);
@@ -104145,11 +106157,12 @@ static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
     c = sqlite3DecOrHexToI64(z, &value);
     if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
 #ifdef SQLITE_OMIT_FLOATING_POINT
-      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
+      sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
 #else
 #ifndef SQLITE_OMIT_HEX_INTEGER
       if( sqlite3_strnicmp(z,"0x",2)==0 ){
-        sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
+        sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T",
+                        negFlag?"-":"",pExpr);
       }else
 #endif
       {
@@ -104193,9 +106206,10 @@ SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
 ** and store the result in register regOut
 */
 SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(
-  Parse *pParse,
-  Column *pCol,
-  int regOut
+  Parse *pParse,     /* Parsing context */
+  Table *pTab,       /* Table containing the generated column */
+  Column *pCol,      /* The generated column */
+  int regOut         /* Put the result in this register */
 ){
   int iAddr;
   Vdbe *v = pParse->pVdbe;
@@ -104206,7 +106220,7 @@ SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(
   }else{
     iAddr = 0;
   }
-  sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);
+  sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
   if( pCol->affinity>=SQLITE_AFF_TEXT ){
     sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
   }
@@ -104242,12 +106256,13 @@ SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
     }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
       Parse *pParse = sqlite3VdbeParser(v);
       if( pCol->colFlags & COLFLAG_BUSY ){
-        sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
+        sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
+                        pCol->zCnName);
       }else{
         int savedSelfTab = pParse->iSelfTab;
         pCol->colFlags |= COLFLAG_BUSY;
         pParse->iSelfTab = iTabCur+1;
-        sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
+        sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut);
         pParse->iSelfTab = savedSelfTab;
         pCol->colFlags &= ~COLFLAG_BUSY;
       }
@@ -104340,6 +106355,7 @@ static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
       int i;
       iResult = pParse->nMem+1;
       pParse->nMem += nResult;
+      assert( ExprUseXList(p) );
       for(i=0; i<nResult; i++){
         sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
       }
@@ -104414,6 +106430,7 @@ static int exprCodeInlineFunction(
   ** Test-only SQL functions that are only usable if enabled
   ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
   */
+#if !defined(SQLITE_UNTESTABLE)
     case INLINEFUNC_expr_compare: {
       /* Compare two expressions using sqlite3ExprCompare() */
       assert( nFarg==2 );
@@ -104447,7 +106464,6 @@ static int exprCodeInlineFunction(
       break;
     }
 
-#ifdef SQLITE_DEBUG
     case INLINEFUNC_affinity: {
       /* The AFFINITY() function evaluates to a string that describes
       ** the type affinity of the argument.  This is used for testing of
@@ -104461,7 +106477,7 @@ static int exprCodeInlineFunction(
               (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
       break;
     }
-#endif
+#endif /* !defined(SQLITE_UNTESTABLE) */
   }
   return target;
 }
@@ -104515,7 +106531,8 @@ expr_code_doover:
         if( pCol->iColumn<0 ){
           VdbeComment((v,"%s.rowid",pTab->zName));
         }else{
-          VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName));
+          VdbeComment((v,"%s.%s",
+              pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
           if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
             sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
           }
@@ -104537,6 +106554,7 @@ expr_code_doover:
         */
         int aff;
         iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
+        assert( ExprUseYTab(pExpr) );
         if( pExpr->y.pTab ){
           aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
         }else{
@@ -104560,9 +106578,11 @@ expr_code_doover:
           ** immediately prior to the first column.
           */
           Column *pCol;
-          Table *pTab = pExpr->y.pTab;
+          Table *pTab;
           int iSrc;
           int iCol = pExpr->iColumn;
+          assert( ExprUseYTab(pExpr) );
+          pTab = pExpr->y.pTab;
           assert( pTab!=0 );
           assert( iCol>=XN_ROWID );
           assert( iCol<pTab->nCol );
@@ -104576,12 +106596,12 @@ expr_code_doover:
           if( pCol->colFlags & COLFLAG_GENERATED ){
             if( pCol->colFlags & COLFLAG_BUSY ){
               sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
-                              pCol->zName);
+                              pCol->zCnName);
               return 0;
             }
             pCol->colFlags |= COLFLAG_BUSY;
             if( pCol->colFlags & COLFLAG_NOTAVAIL ){
-              sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
+              sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc);
             }
             pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
             return iSrc;
@@ -104600,6 +106620,7 @@ expr_code_doover:
           iTab = pParse->iSelfTab - 1;
         }
       }
+      assert( ExprUseYTab(pExpr) );
       iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
                                pExpr->iColumn, iTab, target,
                                pExpr->op2);
@@ -104633,7 +106654,7 @@ expr_code_doover:
       ** Expr node to be passed into this function, it will be handled
       ** sanely and not crash.  But keep the assert() to bring the problem
       ** to the attention of the developers. */
-      assert( op==TK_NULL );
+      assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
       return target;
     }
@@ -104677,6 +106698,7 @@ expr_code_doover:
         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
         inReg = target;
       }
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       sqlite3VdbeAddOp2(v, OP_Cast, target,
                         sqlite3AffinityType(pExpr->u.zToken, 0));
       return inReg;
@@ -104699,8 +106721,9 @@ expr_code_doover:
       }else{
         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
-        codeCompare(pParse, pLeft, pExpr->pRight, op,
-            r1, r2, inReg, SQLITE_STOREP2 | p5,
+        sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
+        codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
+            sqlite3VdbeCurrentAddr(v)+2, p5,
             ExprHasProperty(pExpr,EP_Commuted));
         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
@@ -104708,6 +106731,11 @@ expr_code_doover:
         assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
         assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
         assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
+        if( p5==SQLITE_NULLEQ ){
+          sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
+        }else{
+          sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
+        }
         testcase( regFree1==0 );
         testcase( regFree2==0 );
       }
@@ -104810,7 +106838,7 @@ expr_code_doover:
        || NEVER(pExpr->iAgg>=pInfo->nFunc)
       ){
         assert( !ExprHasProperty(pExpr, EP_IntValue) );
-        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
+        sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr);
       }else{
         return pInfo->aFunc[pExpr->iAgg].iMem;
       }
@@ -104838,8 +106866,8 @@ expr_code_doover:
         ** multiple times if we know they always give the same result */
         return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
       }
-      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
       assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
+      assert( ExprUseXList(pExpr) );
       pFarg = pExpr->x.pList;
       nFarg = pFarg ? pFarg->nExpr : 0;
       assert( !ExprHasProperty(pExpr, EP_IntValue) );
@@ -104851,7 +106879,7 @@ expr_code_doover:
       }
 #endif
       if( pDef==0 || pDef->xFinalize!=0 ){
-        sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
+        sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
         break;
       }
       if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
@@ -104928,7 +106956,7 @@ expr_code_doover:
         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
       }
 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
-      if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
+      if( (pDef->funcFlags & SQLITE_FUNC_OFFSET)!=0 && ALWAYS(pFarg!=0) ){
         Expr *pArg = pFarg->a[0].pExpr;
         if( pArg->op==TK_COLUMN ){
           sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
@@ -104958,7 +106986,10 @@ expr_code_doover:
       testcase( op==TK_SELECT );
       if( pParse->db->mallocFailed ){
         return 0;
-      }else if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
+      }else if( op==TK_SELECT
+             && ALWAYS( ExprUseXSelect(pExpr) )
+             && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
+      ){
         sqlite3SubselectError(pParse, nCol, 1);
       }else{
         return sqlite3CodeSubselect(pParse, pExpr);
@@ -104970,10 +107001,9 @@ expr_code_doover:
       if( pExpr->pLeft->iTable==0 ){
         pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
       }
-      assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
-      if( pExpr->iTable!=0
-       && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
-      ){
+      assert( pExpr->pLeft->op==TK_SELECT || pExpr->pLeft->op==TK_ERROR );
+      n = sqlite3ExprVectorSize(pExpr->pLeft);
+      if( pExpr->iTable!=n ){
         sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
                                 pExpr->iTable, n);
       }
@@ -105041,9 +107071,14 @@ expr_code_doover:
       **   p1==1   ->    old.a         p1==4   ->    new.a
       **   p1==2   ->    old.b         p1==5   ->    new.b
       */
-      Table *pTab = pExpr->y.pTab;
-      int iCol = pExpr->iColumn;
-      int p1 = pExpr->iTable * (pTab->nCol+1) + 1
+      Table *pTab;
+      int iCol;
+      int p1;
+
+      assert( ExprUseYTab(pExpr) );
+      pTab = pExpr->y.pTab;
+      iCol = pExpr->iColumn;
+      p1 = pExpr->iTable * (pTab->nCol+1) + 1
                      + sqlite3TableColumnToStorage(pTab, iCol);
 
       assert( pExpr->iTable==0 || pExpr->iTable==1 );
@@ -105054,7 +107089,7 @@ expr_code_doover:
       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
       VdbeComment((v, "r[%d]=%s.%s", target,
         (pExpr->iTable ? "new" : "old"),
-        (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
+        (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
       ));
 
 #ifndef SQLITE_OMIT_FLOATING_POINT
@@ -105131,7 +107166,7 @@ expr_code_doover:
       Expr *pDel = 0;
       sqlite3 *db = pParse->db;
 
-      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
+      assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
       assert(pExpr->x.pList->nExpr > 0);
       pEList = pExpr->x.pList;
       aListelem = pEList->a;
@@ -105328,7 +107363,7 @@ SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   if( inReg!=target ){
     u8 op;
-    if( ExprHasProperty(pExpr,EP_Subquery) ){
+    if( ALWAYS(pExpr) && ExprHasProperty(pExpr,EP_Subquery) ){
       op = OP_Copy;
     }else{
       op = OP_SCopy;
@@ -105476,7 +107511,7 @@ static void exprCodeBetween(
   memset(&compRight, 0, sizeof(Expr));
   memset(&exprAnd, 0, sizeof(Expr));
 
-  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+  assert( ExprUseXList(pExpr) );
   pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
   if( db->mallocFailed==0 ){
     exprAnd.op = TK_AND;
@@ -105866,7 +107901,11 @@ SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,i
 ** Otherwise, if the values are not the same or if pExpr is not a simple
 ** SQL value, zero is returned.
 */
-static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
+static int exprCompareVariable(
+  const Parse *pParse,
+  const Expr *pVar,
+  const Expr *pExpr
+){
   int res = 0;
   int iVar;
   sqlite3_value *pL, *pR = 0;
@@ -105918,7 +107957,12 @@ static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
 ** Argument pParse should normally be NULL. If it is not NULL and pA or
 ** pB causes a return value of 2.
 */
-SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
+SQLITE_PRIVATE int sqlite3ExprCompare(
+  const Parse *pParse,
+  const Expr *pA,
+  const Expr *pB,
+  int iTab
+){
   u32 combinedFlags;
   if( pA==0 || pB==0 ){
     return pB==pA ? 0 : 2;
@@ -105942,7 +107986,9 @@ SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTa
     }
     return 2;
   }
-  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
+  assert( !ExprHasProperty(pA, EP_IntValue) );
+  assert( !ExprHasProperty(pB, EP_IntValue) );
+  if( pA->u.zToken ){
     if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
 #ifndef SQLITE_OMIT_WINDOWFUNC
@@ -105960,7 +108006,12 @@ SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTa
       return 0;
     }else if( pA->op==TK_COLLATE ){
       if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
-    }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
+    }else
+    if( pB->u.zToken!=0
+     && pA->op!=TK_COLUMN
+     && pA->op!=TK_AGG_COLUMN
+     && strcmp(pA->u.zToken,pB->u.zToken)!=0
+    ){
       return 2;
     }
   }
@@ -106002,7 +108053,7 @@ SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTa
 ** Two NULL pointers are considered to be the same.  But a NULL pointer
 ** always differs from a non-NULL pointer.
 */
-SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
+SQLITE_PRIVATE int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){
   int i;
   if( pA==0 && pB==0 ) return 0;
   if( pA==0 || pB==0 ) return 1;
@@ -106021,7 +108072,7 @@ SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
 ** are ignored.
 */
-SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
+SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
   return sqlite3ExprCompare(0,
              sqlite3ExprSkipCollateAndLikely(pA),
              sqlite3ExprSkipCollateAndLikely(pB),
@@ -106035,9 +108086,9 @@ SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
 ** non-NULL if pNN is not NULL
 */
 static int exprImpliesNotNull(
-  Parse *pParse,      /* Parsing context */
-  Expr *p,            /* The expression to be checked */
-  Expr *pNN,          /* The expression that is NOT NULL */
+  const Parse *pParse,/* Parsing context */
+  const Expr *p,      /* The expression to be checked */
+  const Expr *pNN,    /* The expression that is NOT NULL */
   int iTab,           /* Table being evaluated */
   int seenNot         /* Return true only if p can be any non-NULL value */
 ){
@@ -106049,12 +108100,13 @@ static int exprImpliesNotNull(
   switch( p->op ){
     case TK_IN: {
       if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
-      assert( ExprHasProperty(p,EP_xIsSelect)
-           || (p->x.pList!=0 && p->x.pList->nExpr>0) );
+      assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
       return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
     }
     case TK_BETWEEN: {
-      ExprList *pList = p->x.pList;
+      ExprList *pList;
+      assert( ExprUseXList(p) );
+      pList = p->x.pList;
       assert( pList!=0 );
       assert( pList->nExpr==2 );
       if( seenNot ) return 0;
@@ -106130,7 +108182,12 @@ static int exprImpliesNotNull(
 ** improvement.  Returning false might cause a performance reduction, but
 ** it will always give the correct answer and is hence always safe.
 */
-SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
+SQLITE_PRIVATE int sqlite3ExprImpliesExpr(
+  const Parse *pParse,
+  const Expr *pE1,
+  const Expr *pE2,
+  int iTab
+){
   if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
     return 1;
   }
@@ -106226,10 +108283,14 @@ static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
       testcase( pExpr->op==TK_GE );
       /* The y.pTab=0 assignment in wherecode.c always happens after the
       ** impliesNotNullRow() test */
-      if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)
-                               && IsVirtual(pLeft->y.pTab))
-       || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)
-                               && IsVirtual(pRight->y.pTab))
+      assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
+      assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
+      if( (pLeft->op==TK_COLUMN
+           && pLeft->y.pTab!=0
+           && IsVirtual(pLeft->y.pTab))
+       || (pRight->op==TK_COLUMN
+           && pRight->y.pTab!=0
+           && IsVirtual(pRight->y.pTab))
       ){
         return WRC_Prune;
       }
@@ -106338,88 +108399,125 @@ SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
 }
 
 
-/*
-** An instance of the following structure is used by the tree walker
-** to count references to table columns in the arguments of an
-** aggregate function, in order to implement the
-** sqlite3FunctionThisSrc() routine.
-*/
-struct SrcCount {
-  SrcList *pSrc;   /* One particular FROM clause in a nested query */
-  int iSrcInner;   /* Smallest cursor number in this context */
-  int nThis;       /* Number of references to columns in pSrcList */
-  int nOther;      /* Number of references to columns in other FROM clauses */
+/* Structure used to pass information throught the Walker in order to
+** implement sqlite3ReferencesSrcList().
+*/
+struct RefSrcList {
+  sqlite3 *db;         /* Database connection used for sqlite3DbRealloc() */
+  SrcList *pRef;       /* Looking for references to these tables */
+  i64 nExclude;        /* Number of tables to exclude from the search */
+  int *aiExclude;      /* Cursor IDs for tables to exclude from the search */
 };
 
 /*
-** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first
-** SELECT with a FROM clause encountered during this iteration, set
-** SrcCount.iSrcInner to the cursor number of the leftmost object in
-** the FROM cause.
+** Walker SELECT callbacks for sqlite3ReferencesSrcList().
+**
+** When entering a new subquery on the pExpr argument, add all FROM clause
+** entries for that subquery to the exclude list.
+**
+** When leaving the subquery, remove those entries from the exclude list.
 */
-static int selectSrcCount(Walker *pWalker, Select *pSel){
-  struct SrcCount *p = pWalker->u.pSrcCount;
-  if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){
-    pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor;
+static int selectRefEnter(Walker *pWalker, Select *pSelect){
+  struct RefSrcList *p = pWalker->u.pRefSrcList;
+  SrcList *pSrc = pSelect->pSrc;
+  i64 i, j;
+  int *piNew;
+  if( pSrc->nSrc==0 ) return WRC_Continue;
+  j = p->nExclude;
+  p->nExclude += pSrc->nSrc;
+  piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
+  if( piNew==0 ){
+    p->nExclude = 0;
+    return WRC_Abort;
+  }else{
+    p->aiExclude = piNew;
+  }
+  for(i=0; i<pSrc->nSrc; i++, j++){
+     p->aiExclude[j] = pSrc->a[i].iCursor;
   }
   return WRC_Continue;
 }
+static void selectRefLeave(Walker *pWalker, Select *pSelect){
+  struct RefSrcList *p = pWalker->u.pRefSrcList;
+  SrcList *pSrc = pSelect->pSrc;
+  if( p->nExclude ){
+    assert( p->nExclude>=pSrc->nSrc );
+    p->nExclude -= pSrc->nSrc;
+  }
+}
 
-/*
-** Count the number of references to columns.
+/* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
+**
+** Set the 0x01 bit of pWalker->eCode if there is a reference to any
+** of the tables shown in RefSrcList.pRef.
+**
+** Set the 0x02 bit of pWalker->eCode if there is a reference to a
+** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
 */
-static int exprSrcCount(Walker *pWalker, Expr *pExpr){
-  /* There was once a NEVER() on the second term on the grounds that
-  ** sqlite3FunctionUsesThisSrc() was always called before
-  ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet
-  ** been converted into TK_AGG_COLUMN. But this is no longer true due
-  ** to window functions - sqlite3WindowRewrite() may now indirectly call
-  ** FunctionUsesThisSrc() when creating a new sub-select. */
-  if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
+static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){
+  if( pExpr->op==TK_COLUMN
+   || pExpr->op==TK_AGG_COLUMN
+  ){
     int i;
-    struct SrcCount *p = pWalker->u.pSrcCount;
-    SrcList *pSrc = p->pSrc;
+    struct RefSrcList *p = pWalker->u.pRefSrcList;
+    SrcList *pSrc = p->pRef;
     int nSrc = pSrc ? pSrc->nSrc : 0;
     for(i=0; i<nSrc; i++){
-      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
+      if( pExpr->iTable==pSrc->a[i].iCursor ){
+        pWalker->eCode |= 1;
+        return WRC_Continue;
+      }
     }
-    if( i<nSrc ){
-      p->nThis++;
-    }else if( pExpr->iTable<p->iSrcInner ){
-      /* In a well-formed parse tree (no name resolution errors),
-      ** TK_COLUMN nodes with smaller Expr.iTable values are in an
-      ** outer context.  Those are the only ones to count as "other" */
-      p->nOther++;
+    for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
+    if( i>=p->nExclude ){
+      pWalker->eCode |= 2;
     }
   }
   return WRC_Continue;
 }
 
 /*
-** Determine if any of the arguments to the pExpr Function reference
-** pSrcList.  Return true if they do.  Also return true if the function
-** has no arguments or has only constant arguments.  Return false if pExpr
-** references columns but not columns of tables found in pSrcList.
+** Check to see if pExpr references any tables in pSrcList.
+** Possible return values:
+**
+**    1         pExpr does references a table in pSrcList.
+**
+**    0         pExpr references some table that is not defined in either
+**              pSrcList or in subqueries of pExpr itself.
+**
+**   -1         pExpr only references no tables at all, or it only
+**              references tables defined in subqueries of pExpr itself.
+**
+** As currently used, pExpr is always an aggregate function call.  That
+** fact is exploited for efficiency.
 */
-SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
+SQLITE_PRIVATE int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){
   Walker w;
-  struct SrcCount cnt;
-  assert( pExpr->op==TK_AGG_FUNCTION );
+  struct RefSrcList x;
   memset(&w, 0, sizeof(w));
-  w.xExprCallback = exprSrcCount;
-  w.xSelectCallback = selectSrcCount;
-  w.u.pSrcCount = &cnt;
-  cnt.pSrc = pSrcList;
-  cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF;
-  cnt.nThis = 0;
-  cnt.nOther = 0;
+  memset(&x, 0, sizeof(x));
+  w.xExprCallback = exprRefToSrcList;
+  w.xSelectCallback = selectRefEnter;
+  w.xSelectCallback2 = selectRefLeave;
+  w.u.pRefSrcList = &x;
+  x.db = pParse->db;
+  x.pRef = pSrcList;
+  assert( pExpr->op==TK_AGG_FUNCTION );
+  assert( ExprUseXList(pExpr) );
   sqlite3WalkExprList(&w, pExpr->x.pList);
 #ifndef SQLITE_OMIT_WINDOWFUNC
   if( ExprHasProperty(pExpr, EP_WinFunc) ){
     sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
   }
 #endif
-  return cnt.nThis>0 || cnt.nOther==0;
+  sqlite3DbFree(pParse->db, x.aiExclude);
+  if( w.eCode & 0x01 ){
+    return 1;
+  }else if( w.eCode ){
+    return 0;
+  }else{
+    return -1;
+  }
 }
 
 /*
@@ -106554,6 +108652,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
             ){
               pCol = &pAggInfo->aCol[k];
+              assert( ExprUseYTab(pExpr) );
               pCol->pTab = pExpr->y.pTab;
               pCol->iTable = pExpr->iTable;
               pCol->iColumn = pExpr->iColumn;
@@ -106602,6 +108701,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
         */
         struct AggInfo_func *pItem = pAggInfo->aFunc;
         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
+          if( pItem->pFExpr==pExpr ) break;
           if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
             break;
           }
@@ -106616,7 +108716,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
             pItem = &pAggInfo->aFunc[i];
             pItem->pFExpr = pExpr;
             pItem->iMem = ++pParse->nMem;
-            assert( !ExprHasProperty(pExpr, EP_IntValue) );
+            assert( ExprUseUToken(pExpr) );
             pItem->pFunc = sqlite3FindFunction(pParse->db,
                    pExpr->u.zToken,
                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
@@ -106802,6 +108902,7 @@ SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
 static int isAlterableTable(Parse *pParse, Table *pTab){
   if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
 #ifndef SQLITE_OMIT_VIRTUALTABLE
+   || (pTab->tabFlags & TF_Eponymous)!=0
    || ( (pTab->tabFlags & TF_Shadow)!=0
         && sqlite3ReadOnlyShadowTables(pParse->db)
    )
@@ -106825,27 +108926,51 @@ static void renameTestSchema(
   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 */
+  int bNoDQS                      /* Do not allow DQS in the schema */
 ){
   pParse->colNamesSet = 1;
   sqlite3NestedParse(pParse,
       "SELECT 1 "
-      "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
+      "FROM \"%w\"." LEGACY_SCHEMA_TABLE " "
       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
       " AND sql NOT LIKE 'create virtual%%'"
-      " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %Q)=NULL ",
+      " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ",
       zDb,
-      zDb, bTemp, zWhen, zDropColumn
+      zDb, bTemp, zWhen, bNoDQS
   );
 
   if( bTemp==0 ){
     sqlite3NestedParse(pParse,
         "SELECT 1 "
-        "FROM temp." DFLT_SCHEMA_TABLE " "
+        "FROM temp." LEGACY_SCHEMA_TABLE " "
         "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
         " AND sql NOT LIKE 'create virtual%%'"
-        " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %Q)=NULL ",
-        zDb, zWhen, zDropColumn
+        " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ",
+        zDb, zWhen, bNoDQS
+    );
+  }
+}
+
+/*
+** Generate VM code to replace any double-quoted strings (but not double-quoted
+** identifiers) within the "sql" column of the sqlite_schema table in
+** database zDb with their single-quoted equivalents. If argument bTemp is
+** not true, similarly update all SQL statements in the sqlite_schema table
+** of the temp db.
+*/
+static void renameFixQuotes(Parse *pParse, const char *zDb, int bTemp){
+  sqlite3NestedParse(pParse,
+      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
+      " SET sql = sqlite_rename_quotefix(%Q, sql)"
+      "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
+      " AND sql NOT LIKE 'create virtual%%'" , zDb, zDb
+  );
+  if( bTemp==0 ){
+    sqlite3NestedParse(pParse,
+      "UPDATE temp." LEGACY_SCHEMA_TABLE
+      " SET sql = sqlite_rename_quotefix('temp', sql)"
+      "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
+      " AND sql NOT LIKE 'create virtual%%'"
     );
   }
 }
@@ -106881,9 +109006,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   const char *zTabName;     /* Original name of the table */
   Vdbe *v;
   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
-  u32 savedDbFlags;         /* Saved value of db->mDbFlags */
 
-  savedDbFlags = db->mDbFlags;
   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   assert( pSrc->nSrc==1 );
   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
@@ -106892,7 +109015,6 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   if( !pTab ) goto exit_rename_table;
   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   zDb = db->aDb[iDb].zDbSName;
-  db->mDbFlags |= DBFLAG_PreferBuiltin;
 
   /* Get a NULL terminated version of the new table name. */
   zName = sqlite3NameFromToken(db, pName);
@@ -106921,7 +109043,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   }
 
 #ifndef SQLITE_OMIT_VIEW
-  if( pTab->pSelect ){
+  if( IsView(pTab) ){
     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
     goto exit_rename_table;
   }
@@ -106963,7 +109085,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
   ** the schema to use the new table name.  */
   sqlite3NestedParse(pParse,
-      "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
       "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
       "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
       "AND   name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
@@ -106973,7 +109095,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   /* Update the tbl_name and name columns of the sqlite_schema table
   ** as required.  */
   sqlite3NestedParse(pParse,
-      "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
+      "UPDATE %Q." LEGACY_SCHEMA_TABLE " SET "
           "tbl_name = %Q, "
           "name = CASE "
             "WHEN type='table' THEN %Q "
@@ -107008,7 +109130,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
             "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, 'after rename',0) "
+              "  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);
@@ -107033,7 +109155,6 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
 exit_rename_table:
   sqlite3SrcListDelete(db, pSrc);
   sqlite3DbFree(db, zName);
-  db->mDbFlags = savedDbFlags;
 }
 
 /*
@@ -107074,7 +109195,9 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   int r1;                   /* Temporary registers */
 
   db = pParse->db;
-  if( pParse->nErr || db->mallocFailed ) return;
+  assert( db->pParse==pParse );
+  if( pParse->nErr ) return;
+  assert( db->mallocFailed==0 );
   pNew = pParse->pNewTable;
   assert( pNew );
 
@@ -107083,7 +109206,7 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   zDb = db->aDb[iDb].zDbSName;
   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   pCol = &pNew->aCol[pNew->nCol-1];
-  pDflt = pCol->pDflt;
+  pDflt = sqlite3ColumnExpr(pNew, pCol);
   pTab = sqlite3FindTable(db, zTab, zDb);
   assert( pTab );
 
@@ -107117,7 +109240,8 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
     if( pDflt && pDflt->pLeft->op==TK_NULL ){
       pDflt = 0;
     }
-    if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
+    assert( IsOrdinaryTable(pNew) );
+    if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
       sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
           "Cannot add a REFERENCES column with non-NULL default value");
     }
@@ -107154,31 +109278,30 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   if( zCol ){
     char *zEnd = &zCol[pColDef->n-1];
-    u32 savedDbFlags = db->mDbFlags;
     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
       *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: */
+    assert( IsOrdinaryTable(pTab) );
+    assert( IsOrdinaryTable(pNew) );
     sqlite3NestedParse(pParse,
-        "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+        "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
           "sql = printf('%%.%ds, ',sql) || %Q"
           " || substr(sql,1+length(printf('%%.%ds',sql))) "
         "WHERE type = 'table' AND name = %Q",
-      zDb, pNew->addColOffset, zCol, pNew->addColOffset,
+      zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset,
       zTab
     );
     sqlite3DbFree(db, zCol);
-    db->mDbFlags = savedDbFlags;
   }
 
-  /* Make sure the schema version is at least 3.  But do not upgrade
-  ** from less than 3 to 4, as that will corrupt any preexisting DESC
-  ** index.
-  */
   v = sqlite3GetVdbe(pParse);
   if( v ){
+    /* Make sure the schema version is at least 3.  But do not upgrade
+    ** from less than 3 to 4, as that will corrupt any preexisting DESC
+    ** index.
+    */
     r1 = sqlite3GetTempReg(pParse);
     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
     sqlite3VdbeUsesBtree(v, iDb);
@@ -107187,10 +109310,25 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
     VdbeCoverage(v);
     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
     sqlite3ReleaseTempReg(pParse, r1);
-  }
 
-  /* Reload the table definition */
-  renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
+    /* Reload the table definition */
+    renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd);
+
+    /* Verify that constraints are still satisfied */
+    if( pNew->pCheck!=0
+     || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
+    ){
+      sqlite3NestedParse(pParse,
+        "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
+        " THEN raise(ABORT,'CHECK constraint failed')"
+        " ELSE raise(ABORT,'NOT NULL constraint failed')"
+        " END"
+        "  FROM pragma_quick_check(%Q,%Q)"
+        " WHERE quick_check GLOB 'CHECK*' OR quick_check GLOB 'NULL*'",
+        zTab, zDb
+      );
+    }
+  }
 }
 
 /*
@@ -107231,7 +109369,7 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
 #endif
 
   /* Make sure this is not an attempt to ALTER a view. */
-  if( pTab->pSelect ){
+  if( IsView(pTab) ){
     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
     goto exit_begin_add_column;
   }
@@ -107240,7 +109378,8 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   }
 
   sqlite3MayAbort(pParse);
-  assert( pTab->addColOffset>0 );
+  assert( IsOrdinaryTable(pTab) );
+  assert( pTab->u.tab.addColOffset>0 );
   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 
   /* Put a copy of the Table struct in Parse.pNewTable for the
@@ -107267,13 +109406,13 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   for(i=0; i<pNew->nCol; i++){
     Column *pCol = &pNew->aCol[i];
-    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
-    pCol->hName = sqlite3StrIHash(pCol->zName);
-    pCol->zColl = 0;
-    pCol->pDflt = 0;
+    pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName);
+    pCol->hName = sqlite3StrIHash(pCol->zCnName);
   }
+  assert( IsOrdinaryTable(pNew) );
+  pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0);
   pNew->pSchema = db->aDb[iDb].pSchema;
-  pNew->addColOffset = pTab->addColOffset;
+  pNew->u.tab.addColOffset = pTab->u.tab.addColOffset;
   pNew->nTabRef = 1;
 
 exit_begin_add_column:
@@ -107293,7 +109432,7 @@ exit_begin_add_column:
 static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
   const char *zType = 0;
 #ifndef SQLITE_OMIT_VIEW
-  if( pTab->pSelect ){
+  if( IsView(pTab) ){
     zType = "view";
   }
 #endif
@@ -107360,13 +109499,17 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn(
   zOld = sqlite3NameFromToken(db, pOld);
   if( !zOld ) goto exit_rename_column;
   for(iCol=0; iCol<pTab->nCol; iCol++){
-    if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
+    if( 0==sqlite3StrICmp(pTab->aCol[iCol].zCnName, zOld) ) break;
   }
   if( iCol==pTab->nCol ){
-    sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
+    sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pOld);
     goto exit_rename_column;
   }
 
+  /* Ensure the schema contains no double-quoted strings */
+  renameTestSchema(pParse, zDb, iSchema==1, "", 0);
+  renameFixQuotes(pParse, zDb, iSchema==1);
+
   /* Do the rename operation using a recursive UPDATE statement that
   ** uses the sqlite_rename_column() SQL function to compute the new
   ** CREATE statement text for the sqlite_schema table.
@@ -107377,18 +109520,17 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn(
   assert( pNew->n>0 );
   bQuote = sqlite3Isquote(pNew->z[0]);
   sqlite3NestedParse(pParse,
-      "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
-      " AND (type != 'index' OR tbl_name = %Q)"
-      " AND sql NOT LIKE 'create virtual%%'",
+      " AND (type != 'index' OR tbl_name = %Q)",
       zDb,
       zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
       pTab->zName
   );
 
   sqlite3NestedParse(pParse,
-      "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
+      "UPDATE temp." LEGACY_SCHEMA_TABLE " SET "
       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
       "WHERE type IN ('trigger', 'view')",
       zDb, pTab->zName, iCol, zNew, bQuote
@@ -107396,7 +109538,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn(
 
   /* Drop and reload the database schema. */
   renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
-  renameTestSchema(pParse, zDb, iSchema==1, "after rename", 0);
+  renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
 
  exit_rename_column:
   sqlite3SrcListDelete(db, pSrc);
@@ -107423,7 +109565,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn(
 ** the parse tree.
 */
 struct RenameToken {
-  void *p;               /* Parse tree element created by token t */
+  const void *p;         /* Parse tree element created by token t */
   Token t;               /* The token that created parse tree element p */
   RenameToken *pNext;    /* Next is a list of all RenameToken objects */
 };
@@ -107465,9 +109607,11 @@ struct RenameCtx {
 ** Technically, as x no longer points into a valid object or to the byte
 ** following a valid object, it may not be used in comparison operations.
 */
-static void renameTokenCheckAll(Parse *pParse, void *pPtr){
-  if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
-    RenameToken *p;
+static void renameTokenCheckAll(Parse *pParse, const void *pPtr){
+  assert( pParse==pParse->db->pParse );
+  assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
+  if( pParse->nErr==0 ){
+    const RenameToken *p;
     u8 i = 0;
     for(p=pParse->pRename; p; p=p->pNext){
       if( p->p ){
@@ -107493,7 +109637,11 @@ static void renameTokenCheckAll(Parse *pParse, void *pPtr){
 ** with tail recursion in tokenExpr() routine, for a small performance
 ** improvement.
 */
-SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
+SQLITE_PRIVATE const void *sqlite3RenameTokenMap(
+  Parse *pParse,
+  const void *pPtr,
+  const Token *pToken
+){
   RenameToken *pNew;
   assert( pPtr || pParse->db->mallocFailed );
   renameTokenCheckAll(pParse, pPtr);
@@ -107515,7 +109663,7 @@ SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pTo
 ** with parse tree element pFrom. This function remaps the associated token
 ** to parse tree element pTo.
 */
-SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
+SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, const void *pTo, const void *pFrom){
   RenameToken *p;
   renameTokenCheckAll(pParse, pTo);
   for(p=pParse->pRename; p; p=p->pNext){
@@ -107531,7 +109679,10 @@ SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFro
 */
 static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
   Parse *pParse = pWalker->pParse;
-  sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
+  sqlite3RenameTokenRemap(pParse, 0, (const void*)pExpr);
+  if( ExprUseYTab(pExpr) ){
+    sqlite3RenameTokenRemap(pParse, 0, (const void*)&pExpr->y.pTab);
+  }
   return WRC_Continue;
 }
 
@@ -107542,15 +109693,31 @@ static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
 static void renameWalkWith(Walker *pWalker, Select *pSelect){
   With *pWith = pSelect->pWith;
   if( pWith ){
+    Parse *pParse = pWalker->pParse;
     int i;
+    With *pCopy = 0;
+    assert( pWith->nCte>0 );
+    if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
+      /* Push a copy of the With object onto the with-stack. We use a copy
+      ** here as the original will be expanded and resolved (flags SF_Expanded
+      ** and SF_Resolved) below. And the parser code that uses the with-stack
+      ** fails if the Select objects on it have already been expanded and
+      ** resolved.  */
+      pCopy = sqlite3WithDup(pParse->db, pWith);
+      pCopy = sqlite3WithPush(pParse, pCopy, 1);
+    }
     for(i=0; i<pWith->nCte; i++){
       Select *p = pWith->a[i].pSelect;
       NameContext sNC;
       memset(&sNC, 0, sizeof(sNC));
-      sNC.pParse = pWalker->pParse;
-      sqlite3SelectPrep(sNC.pParse, p, &sNC);
+      sNC.pParse = pParse;
+      if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
+      if( sNC.pParse->db->mallocFailed ) return;
       sqlite3WalkSelect(pWalker, p);
-      sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
+      sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
+    }
+    if( pCopy && pParse->pWith==pCopy ){
+      pParse->pWith = pCopy->pOuter;
     }
   }
 }
@@ -107560,12 +109727,12 @@ static void renameWalkWith(Walker *pWalker, Select *pSelect){
 */
 static void unmapColumnIdlistNames(
   Parse *pParse,
-  IdList *pIdList
+  const IdList *pIdList
 ){
   if( pIdList ){
     int ii;
     for(ii=0; ii<pIdList->nId; ii++){
-      sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
+      sqlite3RenameTokenRemap(pParse, 0, (const void*)pIdList->a[ii].zName);
     }
   }
 }
@@ -107577,7 +109744,11 @@ static int renameUnmapSelectCb(Walker *pWalker, Select *p){
   Parse *pParse = pWalker->pParse;
   int i;
   if( pParse->nErr ) return WRC_Abort;
-  if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
+  testcase( p->selFlags & SF_View );
+  testcase( p->selFlags & SF_CopyCte );
+  if( p->selFlags & (SF_View|SF_CopyCte) ){
+    return WRC_Prune;
+  }
   if( ALWAYS(p->pEList) ){
     ExprList *pList = p->pEList;
     for(i=0; i<pList->nExpr; i++){
@@ -107590,7 +109761,7 @@ static int renameUnmapSelectCb(Walker *pWalker, Select *p){
     SrcList *pSrc = p->pSrc;
     for(i=0; i<pSrc->nSrc; i++){
       sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
-      if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
+      sqlite3WalkExpr(pWalker, pSrc->a[i].pOn);
       unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
     }
   }
@@ -107658,10 +109829,12 @@ static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
 static RenameToken *renameTokenFind(
   Parse *pParse,
   struct RenameCtx *pCtx,
-  void *pPtr
+  const void *pPtr
 ){
   RenameToken **pp;
-  assert( pPtr!=0 );
+  if( NEVER(pPtr==0) ){
+    return 0;
+  }
   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
     if( (*pp)->p==pPtr ){
       RenameToken *pToken = *pp;
@@ -107683,7 +109856,11 @@ static RenameToken *renameTokenFind(
 ** descend into sub-select statements.
 */
 static int renameColumnSelectCb(Walker *pWalker, Select *p){
-  if( p->selFlags & SF_View ) return WRC_Prune;
+  if( p->selFlags & (SF_View|SF_CopyCte) ){
+    testcase( p->selFlags & SF_View );
+    testcase( p->selFlags & SF_CopyCte );
+    return WRC_Prune;
+  }
   renameWalkWith(pWalker, p);
   return WRC_Continue;
 }
@@ -107706,6 +109883,7 @@ static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
   }else if( pExpr->op==TK_COLUMN
    && pExpr->iColumn==p->iCol
+   && ALWAYS(ExprUseYTab(pExpr))
    && p->pTab==pExpr->y.pTab
   ){
     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
@@ -107754,12 +109932,12 @@ static void renameColumnParseError(
   const char *zN = (const char*)sqlite3_value_text(pObject);
   char *zErr;
 
-  zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
+  zErr = sqlite3MPrintf(pParse->db, "error in %s %s%s%s: %s",
       zT, zN, (zWhen[0] ? " " : ""), zWhen,
       pParse->zErrMsg
   );
   sqlite3_result_error(pCtx, zErr, -1);
-  sqlite3_free(zErr);
+  sqlite3DbFree(pParse->db, zErr);
 }
 
 /*
@@ -107771,18 +109949,18 @@ static void renameColumnParseError(
 static void renameColumnElistNames(
   Parse *pParse,
   RenameCtx *pCtx,
-  ExprList *pEList,
+  const ExprList *pEList,
   const char *zOld
 ){
   if( pEList ){
     int i;
     for(i=0; i<pEList->nExpr; i++){
-      char *zName = pEList->a[i].zEName;
+      const char *zName = pEList->a[i].zEName;
       if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
        && ALWAYS(zName!=0)
        && 0==sqlite3_stricmp(zName, zOld)
       ){
-        renameTokenFind(pParse, pCtx, (void*)zName);
+        renameTokenFind(pParse, pCtx, (const void*)zName);
       }
     }
   }
@@ -107796,15 +109974,15 @@ static void renameColumnElistNames(
 static void renameColumnIdlistNames(
   Parse *pParse,
   RenameCtx *pCtx,
-  IdList *pIdList,
+  const IdList *pIdList,
   const char *zOld
 ){
   if( pIdList ){
     int i;
     for(i=0; i<pIdList->nId; i++){
-      char *zName = pIdList->a[i].zName;
+      const char *zName = pIdList->a[i].zName;
       if( 0==sqlite3_stricmp(zName, zOld) ){
-        renameTokenFind(pParse, pCtx, (void*)zName);
+        renameTokenFind(pParse, pCtx, (const void*)zName);
       }
     }
   }
@@ -107820,32 +109998,25 @@ static int renameParseSql(
   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 */
-  const char *zDropColumn         /* Name of column being dropped */
+  int bTemp                       /* True if SQL is from temp schema */
 ){
   int rc;
-  char *zErr = 0;
 
-  db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
-  if( zDropColumn ){
-    db->init.bDropColumn = 1;
-    db->init.azInit = (char**)&zDropColumn;
+  sqlite3ParseObjectInit(p, db);
+  if( zSql==0 ){
+    return SQLITE_NOMEM;
   }
-
-  /* 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
-  ** trigger object, the database must be corrupt. */
-  memset(p, 0, sizeof(Parse));
+  if( sqlite3StrNICmp(zSql,"CREATE ",7)!=0 ){
+    return SQLITE_CORRUPT_BKPT;
+  }
+  db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
   p->eParseMode = PARSE_MODE_RENAME;
   p->db = db;
   p->nQueryLoop = 1;
-  rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
-  assert( p->zErrMsg==0 );
-  assert( rc!=SQLITE_OK || zErr==0 );
-  p->zErrMsg = zErr;
+  rc = sqlite3RunParser(p, zSql);
   if( db->mallocFailed ) rc = SQLITE_NOMEM;
   if( rc==SQLITE_OK
-   && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
+   && NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0)
   ){
     rc = SQLITE_CORRUPT_BKPT;
   }
@@ -107863,7 +110034,6 @@ static int renameParseSql(
 #endif
 
   db->init.iDb = 0;
-  db->init.bDropColumn = 0;
   return rc;
 }
 
@@ -107883,51 +110053,76 @@ static int renameEditSql(
   const char *zNew,               /* New token text */
   int bQuote                      /* True to always quote token */
 ){
-  int nNew = sqlite3Strlen30(zNew);
-  int nSql = sqlite3Strlen30(zSql);
+  i64 nNew = sqlite3Strlen30(zNew);
+  i64 nSql = sqlite3Strlen30(zSql);
   sqlite3 *db = sqlite3_context_db_handle(pCtx);
   int rc = SQLITE_OK;
-  char *zQuot;
+  char *zQuot = 0;
   char *zOut;
-  int nQuot;
-
-  /* Set zQuot to point to a buffer containing a quoted copy of the
-  ** identifier zNew. If the corresponding identifier in the original
-  ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
-  ** point to zQuot so that all substitutions are made using the
-  ** quoted version of the new column name.  */
-  zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
-  if( zQuot==0 ){
-    return SQLITE_NOMEM;
+  i64 nQuot = 0;
+  char *zBuf1 = 0;
+  char *zBuf2 = 0;
+
+  if( zNew ){
+    /* Set zQuot to point to a buffer containing a quoted copy of the
+    ** identifier zNew. If the corresponding identifier in the original
+    ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
+    ** point to zQuot so that all substitutions are made using the
+    ** quoted version of the new column name.  */
+    zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
+    if( zQuot==0 ){
+      return SQLITE_NOMEM;
+    }else{
+      nQuot = sqlite3Strlen30(zQuot)-1;
+    }
+
+    assert( nQuot>=nNew );
+    zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
   }else{
-    nQuot = sqlite3Strlen30(zQuot);
-  }
-  if( bQuote ){
-    zNew = zQuot;
-    nNew = nQuot;
+    zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
+    if( zOut ){
+      zBuf1 = &zOut[nSql*2+1];
+      zBuf2 = &zOut[nSql*4+2];
+    }
   }
 
   /* At this point pRename->pList contains a list of RenameToken objects
   ** corresponding to all tokens in the input SQL that must be replaced
-  ** with the new column name. All that remains is to construct and
-  ** return the edited SQL string. */
-  assert( nQuot>=nNew );
-  zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
+  ** with the new column name, or with single-quoted versions of themselves.
+  ** All that remains is to construct and return the edited SQL string. */
   if( zOut ){
     int nOut = nSql;
     memcpy(zOut, zSql, nSql);
     while( pRename->pList ){
       int iOff;                   /* Offset of token to replace in zOut */
-      RenameToken *pBest = renameColumnTokenNext(pRename);
-
       u32 nReplace;
       const char *zReplace;
-      if( sqlite3IsIdChar(*pBest->t.z) ){
-        nReplace = nNew;
-        zReplace = zNew;
+      RenameToken *pBest = renameColumnTokenNext(pRename);
+
+      if( zNew ){
+        if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
+          nReplace = nNew;
+          zReplace = zNew;
+        }else{
+          nReplace = nQuot;
+          zReplace = zQuot;
+          if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
+        }
       }else{
-        nReplace = nQuot;
-        zReplace = zQuot;
+        /* Dequote the double-quoted token. Then requote it again, this time
+        ** using single quotes. If the character immediately following the
+        ** original token within the input SQL was a single quote ('), then
+        ** add another space after the new, single-quoted version of the
+        ** token. This is so that (SELECT "string"'alias') maps to
+        ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias').  */
+        memcpy(zBuf1, pBest->t.z, pBest->t.n);
+        zBuf1[pBest->t.n] = 0;
+        sqlite3Dequote(zBuf1);
+        sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
+            pBest->t.z[pBest->t.n]=='\'' ? " " : ""
+        );
+        zReplace = zBuf2;
+        nReplace = sqlite3Strlen30(zReplace);
       }
 
       iOff = pBest->t.z - zSql;
@@ -108011,6 +110206,9 @@ static int renameResolveTrigger(Parse *pParse){
             }
           }
         }
+        if( rc==SQLITE_OK && db->mallocFailed ){
+          rc = SQLITE_NOMEM;
+        }
         sNC.pSrcList = pSrc;
         if( rc==SQLITE_OK && pStep->pWhere ){
           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
@@ -108096,13 +110294,13 @@ static void renameParseCleanup(Parse *pParse){
   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   sqlite3DbFree(db, pParse->zErrMsg);
   renameTokenFree(db, pParse->pRename);
-  sqlite3ParserReset(pParse);
+  sqlite3ParseObjectReset(pParse);
 }
 
 /*
 ** SQL function:
 **
-**     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
+**     sqlite_rename_column(SQL,TYPE,OBJ,DB,TABLE,COL,NEWNAME,QUOTE,TEMP)
 **
 **   0. zSql:     SQL statement to rewrite
 **   1. type:     Type of object ("table", "view" etc.)
@@ -108120,7 +110318,8 @@ static void renameParseCleanup(Parse *pParse){
 **
 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
 ** It is only accessible to SQL created using sqlite3NestedParse().  It is
-** not reachable from ordinary SQL passed into sqlite3_prepare().
+** not reachable from ordinary SQL passed into sqlite3_prepare() unless the
+** SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test setting is enabled.
 */
 static void renameColumnFunc(
   sqlite3_context *context,
@@ -108158,14 +110357,14 @@ static void renameColumnFunc(
     sqlite3BtreeLeaveAll(db);
     return;
   }
-  zOld = pTab->aCol[iCol].zName;
+  zOld = pTab->aCol[iCol].zCnName;
   memset(&sCtx, 0, sizeof(sCtx));
   sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
 
 #ifndef SQLITE_OMIT_AUTHORIZATION
   db->xAuth = 0;
 #endif
-  rc = renameParseSql(&sParse, zDb, db, zSql, bTemp, 0);
+  rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
 
   /* Find tokens that need to be replaced. */
   memset(&sWalker, 0, sizeof(Walker));
@@ -108177,8 +110376,8 @@ static void renameColumnFunc(
   sCtx.pTab = pTab;
   if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
   if( sParse.pNewTable ){
-    Select *pSelect = sParse.pNewTable->pSelect;
-    if( pSelect ){
+    if( IsView(sParse.pNewTable) ){
+      Select *pSelect = sParse.pNewTable->u.view.pSelect;
       pSelect->selFlags &= ~SF_View;
       sParse.rc = SQLITE_OK;
       sqlite3SelectPrep(&sParse, pSelect, 0);
@@ -108187,16 +110386,17 @@ static void renameColumnFunc(
         sqlite3WalkSelect(&sWalker, pSelect);
       }
       if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
-    }else{
+    }else if( IsOrdinaryTable(sParse.pNewTable) ){
       /* A regular table */
       int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
       FKey *pFKey;
-      assert( sParse.pNewTable->pSelect==0 );
       sCtx.pTab = sParse.pNewTable;
       if( bFKOnly==0 ){
-        renameTokenFind(
-            &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
-        );
+        if( iCol<sParse.pNewTable->nCol ){
+          renameTokenFind(
+              &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
+          );
+        }
         if( sCtx.iCol<0 ){
           renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
         }
@@ -108209,12 +110409,15 @@ static void renameColumnFunc(
         }
 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
         for(i=0; i<sParse.pNewTable->nCol; i++){
-          sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
+          Expr *pExpr = sqlite3ColumnExpr(sParse.pNewTable,
+                                                  &sParse.pNewTable->aCol[i]);
+          sqlite3WalkExpr(&sWalker, pExpr);
         }
 #endif
       }
 
-      for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+      assert( IsOrdinaryTable(sParse.pNewTable) );
+      for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
         for(i=0; i<pFKey->nCol; i++){
           if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
             renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
@@ -108265,7 +110468,9 @@ static void renameColumnFunc(
 
 renameColumnFunc_done:
   if( rc!=SQLITE_OK ){
-    if( sParse.zErrMsg ){
+    if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){
+      sqlite3_result_value(context, argv[0]);
+    }else if( sParse.zErrMsg ){
       renameColumnParseError(context, "", argv[1], argv[2], &sParse);
     }else{
       sqlite3_result_error_code(context, rc);
@@ -108285,7 +110490,10 @@ renameColumnFunc_done:
 */
 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
   RenameCtx *p = pWalker->u.pRename;
-  if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
+  if( pExpr->op==TK_COLUMN
+   && ALWAYS(ExprUseYTab(pExpr))
+   && p->pTab==pExpr->y.pTab
+  ){
     renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
   }
   return WRC_Continue;
@@ -108298,8 +110506,12 @@ static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
   int i;
   RenameCtx *p = pWalker->u.pRename;
   SrcList *pSrc = pSelect->pSrc;
-  if( pSelect->selFlags & SF_View ) return WRC_Prune;
-  if( pSrc==0 ){
+  if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
+    testcase( pSelect->selFlags & SF_View );
+    testcase( pSelect->selFlags & SF_CopyCte );
+    return WRC_Prune;
+  }
+  if( NEVER(pSrc==0) ){
     assert( pWalker->pParse->db->mallocFailed );
     return WRC_Abort;
   }
@@ -108369,35 +110581,38 @@ static void renameTableFunc(
     sWalker.xSelectCallback = renameTableSelectCb;
     sWalker.u.pRename = &sCtx;
 
-    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp, 0);
+    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
 
     if( rc==SQLITE_OK ){
       int isLegacy = (db->flags & SQLITE_LegacyAlter);
       if( sParse.pNewTable ){
         Table *pTab = sParse.pNewTable;
 
-        if( pTab->pSelect ){
+        if( IsView(pTab) ){
           if( isLegacy==0 ){
-            Select *pSelect = pTab->pSelect;
+            Select *pSelect = pTab->u.view.pSelect;
             NameContext sNC;
             memset(&sNC, 0, sizeof(sNC));
             sNC.pParse = &sParse;
 
             assert( pSelect->selFlags & SF_View );
             pSelect->selFlags &= ~SF_View;
-            sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
+            sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);
             if( sParse.nErr ){
               rc = sParse.rc;
             }else{
-              sqlite3WalkSelect(&sWalker, pTab->pSelect);
+              sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect);
             }
           }
         }else{
           /* Modify any FK definitions to point to the new table. */
 #ifndef SQLITE_OMIT_FOREIGN_KEY
-          if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
+          if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys))
+           && !IsVirtual(pTab)
+          ){
             FKey *pFKey;
-            for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+            assert( IsOrdinaryTable(pTab) );
+            for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
               if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
                 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
               }
@@ -108454,7 +110669,9 @@ static void renameTableFunc(
       rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
     }
     if( rc!=SQLITE_OK ){
-      if( sParse.zErrMsg ){
+      if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){
+        sqlite3_result_value(context, argv[3]);
+      }else if( sParse.zErrMsg ){
         renameColumnParseError(context, "", argv[1], argv[2], &sParse);
       }else{
         sqlite3_result_error_code(context, rc);
@@ -108472,7 +110689,131 @@ static void renameTableFunc(
   return;
 }
 
-/*
+static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
+  if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
+    renameTokenFind(pWalker->pParse, pWalker->u.pRename, (const void*)pExpr);
+  }
+  return WRC_Continue;
+}
+
+/* SQL function: sqlite_rename_quotefix(DB,SQL)
+**
+** Rewrite the DDL statement "SQL" so that any string literals that use
+** double-quotes use single quotes instead.
+**
+** Two arguments must be passed:
+**
+**   0: Database name ("main", "temp" etc.).
+**   1: SQL statement to edit.
+**
+** The returned value is the modified SQL statement. For example, given
+** the database schema:
+**
+**   CREATE TABLE t1(a, b, c);
+**
+**   SELECT sqlite_rename_quotefix('main',
+**       'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
+**   );
+**
+** returns the string:
+**
+**   CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
+**
+** If there is a error in the input SQL, then raise an error, except
+** if PRAGMA writable_schema=ON, then just return the input string
+** unmodified following an error.
+*/
+static void renameQuotefixFunc(
+  sqlite3_context *context,
+  int NotUsed,
+  sqlite3_value **argv
+){
+  sqlite3 *db = sqlite3_context_db_handle(context);
+  char const *zDb = (const char*)sqlite3_value_text(argv[0]);
+  char const *zInput = (const char*)sqlite3_value_text(argv[1]);
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  sqlite3_xauth xAuth = db->xAuth;
+  db->xAuth = 0;
+#endif
+
+  sqlite3BtreeEnterAll(db);
+
+  UNUSED_PARAMETER(NotUsed);
+  if( zDb && zInput ){
+    int rc;
+    Parse sParse;
+    rc = renameParseSql(&sParse, zDb, db, zInput, 0);
+
+    if( rc==SQLITE_OK ){
+      RenameCtx sCtx;
+      Walker sWalker;
+
+      /* Walker to find tokens that need to be replaced. */
+      memset(&sCtx, 0, sizeof(RenameCtx));
+      memset(&sWalker, 0, sizeof(Walker));
+      sWalker.pParse = &sParse;
+      sWalker.xExprCallback = renameQuotefixExprCb;
+      sWalker.xSelectCallback = renameColumnSelectCb;
+      sWalker.u.pRename = &sCtx;
+
+      if( sParse.pNewTable ){
+        if( IsView(sParse.pNewTable) ){
+          Select *pSelect = sParse.pNewTable->u.view.pSelect;
+          pSelect->selFlags &= ~SF_View;
+          sParse.rc = SQLITE_OK;
+          sqlite3SelectPrep(&sParse, pSelect, 0);
+          rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
+          if( rc==SQLITE_OK ){
+            sqlite3WalkSelect(&sWalker, pSelect);
+          }
+        }else{
+          int i;
+          sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+          for(i=0; i<sParse.pNewTable->nCol; i++){
+            sqlite3WalkExpr(&sWalker,
+               sqlite3ColumnExpr(sParse.pNewTable,
+                                         &sParse.pNewTable->aCol[i]));
+          }
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+        }
+      }else if( sParse.pNewIndex ){
+        sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
+        sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
+      }else{
+#ifndef SQLITE_OMIT_TRIGGER
+        rc = renameResolveTrigger(&sParse);
+        if( rc==SQLITE_OK ){
+          renameWalkTrigger(&sWalker, sParse.pNewTrigger);
+        }
+#endif /* SQLITE_OMIT_TRIGGER */
+      }
+
+      if( rc==SQLITE_OK ){
+        rc = renameEditSql(context, &sCtx, zInput, 0, 0);
+      }
+      renameTokenFree(db, sCtx.pList);
+    }
+    if( rc!=SQLITE_OK ){
+      if( sqlite3WritableSchema(db) && rc==SQLITE_ERROR ){
+        sqlite3_result_value(context, argv[1]);
+      }else{
+        sqlite3_result_error_code(context, rc);
+      }
+    }
+    renameParseCleanup(&sParse);
+  }
+
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  db->xAuth = xAuth;
+#endif
+
+  sqlite3BtreeLeaveAll(db);
+}
+
+/* Function:  sqlite_rename_test(DB,SQL,TYPE,NAME,ISTEMP,WHEN,DQS)
+**
 ** An SQL user function that checks that there are no parse or symbol
 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
 ** After an ALTER TABLE .. RENAME operation is performed and the schema
@@ -108485,13 +110826,15 @@ static void renameTableFunc(
 **   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.
+**   6: True to disable the DQS quirk when parsing SQL.
 **
-** Unless it finds an error, this function normally returns NULL. However, it
-** returns integer value 1 if:
+** The return value is computed as follows:
 **
-**   * the SQL argument creates a trigger, and
-**   * the table that the trigger is attached to is in database zDb.
+**   A. If an error is seen and not in PRAGMA writable_schema=ON mode,
+**      then raise the error.
+**   B. Else if a trigger is created and the the table that the trigger is
+**      attached to is in database zDb, then return 1.
+**   C. Otherwise return NULL.
 */
 static void renameTableTest(
   sqlite3_context *context,
@@ -108504,7 +110847,7 @@ static void renameTableTest(
   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]);
+  int bNoDQS = sqlite3_value_int(argv[6]);
 
 #ifndef SQLITE_OMIT_AUTHORIZATION
   sqlite3_xauth xAuth = db->xAuth;
@@ -108512,16 +110855,20 @@ static void renameTableTest(
 #endif
 
   UNUSED_PARAMETER(NotUsed);
+
   if( zDb && zInput ){
     int rc;
     Parse sParse;
-    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp, zDropColumn);
+    int flags = db->flags;
+    if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
+    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
+    db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
     if( rc==SQLITE_OK ){
-      if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
+      if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){
         NameContext sNC;
         memset(&sNC, 0, sizeof(sNC));
         sNC.pParse = &sParse;
-        sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
+        sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC);
         if( sParse.nErr ) rc = sParse.rc;
       }
 
@@ -108532,12 +110879,16 @@ static void renameTableTest(
         if( rc==SQLITE_OK ){
           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
           int i2 = sqlite3FindDbName(db, zDb);
-          if( i1==i2 ) sqlite3_result_int(context, 1);
+          if( i1==i2 ){
+            /* Handle output case B */
+            sqlite3_result_int(context, 1);
+          }
         }
       }
     }
 
-    if( rc!=SQLITE_OK && zWhen ){
+    if( rc!=SQLITE_OK && zWhen && !sqlite3WritableSchema(db) ){
+      /* Output case A */
       renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
     }
     renameParseCleanup(&sParse);
@@ -108583,7 +110934,7 @@ static void dropColumnFunc(
 #endif
 
   UNUSED_PARAMETER(NotUsed);
-  rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1, 0);
+  rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
   if( rc!=SQLITE_OK ) goto drop_column_done;
   pTab = sParse.pNewTable;
   if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
@@ -108592,13 +110943,14 @@ static void dropColumnFunc(
     goto drop_column_done;
   }
 
-  pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
+  pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName);
   if( iCol<pTab->nCol-1 ){
     RenameToken *pEnd;
-    pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
+    pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName);
     zEnd = (const char*)pEnd->t.z;
   }else{
-    zEnd = (const char*)&zSql[pTab->addColOffset];
+    assert( IsOrdinaryTable(pTab) );
+    zEnd = (const char*)&zSql[pTab->u.tab.addColOffset];
     while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
   }
 
@@ -108624,7 +110976,7 @@ drop_column_done:
 ** 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){
+SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, const Token *pName){
   sqlite3 *db = pParse->db;       /* Database handle */
   Table *pTab;                    /* Table to modify */
   int iDb;                        /* Index of db containing pTab in aDb[] */
@@ -108652,7 +111004,7 @@ SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *
   }
   iCol = sqlite3ColumnIndex(pTab, zCol);
   if( iCol<0 ){
-    sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
+    sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pName);
     goto exit_drop_column;
   }
 
@@ -108676,9 +111028,16 @@ SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *
   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   assert( iDb>=0 );
   zDb = db->aDb[iDb].zDbSName;
+#ifndef SQLITE_OMIT_AUTHORIZATION
+  /* Invoke the authorization callback. */
+  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){
+    goto exit_drop_column;
+  }
+#endif
   renameTestSchema(pParse, zDb, iDb==1, "", 0);
+  renameFixQuotes(pParse, zDb, iDb==1);
   sqlite3NestedParse(pParse,
-      "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
+      "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
       "sql = sqlite_drop_column(%d, sql, %d) "
       "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
       , zDb, iDb, iCol, pTab->zName
@@ -108686,7 +111045,7 @@ SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *
 
   /* Drop and reload the database schema. */
   renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
-  renameTestSchema(pParse, zDb, iDb==1, "after drop column", zCol);
+  renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
 
   /* Edit rows of table on disk */
   if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
@@ -108702,33 +111061,50 @@ SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *
     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);
+      pParse->nMem += pTab->nCol;
     }else{
       pPk = sqlite3PrimaryKeyIndex(pTab);
+      pParse->nMem += pPk->nColumn;
+      for(i=0; i<pPk->nKeyCol; i++){
+        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
+      }
+      nField = pPk->nKeyCol;
     }
+    regRec = ++pParse->nMem;
     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);
+          if( iPos<pPk->nKeyCol ) continue;
           regOut = reg+1+iPos-(iPos>iColPos);
         }else{
           regOut = reg+1+nField;
         }
-        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
+        if( i==pTab->iPKey ){
+          sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
+        }else{
+          sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
+        }
         nField++;
       }
     }
-    regRec = reg + pTab->nCol;
+    if( nField==0 ){
+      /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
+      pParse->nMem++;
+      sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
+      nField = 1;
+    }
     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);
     }
+    sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
 
     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
     sqlite3VdbeJumpHere(v, addr);
@@ -108748,6 +111124,7 @@ SQLITE_PRIVATE void sqlite3AlterFunctions(void){
     INTERNAL_FUNCTION(sqlite_rename_table,   7, renameTableFunc),
     INTERNAL_FUNCTION(sqlite_rename_test,    7, renameTableTest),
     INTERNAL_FUNCTION(sqlite_drop_column,    3, dropColumnFunc),
+    INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
   };
   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
 }
@@ -109190,7 +111567,6 @@ static void statInit(
       + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
   }
 #endif
-  db = sqlite3_context_db_handle(context);
   p = sqlite3DbMallocZero(db, n);
   if( p==0 ){
     sqlite3_result_error_nomem(context);
@@ -109609,28 +111985,19 @@ static void statGet(
     **
     **        I = (K+D-1)/D
     */
-    char *z;
-    int i;
-
-    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
-    if( zRet==0 ){
-      sqlite3_result_error_nomem(context);
-      return;
-    }
+    sqlite3_str sStat;   /* Text of the constructed "stat" line */
+    int i;               /* Loop counter */
 
-    sqlite3_snprintf(24, zRet, "%llu",
+    sqlite3StrAccumInit(&sStat, 0, 0, 0, (p->nKeyCol+1)*100);
+    sqlite3_str_appendf(&sStat, "%llu",
         p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
-    z = zRet + sqlite3Strlen30(zRet);
     for(i=0; i<p->nKeyCol; i++){
       u64 nDistinct = p->current.anDLt[i] + 1;
       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
-      sqlite3_snprintf(24, z, " %llu", iVal);
-      z += sqlite3Strlen30(z);
+      sqlite3_str_appendf(&sStat, " %llu", iVal);
       assert( p->current.anEq[i] );
     }
-    assert( z[0]=='\0' && z>zRet );
-
-    sqlite3_result_text(context, zRet, -1, sqlite3_free);
+    sqlite3ResultStrAccum(context, &sStat);
   }
 #ifdef SQLITE_ENABLE_STAT4
   else if( eCall==STAT_GET_ROWID ){
@@ -109649,6 +112016,8 @@ static void statGet(
     }
   }else{
     tRowcnt *aCnt = 0;
+    sqlite3_str sStat;
+    int i;
 
     assert( p->iGet<p->nSample );
     switch( eCall ){
@@ -109660,23 +112029,12 @@ static void statGet(
         break;
       }
     }
-
-    {
-      char *zRet = sqlite3MallocZero(p->nCol * 25);
-      if( zRet==0 ){
-        sqlite3_result_error_nomem(context);
-      }else{
-        int i;
-        char *z = zRet;
-        for(i=0; i<p->nCol; i++){
-          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
-          z += sqlite3Strlen30(z);
-        }
-        assert( z[0]=='\0' && z>zRet );
-        z[-1] = '\0';
-        sqlite3_result_text(context, zRet, -1, sqlite3_free);
-      }
+    sqlite3StrAccumInit(&sStat, 0, 0, 0, p->nCol*100);
+    for(i=0; i<p->nCol; i++){
+      sqlite3_str_appendf(&sStat, "%llu ", (u64)aCnt[i]);
     }
+    if( sStat.nChar ) sStat.nChar--;
+    sqlite3ResultStrAccum(context, &sStat);
   }
 #endif /* SQLITE_ENABLE_STAT4 */
 #ifndef SQLITE_DEBUG
@@ -109725,7 +112083,7 @@ static void analyzeVdbeCommentIndexWithColumnName(
   }else if( i==XN_EXPR ){
     VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
   }else{
-    VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zName));
+    VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zCnName));
   }
 }
 #else
@@ -109772,7 +112130,7 @@ static void analyzeOneTable(
   if( v==0 || NEVER(pTab==0) ){
     return;
   }
-  if( pTab->tnum==0 ){
+  if( !IsOrdinaryTable(pTab) ){
     /* Do not gather statistics on views or virtual tables */
     return;
   }
@@ -110597,9 +112955,12 @@ static int loadStatTbl(
 */
 static int loadStat4(sqlite3 *db, const char *zDb){
   int rc = SQLITE_OK;             /* Result codes from subroutines */
+  const Table *pStat4;
 
   assert( db->lookaside.bDisable );
-  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
+  if( (pStat4 = sqlite3FindTable(db, "sqlite_stat4", zDb))!=0
+   && IsOrdinaryTable(pStat4)
+  ){
     rc = loadStatTbl(db,
       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
@@ -110636,6 +112997,7 @@ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   char *zSql;
   int rc = SQLITE_OK;
   Schema *pSchema = db->aDb[iDb].pSchema;
+  const Table *pStat1;
 
   assert( iDb>=0 && iDb<db->nDb );
   assert( db->aDb[iDb].pBt!=0 );
@@ -110658,7 +113020,9 @@ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   /* Load new statistics out of the sqlite_stat1 table */
   sInfo.db = db;
   sInfo.zDatabase = db->aDb[iDb].zDbSName;
-  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
+  if( (pStat1 = sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase))
+   && IsOrdinaryTable(pStat1)
+  ){
     zSql = sqlite3MPrintf(db,
         "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
     if( zSql==0 ){
@@ -110798,7 +113162,7 @@ static void attachFunc(
   if( zFile==0 ) zFile = "";
   if( zName==0 ) zName = "";
 
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
 # define REOPEN_AS_MEMDB(db)  (db->init.reopenMemdb)
 #else
 # define REOPEN_AS_MEMDB(db)  (0)
@@ -111049,17 +113413,18 @@ static void codeAttach(
   sName.pParse = pParse;
 
   if(
-      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
-      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
-      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
+      SQLITE_OK!=resolveAttachExpr(&sName, pFilename) ||
+      SQLITE_OK!=resolveAttachExpr(&sName, pDbname) ||
+      SQLITE_OK!=resolveAttachExpr(&sName, pKey)
   ){
     goto attach_end;
   }
 
 #ifndef SQLITE_OMIT_AUTHORIZATION
-  if( pAuthArg ){
+  if( ALWAYS(pAuthArg) ){
     char *zAuthArg;
     if( pAuthArg->op==TK_STRING ){
+      assert( !ExprHasProperty(pAuthArg, EP_IntValue) );
       zAuthArg = pAuthArg->u.zToken;
     }else{
       zAuthArg = 0;
@@ -111167,14 +113532,17 @@ static int fixSelectCb(Walker *p, Select *pSelect){
   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;
+      if( pItem->zDatabase ){
+        if( 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->fg.notCte = 1;
       }
-      sqlite3DbFree(db, pItem->zDatabase);
-      pItem->zDatabase = 0;
       pItem->pSchema = pFix->pSchema;
       pItem->fg.fromDDL = 1;
     }
@@ -111214,7 +113582,7 @@ SQLITE_PRIVATE void sqlite3FixInit(
   pFix->w.pParse = pParse;
   pFix->w.xExprCallback = fixExprCb;
   pFix->w.xSelectCallback = fixSelectCb;
-  pFix->w.xSelectCallback2 = 0;
+  pFix->w.xSelectCallback2 = sqlite3WalkWinDefnDummyCallback;
   pFix->w.walkerDepth = 0;
   pFix->w.eCode = 0;
   pFix->w.u.pFix = pFix;
@@ -111276,14 +113644,16 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep(
       return 1;
     }
 #ifndef SQLITE_OMIT_UPSERT
-    if( pStep->pUpsert ){
-      Upsert *pUp = pStep->pUpsert;
-      if( sqlite3WalkExprList(&pFix->w, pUp->pUpsertTarget)
-       || sqlite3WalkExpr(&pFix->w, pUp->pUpsertTargetWhere)
-       || sqlite3WalkExprList(&pFix->w, pUp->pUpsertSet)
-       || sqlite3WalkExpr(&pFix->w, pUp->pUpsertWhere)
-      ){
-        return 1;
+    {
+      Upsert *pUp;
+      for(pUp=pStep->pUpsert; pUp; pUp=pUp->pNextUpsert){
+        if( sqlite3WalkExprList(&pFix->w, pUp->pUpsertTarget)
+         || sqlite3WalkExpr(&pFix->w, pUp->pUpsertTargetWhere)
+         || sqlite3WalkExprList(&pFix->w, pUp->pUpsertSet)
+         || sqlite3WalkExpr(&pFix->w, pUp->pUpsertWhere)
+        ){
+          return 1;
+        }
       }
     }
 #endif
@@ -111473,10 +113843,10 @@ SQLITE_PRIVATE void sqlite3AuthRead(
 
   if( iCol>=0 ){
     assert( iCol<pTab->nCol );
-    zCol = pTab->aCol[iCol].zName;
+    zCol = pTab->aCol[iCol].zCnName;
   }else if( pTab->iPKey>=0 ){
     assert( pTab->iPKey<pTab->nCol );
-    zCol = pTab->aCol[pTab->iPKey].zName;
+    zCol = pTab->aCol[pTab->iPKey].zCnName;
   }else{
     zCol = "ROWID";
   }
@@ -111615,7 +113985,7 @@ struct TableLock {
 ** code to make the lock occur is generated by a later call to
 ** codeTableLocks() which occurs during sqlite3FinishCoding().
 */
-SQLITE_PRIVATE void sqlite3TableLock(
+static SQLITE_NOINLINE void lockTable(
   Parse *pParse,     /* Parsing context */
   int iDb,           /* Index of the database containing the table to lock */
   Pgno iTab,         /* Root page number of the table to be locked */
@@ -111628,8 +113998,6 @@ SQLITE_PRIVATE void sqlite3TableLock(
   TableLock *p;
   assert( iDb>=0 );
 
-  if( iDb==1 ) return;
-  if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
   pToplevel = sqlite3ParseToplevel(pParse);
   for(i=0; i<pToplevel->nTableLock; i++){
     p = &pToplevel->aTableLock[i];
@@ -111653,6 +114021,17 @@ SQLITE_PRIVATE void sqlite3TableLock(
     sqlite3OomFault(pToplevel->db);
   }
 }
+SQLITE_PRIVATE void sqlite3TableLock(
+  Parse *pParse,     /* Parsing context */
+  int iDb,           /* Index of the database containing the table to lock */
+  Pgno iTab,         /* Root page number of the table to be locked */
+  u8 isWriteLock,    /* True for a write lock */
+  const char *zName  /* Name of the table to be locked */
+){
+  if( iDb==1 ) return;
+  if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
+  lockTable(pParse, iDb, iTab, isWriteLock, zName);
+}
 
 /*
 ** Code an OP_TableLock instruction for each table locked by the
@@ -111703,11 +114082,13 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
 
   assert( pParse->pToplevel==0 );
   db = pParse->db;
+  assert( db->pParse==pParse );
   if( pParse->nested ) return;
-  if( db->mallocFailed || pParse->nErr ){
-    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
+  if( pParse->nErr ){
+    if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
     return;
   }
+  assert( db->mallocFailed==0 );
 
   /* Begin by generating some termination code at the end of the
   ** vdbe program
@@ -111730,17 +114111,22 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
       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);
+      if( NEVER(pReturning->nRetCol==0) ){
+        assert( CORRUPT_DB );
+      }else{
+        sqlite3VdbeAddOp0(v, OP_FkCheck);
+        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);
       }
-      sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
-      sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
-      VdbeCoverage(v);
-      sqlite3VdbeJumpHere(v, addrRewind);
     }
     sqlite3VdbeAddOp0(v, OP_Halt);
 
@@ -111821,7 +114207,11 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
 
       if( pParse->bReturning ){
         Returning *pRet = pParse->u1.pReturning;
-        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
+        if( NEVER(pRet->nRetCol==0) ){
+          assert( CORRUPT_DB );
+        }else{
+          sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
+        }
       }
 
       /* Finally, jump back to the beginning of the executable code. */
@@ -111831,7 +114221,9 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
 
   /* Get the VDBE program ready for execution
   */
-  if( v && pParse->nErr==0 && !db->mallocFailed ){
+  assert( v!=0 || pParse->nErr );
+  assert( db->mallocFailed==0 || pParse->nErr );
+  if( pParse->nErr==0 ){
     /* A minimum of one cursor is required if autoincrement is used
     *  See ticket [a696379c1f08866] */
     assert( pParse->pAinc==0 || pParse->nTab>0 );
@@ -111845,20 +114237,21 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
 /*
 ** Run the parser and code generator recursively in order to generate
 ** code for the SQL statement given onto the end of the pParse context
-** currently under construction.  When the parser is run recursively
-** this way, the final OP_Halt is not appended and other initialization
-** and finalization steps are omitted because those are handling by the
-** outermost parser.
+** currently under construction.  Notes:
+**
+**   *  The final OP_Halt is not appended and other initialization
+**      and finalization steps are omitted because those are handling by the
+**      outermost parser.
 **
-** Not everything is nestable.  This facility is designed to permit
-** INSERT, UPDATE, and DELETE operations against the schema table.  Use
-** care if you decide to try to use this routine for some other purposes.
+**   *  Built-in SQL functions always take precedence over application-defined
+**      SQL functions.  In other words, it is not possible to override a
+**      built-in function.
 */
 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   va_list ap;
   char *zSql;
-  char *zErrMsg = 0;
   sqlite3 *db = pParse->db;
+  u32 savedDbFlags = db->mDbFlags;
   char saveBuf[PARSE_TAIL_SZ];
 
   if( pParse->nErr ) return;
@@ -111877,8 +114270,11 @@ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   pParse->nested++;
   memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
   memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
-  sqlite3RunParser(pParse, zSql, &zErrMsg);
-  sqlite3DbFree(db, zErrMsg);
+  db->mDbFlags |= DBFLAG_PreferBuiltin;
+  sqlite3RunParser(pParse, zSql);
+  sqlite3DbFree(db, pParse->zErrMsg);
+  pParse->zErrMsg = 0;
+  db->mDbFlags = savedDbFlags;
   sqlite3DbFree(db, zSql);
   memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
   pParse->nested--;
@@ -111935,17 +114331,17 @@ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const cha
     p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
     if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
       if( i==1 ){
-        if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0
-         || sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0
-         || sqlite3StrICmp(zName+7, &DFLT_SCHEMA_TABLE[7])==0
+        if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
+         || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
+         || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
         ){
           p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
-                              DFLT_TEMP_SCHEMA_TABLE);
+                              LEGACY_TEMP_SCHEMA_TABLE);
         }
       }else{
-        if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){
+        if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
           p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
-                              DFLT_SCHEMA_TABLE);
+                              LEGACY_SCHEMA_TABLE);
         }
       }
     }
@@ -111963,11 +114359,11 @@ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const cha
       if( p ) break;
     }
     if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
-      if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){
-        p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, DFLT_SCHEMA_TABLE);
-      }else if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 ){
+      if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
+        p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
+      }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
         p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
-                            DFLT_TEMP_SCHEMA_TABLE);
+                            LEGACY_TEMP_SCHEMA_TABLE);
       }
     }
   }
@@ -112007,12 +114403,13 @@ SQLITE_PRIVATE Table *sqlite3LocateTable(
     /* If zName is the not the name of a table in the schema created using
     ** CREATE, then check to see if it is the name of an virtual table that
     ** can be an eponymous virtual table. */
-    if( pParse->disableVtab==0 ){
+    if( pParse->disableVtab==0 && db->init.busy==0 ){
       Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
       if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
         pMod = sqlite3PragmaVtabRegister(db, zName);
       }
       if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
+        testcase( pMod->pEpoTab==0 );
         return pMod->pEpoTab;
       }
     }
@@ -112030,6 +114427,8 @@ SQLITE_PRIVATE Table *sqlite3LocateTable(
     }else{
       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
     }
+  }else{
+    assert( HasRowid(p) || p->iPKey<0 );
   }
 
   return p;
@@ -112060,6 +114459,22 @@ SQLITE_PRIVATE Table *sqlite3LocateTableItem(
   return sqlite3LocateTable(pParse, flags, p->zName, zDb);
 }
 
+/*
+** Return the preferred table name for system tables.  Translate legacy
+** names into the new preferred names, as appropriate.
+*/
+SQLITE_PRIVATE const char *sqlite3PreferredTableName(const char *zName){
+  if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
+    if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
+      return PREFERRED_SCHEMA_TABLE;
+    }
+    if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
+      return PREFERRED_TEMP_SCHEMA_TABLE;
+    }
+  }
+  return zName;
+}
+
 /*
 ** Locate the in-memory structure that describes
 ** a particular index given the name of that index
@@ -112224,6 +114639,84 @@ SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   db->mDbFlags &= ~DBFLAG_SchemaChange;
 }
 
+/*
+** Set the expression associated with a column.  This is usually
+** the DEFAULT value, but might also be the expression that computes
+** the value for a generated column.
+*/
+SQLITE_PRIVATE void sqlite3ColumnSetExpr(
+  Parse *pParse,    /* Parsing context */
+  Table *pTab,      /* The table containing the column */
+  Column *pCol,     /* The column to receive the new DEFAULT expression */
+  Expr *pExpr       /* The new default expression */
+){
+  ExprList *pList;
+  assert( IsOrdinaryTable(pTab) );
+  pList = pTab->u.tab.pDfltList;
+  if( pCol->iDflt==0
+   || NEVER(pList==0)
+   || NEVER(pList->nExpr<pCol->iDflt)
+  ){
+    pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
+    pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
+  }else{
+    sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
+    pList->a[pCol->iDflt-1].pExpr = pExpr;
+  }
+}
+
+/*
+** Return the expression associated with a column.  The expression might be
+** the DEFAULT clause or the AS clause of a generated column.
+** Return NULL if the column has no associated expression.
+*/
+SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
+  if( pCol->iDflt==0 ) return 0;
+  if( NEVER(!IsOrdinaryTable(pTab)) ) return 0;
+  if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
+  if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
+  return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
+}
+
+/*
+** Set the collating sequence name for a column.
+*/
+SQLITE_PRIVATE void sqlite3ColumnSetColl(
+  sqlite3 *db,
+  Column *pCol,
+  const char *zColl
+){
+  i64 nColl;
+  i64 n;
+  char *zNew;
+  assert( zColl!=0 );
+  n = sqlite3Strlen30(pCol->zCnName) + 1;
+  if( pCol->colFlags & COLFLAG_HASTYPE ){
+    n += sqlite3Strlen30(pCol->zCnName+n) + 1;
+  }
+  nColl = sqlite3Strlen30(zColl) + 1;
+  zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
+  if( zNew ){
+    pCol->zCnName = zNew;
+    memcpy(pCol->zCnName + n, zColl, nColl);
+    pCol->colFlags |= COLFLAG_HASCOLL;
+  }
+}
+
+/*
+** Return the collating squence name for a column
+*/
+SQLITE_PRIVATE const char *sqlite3ColumnColl(Column *pCol){
+  const char *z;
+  if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
+  z = pCol->zCnName;
+  while( *z ){ z++; }
+  if( pCol->colFlags & COLFLAG_HASTYPE ){
+    do{ z++; }while( *z );
+  }
+  return z+1;
+}
+
 /*
 ** Delete memory allocated for the column names of a table or view (the
 ** Table.aCol[] array).
@@ -112234,12 +114727,20 @@ SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
   assert( pTable!=0 );
   if( (pCol = pTable->aCol)!=0 ){
     for(i=0; i<pTable->nCol; i++, pCol++){
-      assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) );
-      sqlite3DbFree(db, pCol->zName);
-      sqlite3ExprDelete(db, pCol->pDflt);
-      sqlite3DbFree(db, pCol->zColl);
+      assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
+      sqlite3DbFree(db, pCol->zCnName);
     }
     sqlite3DbFree(db, pTable->aCol);
+    if( IsOrdinaryTable(pTable) ){
+      sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
+    }
+    if( db==0 || db->pnBytesFreed==0 ){
+      pTable->aCol = 0;
+      pTable->nCol = 0;
+      if( IsOrdinaryTable(pTable) ){
+        pTable->u.tab.pDfltList = 0;
+      }
+    }
   }
 }
 
@@ -112291,19 +114792,25 @@ static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
     sqlite3FreeIndex(db, pIndex);
   }
 
-  /* Delete any foreign keys attached to this table. */
-  sqlite3FkDelete(db, pTable);
+  if( IsOrdinaryTable(pTable) ){
+    sqlite3FkDelete(db, pTable);
+  }
+#ifndef SQLITE_OMIT_VIRTUAL_TABLE
+  else if( IsVirtual(pTable) ){
+    sqlite3VtabClear(db, pTable);
+  }
+#endif
+  else{
+    assert( IsView(pTable) );
+    sqlite3SelectDelete(db, pTable->u.view.pSelect);
+  }
 
   /* Delete the Table structure itself.
   */
   sqlite3DeleteColumnNames(db, pTable);
   sqlite3DbFree(db, pTable->zName);
   sqlite3DbFree(db, pTable->zColAff);
-  sqlite3SelectDelete(db, pTable->pSelect);
   sqlite3ExprListDelete(db, pTable->pCheck);
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-  sqlite3VtabClear(db, pTable);
-#endif
   sqlite3DbFree(db, pTable);
 
   /* Verify that no lookaside memory was used by schema tables */
@@ -112349,10 +114856,10 @@ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char
 ** are not \000 terminated and are not persistent.  The returned string
 ** is \000 terminated and is persistent.
 */
-SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
+SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
   char *zName;
   if( pName ){
-    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
+    zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
     sqlite3Dequote(zName);
   }else{
     zName = 0;
@@ -112366,7 +114873,7 @@ SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
 */
 SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *p, int iDb){
   Vdbe *v = sqlite3GetVdbe(p);
-  sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, DFLT_SCHEMA_TABLE);
+  sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
   if( p->nTab==0 ){
     p->nTab = 1;
@@ -112446,7 +114953,7 @@ SQLITE_PRIVATE int sqlite3TwoPartName(
       return -1;
     }
   }else{
-    assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
+    assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
              || (db->mDbFlags & DBFLAG_Vacuum)!=0);
     iDb = db->init.iDb;
     *pUnqual = pName1;
@@ -112615,6 +115122,23 @@ SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
 }
 #endif
 
+/*
+** Insert a single OP_JournalMode query opcode in order to force the
+** prepared statement to return false for sqlite3_stmt_readonly().  This
+** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
+** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
+** will return false for sqlite3_stmt_readonly() even if that statement
+** is a read-only no-op.
+*/
+static void sqlite3ForceNotReadOnly(Parse *pParse){
+  int iReg = ++pParse->nMem;
+  Vdbe *v = sqlite3GetVdbe(pParse);
+  if( v ){
+    sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
+    sqlite3VdbeUsesBtree(v, 0);
+  }
+}
+
 /*
 ** Begin constructing a new table representation in memory.  This is
 ** the first of several action routines that get called in response
@@ -112710,10 +115234,12 @@ SQLITE_PRIVATE void sqlite3StartTable(
     pTable = sqlite3FindTable(db, zName, zDb);
     if( pTable ){
       if( !noErr ){
-        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
+        sqlite3ErrorMsg(pParse, "%s %T already exists",
+                        (IsView(pTable)? "view" : "table"), pName);
       }else{
         assert( !db->init.busy || CORRUPT_DB );
         sqlite3CodeVerifySchema(pParse, iDb);
+        sqlite3ForceNotReadOnly(pParse);
       }
       goto begin_table_error;
     }
@@ -112742,17 +115268,6 @@ SQLITE_PRIVATE void sqlite3StartTable(
   assert( pParse->pNewTable==0 );
   pParse->pNewTable = pTable;
 
-  /* If this is the magic sqlite_sequence table used by autoincrement,
-  ** then record a pointer to this table in the main database structure
-  ** so that INSERT can find the table easily.
-  */
-#ifndef SQLITE_OMIT_AUTOINCREMENT
-  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
-    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
-    pTable->pSchema->pSeqTab = pTable;
-  }
-#endif
-
   /* Begin generating the code that will insert the table record into
   ** the schema table.  Note in particular that we must go ahead
   ** and allocate the record number for the table entry now.  Before any
@@ -112822,6 +115337,7 @@ SQLITE_PRIVATE void sqlite3StartTable(
 
   /* If an error occurs, we jump here */
 begin_table_error:
+  pParse->checkSchema = 1;
   sqlite3DbFree(db, zName);
   return;
 }
@@ -112831,7 +115347,7 @@ begin_table_error:
 */
 #if SQLITE_ENABLE_HIDDEN_COLUMNS
 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
-  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
+  if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
     pCol->colFlags |= COLFLAG_HIDDEN;
     if( pTab ) pTab->tabFlags |= TF_HasHidden;
   }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
@@ -112901,6 +115417,7 @@ SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){
   pRet->retTrig.tr_tm = TRIGGER_AFTER;
   pRet->retTrig.bReturning = 1;
   pRet->retTrig.pSchema = db->aDb[1].pSchema;
+  pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
   pRet->retTrig.step_list = &pRet->retTStep;
   pRet->retTStep.op = TK_RETURNING;
   pRet->retTStep.pTrig = &pRet->retTrig;
@@ -112921,7 +115438,7 @@ SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){
 ** first to get things going.  Then this routine is called for each
 ** column.
 */
-SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
+SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
   Table *p;
   int i;
   char *z;
@@ -112929,55 +115446,96 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
   Column *pCol;
   sqlite3 *db = pParse->db;
   u8 hName;
+  Column *aNew;
+  u8 eType = COLTYPE_CUSTOM;
+  u8 szEst = 1;
+  char affinity = SQLITE_AFF_BLOB;
 
   if( (p = pParse->pNewTable)==0 ) return;
   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
     return;
   }
-  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
+  if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
+
+  /* Because keywords GENERATE ALWAYS can be converted into indentifiers
+  ** by the parser, we can sometimes end up with a typename that ends
+  ** with "generated always".  Check for this case and omit the surplus
+  ** text. */
+  if( sType.n>=16
+   && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
+  ){
+    sType.n -= 6;
+    while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
+    if( sType.n>=9
+     && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
+    ){
+      sType.n -= 9;
+      while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
+    }
+  }
+
+  /* Check for standard typenames.  For standard typenames we will
+  ** set the Column.eType field rather than storing the typename after
+  ** the column name, in order to save space. */
+  if( sType.n>=3 ){
+    sqlite3DequoteToken(&sType);
+    for(i=0; i<SQLITE_N_STDTYPE; i++){
+       if( sType.n==sqlite3StdTypeLen[i]
+        && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
+       ){
+         sType.n = 0;
+         eType = i+1;
+         affinity = sqlite3StdTypeAffinity[i];
+         if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
+         break;
+       }
+    }
+  }
+
+  z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
   if( z==0 ) return;
-  if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
-  memcpy(z, pName->z, pName->n);
-  z[pName->n] = 0;
+  if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
+  memcpy(z, sName.z, sName.n);
+  z[sName.n] = 0;
   sqlite3Dequote(z);
   hName = sqlite3StrIHash(z);
   for(i=0; i<p->nCol; i++){
-    if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zName)==0 ){
+    if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
       sqlite3DbFree(db, z);
       return;
     }
   }
-  if( (p->nCol & 0x7)==0 ){
-    Column *aNew;
-    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
-    if( aNew==0 ){
-      sqlite3DbFree(db, z);
-      return;
-    }
-    p->aCol = aNew;
+  aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
+  if( aNew==0 ){
+    sqlite3DbFree(db, z);
+    return;
   }
+  p->aCol = aNew;
   pCol = &p->aCol[p->nCol];
   memset(pCol, 0, sizeof(p->aCol[0]));
-  pCol->zName = z;
+  pCol->zCnName = z;
   pCol->hName = hName;
   sqlite3ColumnPropertiesFromName(p, pCol);
 
-  if( pType->n==0 ){
+  if( sType.n==0 ){
     /* If there is no type specified, columns have the default affinity
     ** 'BLOB' with a default size of 4 bytes. */
-    pCol->affinity = SQLITE_AFF_BLOB;
-    pCol->szEst = 1;
+    pCol->affinity = affinity;
+    pCol->eCType = eType;
+    pCol->szEst = szEst;
 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
-    if( 4>=sqlite3GlobalConfig.szSorterRef ){
-      pCol->colFlags |= COLFLAG_SORTERREF;
+    if( affinity==SQLITE_AFF_BLOB ){
+      if( 4>=sqlite3GlobalConfig.szSorterRef ){
+        pCol->colFlags |= COLFLAG_SORTERREF;
+      }
     }
 #endif
   }else{
     zType = z + sqlite3Strlen30(z) + 1;
-    memcpy(zType, pType->z, pType->n);
-    zType[pType->n] = 0;
+    memcpy(zType, sType.z, sType.n);
+    zType[sType.n] = 0;
     sqlite3Dequote(zType);
     pCol->affinity = sqlite3AffinityType(zType, pCol);
     pCol->colFlags |= COLFLAG_HASTYPE;
@@ -113132,7 +115690,7 @@ SQLITE_PRIVATE void sqlite3AddDefaultValue(
     pCol = &(p->aCol[p->nCol-1]);
     if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
-          pCol->zName);
+          pCol->zCnName);
 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
     }else if( pCol->colFlags & COLFLAG_GENERATED ){
       testcase( pCol->colFlags & COLFLAG_VIRTUAL );
@@ -113143,15 +115701,15 @@ SQLITE_PRIVATE void sqlite3AddDefaultValue(
       /* A copy of pExpr is used instead of the original, as pExpr contains
       ** tokens that point to volatile memory.
       */
-      Expr x;
-      sqlite3ExprDelete(db, pCol->pDflt);
+      Expr x, *pDfltExpr;
       memset(&x, 0, sizeof(x));
       x.op = TK_SPAN;
       x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
       x.pLeft = pExpr;
       x.flags = EP_Skip;
-      pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
+      pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
       sqlite3DbFree(db, x.u.zToken);
+      sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
     }
   }
   if( IN_RENAME_OBJECT ){
@@ -113247,9 +115805,11 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey(
       assert( pCExpr!=0 );
       sqlite3StringToId(pCExpr);
       if( pCExpr->op==TK_ID ){
-        const char *zCName = pCExpr->u.zToken;
+        const char *zCName;
+        assert( !ExprHasProperty(pCExpr, EP_IntValue) );
+        zCName = pCExpr->u.zToken;
         for(iCol=0; iCol<pTab->nCol; iCol++){
-          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
+          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
             pCol = &pTab->aCol[iCol];
             makeColumnPartOfPrimaryKey(pParse, pCol);
             break;
@@ -113260,7 +115820,7 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   }
   if( nTerm==1
    && pCol
-   && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
+   && pCol->eCType==COLTYPE_INTEGER
    && sortOrder!=SQLITE_SO_DESC
   ){
     if( IN_RENAME_OBJECT && pList ){
@@ -113340,8 +115900,7 @@ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
 
   if( sqlite3LocateCollSeq(pParse, zColl) ){
     Index *pIdx;
-    sqlite3DbFree(db, p->aCol[i].zColl);
-    p->aCol[i].zColl = zColl;
+    sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
 
     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
     ** then an index may have been created on this column before the
@@ -113350,12 +115909,11 @@ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
       assert( pIdx->nKeyCol==1 );
       if( pIdx->aiColumn[0]==i ){
-        pIdx->azColl[0] = p->aCol[i].zColl;
+        pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
       }
     }
-  }else{
-    sqlite3DbFree(db, zColl);
   }
+  sqlite3DbFree(db, zColl);
 }
 
 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
@@ -113375,7 +115933,7 @@ SQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType
     sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
     goto generated_done;
   }
-  if( pCol->pDflt ) goto generated_error;
+  if( pCol->iDflt>0 ) goto generated_error;
   if( pType ){
     if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
       /* no-op */
@@ -113393,13 +115951,13 @@ SQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType
   if( pCol->colFlags & COLFLAG_PRIMKEY ){
     makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
   }
-  pCol->pDflt = pExpr;
+  sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
   pExpr = 0;
   goto generated_done;
 
 generated_error:
   sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
-                  pCol->zName);
+                  pCol->zCnName);
 generated_done:
   sqlite3ExprDelete(pParse->db, pExpr);
 #else
@@ -113501,7 +116059,7 @@ static char *createTableStmt(sqlite3 *db, Table *p){
   Column *pCol;
   n = 0;
   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
-    n += identLength(pCol->zName) + 5;
+    n += identLength(pCol->zCnName) + 5;
   }
   n += identLength(p->zName);
   if( n<50 ){
@@ -113537,7 +116095,7 @@ static char *createTableStmt(sqlite3 *db, Table *p){
     sqlite3_snprintf(n-k, &zStmt[k], zSep);
     k += sqlite3Strlen30(&zStmt[k]);
     zSep = zSep2;
-    identPut(zStmt, &k, pCol->zName);
+    identPut(zStmt, &k, pCol->zCnName);
     assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
     assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
     testcase( pCol->affinity==SQLITE_AFF_BLOB );
@@ -113621,7 +116179,6 @@ static void estimateIndexWidth(Index *pIdx){
 */
 static int hasColumn(const i16 *aiCol, int nCol, int x){
   while( nCol-- > 0 ){
-    assert( aiCol[0]>=0 );
     if( x==*(aiCol++) ){
       return 1;
     }
@@ -113734,7 +116291,9 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   */
   if( !db->init.imposterTable ){
     for(i=0; i<pTab->nCol; i++){
-      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
+      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
+       && (pTab->aCol[i].notNull==OE_None)
+      ){
         pTab->aCol[i].notNull = OE_Abort;
       }
     }
@@ -113756,10 +116315,13 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   if( pTab->iPKey>=0 ){
     ExprList *pList;
     Token ipkToken;
-    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
+    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
     pList = sqlite3ExprListAppend(pParse, 0,
                   sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
-    if( pList==0 ) return;
+    if( pList==0 ){
+      pTab->tabFlags &= ~TF_WithoutRowid;
+      return;
+    }
     if( IN_RENAME_OBJECT ){
       sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
     }
@@ -113768,7 +116330,11 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
     pTab->iPKey = -1;
     sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
                        SQLITE_IDXTYPE_PRIMARYKEY);
-    if( db->mallocFailed || pParse->nErr ) return;
+    if( pParse->nErr ){
+      pTab->tabFlags &= ~TF_WithoutRowid;
+      return;
+    }
+    assert( db->mallocFailed==0 );
     pPk = sqlite3PrimaryKeyIndex(pTab);
     assert( pPk->nKeyCol==1 );
   }else{
@@ -113880,7 +116446,7 @@ SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *
   nName = sqlite3Strlen30(pTab->zName);
   if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
   if( zName[nName]!='_' ) return 0;
-  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
+  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
   if( pMod==0 ) return 0;
   if( pMod->pModule->iVersion<3 ) return 0;
   if( pMod->pModule->xShadowName==0 ) return 0;
@@ -113888,6 +116454,41 @@ SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *
 }
 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
 
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Table pTab is a virtual table.  If it the virtual table implementation
+** exists and has an xShadowName method, then loop over all other ordinary
+** tables within the same schema looking for shadow tables of pTab, and mark
+** any shadow tables seen using the TF_Shadow flag.
+*/
+SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
+  int nName;                    /* Length of pTab->zName */
+  Module *pMod;                 /* Module for the virtual table */
+  HashElem *k;                  /* For looping through the symbol table */
+
+  assert( IsVirtual(pTab) );
+  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
+  if( pMod==0 ) return;
+  if( NEVER(pMod->pModule==0) ) return;
+  if( pMod->pModule->iVersion<3 ) return;
+  if( pMod->pModule->xShadowName==0 ) return;
+  assert( pTab->zName!=0 );
+  nName = sqlite3Strlen30(pTab->zName);
+  for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
+    Table *pOther = sqliteHashData(k);
+    assert( pOther->zName!=0 );
+    if( !IsOrdinaryTable(pOther) ) continue;
+    if( pOther->tabFlags & TF_Shadow ) continue;
+    if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
+     && pOther->zName[nName]=='_'
+     && pMod->pModule->xShadowName(pOther->zName+nName+1)
+    ){
+      pOther->tabFlags |= TF_Shadow;
+    }
+  }
+}
+#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
+
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 /*
 ** Return true if zName is a shadow table name in the current database
@@ -113961,7 +116562,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
   Parse *pParse,          /* Parse context */
   Token *pCons,           /* The ',' token after the last column defn. */
   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
-  u8 tabOpts,             /* Extra table options. Usually 0. */
+  u32 tabOpts,            /* Extra table options. Usually 0. */
   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
 ){
   Table *p;                 /* The new table */
@@ -113972,7 +116573,6 @@ SQLITE_PRIVATE void sqlite3EndTable(
   if( pEnd==0 && pSelect==0 ){
     return;
   }
-  assert( !db->mallocFailed );
   p = pParse->pNewTable;
   if( p==0 ) return;
 
@@ -113990,7 +116590,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
   ** table itself.  So mark it read-only.
   */
   if( db->init.busy ){
-    if( pSelect ){
+    if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
       sqlite3ErrorMsg(pParse, "");
       return;
     }
@@ -113998,6 +116598,44 @@ SQLITE_PRIVATE void sqlite3EndTable(
     if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
   }
 
+  /* Special processing for tables that include the STRICT keyword:
+  **
+  **   *  Do not allow custom column datatypes.  Every column must have
+  **      a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
+  **
+  **   *  If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
+  **      then all columns of the PRIMARY KEY must have a NOT NULL
+  **      constraint.
+  */
+  if( tabOpts & TF_Strict ){
+    int ii;
+    p->tabFlags |= TF_Strict;
+    for(ii=0; ii<p->nCol; ii++){
+      Column *pCol = &p->aCol[ii];
+      if( pCol->eCType==COLTYPE_CUSTOM ){
+        if( pCol->colFlags & COLFLAG_HASTYPE ){
+          sqlite3ErrorMsg(pParse,
+            "unknown datatype for %s.%s: \"%s\"",
+            p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
+          );
+        }else{
+          sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
+                          p->zName, pCol->zCnName);
+        }
+        return;
+      }else if( pCol->eCType==COLTYPE_ANY ){
+        pCol->affinity = SQLITE_AFF_BLOB;
+      }
+      if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
+       && p->iPKey!=ii
+       && pCol->notNull == OE_None
+      ){
+        pCol->notNull = OE_Abort;
+        p->tabFlags |= TF_HasNotNull;
+      }
+    }
+  }
+
   assert( (p->tabFlags & TF_HasPrimaryKey)==0
        || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
   assert( (p->tabFlags & TF_HasPrimaryKey)!=0
@@ -114042,7 +116680,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
     for(ii=0; ii<p->nCol; ii++){
       u32 colFlags = p->aCol[ii].colFlags;
       if( (colFlags & COLFLAG_GENERATED)!=0 ){
-        Expr *pX = p->aCol[ii].pDflt;
+        Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
         testcase( colFlags & COLFLAG_VIRTUAL );
         testcase( colFlags & COLFLAG_STORED );
         if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
@@ -114052,8 +116690,8 @@ SQLITE_PRIVATE void sqlite3EndTable(
           ** tree that have been allocated from lookaside memory, which is
           ** illegal in a schema and will lead to errors or heap corruption
           ** when the database connection closes. */
-          sqlite3ExprDelete(db, pX);
-          p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
+          sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
+               sqlite3ExprAlloc(db, TK_NULL, 0, 0));
         }
       }else{
         nNG++;
@@ -114093,7 +116731,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
     /*
     ** Initialize zType for the new view or table.
     */
-    if( p->pSelect==0 ){
+    if( IsOrdinaryTable(p) ){
       /* A regular table */
       zType = "table";
       zType2 = "TABLE";
@@ -114127,6 +116765,11 @@ SQLITE_PRIVATE void sqlite3EndTable(
       int addrInsLoop;    /* Top of the loop for inserting rows */
       Table *pSelTab;     /* A table that describes the SELECT results */
 
+      if( IN_SPECIAL_PARSE ){
+        pParse->rc = SQLITE_ERROR;
+        pParse->nErr++;
+        return;
+      }
       regYield = ++pParse->nMem;
       regRec = ++pParse->nMem;
       regRowid = ++pParse->nMem;
@@ -114179,7 +116822,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
     ** the information we've collected.
     */
     sqlite3NestedParse(pParse,
-      "UPDATE %Q." DFLT_SCHEMA_TABLE
+      "UPDATE %Q." LEGACY_SCHEMA_TABLE
       " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
       " WHERE rowid=#%d",
       db->aDb[iDb].zDbSName,
@@ -114197,7 +116840,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
     /* Check to see if we need to create an sqlite_sequence table for
     ** keeping track of autoincrement keys.
     */
-    if( (p->tabFlags & TF_Autoincrement)!=0 ){
+    if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
       Db *pDb = &db->aDb[iDb];
       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
       if( pDb->pSchema->pSeqTab==0 ){
@@ -114220,6 +116863,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
     Table *pOld;
     Schema *pSchema = p->pSchema;
     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+    assert( HasRowid(p) || p->iPKey<0 );
     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
     if( pOld ){
       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
@@ -114228,15 +116872,26 @@ SQLITE_PRIVATE void sqlite3EndTable(
     }
     pParse->pNewTable = 0;
     db->mDbFlags |= DBFLAG_SchemaChange;
+
+    /* If this is the magic sqlite_sequence table used by autoincrement,
+    ** then record a pointer to this table in the main database structure
+    ** so that INSERT can find the table easily.  */
+    assert( !pParse->nested );
+#ifndef SQLITE_OMIT_AUTOINCREMENT
+    if( strcmp(p->zName, "sqlite_sequence")==0 ){
+      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
+      p->pSchema->pSeqTab = p;
+    }
+#endif
   }
 
 #ifndef SQLITE_OMIT_ALTERTABLE
-  if( !pSelect && !p->pSelect ){
+  if( !pSelect && IsOrdinaryTable(p) ){
     assert( pCons && pEnd );
     if( pCons->z==0 ){
       pCons = pEnd;
     }
-    p->addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
+    p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
   }
 #endif
 }
@@ -114271,6 +116926,16 @@ SQLITE_PRIVATE void sqlite3CreateView(
   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   p = pParse->pNewTable;
   if( p==0 || pParse->nErr ) goto create_view_fail;
+
+  /* Legacy versions of SQLite allowed the use of the magic "rowid" column
+  ** on a view, even though views do not have rowids.  The following flag
+  ** setting fixes this problem.  But the fix can be disabled by compiling
+  ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
+  ** depend upon the old buggy behavior. */
+#ifndef SQLITE_ALLOW_ROWID_IN_VIEW
+  p->tabFlags |= TF_NoVisibleRowid;
+#endif
+
   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
@@ -114283,12 +116948,13 @@ SQLITE_PRIVATE void sqlite3CreateView(
   */
   pSelect->selFlags |= SF_View;
   if( IN_RENAME_OBJECT ){
-    p->pSelect = pSelect;
+    p->u.view.pSelect = pSelect;
     pSelect = 0;
   }else{
-    p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
+    p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   }
   p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
+  p->eTabType = TABTYP_VIEW;
   if( db->mallocFailed ) goto create_view_fail;
 
   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
@@ -114342,13 +117008,12 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   assert( pTable );
 
 #ifndef SQLITE_OMIT_VIRTUALTABLE
-  db->nSchemaLock++;
-  rc = sqlite3VtabCallConnect(pParse, pTable);
-  db->nSchemaLock--;
-  if( rc ){
-    return 1;
+  if( IsVirtual(pTable) ){
+    db->nSchemaLock++;
+    rc = sqlite3VtabCallConnect(pParse, pTable);
+    db->nSchemaLock--;
+    return rc;
   }
-  if( IsVirtual(pTable) ) return 0;
 #endif
 
 #ifndef SQLITE_OMIT_VIEW
@@ -114385,8 +117050,8 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   ** to be permanent.  So the computation is done on a copy of the SELECT
   ** statement that defines the view.
   */
-  assert( pTable->pSelect );
-  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
+  assert( IsView(pTable) );
+  pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
   if( pSel ){
     u8 eParseMode = pParse->eParseMode;
     pParse->eParseMode = PARSE_MODE_NORMAL;
@@ -114415,10 +117080,10 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
       */
       sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
                                  &pTable->nCol, &pTable->aCol);
-      if( db->mallocFailed==0
-       && pParse->nErr==0
+      if( pParse->nErr==0
        && pTable->nCol==pSel->pEList->nExpr
       ){
+        assert( db->mallocFailed==0 );
         sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
                                                SQLITE_AFF_NONE);
       }
@@ -114445,8 +117110,6 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   pTable->pSchema->schemaFlags |= DB_UnresetViews;
   if( db->mallocFailed ){
     sqlite3DeleteColumnNames(db, pTable);
-    pTable->aCol = 0;
-    pTable->nCol = 0;
   }
 #endif /* SQLITE_OMIT_VIEW */
   return nErr;
@@ -114463,10 +117126,8 @@ static void sqliteViewResetAll(sqlite3 *db, int idx){
   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
     Table *pTab = sqliteHashData(i);
-    if( pTab->pSelect ){
+    if( IsView(pTab) ){
       sqlite3DeleteColumnNames(db, pTab);
-      pTab->aCol = 0;
-      pTab->nCol = 0;
     }
   }
   DbClearProperty(db, idx, DB_UnresetViews);
@@ -114540,7 +117201,7 @@ static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   ** token for additional information.
   */
   sqlite3NestedParse(pParse,
-     "UPDATE %Q." DFLT_SCHEMA_TABLE
+     "UPDATE %Q." LEGACY_SCHEMA_TABLE
      " SET rootpage=%d WHERE #%d AND rootpage=#%d",
      pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
 #endif
@@ -114675,7 +117336,7 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in
   ** database.
   */
   sqlite3NestedParse(pParse,
-      "DELETE FROM %Q." DFLT_SCHEMA_TABLE
+      "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
       " WHERE tbl_name=%Q and type!='trigger'",
       pDb->zDbSName, pTab->zName);
   if( !isView && !IsVirtual(pTab) ){
@@ -114703,6 +117364,7 @@ SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db){
   if( (db->flags & SQLITE_Defensive)!=0
    && db->pVtabCtx==0
    && db->nVdbeExec==0
+   && !sqlite3VtabInSync(db)
   ){
     return 1;
   }
@@ -114722,6 +117384,9 @@ static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
   if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
     return 1;
   }
+  if( pTab->tabFlags & TF_Eponymous ){
+    return 1;
+  }
   return 0;
 }
 
@@ -114747,7 +117412,10 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView,
   if( noErr ) db->suppressErr--;
 
   if( pTab==0 ){
-    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
+    if( noErr ){
+      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
+      sqlite3ForceNotReadOnly(pParse);
+    }
     goto exit_drop_table;
   }
   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
@@ -114803,11 +117471,11 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView,
   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   ** on a table.
   */
-  if( isView && pTab->pSelect==0 ){
+  if( isView && !IsView(pTab) ){
     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
     goto exit_drop_table;
   }
-  if( !isView && pTab->pSelect ){
+  if( !isView && IsView(pTab) ){
     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
     goto exit_drop_table;
   }
@@ -114858,7 +117526,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
   FKey *pFKey = 0;
   FKey *pNextTo;
   Table *p = pParse->pNewTable;
-  int nByte;
+  i64 nByte;
   int i;
   int nCol;
   char *z;
@@ -114871,7 +117539,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
     if( pToCol && pToCol->nExpr!=1 ){
       sqlite3ErrorMsg(pParse, "foreign key on %s"
          " should reference only one column of table %T",
-         p->aCol[iCol].zName, pTo);
+         p->aCol[iCol].zCnName, pTo);
       goto fk_end;
     }
     nCol = 1;
@@ -114894,7 +117562,8 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
     goto fk_end;
   }
   pFKey->pFrom = p;
-  pFKey->pNextFrom = p->pFKey;
+  assert( IsOrdinaryTable(p) );
+  pFKey->pNextFrom = p->u.tab.pFKey;
   z = (char*)&pFKey->aCol[nCol];
   pFKey->zTo = z;
   if( IN_RENAME_OBJECT ){
@@ -114911,7 +117580,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
     for(i=0; i<nCol; i++){
       int j;
       for(j=0; j<p->nCol; j++){
-        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){
+        if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
           pFKey->aCol[i].iFrom = j;
           break;
         }
@@ -114959,7 +117628,8 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
 
   /* Link the foreign key to the table as the last step.
   */
-  p->pFKey = pFKey;
+  assert( IsOrdinaryTable(p) );
+  p->u.tab.pFKey = pFKey;
   pFKey = 0;
 
 fk_end:
@@ -114980,7 +117650,9 @@ SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
 #ifndef SQLITE_OMIT_FOREIGN_KEY
   Table *pTab;
   FKey *pFKey;
-  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
+  if( (pTab = pParse->pNewTable)==0 ) return;
+  if( NEVER(!IsOrdinaryTable(pTab)) ) return;
+  if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   pFKey->isDeferred = (u8)isDeferred;
 #endif
@@ -115030,7 +117702,7 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
     tnum = pIndex->tnum;
   }
   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
-  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
+  assert( pKey!=0 || pParse->nErr );
 
   /* Open the sorter cursor if we are to use one. */
   iSorter = pParse->nTab++;
@@ -115194,9 +117866,11 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
   char *zExtra = 0;                /* Extra space after the Index object */
   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
 
-  if( db->mallocFailed || pParse->nErr>0 ){
+  assert( db->pParse==pParse );
+  if( pParse->nErr ){
     goto exit_create_index;
   }
+  assert( db->mallocFailed==0 );
   if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
     goto exit_create_index;
   }
@@ -115260,7 +117934,6 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
   pDb = &db->aDb[iDb];
 
   assert( pTab!=0 );
-  assert( pParse->nErr==0 );
   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
        && db->init.busy==0
        && pTblName!=0
@@ -115272,7 +117945,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
     goto exit_create_index;
   }
 #ifndef SQLITE_OMIT_VIEW
-  if( pTab->pSelect ){
+  if( IsView(pTab) ){
     sqlite3ErrorMsg(pParse, "views may not be indexed");
     goto exit_create_index;
   }
@@ -115317,6 +117990,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
         }else{
           assert( !db->init.busy );
           sqlite3CodeVerifySchema(pParse, iDb);
+          sqlite3ForceNotReadOnly(pParse);
         }
         goto exit_create_index;
       }
@@ -115362,7 +118036,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
     Token prevCol;
     Column *pCol = &pTab->aCol[pTab->nCol-1];
     pCol->colFlags |= COLFLAG_UNIQUE;
-    sqlite3TokenInit(&prevCol, pCol->zName);
+    sqlite3TokenInit(&prevCol, pCol->zCnName);
     pList = sqlite3ExprListAppend(pParse, 0,
               sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
     if( pList==0 ) goto exit_create_index;
@@ -115380,6 +118054,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
     Expr *pExpr = pList->a[i].pExpr;
     assert( pExpr!=0 );
     if( pExpr->op==TK_COLLATE ){
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
     }
   }
@@ -115475,6 +118150,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
     zColl = 0;
     if( pListItem->pExpr->op==TK_COLLATE ){
       int nColl;
+      assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
       zColl = pListItem->pExpr->u.zToken;
       nColl = sqlite3Strlen30(zColl) + 1;
       assert( nExtra>=nColl );
@@ -115483,7 +118159,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
       zExtra += nColl;
       nExtra -= nColl;
     }else if( j>=0 ){
-      zColl = pTab->aCol[j].zColl;
+      zColl = sqlite3ColumnColl(&pTab->aCol[j]);
     }
     if( !zColl ) zColl = sqlite3StrBINARY;
     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
@@ -115681,13 +118357,13 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
       /* Add an entry in sqlite_schema for this index
       */
       sqlite3NestedParse(pParse,
-          "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
-          db->aDb[iDb].zDbSName,
-          pIndex->zName,
-          pTab->zName,
-          iMem,
-          zStmt
-          );
+         "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
+         db->aDb[iDb].zDbSName,
+         pIndex->zName,
+         pTab->zName,
+         iMem,
+         zStmt
+      );
       sqlite3DbFree(db, zStmt);
 
       /* Fill the index with data and reparse the schema. Code an OP_Expire
@@ -115723,7 +118399,7 @@ exit_create_index:
     ** 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 **ppFrom;
     Index *pThis;
     for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
       Index *pNext;
@@ -115797,7 +118473,7 @@ SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   if( x<99 ){
     pIdx->pTable->nRowLogEst = x = 99;
   }
-  if( pIdx->pPartIdxWhere!=0 ) x -= 10;  assert( 10==sqlite3LogEst(2) );
+  if( pIdx->pPartIdxWhere!=0 ){ x -= 10;  assert( 10==sqlite3LogEst(2) ); }
   a[0] = x;
 
   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
@@ -115821,10 +118497,10 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists
   sqlite3 *db = pParse->db;
   int iDb;
 
-  assert( pParse->nErr==0 );   /* Never called with prior errors */
   if( db->mallocFailed ){
     goto exit_drop_index;
   }
+  assert( pParse->nErr==0 );   /* Never called with prior non-OOM errors */
   assert( pName->nSrc==1 );
   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
     goto exit_drop_index;
@@ -115832,9 +118508,10 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists
   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   if( pIndex==0 ){
     if( !ifExists ){
-      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
+      sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
     }else{
       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
+      sqlite3ForceNotReadOnly(pParse);
     }
     pParse->checkSchema = 1;
     goto exit_drop_index;
@@ -115854,7 +118531,7 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists
     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
       goto exit_drop_index;
     }
-    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
+    if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
       goto exit_drop_index;
     }
@@ -115866,7 +118543,7 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists
   if( v ){
     sqlite3BeginWriteOperation(pParse, 1, iDb);
     sqlite3NestedParse(pParse,
-       "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
+       "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
        db->aDb[iDb].zDbSName, pIndex->zName
     );
     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
@@ -116146,8 +118823,8 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   int i;
   SrcItem *pItem;
-  assert(pList || pParse->db->mallocFailed );
-  if( pList ){
+  assert( pList || pParse->db->mallocFailed );
+  if( ALWAYS(pList) ){
     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
       if( pItem->iCursor>=0 ) continue;
       pItem->iCursor = pParse->nTab++;
@@ -116234,7 +118911,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   pItem->pUsing = pUsing;
   return p;
 
- append_from_error:
+append_from_error:
   assert( p==0 );
   sqlite3ExprDelete(db, pOn);
   sqlite3IdListDelete(db, pUsing);
@@ -116262,6 +118939,7 @@ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pI
     }else{
       pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
       pItem->fg.isIndexedBy = 1;
+      assert( pItem->fg.isCte==0 );  /* No collision on union u2 */
     }
   }
 }
@@ -116574,7 +119252,7 @@ SQLITE_PRIVATE void sqlite3UniqueConstraint(
     for(j=0; j<pIdx->nKeyCol; j++){
       char *zCol;
       assert( pIdx->aiColumn[j]>=0 );
-      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
+      zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
       if( j ) sqlite3_str_append(&errMsg, ", ", 2);
       sqlite3_str_appendall(&errMsg, pTab->zName);
       sqlite3_str_append(&errMsg, ".", 1);
@@ -116601,7 +119279,7 @@ SQLITE_PRIVATE void sqlite3RowidConstraint(
   int rc;
   if( pTab->iPKey>=0 ){
     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
-                          pTab->aCol[pTab->iPKey].zName);
+                          pTab->aCol[pTab->iPKey].zCnName);
     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
   }else{
     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
@@ -117242,6 +119920,7 @@ SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(
 ){
   FuncDef *p;
   for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
+    assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
     if( sqlite3StrICmp(p->zName, zFunc)==0 ){
       return p;
     }
@@ -117262,7 +119941,7 @@ SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
     const char *zName = aDef[i].zName;
     int nName = sqlite3Strlen30(zName);
     int h = SQLITE_FUNC_HASH(zName[0], nName);
-    assert( zName[0]>='a' && zName[0]<='z' );
+    assert( aDef[i].funcFlags & SQLITE_FUNC_BUILTIN );
     pOther = sqlite3FunctionSearch(h, zName);
     if( pOther ){
       assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
@@ -117488,6 +120167,16 @@ SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   return pTab;
 }
 
+/* Generate byte-code that will report the number of rows modified
+** by a DELETE, INSERT, or UPDATE statement.
+*/
+SQLITE_PRIVATE void sqlite3CodeChangeCount(Vdbe *v, int regCounter, const char *zColName){
+  sqlite3VdbeAddOp0(v, OP_FkCheck);
+  sqlite3VdbeAddOp2(v, OP_ResultRow, regCounter, 1);
+  sqlite3VdbeSetNumCols(v, 1);
+  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zColName, SQLITE_STATIC);
+}
+
 /* Return true if table pTab is read-only.
 **
 ** A table is read-only if any of the following are true:
@@ -117528,7 +120217,7 @@ SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
     return 1;
   }
 #ifndef SQLITE_OMIT_VIEW
-  if( !viewOk && pTab->pSelect ){
+  if( !viewOk && IsView(pTab) ){
     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
     return 1;
   }
@@ -117632,13 +120321,13 @@ SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   }else{
     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
     if( pPk->nKeyCol==1 ){
-      const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
+      const char *zName = pTab->aCol[pPk->aiColumn[0]].zCnName;
       pLhs = sqlite3Expr(db, TK_ID, zName);
       pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
     }else{
       int i;
       for(i=0; i<pPk->nKeyCol; i++){
-        Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
+        Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zCnName);
         pEList = sqlite3ExprListAppend(pParse, pEList, p);
       }
       pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
@@ -117654,6 +120343,7 @@ SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   pSelectSrc = sqlite3SrcListDup(db, pSrc, 0);
   pSrc->a[0].pTab = pTab;
   if( pSrc->a[0].fg.isIndexedBy ){
+    assert( pSrc->a[0].fg.isCte==0 );
     pSrc->a[0].u2.pIBIndex = 0;
     pSrc->a[0].fg.isIndexedBy = 0;
     sqlite3DbFree(db, pSrc->a[0].u1.zIndexedBy);
@@ -117726,9 +120416,11 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
 
   memset(&sContext, 0, sizeof(sContext));
   db = pParse->db;
-  if( pParse->nErr || db->mallocFailed ){
+  assert( db->pParse==pParse );
+  if( pParse->nErr ){
     goto delete_from_cleanup;
   }
+  assert( db->mallocFailed==0 );
   assert( pTabList->nSrc==1 );
 
 
@@ -117745,7 +120437,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
   */
 #ifndef SQLITE_OMIT_TRIGGER
   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
-  isView = pTab->pSelect!=0;
+  isView = IsView(pTab);
 #else
 # define pTrigger 0
 # define isView 0
@@ -117872,6 +120564,9 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
       assert( pIdx->pSchema==pTab->pSchema );
       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
+      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
+        sqlite3VdbeChangeP3(v, -1, memCnt ? memCnt : -1);
+      }
     }
   }else
 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
@@ -117906,7 +120601,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
     **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
     **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
     */
-    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
+    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,0,wcf,iTabCur+1);
     if( pWInfo==0 ) goto delete_from_cleanup;
     eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
     assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
@@ -117992,7 +120687,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
     if( eOnePass!=ONEPASS_OFF ){
       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
       if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
-        assert( pPk!=0 || pTab->pSelect!=0 );
+        assert( pPk!=0 || IsView(pTab) );
         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
         VdbeCoverage(v);
       }
@@ -118059,9 +120754,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
   ** invoke the callback function.
   */
   if( memCnt ){
-    sqlite3VdbeAddOp2(v, OP_ChngCntRow, memCnt, 1);
-    sqlite3VdbeSetNumCols(v, 1);
-    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
+    sqlite3CodeChangeCount(v, memCnt, "rows deleted");
   }
 
 delete_from_cleanup:
@@ -118226,7 +120919,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   ** the update-hook is not invoked for rows removed by REPLACE, but the
   ** pre-update-hook is.
   */
-  if( pTab->pSelect==0 ){
+  if( !IsView(pTab) ){
     u8 p5 = 0;
     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
@@ -118383,13 +121076,15 @@ SQLITE_PRIVATE int sqlite3GenerateIndexKey(
       continue;
     }
     sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
-    /* If the column affinity is REAL but the number is an integer, then it
-    ** might be stored in the table as an integer (using a compact
-    ** representation) then converted to REAL by an OP_RealAffinity opcode.
-    ** But we are getting ready to store this value back into an index, where
-    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
-    ** opcode if it is present */
-    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
+    if( pIdx->aiColumn[j]>=0 ){
+      /* If the column affinity is REAL but the number is an integer, then it
+      ** might be stored in the table as an integer (using a compact
+      ** representation) then converted to REAL by an OP_RealAffinity opcode.
+      ** But we are getting ready to store this value back into an index, where
+      ** it should be converted by to INTEGER again.  So omit the
+      ** OP_RealAffinity opcode if it is present */
+      sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
+    }
   }
   if( regOut ){
     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
@@ -118510,6 +121205,18 @@ static void typeofFunc(
   sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
 }
 
+/* subtype(X)
+**
+** Return the subtype of X
+*/
+static void subtypeFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  UNUSED_PARAMETER(argc);
+  sqlite3_result_int(context, sqlite3_value_subtype(argv[0]));
+}
 
 /*
 ** Implementation of the length() function
@@ -118671,7 +121378,7 @@ endInstrOOM:
 }
 
 /*
-** Implementation of the printf() function.
+** Implementation of the printf() (a.k.a. format()) SQL function.
 */
 static void printfFunc(
   sqlite3_context *context,
@@ -118984,9 +121691,9 @@ static void last_insert_rowid(
 /*
 ** Implementation of the changes() SQL function.
 **
-** IMP: R-62073-11209 The changes() SQL function is a wrapper
-** around the sqlite3_changes() C/C++ function and hence follows the same
-** rules for counting changes.
+** IMP: R-32760-32347 The changes() SQL function is a wrapper
+** around the sqlite3_changes64() C/C++ function and hence follows the
+** same rules for counting changes.
 */
 static void changes(
   sqlite3_context *context,
@@ -118995,12 +121702,12 @@ static void changes(
 ){
   sqlite3 *db = sqlite3_context_db_handle(context);
   UNUSED_PARAMETER2(NotUsed, NotUsed2);
-  sqlite3_result_int(context, sqlite3_changes(db));
+  sqlite3_result_int64(context, sqlite3_changes64(db));
 }
 
 /*
 ** Implementation of the total_changes() SQL function.  The return value is
-** the same as the sqlite3_total_changes() API function.
+** the same as the sqlite3_total_changes64() API function.
 */
 static void total_changes(
   sqlite3_context *context,
@@ -119009,9 +121716,9 @@ static void total_changes(
 ){
   sqlite3 *db = sqlite3_context_db_handle(context);
   UNUSED_PARAMETER2(NotUsed, NotUsed2);
-  /* IMP: R-52756-41993 This function is a wrapper around the
-  ** sqlite3_total_changes() C/C++ interface. */
-  sqlite3_result_int(context, sqlite3_total_changes(db));
+  /* IMP: R-11217-42568 This function is a wrapper around the
+  ** sqlite3_total_changes64() C/C++ interface. */
+  sqlite3_result_int64(context, sqlite3_total_changes64(db));
 }
 
 /*
@@ -119440,39 +122147,42 @@ static const char hexdigits[] = {
 };
 
 /*
-** Implementation of the QUOTE() function.  This function takes a single
-** argument.  If the argument is numeric, the return value is the same as
-** the argument.  If the argument is NULL, the return value is the string
-** "NULL".  Otherwise, the argument is enclosed in single quotes with
-** single-quote escapes.
+** Append to pStr text that is the SQL literal representation of the
+** value contained in pValue.
 */
-static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
-  assert( argc==1 );
-  UNUSED_PARAMETER(argc);
-  switch( sqlite3_value_type(argv[0]) ){
+SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){
+  /* As currently implemented, the string must be initially empty.
+  ** we might relax this requirement in the future, but that will
+  ** require enhancements to the implementation. */
+  assert( pStr!=0 && pStr->nChar==0 );
+
+  switch( sqlite3_value_type(pValue) ){
     case SQLITE_FLOAT: {
       double r1, r2;
-      char zBuf[50];
-      r1 = sqlite3_value_double(argv[0]);
-      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
-      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
-      if( r1!=r2 ){
-        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
+      const char *zVal;
+      r1 = sqlite3_value_double(pValue);
+      sqlite3_str_appendf(pStr, "%!.15g", r1);
+      zVal = sqlite3_str_value(pStr);
+      if( zVal ){
+        sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8);
+        if( r1!=r2 ){
+          sqlite3_str_reset(pStr);
+          sqlite3_str_appendf(pStr, "%!.20e", r1);
+        }
       }
-      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
       break;
     }
     case SQLITE_INTEGER: {
-      sqlite3_result_value(context, argv[0]);
+      sqlite3_str_appendf(pStr, "%lld", sqlite3_value_int64(pValue));
       break;
     }
     case SQLITE_BLOB: {
-      char *zText = 0;
-      char const *zBlob = sqlite3_value_blob(argv[0]);
-      int nBlob = sqlite3_value_bytes(argv[0]);
-      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
-      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
-      if( zText ){
+      char const *zBlob = sqlite3_value_blob(pValue);
+      int nBlob = sqlite3_value_bytes(pValue);
+      assert( zBlob==sqlite3_value_blob(pValue) ); /* No encoding change */
+      sqlite3StrAccumEnlarge(pStr, nBlob*2 + 4);
+      if( pStr->accError==0 ){
+        char *zText = pStr->zText;
         int i;
         for(i=0; i<nBlob; i++){
           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
@@ -119482,42 +122192,48 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
         zText[(nBlob*2)+3] = '\0';
         zText[0] = 'X';
         zText[1] = '\'';
-        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
-        sqlite3_free(zText);
+        pStr->nChar = nBlob*2 + 3;
       }
       break;
     }
     case SQLITE_TEXT: {
-      int i,j;
-      u64 n;
-      const unsigned char *zArg = sqlite3_value_text(argv[0]);
-      char *z;
-
-      if( zArg==0 ) return;
-      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
-      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
-      if( z ){
-        z[0] = '\'';
-        for(i=0, j=1; zArg[i]; i++){
-          z[j++] = zArg[i];
-          if( zArg[i]=='\'' ){
-            z[j++] = '\'';
-          }
-        }
-        z[j++] = '\'';
-        z[j] = 0;
-        sqlite3_result_text(context, z, j, sqlite3_free);
-      }
+      const unsigned char *zArg = sqlite3_value_text(pValue);
+      sqlite3_str_appendf(pStr, "%Q", zArg);
       break;
     }
     default: {
-      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
-      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
+      assert( sqlite3_value_type(pValue)==SQLITE_NULL );
+      sqlite3_str_append(pStr, "NULL", 4);
       break;
     }
   }
 }
 
+/*
+** Implementation of the QUOTE() function.
+**
+** The quote(X) function returns the text of an SQL literal which is the
+** value of its argument suitable for inclusion into an SQL statement.
+** Strings are surrounded by single-quotes with escapes on interior quotes
+** as needed. BLOBs are encoded as hexadecimal literals. Strings with
+** embedded NUL characters cannot be represented as string literals in SQL
+** and hence the returned string literal is truncated prior to the first NUL.
+*/
+static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
+  sqlite3_str str;
+  sqlite3 *db = sqlite3_context_db_handle(context);
+  assert( argc==1 );
+  UNUSED_PARAMETER(argc);
+  sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
+  sqlite3QuoteValue(&str,argv[0]);
+  sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
+                      SQLITE_DYNAMIC);
+  if( str.accError!=SQLITE_OK ){
+    sqlite3_result_null(context);
+    sqlite3_result_error_code(context, str.accError);
+  }
+}
+
 /*
 ** The unicode() function.  Return the integer unicode code-point value
 ** for the first character of the input string.
@@ -119729,10 +122445,10 @@ static void trimFunc(
 ){
   const unsigned char *zIn;         /* Input string */
   const unsigned char *zCharSet;    /* Set of characters to trim */
-  int nIn;                          /* Number of bytes in input */
+  unsigned int nIn;                 /* Number of bytes in input */
   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   int i;                            /* Loop counter */
-  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
+  unsigned int *aLen = 0;           /* Length of each character in zCharSet */
   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   int nChar;                        /* Number of characters in zCharSet */
 
@@ -119741,13 +122457,13 @@ static void trimFunc(
   }
   zIn = sqlite3_value_text(argv[0]);
   if( zIn==0 ) return;
-  nIn = sqlite3_value_bytes(argv[0]);
+  nIn = (unsigned)sqlite3_value_bytes(argv[0]);
   assert( zIn==sqlite3_value_text(argv[0]) );
   if( argc==1 ){
-    static const unsigned char lenOne[] = { 1 };
+    static const unsigned lenOne[] = { 1 };
     static unsigned char * const azOne[] = { (u8*)" " };
     nChar = 1;
-    aLen = (u8*)lenOne;
+    aLen = (unsigned*)lenOne;
     azChar = (unsigned char **)azOne;
     zCharSet = 0;
   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
@@ -119758,15 +122474,16 @@ static void trimFunc(
       SQLITE_SKIP_UTF8(z);
     }
     if( nChar>0 ){
-      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
+      azChar = contextMalloc(context,
+                     ((i64)nChar)*(sizeof(char*)+sizeof(unsigned)));
       if( azChar==0 ){
         return;
       }
-      aLen = (unsigned char*)&azChar[nChar];
+      aLen = (unsigned*)&azChar[nChar];
       for(z=zCharSet, nChar=0; *z; nChar++){
         azChar[nChar] = (unsigned char *)z;
         SQLITE_SKIP_UTF8(z);
-        aLen[nChar] = (u8)(z - azChar[nChar]);
+        aLen[nChar] = (unsigned)(z - azChar[nChar]);
       }
     }
   }
@@ -119774,7 +122491,7 @@ static void trimFunc(
     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
     if( flags & 1 ){
       while( nIn>0 ){
-        int len = 0;
+        unsigned int len = 0;
         for(i=0; i<nChar; i++){
           len = aLen[i];
           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
@@ -119786,7 +122503,7 @@ static void trimFunc(
     }
     if( flags & 2 ){
       while( nIn>0 ){
-        int len = 0;
+        unsigned int len = 0;
         for(i=0; i<nChar; i++){
           len = aLen[i];
           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
@@ -120127,97 +122844,167 @@ static void minMaxFinalize(sqlite3_context *context){
 
 /*
 ** group_concat(EXPR, ?SEPARATOR?)
+**
+** The SEPARATOR goes before the EXPR string.  This is tragic.  The
+** groupConcatInverse() implementation would have been easier if the
+** SEPARATOR were appended after EXPR.  And the order is undocumented,
+** so we could change it, in theory.  But the old behavior has been
+** around for so long that we dare not, for fear of breaking something.
 */
+typedef struct {
+  StrAccum str;          /* The accumulated concatenation */
+#ifndef SQLITE_OMIT_WINDOWFUNC
+  int nAccum;            /* Number of strings presently concatenated */
+  int nFirstSepLength;   /* Used to detect separator length change */
+  /* If pnSepLengths!=0, refs an array of inter-string separator lengths,
+  ** stored as actually incorporated into presently accumulated result.
+  ** (Hence, its slots in use number nAccum-1 between method calls.)
+  ** If pnSepLengths==0, nFirstSepLength is the length used throughout.
+  */
+  int *pnSepLengths;
+#endif
+} GroupConcatCtx;
+
 static void groupConcatStep(
   sqlite3_context *context,
   int argc,
   sqlite3_value **argv
 ){
   const char *zVal;
-  StrAccum *pAccum;
+  GroupConcatCtx *pGCC;
   const char *zSep;
   int nVal, nSep;
   assert( argc==1 || argc==2 );
   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
-  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
-
-  if( pAccum ){
+  pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
+  if( pGCC ){
     sqlite3 *db = sqlite3_context_db_handle(context);
-    int firstTerm = pAccum->mxAlloc==0;
-    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
-    if( !firstTerm ){
-      if( argc==2 ){
-        zSep = (char*)sqlite3_value_text(argv[1]);
-        nSep = sqlite3_value_bytes(argv[1]);
-      }else{
-        zSep = ",";
-        nSep = 1;
+    int firstTerm = pGCC->str.mxAlloc==0;
+    pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
+    if( argc==1 ){
+      if( !firstTerm ){
+        sqlite3_str_appendchar(&pGCC->str, 1, ',');
       }
-      if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+      else{
+        pGCC->nFirstSepLength = 1;
+      }
+#endif
+    }else if( !firstTerm ){
+      zSep = (char*)sqlite3_value_text(argv[1]);
+      nSep = sqlite3_value_bytes(argv[1]);
+      if( zSep ){
+        sqlite3_str_append(&pGCC->str, zSep, nSep);
+      }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+      else{
+        nSep = 0;
+      }
+      if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){
+        int *pnsl = pGCC->pnSepLengths;
+        if( pnsl == 0 ){
+          /* First separator length variation seen, start tracking them. */
+          pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int));
+          if( pnsl!=0 ){
+            int i = 0, nA = pGCC->nAccum-1;
+            while( i<nA ) pnsl[i++] = pGCC->nFirstSepLength;
+          }
+        }else{
+          pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int));
+        }
+        if( pnsl!=0 ){
+          if( ALWAYS(pGCC->nAccum>0) ){
+            pnsl[pGCC->nAccum-1] = nSep;
+          }
+          pGCC->pnSepLengths = pnsl;
+        }else{
+          sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM);
+        }
+      }
+#endif
+    }
+#ifndef SQLITE_OMIT_WINDOWFUNC
+    else{
+      pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]);
     }
+    pGCC->nAccum += 1;
+#endif
     zVal = (char*)sqlite3_value_text(argv[0]);
     nVal = sqlite3_value_bytes(argv[0]);
-    if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
+    if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal);
   }
 }
+
 #ifndef SQLITE_OMIT_WINDOWFUNC
 static void groupConcatInverse(
   sqlite3_context *context,
   int argc,
   sqlite3_value **argv
 ){
-  int n;
-  StrAccum *pAccum;
+  GroupConcatCtx *pGCC;
   assert( argc==1 || argc==2 );
+  (void)argc;  /* Suppress unused parameter warning */
   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
-  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
-  /* pAccum is always non-NULL since groupConcatStep() will have always
+  pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
+  /* pGCC is always non-NULL since groupConcatStep() will have always
   ** run frist to initialize it */
-  if( ALWAYS(pAccum) ){
-    n = sqlite3_value_bytes(argv[0]);
-    if( argc==2 ){
-      n += sqlite3_value_bytes(argv[1]);
+  if( ALWAYS(pGCC) ){
+    int nVS;
+    /* Must call sqlite3_value_text() to convert the argument into text prior
+    ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */
+    (void)sqlite3_value_text(argv[0]);
+    nVS = sqlite3_value_bytes(argv[0]);
+    pGCC->nAccum -= 1;
+    if( pGCC->pnSepLengths!=0 ){
+      assert(pGCC->nAccum >= 0);
+      if( pGCC->nAccum>0 ){
+        nVS += *pGCC->pnSepLengths;
+        memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1,
+               (pGCC->nAccum-1)*sizeof(int));
+      }
     }else{
-      n++;
+      /* If removing single accumulated string, harmlessly over-do. */
+      nVS += pGCC->nFirstSepLength;
     }
-    if( n>=(int)pAccum->nChar ){
-      pAccum->nChar = 0;
+    if( nVS>=(int)pGCC->str.nChar ){
+      pGCC->str.nChar = 0;
     }else{
-      pAccum->nChar -= n;
-      memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
+      pGCC->str.nChar -= nVS;
+      memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar);
+    }
+    if( pGCC->str.nChar==0 ){
+      pGCC->str.mxAlloc = 0;
+      sqlite3_free(pGCC->pnSepLengths);
+      pGCC->pnSepLengths = 0;
     }
-    if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
   }
 }
 #else
 # define groupConcatInverse 0
 #endif /* SQLITE_OMIT_WINDOWFUNC */
 static void groupConcatFinalize(sqlite3_context *context){
-  StrAccum *pAccum;
-  pAccum = sqlite3_aggregate_context(context, 0);
-  if( pAccum ){
-    if( pAccum->accError==SQLITE_TOOBIG ){
-      sqlite3_result_error_toobig(context);
-    }else if( pAccum->accError==SQLITE_NOMEM ){
-      sqlite3_result_error_nomem(context);
-    }else{
-      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
-                          sqlite3_free);
-    }
+  GroupConcatCtx *pGCC
+    = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
+  if( pGCC ){
+    sqlite3ResultStrAccum(context, &pGCC->str);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+    sqlite3_free(pGCC->pnSepLengths);
+#endif
   }
 }
 #ifndef SQLITE_OMIT_WINDOWFUNC
 static void groupConcatValue(sqlite3_context *context){
-  sqlite3_str *pAccum;
-  pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
-  if( pAccum ){
+  GroupConcatCtx *pGCC
+    = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
+  if( pGCC ){
+    StrAccum *pAccum = &pGCC->str;
     if( pAccum->accError==SQLITE_TOOBIG ){
       sqlite3_result_error_toobig(context);
     }else if( pAccum->accError==SQLITE_NOMEM ){
       sqlite3_result_error_nomem(context);
     }else{
       const char *zText = sqlite3_str_value(pAccum);
-      sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
+      sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
     }
   }
 }
@@ -120281,11 +123068,12 @@ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocas
   int nExpr;
   assert( pExpr!=0 );
   assert( pExpr->op==TK_FUNCTION );
+  assert( ExprUseXList(pExpr) );
   if( !pExpr->x.pList ){
     return 0;
   }
-  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   nExpr = pExpr->x.pList->nExpr;
+  assert( !ExprHasProperty(pExpr, EP_IntValue) );
   pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
   if( pDef==0 ) return 0;
@@ -120309,6 +123097,7 @@ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocas
     Expr *pEscape = pExpr->x.pList->a[2].pExpr;
     char *zEscape;
     if( pEscape->op!=TK_STRING ) return 0;
+    assert( !ExprHasProperty(pEscape, EP_IntValue) );
     zEscape = pEscape->u.zToken;
     if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
     if( zEscape[0]==aWc[0] ) return 0;
@@ -120484,9 +123273,7 @@ static void math2Func(
 }
 
 /*
-** Implementation of 2-argument SQL math functions:
-**
-**   power(X,Y)  - Compute X to the Y-th power
+** Implementation of 0-argument pi() function.
 */
 static void piFunc(
   sqlite3_context *context,
@@ -120537,12 +123324,12 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
   */
   static FuncDef aBuiltinFunc[] = {
 /***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
+#if !defined(SQLITE_UNTESTABLE)
     TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),
     TEST_FUNC(expr_compare,        2, INLINEFUNC_expr_compare,        0),
     TEST_FUNC(expr_implies_expr,   2, INLINEFUNC_expr_implies_expr,   0),
-#ifdef SQLITE_DEBUG
-    TEST_FUNC(affinity,          1, INLINEFUNC_affinity, 0),
-#endif
+    TEST_FUNC(affinity,            1, INLINEFUNC_affinity,            0),
+#endif /* !defined(SQLITE_UNTESTABLE) */
 /***** Regular functions *****/
 #ifdef SQLITE_SOUNDEX
     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
@@ -120562,8 +123349,8 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
     INLINE_FUNC(likelihood,      2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
     INLINE_FUNC(likely,          1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
-    FUNCTION2(sqlite_offset,     1, 0, 0, noopFunc,  SQLITE_FUNC_OFFSET|
-                                                     SQLITE_FUNC_TYPEOF),
+    {1, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_OFFSET|SQLITE_FUNC_TYPEOF,
+     0, 0, noopFunc, 0, 0, 0, "sqlite_offset", {0} },
 #endif
     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
@@ -120574,15 +123361,17 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
     FUNCTION(min,                0, 0, 1, 0                ),
     WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
-                                          SQLITE_FUNC_MINMAX ),
+                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
     FUNCTION(max,                0, 1, 1, 0                ),
     WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
-                                          SQLITE_FUNC_MINMAX ),
+                                 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
+    FUNCTION2(subtype,           1, 0, 0, subtypeFunc, SQLITE_FUNC_TYPEOF),
     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
     FUNCTION(instr,              2, 0, 0, instrFunc        ),
     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
+    FUNCTION(format,            -1, 0, 0, printfFunc       ),
     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
     FUNCTION(char,              -1, 0, 0, charFunc         ),
     FUNCTION(abs,                1, 0, 0, absFunc          ),
@@ -120614,9 +123403,10 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
     WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
     WAGGREGATE(avg,   1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
     WAGGREGATE(count, 0,0,0, countStep,
-        countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT  ),
+        countFinalize, countFinalize, countInverse,
+        SQLITE_FUNC_COUNT|SQLITE_FUNC_ANYORDER  ),
     WAGGREGATE(count, 1,0,0, countStep,
-        countFinalize, countFinalize, countInverse, 0  ),
+        countFinalize, countFinalize, countInverse, SQLITE_FUNC_ANYORDER ),
     WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
         groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
     WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
@@ -120680,6 +123470,7 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 #endif
   sqlite3WindowFunctions();
   sqlite3RegisterDateTimeFunctions();
+  sqlite3RegisterJsonFunctions();
   sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
 
 #if 0  /* Enable to print out how the built-in functions are hashed */
@@ -120691,6 +123482,7 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
         int n = sqlite3Strlen30(p->zName);
         int h = p->zName[0] + n;
+        assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
         printf(" %s(%d)", p->zName, h);
       }
       printf("\n");
@@ -120918,7 +123710,9 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(
     */
     if( pParent->iPKey>=0 ){
       if( !zKey ) return 0;
-      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
+      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zCnName, zKey) ){
+        return 0;
+      }
     }
   }else if( paiCol ){
     assert( nCol>1 );
@@ -120960,11 +123754,11 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(
           /* If the index uses a collation sequence that is different from
           ** the default collation sequence for the column, this index is
           ** unusable. Bail out early in this case.  */
-          zDfltColl = pParent->aCol[iCol].zColl;
+          zDfltColl = sqlite3ColumnColl(&pParent->aCol[iCol]);
           if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
 
-          zIdxCol = pParent->aCol[iCol].zName;
+          zIdxCol = pParent->aCol[iCol].zCnName;
           for(j=0; j<nCol; j++){
             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
@@ -121188,7 +123982,7 @@ static Expr *exprTableRegister(
       pCol = &pTab->aCol[iCol];
       pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
       pExpr->affExpr = pCol->affinity;
-      zColl = pCol->zColl;
+      zColl = sqlite3ColumnColl(pCol);
       if( zColl==0 ) zColl = db->pDfltColl->zName;
       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
     }else{
@@ -121211,6 +124005,7 @@ static Expr *exprTableColumn(
 ){
   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
   if( pExpr ){
+    assert( ExprUseYTab(pExpr) );
     pExpr->y.pTab = pTab;
     pExpr->iTable = iCursor;
     pExpr->iColumn = iCol;
@@ -121297,7 +124092,7 @@ static void fkScanChildren(
     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
     assert( iCol>=0 );
-    zCol = pFKey->pFrom->aCol[iCol].zName;
+    zCol = pFKey->pFrom->aCol[iCol].zCnName;
     pRight = sqlite3Expr(db, TK_ID, zCol);
     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
     pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
@@ -121332,7 +124127,7 @@ static void fkScanChildren(
         i16 iCol = pIdx->aiColumn[i];
         assert( iCol>=0 );
         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
-        pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName);
+        pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zCnName);
         pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
         pAll = sqlite3ExprAnd(pParse, pAll, pEq);
       }
@@ -121351,7 +124146,7 @@ static void fkScanChildren(
   ** clause. For each row found, increment either the deferred or immediate
   ** foreign key constraint counter. */
   if( pParse->nErr==0 ){
-    pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
+    pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0, 0);
     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
     if( pWInfo ){
       sqlite3WhereEnd(pWInfo);
@@ -121402,6 +124197,25 @@ static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   }
 }
 
+/*
+** Clear the apTrigger[] cache of CASCADE triggers for all foreign keys
+** in a particular database.  This needs to happen when the schema
+** changes.
+*/
+SQLITE_PRIVATE void sqlite3FkClearTriggerCache(sqlite3 *db, int iDb){
+  HashElem *k;
+  Hash *pHash = &db->aDb[iDb].pSchema->tblHash;
+  for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k)){
+    Table *pTab = sqliteHashData(k);
+    FKey *pFKey;
+    if( !IsOrdinaryTable(pTab) ) continue;
+    for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
+      fkTriggerDelete(db, pFKey->apTrigger[0]); pFKey->apTrigger[0] = 0;
+      fkTriggerDelete(db, pFKey->apTrigger[1]); pFKey->apTrigger[1] = 0;
+    }
+  }
+}
+
 /*
 ** This function is called to generate code that runs when table pTab is
 ** being dropped from the database. The SrcList passed as the second argument
@@ -121421,12 +124235,12 @@ static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
 */
 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   sqlite3 *db = pParse->db;
-  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){
+  if( (db->flags&SQLITE_ForeignKeys) && IsOrdinaryTable(pTab) ){
     int iSkip = 0;
     Vdbe *v = sqlite3GetVdbe(pParse);
 
     assert( v );                  /* VDBE has already been allocated */
-    assert( pTab->pSelect==0 );   /* Not a view */
+    assert( IsOrdinaryTable(pTab) );
     if( sqlite3FkReferences(pTab)==0 ){
       /* Search for a deferred foreign key constraint for which this table
       ** is the child table. If one cannot be found, return without
@@ -121434,7 +124248,7 @@ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTa
       ** the entire DELETE if there are no outstanding deferred constraints
       ** when this statement is run.  */
       FKey *p;
-      for(p=pTab->pFKey; p; p=p->pNextFrom){
+      for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
       }
       if( !p ) return;
@@ -121523,7 +124337,7 @@ static int fkParentIsModified(
       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
         Column *pCol = &pTab->aCol[iKey];
         if( zKey ){
-          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
+          if( 0==sqlite3StrICmp(pCol->zCnName, zKey) ) return 1;
         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
           return 1;
         }
@@ -121590,13 +124404,14 @@ SQLITE_PRIVATE void sqlite3FkCheck(
 
   /* If foreign-keys are disabled, this function is a no-op. */
   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
+  if( !IsOrdinaryTable(pTab) ) return;
 
   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   zDb = db->aDb[iDb].zDbSName;
 
   /* Loop through all the foreign key constraints for which pTab is the
   ** child table (the table that the foreign key definition is part of).  */
-  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
+  for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
     Table *pTo;                   /* Parent table of foreign key pFKey */
     Index *pIdx = 0;              /* Index on key columns in pTo */
     int *aiFree = 0;
@@ -121663,7 +124478,7 @@ SQLITE_PRIVATE void sqlite3FkCheck(
       ** values read from the parent table are NULL. */
       if( db->xAuth ){
         int rcauth;
-        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
+        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
         bIgnore = (rcauth==SQLITE_IGNORE);
       }
@@ -121778,10 +124593,10 @@ SQLITE_PRIVATE u32 sqlite3FkOldmask(
   Table *pTab                     /* Table being modified */
 ){
   u32 mask = 0;
-  if( pParse->db->flags&SQLITE_ForeignKeys ){
+  if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
     FKey *p;
     int i;
-    for(p=pTab->pFKey; p; p=p->pNextFrom){
+    for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
     }
     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
@@ -121831,19 +124646,19 @@ SQLITE_PRIVATE int sqlite3FkRequired(
 ){
   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( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
     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.  */
-      bHaveFK = (sqlite3FkReferences(pTab) || pTab->pFKey);
+      bHaveFK = (sqlite3FkReferences(pTab) || pTab->u.tab.pFKey);
     }else{
       /* This is an UPDATE. Foreign key processing is only required if the
       ** operation modifies one or more child or parent key columns. */
       FKey *p;
 
       /* Check if any child key columns are being modified. */
-      for(p=pTab->pFKey; p; p=p->pNextFrom){
+      for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
         if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
           if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) eRet = 2;
           bHaveFK = 1;
@@ -121936,8 +124751,8 @@ static Trigger *fkActionTrigger(
       assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
       sqlite3TokenInit(&tToCol,
-                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
-      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
+                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zCnName);
+      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zCnName);
 
       /* Create the expression "OLD.zToCol = zFromCol". It is important
       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
@@ -121982,7 +124797,7 @@ static Trigger *fkActionTrigger(
             testcase( pCol->colFlags & COLFLAG_STORED );
             pDflt = 0;
           }else{
-            pDflt = pCol->pDflt;
+            pDflt = sqlite3ColumnExpr(pFKey->pFrom, pCol);
           }
           if( pDflt ){
             pNew = sqlite3ExprDup(db, pDflt, 0);
@@ -122119,9 +124934,9 @@ SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
   FKey *pFKey;                    /* Iterator variable */
   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
 
-  assert( db==0 || IsVirtual(pTab)
-         || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
-  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
+  assert( IsOrdinaryTable(pTab) );
+  for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pNext){
+    assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
 
     /* Remove the FK from the fkeyHash hash table. */
     if( !db || db->pnBytesFreed==0 ){
@@ -122201,7 +125016,7 @@ SQLITE_PRIVATE void sqlite3OpenTable(
   }else{
     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
     assert( pPk!=0 );
-    assert( pPk->tnum==pTab->tnum );
+    assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
     VdbeComment((v, "%s", pTab->zName));
@@ -122268,28 +125083,68 @@ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
 }
 
 /*
+** Make changes to the evolving bytecode to do affinity transformations
+** of values that are about to be gathered into a row for table pTab.
+**
+** For ordinary (legacy, non-strict) tables:
+** -----------------------------------------
+**
 ** Compute the affinity string for table pTab, if it has not already been
 ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
 **
-** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
-** if iReg>0 then code an OP_Affinity opcode that will set the affinities
-** for register iReg and following.  Or if affinities exists and iReg==0,
+** If the affinity string is empty (because it was all SQLITE_AFF_BLOB entries
+** which were then optimized out) then this routine becomes a no-op.
+**
+** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
+** affinities for register iReg and following.  Or if iReg==0,
 ** then just set the P4 operand of the previous opcode (which should  be
 ** an OP_MakeRecord) to the affinity string.
 **
 ** A column affinity string has one character per column:
 **
-**  Character      Column affinity
-**  ------------------------------
-**  'A'            BLOB
-**  'B'            TEXT
-**  'C'            NUMERIC
-**  'D'            INTEGER
-**  'E'            REAL
+**    Character      Column affinity
+**    ---------      ---------------
+**    'A'            BLOB
+**    'B'            TEXT
+**    'C'            NUMERIC
+**    'D'            INTEGER
+**    'E'            REAL
+**
+** For STRICT tables:
+** ------------------
+**
+** Generate an appropropriate OP_TypeCheck opcode that will verify the
+** datatypes against the column definitions in pTab.  If iReg==0, that
+** means an OP_MakeRecord opcode has already been generated and should be
+** the last opcode generated.  The new OP_TypeCheck needs to be inserted
+** before the OP_MakeRecord.  The new OP_TypeCheck should use the same
+** register set as the OP_MakeRecord.  If iReg>0 then register iReg is
+** the first of a series of registers that will form the new record.
+** Apply the type checking to that array of registers.
 */
 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
   int i, j;
-  char *zColAff = pTab->zColAff;
+  char *zColAff;
+  if( pTab->tabFlags & TF_Strict ){
+    if( iReg==0 ){
+      /* Move the previous opcode (which should be OP_MakeRecord) forward
+      ** by one slot and insert a new OP_TypeCheck where the current
+      ** OP_MakeRecord is found */
+      VdbeOp *pPrev;
+      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
+      pPrev = sqlite3VdbeGetOp(v, -1);
+      assert( pPrev!=0 );
+      assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
+      pPrev->opcode = OP_TypeCheck;
+      sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
+    }else{
+      /* Insert an isolated OP_Typecheck */
+      sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
+      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
+    }
+    return;
+  }
+  zColAff = pTab->zColAff;
   if( zColAff==0 ){
     sqlite3 *db = sqlite3VdbeDb(v);
     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
@@ -122299,7 +125154,7 @@ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
     }
 
     for(i=j=0; i<pTab->nCol; i++){
-      assert( pTab->aCol[i].affinity!=0 );
+      assert( pTab->aCol[i].affinity!=0 || sqlite3VdbeParser(v)->nErr>0 );
       if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
         zColAff[j++] = pTab->aCol[i].affinity;
       }
@@ -122315,6 +125170,8 @@ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
     if( iReg ){
       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
     }else{
+      assert( sqlite3VdbeGetOp(v, -1)->opcode==OP_MakeRecord
+              || sqlite3VdbeDb(v)->mallocFailed );
       sqlite3VdbeChangeP4(v, -1, zColAff, i);
     }
   }
@@ -122398,24 +125255,30 @@ SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(
   ** that appropriate affinity has been applied to the regular columns
   */
   sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
-  if( (pTab->tabFlags & TF_HasStored)!=0
-   && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity
-  ){
-    /* Change the OP_Affinity argument to '@' (NONE) for all stored
-    ** columns.  '@' is the no-op affinity and those columns have not
-    ** yet been computed. */
-    int ii, jj;
-    char *zP4 = pOp->p4.z;
-    assert( zP4!=0 );
-    assert( pOp->p4type==P4_DYNAMIC );
-    for(ii=jj=0; zP4[jj]; ii++){
-      if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
-        continue;
-      }
-      if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
-        zP4[jj] = SQLITE_AFF_NONE;
+  if( (pTab->tabFlags & TF_HasStored)!=0 ){
+    pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
+    if( pOp->opcode==OP_Affinity ){
+      /* Change the OP_Affinity argument to '@' (NONE) for all stored
+      ** columns.  '@' is the no-op affinity and those columns have not
+      ** yet been computed. */
+      int ii, jj;
+      char *zP4 = pOp->p4.z;
+      assert( zP4!=0 );
+      assert( pOp->p4type==P4_DYNAMIC );
+      for(ii=jj=0; zP4[jj]; ii++){
+        if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
+          continue;
+        }
+        if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
+          zP4[jj] = SQLITE_AFF_NONE;
+        }
+        jj++;
       }
-      jj++;
+    }else if( pOp->opcode==OP_TypeCheck ){
+      /* If an OP_TypeCheck was generated because the table is STRICT,
+      ** then set the P3 operand to indicate that generated columns should
+      ** not be checked */
+      pOp->p3 = 1;
     }
   }
 
@@ -122451,7 +125314,7 @@ SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(
         int x;
         pCol->colFlags |= COLFLAG_BUSY;
         w.eCode = 0;
-        sqlite3WalkExpr(&w, pCol->pDflt);
+        sqlite3WalkExpr(&w, sqlite3ColumnExpr(pTab, pCol));
         pCol->colFlags &= ~COLFLAG_BUSY;
         if( w.eCode & COLFLAG_NOTAVAIL ){
           pRedo = pCol;
@@ -122460,13 +125323,13 @@ SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(
         eProgress = 1;
         assert( pCol->colFlags & COLFLAG_GENERATED );
         x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
-        sqlite3ExprCodeGeneratedColumn(pParse, pCol, x);
+        sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, x);
         pCol->colFlags &= ~COLFLAG_NOTAVAIL;
       }
     }
   }while( pRedo && eProgress );
   if( pRedo ){
-    sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName);
+    sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
   }
   pParse->iSelfTab = 0;
 }
@@ -122516,7 +125379,7 @@ static int autoIncBegin(
     ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
     if( pSeqTab==0
      || !HasRowid(pSeqTab)
-     || IsVirtual(pSeqTab)
+     || NEVER(IsVirtual(pSeqTab))
      || pSeqTab->nCol!=2
     ){
       pParse->nErr++;
@@ -122825,9 +125688,11 @@ SQLITE_PRIVATE void sqlite3Insert(
 #endif
 
   db = pParse->db;
-  if( pParse->nErr || db->mallocFailed ){
+  assert( db->pParse==pParse );
+  if( pParse->nErr ){
     goto insert_cleanup;
   }
+  assert( db->mallocFailed==0 );
   dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
 
   /* If the Select object is really just a simple VALUES() list with a
@@ -122861,7 +125726,7 @@ SQLITE_PRIVATE void sqlite3Insert(
   */
 #ifndef SQLITE_OMIT_TRIGGER
   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
-  isView = pTab->pSelect!=0;
+  isView = IsView(pTab);
 #else
 # define pTrigger 0
 # define tmask 0
@@ -122903,7 +125768,11 @@ SQLITE_PRIVATE void sqlite3Insert(
   **
   ** This is the 2nd template.
   */
-  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
+  if( pColumn==0
+   && pSelect!=0
+   && pTrigger==0
+   && xferOptimization(pParse, pTab, pSelect, onError, iDb)
+  ){
     assert( !pTrigger );
     assert( pList==0 );
     goto insert_end;
@@ -122952,7 +125821,7 @@ SQLITE_PRIVATE void sqlite3Insert(
     }
     for(i=0; i<pColumn->nId; i++){
       for(j=0; j<pTab->nCol; j++){
-        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
+        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
           pColumn->a[i].idx = j;
           if( i!=j ) bIdListInOrder = 0;
           if( j==pTab->iPKey ){
@@ -122962,7 +125831,7 @@ SQLITE_PRIVATE void sqlite3Insert(
           if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
             sqlite3ErrorMsg(pParse,
                "cannot INSERT into generated column \"%s\"",
-               pTab->aCol[j].zName);
+               pTab->aCol[j].zCnName);
             goto insert_cleanup;
           }
 #endif
@@ -122975,7 +125844,7 @@ SQLITE_PRIVATE void sqlite3Insert(
           bIdListInOrder = 0;
         }else{
           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
-              pTabList, 0, pColumn->a[i].zName);
+              pTabList->a, pColumn->a[i].zName);
           pParse->checkSchema = 1;
           goto insert_cleanup;
         }
@@ -123003,7 +125872,9 @@ SQLITE_PRIVATE void sqlite3Insert(
     dest.nSdst = pTab->nCol;
     rc = sqlite3Select(pParse, pSelect, &dest);
     regFromSelect = dest.iSdst;
-    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
+    assert( db->pParse==pParse );
+    if( rc || pParse->nErr ) goto insert_cleanup;
+    assert( db->mallocFailed==0 );
     sqlite3VdbeEndCoroutine(v, regYield);
     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
     assert( pSelect->pEList );
@@ -123103,7 +125974,7 @@ SQLITE_PRIVATE void sqlite3Insert(
     if( nColumn!=(pTab->nCol-nHidden) ){
       sqlite3ErrorMsg(pParse,
          "table %S has %d columns but %d values were supplied",
-         pTabList, 0, pTab->nCol-nHidden, nColumn);
+         pTabList->a, pTab->nCol-nHidden, nColumn);
      goto insert_cleanup;
     }
   }
@@ -123147,7 +126018,7 @@ SQLITE_PRIVATE void sqlite3Insert(
               pTab->zName);
       goto insert_cleanup;
     }
-    if( pTab->pSelect ){
+    if( IsView(pTab) ){
       sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
       goto insert_cleanup;
     }
@@ -123246,7 +126117,9 @@ SQLITE_PRIVATE void sqlite3Insert(
       }else if( pColumn==0 ){
         /* Hidden columns that are not explicitly named in the INSERT
         ** get there default value */
-        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+        sqlite3ExprCodeFactorable(pParse,
+            sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
+            iRegStore);
         continue;
       }
     }
@@ -123255,13 +126128,17 @@ SQLITE_PRIVATE void sqlite3Insert(
       if( j>=pColumn->nId ){
         /* A column not named in the insert column list gets its
         ** default value */
-        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+        sqlite3ExprCodeFactorable(pParse,
+            sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
+            iRegStore);
         continue;
       }
       k = j;
     }else if( nColumn==0 ){
       /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */
-      sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+      sqlite3ExprCodeFactorable(pParse,
+          sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
+          iRegStore);
       continue;
     }else{
       k = i - nHidden;
@@ -123406,7 +126283,7 @@ SQLITE_PRIVATE void sqlite3Insert(
     }else
 #endif
     {
-      int isReplace;    /* Set to true if constraints may cause a replace */
+      int isReplace = 0;/* Set to true if constraints may cause a replace */
       int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
@@ -123426,6 +126303,13 @@ SQLITE_PRIVATE void sqlite3Insert(
           regIns, aRegIdx, 0, appendFlag, bUseSeek
       );
     }
+#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
+  }else if( pParse->bReturning ){
+    /* If there is a RETURNING clause, populate the rowid register with
+    ** constant value -1, in case one or more of the returned expressions
+    ** refer to the "rowid" of the view.  */
+    sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
+#endif
   }
 
   /* Update the count of rows that are inserted
@@ -123479,9 +126363,7 @@ insert_end:
   ** invoke the callback function.
   */
   if( regRowCount ){
-    sqlite3VdbeAddOp2(v, OP_ChngCntRow, regRowCount, 1);
-    sqlite3VdbeSetNumCols(v, 1);
-    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
+    sqlite3CodeChangeCount(v, regRowCount, "rows inserted");
   }
 
 insert_cleanup:
@@ -123769,7 +126651,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   db = pParse->db;
   v = pParse->pVdbe;
   assert( v!=0 );
-  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
+  assert( !IsView(pTab) );  /* This table is not a VIEW */
   nCol = pTab->nCol;
 
   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
@@ -123820,7 +126702,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         }
         if( onError==OE_Replace ){
           if( b2ndPass        /* REPLACE becomes ABORT on the 2nd pass */
-           || pCol->pDflt==0  /* REPLACE is ABORT if no DEFAULT value */
+           || pCol->iDflt==0  /* REPLACE is ABORT if no DEFAULT value */
           ){
             testcase( pCol->colFlags & COLFLAG_VIRTUAL );
             testcase( pCol->colFlags & COLFLAG_STORED );
@@ -123842,7 +126724,8 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
             VdbeCoverage(v);
             assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
             nSeenReplace++;
-            sqlite3ExprCodeCopy(pParse, pCol->pDflt, iReg);
+            sqlite3ExprCodeCopy(pParse,
+               sqlite3ColumnExpr(pTab, pCol), iReg);
             sqlite3VdbeJumpHere(v, addr1);
             break;
           }
@@ -123852,7 +126735,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
           case OE_Rollback:
           case OE_Fail: {
             char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
-                                        pCol->zName);
+                                        pCol->zCnName);
             sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
                               onError, iReg);
             sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
@@ -124105,6 +126988,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     if( onError==OE_Replace      /* IPK rule is REPLACE */
      && onError!=overrideError   /* Rules for other constraints are different */
      && pTab->pIndex             /* There exist other constraints */
+     && !upsertIpkDelay          /* IPK check already deferred by UPSERT */
     ){
       ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
       VdbeComment((v, "defer IPK REPLACE until last"));
@@ -124270,7 +127154,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
         x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
         sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
-        VdbeComment((v, "%s", pTab->aCol[iField].zName));
+        VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
       }
     }
     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
@@ -124322,6 +127206,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
     ** must be explicitly deleted in order to ensure any pre-update hook
     ** is invoked.  */
+    assert( IsOrdinaryTable(pTab) );
 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
      && pPk==pIdx                                   /* Condition 2 */
@@ -124329,7 +127214,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
      && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
           0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
      && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
-         (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
+         (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
     ){
       sqlite3VdbeResolveLabel(v, addrUniqueOk);
       continue;
@@ -124364,7 +127249,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
             x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
             VdbeComment((v, "%s.%s", pTab->zName,
-                         pTab->aCol[pPk->aiColumn[i]].zName));
+                         pTab->aCol[pPk->aiColumn[i]].zCnName));
           }
         }
         if( isUpdate ){
@@ -124428,7 +127313,8 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
 
         assert( onError==OE_Replace );
         nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
-        assert( nConflictCk>0 );
+        assert( nConflictCk>0 || db->mallocFailed );
+        testcase( nConflictCk<=0 );
         testcase( nConflictCk>1 );
         if( regTrigCnt ){
           sqlite3MultiWrite(pParse);
@@ -124511,6 +127397,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   if( ipkTop ){
     sqlite3VdbeGoto(v, ipkTop);
     VdbeComment((v, "Do IPK REPLACE"));
+    assert( ipkBottom>0 );
     sqlite3VdbeJumpHere(v, ipkBottom);
   }
 
@@ -124563,7 +127450,7 @@ SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
   if( pTab->pSchema->file_format<2 ) return;
 
   for(i=pTab->nCol-1; i>0; i--){
-    if( pTab->aCol[i].pDflt!=0 ) break;
+    if( pTab->aCol[i].iDflt!=0 ) break;
     if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
   }
   sqlite3VdbeChangeP5(v, i+1);
@@ -124628,7 +127515,7 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion(
 
   v = pParse->pVdbe;
   assert( v!=0 );
-  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
+  assert( !IsView(pTab) );  /* This table is not a VIEW */
   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
     /* All REPLACE indexes are at the end of the list */
     assert( pIdx->onError!=OE_Replace
@@ -124641,7 +127528,6 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion(
     }
     pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
-      assert( pParse->nested==0 );
       pik_flags |= OPFLAG_NCHANGE;
       pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
       if( update_flags==0 ){
@@ -124714,8 +127600,9 @@ SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   assert( op==OP_OpenWrite || p5==0 );
   if( IsVirtual(pTab) ){
     /* This routine is a no-op for virtual tables. Leave the output
-    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
-    ** can detect if they are used by mistake in the caller. */
+    ** variables *piDataCur and *piIdxCur set to illegal cursor numbers
+    ** for improved error detection. */
+    *piDataCur = *piIdxCur = -999;
     return 0;
   }
   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
@@ -124856,18 +127743,13 @@ static int xferOptimization(
   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   int regData, regRowid;           /* Registers holding data and rowid */
 
-  if( pSelect==0 ){
-    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
-  }
+  assert( pSelect!=0 );
   if( pParse->pWith || pSelect->pWith ){
     /* Do not attempt to process this query if there are an WITH clauses
     ** attached to it. Proceeding may generate a false "no such table: xxx"
     ** error if pSelect reads from a CTE named "xxx".  */
     return 0;
   }
-  if( sqlite3TriggerList(pParse, pDest) ){
-    return 0;   /* tab1 must not have triggers */
-  }
 #ifndef SQLITE_OMIT_VIRTUALTABLE
   if( IsVirtual(pDest) ){
     return 0;   /* tab1 must not be a virtual table */
@@ -124930,13 +127812,8 @@ static int xferOptimization(
   if( HasRowid(pDest)!=HasRowid(pSrc) ){
     return 0;   /* source and destination must both be WITHOUT ROWID or not */
   }
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-  if( IsVirtual(pSrc) ){
-    return 0;   /* tab2 must not be a virtual table */
-  }
-#endif
-  if( pSrc->pSelect ){
-    return 0;   /* tab2 may not be a view */
+  if( !IsOrdinaryTable(pSrc) ){
+    return 0;   /* tab2 may not be a view or virtual table */
   }
   if( pDest->nCol!=pSrc->nCol ){
     return 0;   /* Number of columns must be the same in tab1 and tab2 */
@@ -124944,6 +127821,9 @@ static int xferOptimization(
   if( pDest->iPKey!=pSrc->iPKey ){
     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   }
+  if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
+    return 0;   /* Cannot feed from a non-strict into a strict table */
+  }
   for(i=0; i<pDest->nCol; i++){
     Column *pDestCol = &pDest->aCol[i];
     Column *pSrcCol = &pSrc->aCol[i];
@@ -124980,7 +127860,9 @@ static int xferOptimization(
     ** This requirement could be relaxed for VIRTUAL columns, I suppose.
     */
     if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
-      if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){
+      if( sqlite3ExprCompare(0,
+             sqlite3ColumnExpr(pSrc, pSrcCol),
+             sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
         testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
         testcase( pDestCol->colFlags & COLFLAG_STORED );
         return 0;  /* Different generator expressions */
@@ -124990,7 +127872,8 @@ static int xferOptimization(
     if( pDestCol->affinity!=pSrcCol->affinity ){
       return 0;    /* Affinity must be the same on all columns */
     }
-    if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
+    if( sqlite3_stricmp(sqlite3ColumnColl(pDestCol),
+                        sqlite3ColumnColl(pSrcCol))!=0 ){
       return 0;    /* Collating sequence must be the same on all columns */
     }
     if( pDestCol->notNull && !pSrcCol->notNull ){
@@ -124998,11 +127881,15 @@ static int xferOptimization(
     }
     /* Default values for second and subsequent columns need to match. */
     if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
-      assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
-      assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
-      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
-       || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
-                                       pSrcCol->pDflt->u.zToken)!=0)
+      Expr *pDestExpr = sqlite3ColumnExpr(pDest, pDestCol);
+      Expr *pSrcExpr = sqlite3ColumnExpr(pSrc, pSrcCol);
+      assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
+      assert( pDestExpr==0 || !ExprHasProperty(pDestExpr, EP_IntValue) );
+      assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
+      assert( pSrcExpr==0 || !ExprHasProperty(pSrcExpr, EP_IntValue) );
+      if( (pDestExpr==0)!=(pSrcExpr==0)
+       || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
+                                       pSrcExpr->u.zToken)!=0)
       ){
         return 0;    /* Default values must be the same for all columns */
       }
@@ -125039,7 +127926,8 @@ static int xferOptimization(
   ** the extra complication to make this rule less restrictive is probably
   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
   */
-  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
+  assert( IsOrdinaryTable(pDest) );
+  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
     return 0;
   }
 #endif
@@ -125717,6 +128605,20 @@ struct sqlite3_api_routines {
   sqlite3_file *(*database_file_object)(const char*);
   /* Version 3.34.0 and later */
   int (*txn_state)(sqlite3*,const char*);
+  /* Version 3.36.1 and later */
+  sqlite3_int64 (*changes64)(sqlite3*);
+  sqlite3_int64 (*total_changes64)(sqlite3*);
+  /* Version 3.37.0 and later */
+  int (*autovacuum_pages)(sqlite3*,
+     unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
+     void*, void(*)(void*));
+  /* Version 3.38.0 and later */
+  int (*error_offset)(sqlite3*);
+  int (*vtab_rhs_value)(sqlite3_index_info*,int,sqlite3_value**);
+  int (*vtab_distinct)(sqlite3_index_info*);
+  int (*vtab_in)(sqlite3_index_info*,int,int);
+  int (*vtab_in_first)(sqlite3_value*,sqlite3_value**);
+  int (*vtab_in_next)(sqlite3_value*,sqlite3_value**);
 };
 
 /*
@@ -126023,6 +128925,18 @@ typedef int (*sqlite3_loadext_entry)(
 #define sqlite3_database_file_object   sqlite3_api->database_file_object
 /* Version 3.34.0 and later */
 #define sqlite3_txn_state              sqlite3_api->txn_state
+/* Version 3.36.1 and later */
+#define sqlite3_changes64              sqlite3_api->changes64
+#define sqlite3_total_changes64        sqlite3_api->total_changes64
+/* Version 3.37.0 and later */
+#define sqlite3_autovacuum_pages       sqlite3_api->autovacuum_pages
+/* Version 3.38.0 and later */
+#define sqlite3_error_offset           sqlite3_api->error_offset
+#define sqlite3_vtab_rhs_value         sqlite3_api->vtab_rhs_value
+#define sqlite3_vtab_distinct          sqlite3_api->vtab_distinct
+#define sqlite3_vtab_in                sqlite3_api->vtab_in
+#define sqlite3_vtab_in_first          sqlite3_api->vtab_in_first
+#define sqlite3_vtab_in_next           sqlite3_api->vtab_in_next
 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
 
 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
@@ -126507,6 +129421,18 @@ static const sqlite3_api_routines sqlite3Apis = {
   sqlite3_database_file_object,
   /* Version 3.34.0 and later */
   sqlite3_txn_state,
+  /* Version 3.36.1 and later */
+  sqlite3_changes64,
+  sqlite3_total_changes64,
+  /* Version 3.37.0 and later */
+  sqlite3_autovacuum_pages,
+  /* Version 3.38.0 and later */
+  sqlite3_error_offset,
+  sqlite3_vtab_rhs_value,
+  sqlite3_vtab_distinct,
+  sqlite3_vtab_in,
+  sqlite3_vtab_in_first,
+  sqlite3_vtab_in_next
 };
 
 /* True if x is the directory separator character
@@ -126542,7 +129468,7 @@ static int sqlite3LoadExtension(
   const char *zEntry;
   char *zAltEntry = 0;
   void **aHandle;
-  u64 nMsg = 300 + sqlite3Strlen30(zFile);
+  u64 nMsg = strlen(zFile);
   int ii;
   int rc;
 
@@ -126576,6 +129502,12 @@ static int sqlite3LoadExtension(
 
   zEntry = zProc ? zProc : "sqlite3_extension_init";
 
+  /* tag-20210611-1.  Some dlopen() implementations will segfault if given
+  ** an oversize filename.  Most filesystems have a pathname limit of 4K,
+  ** so limit the extension filename length to about twice that.
+  ** https://sqlite.org/forum/forumpost/08a0d6d9bf */
+  if( nMsg>SQLITE_MAX_PATHLEN ) goto extension_not_found;
+
   handle = sqlite3OsDlOpen(pVfs, zFile);
 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
@@ -126585,17 +129517,7 @@ static int sqlite3LoadExtension(
     sqlite3_free(zAltFile);
   }
 #endif
-  if( handle==0 ){
-    if( pzErrMsg ){
-      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
-      if( zErrmsg ){
-        sqlite3_snprintf(nMsg, zErrmsg,
-            "unable to open shared library [%s]", zFile);
-        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
-      }
-    }
-    return SQLITE_ERROR;
-  }
+  if( handle==0 ) goto extension_not_found;
   xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
 
   /* If no entry point was specified and the default legacy
@@ -126632,10 +129554,11 @@ static int sqlite3LoadExtension(
   }
   if( xInit==0 ){
     if( pzErrMsg ){
-      nMsg += sqlite3Strlen30(zEntry);
+      nMsg += strlen(zEntry) + 300;
       *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
       if( zErrmsg ){
-        sqlite3_snprintf(nMsg, zErrmsg,
+        assert( nMsg<0x7fffffff );  /* zErrmsg would be NULL if not so */
+        sqlite3_snprintf((int)nMsg, zErrmsg,
             "no entry point [%s] in shared library [%s]", zEntry, zFile);
         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
       }
@@ -126669,6 +129592,19 @@ static int sqlite3LoadExtension(
 
   db->aExtension[db->nExtension++] = handle;
   return SQLITE_OK;
+
+extension_not_found:
+  if( pzErrMsg ){
+    nMsg += 300;
+    *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
+    if( zErrmsg ){
+      assert( nMsg<0x7fffffff );  /* zErrmsg would be NULL if not so */
+      sqlite3_snprintf((int)nMsg, zErrmsg,
+          "unable to open shared library [%.*s]", SQLITE_MAX_PATHLEN, zFile);
+      sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
+    }
+  }
+  return SQLITE_ERROR;
 }
 SQLITE_API int sqlite3_load_extension(
   sqlite3 *db,          /* Load the extension into this database connection */
@@ -126959,13 +129895,14 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
 #define PragTyp_SOFT_HEAP_LIMIT               35
 #define PragTyp_SYNCHRONOUS                   36
 #define PragTyp_TABLE_INFO                    37
-#define PragTyp_TEMP_STORE                    38
-#define PragTyp_TEMP_STORE_DIRECTORY          39
-#define PragTyp_THREADS                       40
-#define PragTyp_WAL_AUTOCHECKPOINT            41
-#define PragTyp_WAL_CHECKPOINT                42
-#define PragTyp_LOCK_STATUS                   43
-#define PragTyp_STATS                         44
+#define PragTyp_TABLE_LIST                    38
+#define PragTyp_TEMP_STORE                    39
+#define PragTyp_TEMP_STORE_DIRECTORY          40
+#define PragTyp_THREADS                       41
+#define PragTyp_WAL_AUTOCHECKPOINT            42
+#define PragTyp_WAL_CHECKPOINT                43
+#define PragTyp_LOCK_STATUS                   44
+#define PragTyp_STATS                         45
 
 /* Property flags associated with various pragma. */
 #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
@@ -126998,45 +129935,51 @@ static const char *const pragCName[] = {
   /*  13 */ "pk",
   /*  14 */ "hidden",
                            /* table_info reuses 8 */
-  /*  15 */ "seqno",       /* Used by: index_xinfo */
-  /*  16 */ "cid",
-  /*  17 */ "name",
-  /*  18 */ "desc",
-  /*  19 */ "coll",
-  /*  20 */ "key",
-  /*  21 */ "name",        /* Used by: function_list */
-  /*  22 */ "builtin",
-  /*  23 */ "type",
-  /*  24 */ "enc",
-  /*  25 */ "narg",
-  /*  26 */ "flags",
-  /*  27 */ "tbl",         /* Used by: stats */
-  /*  28 */ "idx",
-  /*  29 */ "wdth",
-  /*  30 */ "hght",
-  /*  31 */ "flgs",
-  /*  32 */ "seq",         /* Used by: index_list */
-  /*  33 */ "name",
-  /*  34 */ "unique",
-  /*  35 */ "origin",
-  /*  36 */ "partial",
-  /*  37 */ "table",       /* Used by: foreign_key_check */
-  /*  38 */ "rowid",
-  /*  39 */ "parent",
-  /*  40 */ "fkid",
-                           /* index_info reuses 15 */
-  /*  41 */ "seq",         /* Used by: database_list */
-  /*  42 */ "name",
-  /*  43 */ "file",
-  /*  44 */ "busy",        /* Used by: wal_checkpoint */
-  /*  45 */ "log",
-  /*  46 */ "checkpointed",
-                           /* collation_list reuses 32 */
-  /*  47 */ "database",    /* Used by: lock_status */
-  /*  48 */ "status",
-  /*  49 */ "cache_size",  /* Used by: default_cache_size */
+  /*  15 */ "schema",      /* Used by: table_list */
+  /*  16 */ "name",
+  /*  17 */ "type",
+  /*  18 */ "ncol",
+  /*  19 */ "wr",
+  /*  20 */ "strict",
+  /*  21 */ "seqno",       /* Used by: index_xinfo */
+  /*  22 */ "cid",
+  /*  23 */ "name",
+  /*  24 */ "desc",
+  /*  25 */ "coll",
+  /*  26 */ "key",
+  /*  27 */ "name",        /* Used by: function_list */
+  /*  28 */ "builtin",
+  /*  29 */ "type",
+  /*  30 */ "enc",
+  /*  31 */ "narg",
+  /*  32 */ "flags",
+  /*  33 */ "tbl",         /* Used by: stats */
+  /*  34 */ "idx",
+  /*  35 */ "wdth",
+  /*  36 */ "hght",
+  /*  37 */ "flgs",
+  /*  38 */ "seq",         /* Used by: index_list */
+  /*  39 */ "name",
+  /*  40 */ "unique",
+  /*  41 */ "origin",
+  /*  42 */ "partial",
+  /*  43 */ "table",       /* Used by: foreign_key_check */
+  /*  44 */ "rowid",
+  /*  45 */ "parent",
+  /*  46 */ "fkid",
+                           /* index_info reuses 21 */
+  /*  47 */ "seq",         /* Used by: database_list */
+  /*  48 */ "name",
+  /*  49 */ "file",
+  /*  50 */ "busy",        /* Used by: wal_checkpoint */
+  /*  51 */ "log",
+  /*  52 */ "checkpointed",
+                           /* collation_list reuses 38 */
+  /*  53 */ "database",    /* Used by: lock_status */
+  /*  54 */ "status",
+  /*  55 */ "cache_size",  /* Used by: default_cache_size */
                            /* module_list pragma_list reuses 9 */
-  /*  50 */ "timeout",     /* Used by: busy_timeout */
+  /*  56 */ "timeout",     /* Used by: busy_timeout */
 };
 
 /* Definitions of all built-in pragmas */
@@ -127087,7 +130030,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "busy_timeout",
   /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 50, 1,
+  /* ColNames:  */ 56, 1,
   /* iArg:      */ 0 },
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  {/* zName:     */ "cache_size",
@@ -127126,7 +130069,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "collation_list",
   /* ePragTyp:  */ PragTyp_COLLATION_LIST,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 32, 2,
+  /* ColNames:  */ 38, 2,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
@@ -127161,14 +130104,14 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "database_list",
   /* ePragTyp:  */ PragTyp_DATABASE_LIST,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
-  /* ColNames:  */ 41, 3,
+  /* ColNames:  */ 47, 3,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  {/* zName:     */ "default_cache_size",
   /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
-  /* ColNames:  */ 49, 1,
+  /* ColNames:  */ 55, 1,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
@@ -127198,7 +130141,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "foreign_key_check",
   /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
-  /* ColNames:  */ 37, 4,
+  /* ColNames:  */ 43, 4,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
@@ -127241,7 +130184,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "function_list",
   /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 21, 6,
+  /* ColNames:  */ 27, 6,
   /* iArg:      */ 0 },
 #endif
 #endif
@@ -127270,23 +130213,23 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "index_info",
   /* ePragTyp:  */ PragTyp_INDEX_INFO,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
-  /* ColNames:  */ 15, 3,
+  /* ColNames:  */ 21, 3,
   /* iArg:      */ 0 },
  {/* zName:     */ "index_list",
   /* ePragTyp:  */ PragTyp_INDEX_LIST,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
-  /* ColNames:  */ 32, 5,
+  /* ColNames:  */ 38, 5,
   /* iArg:      */ 0 },
  {/* zName:     */ "index_xinfo",
   /* ePragTyp:  */ PragTyp_INDEX_INFO,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
-  /* ColNames:  */ 15, 6,
+  /* ColNames:  */ 21, 6,
   /* iArg:      */ 1 },
 #endif
 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  {/* zName:     */ "integrity_check",
   /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
-  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
+  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
   /* ColNames:  */ 0, 0,
   /* iArg:      */ 0 },
 #endif
@@ -127320,7 +130263,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "lock_status",
   /* ePragTyp:  */ PragTyp_LOCK_STATUS,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 47, 2,
+  /* ColNames:  */ 53, 2,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
@@ -127394,7 +130337,7 @@ static const PragmaName aPragmaName[] = {
 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  {/* zName:     */ "quick_check",
   /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
-  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
+  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
   /* ColNames:  */ 0, 0,
   /* iArg:      */ 0 },
 #endif
@@ -127459,7 +130402,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "stats",
   /* ePragTyp:  */ PragTyp_STATS,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
-  /* ColNames:  */ 27, 5,
+  /* ColNames:  */ 33, 5,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
@@ -127475,6 +130418,11 @@ static const PragmaName aPragmaName[] = {
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
   /* ColNames:  */ 8, 6,
   /* iArg:      */ 0 },
+ {/* zName:     */ "table_list",
+  /* ePragTyp:  */ PragTyp_TABLE_LIST,
+  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1,
+  /* ColNames:  */ 15, 6,
+  /* iArg:      */ 0 },
  {/* zName:     */ "table_xinfo",
   /* ePragTyp:  */ PragTyp_TABLE_INFO,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
@@ -127550,7 +130498,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "wal_checkpoint",
   /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
   /* ePragFlg:  */ PragFlg_NeedSchema,
-  /* ColNames:  */ 44, 3,
+  /* ColNames:  */ 50, 3,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
@@ -127561,7 +130509,7 @@ static const PragmaName aPragmaName[] = {
   /* iArg:      */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
 #endif
 };
-/* Number of pragmas: 67 on by default, 77 total. */
+/* Number of pragmas: 68 on by default, 78 total. */
 
 /************** End of pragma.h **********************************************/
 /************** Continuing where we left off in pragma.c *********************/
@@ -128003,7 +130951,11 @@ SQLITE_PRIVATE void sqlite3Pragma(
 
   /* Locate the pragma in the lookup table */
   pPragma = pragmaLocate(zLeft);
-  if( pPragma==0 ) goto pragma_out;
+  if( pPragma==0 ){
+    /* IMP: R-43042-22504 No error messages are generated if an
+    ** unknown pragma is issued. */
+    goto pragma_out;
+  }
 
   /* Make sure the database schema is loaded if the pragma requires that */
   if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
@@ -128653,6 +131605,14 @@ SQLITE_PRIVATE void sqlite3Pragma(
       }else{
         db->flags &= ~mask;
         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
+        if( (mask & SQLITE_WriteSchema)!=0
+         && sqlite3_stricmp(zRight, "reset")==0
+        ){
+          /* IMP: R-60817-01178 If the argument is "RESET" then schema
+          ** writing is disabled (as with "PRAGMA writable_schema=OFF") and,
+          ** in addition, the schema is reloaded. */
+          sqlite3ResetAllSchemasOfConnection(db);
+        }
       }
 
       /* Many of the flag-pragmas modify the code generated by the SQL
@@ -128693,6 +131653,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       sqlite3ViewGetColumnNames(pParse, pTab);
       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
         int isHidden = 0;
+        const Expr *pColExpr;
         if( pCol->colFlags & COLFLAG_NOINSERT ){
           if( pPragma->iArg==0 ){
             nHidden++;
@@ -128713,13 +131674,16 @@ SQLITE_PRIVATE void sqlite3Pragma(
         }else{
           for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
         }
-        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 );
+        pColExpr = sqlite3ColumnExpr(pTab,pCol);
+        assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
+        assert( pColExpr==0 || !ExprHasProperty(pColExpr, EP_IntValue)
+                  || isHidden>=2 );
         sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
                i-nHidden,
-               pCol->zName,
+               pCol->zCnName,
                sqlite3ColumnType(pCol,""),
                pCol->notNull ? 1 : 0,
-               pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0,
+               (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
                k,
                isHidden);
       }
@@ -128727,6 +131691,85 @@ SQLITE_PRIVATE void sqlite3Pragma(
   }
   break;
 
+  /*
+  **   PRAGMA table_list
+  **
+  ** Return a single row for each table, virtual table, or view in the
+  ** entire schema.
+  **
+  ** schema:     Name of attached database hold this table
+  ** name:       Name of the table itself
+  ** type:       "table", "view", "virtual", "shadow"
+  ** ncol:       Number of columns
+  ** wr:         True for a WITHOUT ROWID table
+  ** strict:     True for a STRICT table
+  */
+  case PragTyp_TABLE_LIST: {
+    int ii;
+    pParse->nMem = 6;
+    sqlite3CodeVerifyNamedSchema(pParse, zDb);
+    for(ii=0; ii<db->nDb; ii++){
+      HashElem *k;
+      Hash *pHash;
+      int initNCol;
+      if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
+
+      /* Ensure that the Table.nCol field is initialized for all views
+      ** and virtual tables.  Each time we initialize a Table.nCol value
+      ** for a table, that can potentially disrupt the hash table, so restart
+      ** the initialization scan.
+      */
+      pHash = &db->aDb[ii].pSchema->tblHash;
+      initNCol = sqliteHashCount(pHash);
+      while( initNCol-- ){
+        for(k=sqliteHashFirst(pHash); 1; k=sqliteHashNext(k) ){
+          Table *pTab;
+          if( k==0 ){ initNCol = 0; break; }
+          pTab = sqliteHashData(k);
+          if( pTab->nCol==0 ){
+            char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
+            if( zSql ){
+              sqlite3_stmt *pDummy = 0;
+              (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0);
+              (void)sqlite3_finalize(pDummy);
+              sqlite3DbFree(db, zSql);
+            }
+            if( db->mallocFailed ){
+              sqlite3ErrorMsg(db->pParse, "out of memory");
+              db->pParse->rc = SQLITE_NOMEM_BKPT;
+            }
+            pHash = &db->aDb[ii].pSchema->tblHash;
+            break;
+          }
+        }
+      }
+
+      for(k=sqliteHashFirst(pHash); k; k=sqliteHashNext(k) ){
+        Table *pTab = sqliteHashData(k);
+        const char *zType;
+        if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
+        if( IsView(pTab) ){
+          zType = "view";
+        }else if( IsVirtual(pTab) ){
+          zType = "virtual";
+        }else if( pTab->tabFlags & TF_Shadow ){
+          zType = "shadow";
+        }else{
+          zType = "table";
+        }
+        sqlite3VdbeMultiLoad(v, 1, "sssiii",
+           db->aDb[ii].zDbSName,
+           sqlite3PreferredTableName(pTab->zName),
+           zType,
+           pTab->nCol,
+           (pTab->tabFlags & TF_WithoutRowid)!=0,
+           (pTab->tabFlags & TF_Strict)!=0
+        );
+      }
+    }
+  }
+  break;
+
 #ifdef SQLITE_DEBUG
   case PragTyp_STATS: {
     Index *pIdx;
@@ -128736,7 +131779,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
       Table *pTab = sqliteHashData(i);
       sqlite3VdbeMultiLoad(v, 1, "ssiii",
-           pTab->zName,
+           sqlite3PreferredTableName(pTab->zName),
            0,
            pTab->szTabRow,
            pTab->nRowLogEst,
@@ -128786,7 +131829,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       for(i=0; i<mx; i++){
         i16 cnum = pIdx->aiColumn[i];
         sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
-                             cnum<0 ? 0 : pTab->aCol[cnum].zName);
+                             cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
         if( pPragma->iArg ){
           sqlite3VdbeMultiLoad(v, 4, "isiX",
             pIdx->aSortOrder[i],
@@ -128855,11 +131898,13 @@ SQLITE_PRIVATE void sqlite3Pragma(
     pParse->nMem = 6;
     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
+        assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
         pragmaFunclistLine(v, p, 1, showInternFunc);
       }
     }
     for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
       p = (FuncDef*)sqliteHashData(j);
+      assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
       pragmaFunclistLine(v, p, 0, showInternFunc);
     }
   }
@@ -128893,8 +131938,8 @@ SQLITE_PRIVATE void sqlite3Pragma(
     FKey *pFK;
     Table *pTab;
     pTab = sqlite3FindTable(db, zRight, zDb);
-    if( pTab ){
-      pFK = pTab->pFKey;
+    if( pTab && IsOrdinaryTable(pTab) ){
+      pFK = pTab->u.tab.pFKey;
       if( pFK ){
         int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
         int i = 0;
@@ -128907,7 +131952,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
                    i,
                    j,
                    pFK->zTo,
-                   pTab->aCol[pFK->aCol[j].iFrom].zName,
+                   pTab->aCol[pFK->aCol[j].iFrom].zCnName,
                    pFK->aCol[j].zCol,
                    actionName(pFK->aAction[1]),  /* ON UPDATE */
                    actionName(pFK->aAction[0]),  /* ON DELETE */
@@ -128953,7 +131998,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
         pTab = (Table*)sqliteHashData(k);
         k = sqliteHashNext(k);
       }
-      if( pTab==0 || pTab->pFKey==0 ) continue;
+      if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
       iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
       zDb = db->aDb[iDb].zDbSName;
       sqlite3CodeVerifySchema(pParse, iDb);
@@ -128961,7 +132006,8 @@ SQLITE_PRIVATE void sqlite3Pragma(
       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
       sqlite3VdbeLoadString(v, regResult, pTab->zName);
-      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
+      assert( IsOrdinaryTable(pTab) );
+      for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
         if( pParent==0 ) continue;
         pIdx = 0;
@@ -128983,7 +132029,8 @@ SQLITE_PRIVATE void sqlite3Pragma(
       if( pFK ) break;
       if( pParse->nTab<i ) pParse->nTab = i;
       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
-      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
+      assert( IsOrdinaryTable(pTab) );
+      for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
         pIdx = 0;
         aiCols = 0;
@@ -128997,6 +132044,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
         ** regRow..regRow+n. If any of the child key values are NULL, this
         ** row cannot cause an FK violation. Jump directly to addrOk in
         ** this case. */
+        if( regRow+pFK->nCol>pParse->nMem ) pParse->nMem = regRow+pFK->nCol;
         for(j=0; j<pFK->nCol; j++){
           int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
           sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
@@ -129183,8 +132231,9 @@ SQLITE_PRIVATE void sqlite3Pragma(
         int loopTop;
         int iDataCur, iIdxCur;
         int r1 = -1;
+        int bStrict;
 
-        if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
+        if( !IsOrdinaryTable(pTab) ) continue;
         if( pObjTab && pObjTab!=pTab ) continue;
         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
@@ -129204,23 +132253,48 @@ SQLITE_PRIVATE void sqlite3Pragma(
           /* Sanity check on record header decoding */
           sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3);
           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
+          VdbeComment((v, "(right-most column)"));
         }
-        /* Verify that all NOT NULL columns really are NOT NULL */
+        /* Verify that all NOT NULL columns really are NOT NULL.  At the
+        ** same time verify the type of the content of STRICT tables */
+        bStrict = (pTab->tabFlags & TF_Strict)!=0;
         for(j=0; j<pTab->nCol; j++){
           char *zErr;
-          int jmp2;
+          Column *pCol = pTab->aCol + j;
+          int doError, jmp2;
           if( j==pTab->iPKey ) continue;
-          if( pTab->aCol[j].notNull==0 ) continue;
+          if( pCol->notNull==0 && !bStrict ) continue;
+          doError = bStrict ? sqlite3VdbeMakeLabel(pParse) : 0;
           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
           if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){
             sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
           }
-          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
-          zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
-                              pTab->aCol[j].zName);
-          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
-          integrityCheckResultRow(v);
-          sqlite3VdbeJumpHere(v, jmp2);
+          if( pCol->notNull ){
+            jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
+            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
+                                pCol->zCnName);
+            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
+            if( bStrict && pCol->eCType!=COLTYPE_ANY ){
+              sqlite3VdbeGoto(v, doError);
+            }else{
+              integrityCheckResultRow(v);
+            }
+            sqlite3VdbeJumpHere(v, jmp2);
+          }
+          if( (pTab->tabFlags & TF_Strict)!=0
+           && pCol->eCType!=COLTYPE_ANY
+          ){
+            jmp2 = sqlite3VdbeAddOp3(v, OP_IsNullOrType, 3, 0,
+                                     sqlite3StdTypeMap[pCol->eCType-1]);
+            VdbeCoverage(v);
+            zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
+                                  sqlite3StdType[pCol->eCType-1],
+                                  pTab->zName, pTab->aCol[j].zCnName);
+            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
+            sqlite3VdbeResolveLabel(v, doError);
+            integrityCheckResultRow(v);
+            sqlite3VdbeJumpHere(v, jmp2);
+          }
         }
         /* Verify CHECK constraints */
         if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
@@ -129754,12 +132828,12 @@ SQLITE_PRIVATE void sqlite3Pragma(
   case PragTyp_ANALYSIS_LIMIT: {
     sqlite3_int64 N;
     if( zRight
-     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
+     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
      && N>=0
     ){
       db->nAnalysisLimit = (int)(N&0x7fffffff);
     }
-    returnSingleInt(v, db->nAnalysisLimit);
+    returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
     break;
   }
 
@@ -130161,10 +133235,15 @@ static void corruptSchema(
     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_AlterRename|INITFLAG_AlterDrop) ){
+  }else if( pData->mInitFlags & (INITFLAG_AlterMask) ){
+    static const char *azAlterType[] = {
+       "rename",
+       "drop column",
+       "add column"
+    };
     *pData->pzErrMsg = sqlite3MPrintf(db,
         "error in %s %s after %s: %s", azObj[0], azObj[1],
-        (pData->mInitFlags & INITFLAG_AlterRename) ? "rename" : "drop column",
+        azAlterType[(pData->mInitFlags&INITFLAG_AlterMask)-1],
         zExtra
     );
     pData->rc = SQLITE_ERROR;
@@ -130228,6 +133307,7 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char
   UNUSED_PARAMETER2(NotUsed, argc);
   assert( sqlite3_mutex_held(db->mutex) );
   db->mDbFlags |= DBFLAG_EncodingFixed;
+  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   pData->nInitRow++;
   if( db->mallocFailed ){
     corruptSchema(pData, argv, 0);
@@ -130235,7 +133315,6 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char
   }
 
   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, 0);
   }else if( argv[4]
@@ -130266,7 +133345,7 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char
       }
     }
     db->init.orphanTrigger = 0;
-    db->init.azInit = argv;
+    db->init.azInit = (const char**)argv;
     pStmt = 0;
     TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
     rc = db->errCode;
@@ -130285,6 +133364,7 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char
         }
       }
     }
+    db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
     sqlite3_finalize(pStmt);
   }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
     corruptSchema(pData, argv, 0);
@@ -130509,18 +133589,22 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
     }
 #endif
   }
+  assert( pDb == &(db->aDb[iDb]) );
   if( db->mallocFailed ){
     rc = SQLITE_NOMEM_BKPT;
     sqlite3ResetAllSchemasOfConnection(db);
-  }
-  if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
-    /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
-    ** the schema loaded, even if errors occurred. In this situation the
-    ** current sqlite3_prepare() operation will fail, but the following one
-    ** will attempt to compile the supplied statement against whatever subset
-    ** of the schema was loaded before the error occurred. The primary
-    ** purpose of this is to allow access to the sqlite_schema table
-    ** even when its contents have been corrupted.
+    pDb = &db->aDb[iDb];
+  }else
+  if( rc==SQLITE_OK || ((db->flags&SQLITE_NoSchemaError) && rc!=SQLITE_NOMEM)){
+    /* Hack: If the SQLITE_NoSchemaError flag is set, then consider
+    ** the schema loaded, even if errors (other than OOM) occurred. In
+    ** this situation the current sqlite3_prepare() operation will fail,
+    ** but the following one will attempt to compile the supplied statement
+    ** against whatever subset of the schema was loaded before the error
+    ** occurred.
+    **
+    ** The primary purpose of this is to allow access to the sqlite_schema
+    ** table even when its contents have been corrupted.
     */
     DbSetProperty(db, iDb, DB_SchemaLoaded);
     rc = SQLITE_OK;
@@ -130630,6 +133714,7 @@ static void schemaIsValid(Parse *pParse){
       rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
         sqlite3OomFault(db);
+        pParse->rc = SQLITE_NOMEM;
       }
       if( rc!=SQLITE_OK ) return;
       openedTransaction = 1;
@@ -130689,8 +133774,14 @@ SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
 /*
 ** Free all memory allocations in the pParse object
 */
-SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
+SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse *pParse){
   sqlite3 *db = pParse->db;
+  assert( db!=0 );
+  assert( db->pParse==pParse );
+  assert( pParse->nested==0 );
+#ifndef SQLITE_OMIT_SHARED_CACHE
+  sqlite3DbFree(db, pParse->aTableLock);
+#endif
   while( pParse->pCleanup ){
     ParseCleanup *pCleanup = pParse->pCleanup;
     pParse->pCleanup = pCleanup->pNext;
@@ -130701,11 +133792,12 @@ SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
   if( pParse->pConstExpr ){
     sqlite3ExprListDelete(db, pParse->pConstExpr);
   }
-  if( db ){
-    assert( db->lookaside.bDisable >= pParse->disableLookaside );
-    db->lookaside.bDisable -= pParse->disableLookaside;
-    db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
-  }
+  assert( db->lookaside.bDisable >= pParse->disableLookaside );
+  db->lookaside.bDisable -= pParse->disableLookaside;
+  db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
+  assert( pParse->db->pParse==pParse );
+  db->pParse = pParse->pOuterParse;
+  pParse->db = 0;
   pParse->disableLookaside = 0;
 }
 
@@ -130718,7 +133810,7 @@ SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
 ** 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.
+** sqlite3ParseObjectReset(), 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
@@ -130758,6 +133850,33 @@ SQLITE_PRIVATE void *sqlite3ParserAddCleanup(
   return pPtr;
 }
 
+/*
+** Turn bulk memory into a valid Parse object and link that Parse object
+** into database connection db.
+**
+** Call sqlite3ParseObjectReset() to undo this operation.
+**
+** Caution:  Do not confuse this routine with sqlite3ParseObjectInit() which
+** is generated by Lemon.
+*/
+SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
+  memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
+  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
+  assert( db->pParse!=pParse );
+  pParse->pOuterParse = db->pParse;
+  db->pParse = pParse;
+  pParse->db = db;
+  if( db->mallocFailed ) sqlite3ErrorMsg(pParse, "out of memory");
+}
+
+/*
+** Maximum number of times that we will try again to prepare a statement
+** that returns SQLITE_ERROR_RETRY.
+*/
+#ifndef SQLITE_MAX_PREPARE_RETRY
+# define SQLITE_MAX_PREPARE_RETRY 25
+#endif
+
 /*
 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
 */
@@ -130770,16 +133889,19 @@ static int sqlite3Prepare(
   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   const char **pzTail       /* OUT: End of parsed string */
 ){
-  char *zErrMsg = 0;        /* Error message */
   int rc = SQLITE_OK;       /* Result code */
   int i;                    /* Loop counter */
   Parse sParse;             /* Parsing context */
 
-  memset(&sParse, 0, PARSE_HDR_SZ);
+  /* sqlite3ParseObjectInit(&sParse, db); // inlined for performance */
+  memset(PARSE_HDR(&sParse), 0, PARSE_HDR_SZ);
   memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
+  sParse.pOuterParse = db->pParse;
+  db->pParse = &sParse;
+  sParse.db = db;
   sParse.pReprepare = pReprepare;
   assert( ppStmt && *ppStmt==0 );
-  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
+  if( db->mallocFailed ) sqlite3ErrorMsg(&sParse, "out of memory");
   assert( sqlite3_mutex_held(db->mutex) );
 
   /* For a long-term use prepared statement avoid the use of
@@ -130832,7 +133954,6 @@ static int sqlite3Prepare(
 
   sqlite3VtabUnlockList(db);
 
-  sParse.db = db;
   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
     char *zSqlCopy;
     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
@@ -130845,14 +133966,14 @@ static int sqlite3Prepare(
     }
     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
     if( zSqlCopy ){
-      sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
+      sqlite3RunParser(&sParse, zSqlCopy);
       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
       sqlite3DbFree(db, zSqlCopy);
     }else{
       sParse.zTail = &zSql[nBytes];
     }
   }else{
-    sqlite3RunParser(&sParse, zSql, &zErrMsg);
+    sqlite3RunParser(&sParse, zSql);
   }
   assert( 0==sParse.nQueryLoop );
 
@@ -130865,9 +133986,10 @@ static int sqlite3Prepare(
   }
   if( db->mallocFailed ){
     sParse.rc = SQLITE_NOMEM_BKPT;
+    sParse.checkSchema = 0;
   }
   if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){
-    if( sParse.checkSchema ){
+    if( sParse.checkSchema && db->init.busy==0 ){
       schemaIsValid(&sParse);
     }
     if( sParse.pVdbe ){
@@ -130875,14 +133997,14 @@ static int sqlite3Prepare(
     }
     assert( 0==(*ppStmt) );
     rc = sParse.rc;
-    if( zErrMsg ){
-      sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
-      sqlite3DbFree(db, zErrMsg);
+    if( sParse.zErrMsg ){
+      sqlite3ErrorWithMsg(db, rc, "%s", sParse.zErrMsg);
+      sqlite3DbFree(db, sParse.zErrMsg);
     }else{
       sqlite3Error(db, rc);
     }
   }else{
-    assert( zErrMsg==0 );
+    assert( sParse.zErrMsg==0 );
     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
     rc = SQLITE_OK;
     sqlite3ErrorClear(db);
@@ -130898,7 +134020,7 @@ static int sqlite3Prepare(
 
 end_prepare:
 
-  sqlite3ParserReset(&sParse);
+  sqlite3ParseObjectReset(&sParse);
   return rc;
 }
 static int sqlite3LockAndPrepare(
@@ -130928,7 +134050,8 @@ static int sqlite3LockAndPrepare(
     ** reset is considered a permanent error. */
     rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
     assert( rc==SQLITE_OK || *ppStmt==0 );
-  }while( rc==SQLITE_ERROR_RETRY
+    if( rc==SQLITE_OK || db->mallocFailed ) break;
+  }while( (rc==SQLITE_ERROR_RETRY && (cnt++)<SQLITE_MAX_PREPARE_RETRY)
        || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
   sqlite3BtreeLeaveAll(db);
   rc = sqlite3ApiExit(db, rc);
@@ -131419,7 +134542,7 @@ SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol){
   u8 h = sqlite3StrIHash(zCol);
   Column *pCol;
   for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
-    if( pCol->hName==h && sqlite3StrICmp(pCol->zName, zCol)==0 ) return i;
+    if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;
   }
   return -1;
 }
@@ -131495,18 +134618,21 @@ static void addWhereTerm(
   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
 
   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
+  assert( pE2!=0 || pEq==0 );  /* Due to db->mallocFailed test
+                               ** in sqlite3DbMallocRawNN() called from
+                               ** sqlite3PExpr(). */
   if( pEq && isOuterJoin ){
     ExprSetProperty(pEq, EP_FromJoin);
     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
     ExprSetVVAProperty(pEq, EP_NoReduce);
-    pEq->iRightJoinTable = pE2->iTable;
+    pEq->w.iRightJoinTable = pE2->iTable;
   }
   *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
 }
 
 /*
 ** Set the EP_FromJoin property on all terms of the given expression.
-** And set the Expr.iRightJoinTable to iTable for every term in the
+** And set the Expr.w.iRightJoinTable to iTable for every term in the
 ** expression.
 **
 ** The EP_FromJoin property is used on terms of an expression to tell
@@ -131516,8 +134642,8 @@ static void addWhereTerm(
 ** WHERE clause during join processing but we need to remember that they
 ** originated in the ON or USING clause.
 **
-** The Expr.iRightJoinTable tells the WHERE clause processing that the
-** expression depends on table iRightJoinTable even if that table is not
+** The Expr.w.iRightJoinTable tells the WHERE clause processing that the
+** expression depends on table w.iRightJoinTable even if that table is not
 ** explicitly mentioned in the expression.  That information is needed
 ** for cases like this:
 **
@@ -131535,11 +134661,14 @@ SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){
     ExprSetProperty(p, EP_FromJoin);
     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
     ExprSetVVAProperty(p, EP_NoReduce);
-    p->iRightJoinTable = iTable;
-    if( p->op==TK_FUNCTION && p->x.pList ){
-      int i;
-      for(i=0; i<p->x.pList->nExpr; i++){
-        sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
+    p->w.iRightJoinTable = iTable;
+    if( p->op==TK_FUNCTION ){
+      assert( ExprUseXList(p) );
+      if( p->x.pList ){
+        int i;
+        for(i=0; i<p->x.pList->nExpr; i++){
+          sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
+        }
       }
     }
     sqlite3SetJoinExpr(p->pLeft, iTable);
@@ -131548,7 +134677,7 @@ SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){
 }
 
 /* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every
-** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
+** term that is marked with EP_FromJoin and w.iRightJoinTable==iTable into
 ** an ordinary term that omits the EP_FromJoin mark.
 **
 ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
@@ -131556,16 +134685,19 @@ SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){
 static void unsetJoinExpr(Expr *p, int iTable){
   while( p ){
     if( ExprHasProperty(p, EP_FromJoin)
-     && (iTable<0 || p->iRightJoinTable==iTable) ){
+     && (iTable<0 || p->w.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++){
-        unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
+    if( p->op==TK_FUNCTION ){
+      assert( ExprUseXList(p) );
+      if( p->x.pList ){
+        int i;
+        for(i=0; i<p->x.pList->nExpr; i++){
+          unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
+        }
       }
     }
     unsetJoinExpr(p->pLeft, iTable);
@@ -131618,7 +134750,7 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){
         int iLeftCol;  /* Matching column in the left table */
 
         if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
-        zName = pRightTab->aCol[j].zName;
+        zName = pRightTab->aCol[j].zCnName;
         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){
           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
                 isOuter, &p->pWhere);
@@ -131889,31 +135021,157 @@ static void codeOffset(
 }
 
 /*
-** Add code that will check to make sure the N registers starting at iMem
-** form a distinct entry.  iTab is a sorting index that holds previously
-** seen combinations of the N values.  A new entry is made in iTab
-** if the current N values are new.
+** Add code that will check to make sure the array of registers starting at
+** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and
+** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies
+** are available. Which is used depends on the value of parameter eTnctType,
+** as follows:
 **
-** A jump to addrRepeat is made and the N+1 values are popped from the
-** stack if the top N elements are not distinct.
-*/
-static void codeDistinct(
+**   WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP:
+**     Build an ephemeral table that contains all entries seen before and
+**     skip entries which have been seen before.
+**
+**     Parameter iTab is the cursor number of an ephemeral table that must
+**     be opened before the VM code generated by this routine is executed.
+**     The ephemeral cursor table is queried for a record identical to the
+**     record formed by the current array of registers. If one is found,
+**     jump to VM address addrRepeat. Otherwise, insert a new record into
+**     the ephemeral cursor and proceed.
+**
+**     The returned value in this case is a copy of parameter iTab.
+**
+**   WHERE_DISTINCT_ORDERED:
+**     In this case rows are being delivered sorted order. The ephermal
+**     table is not required. Instead, the current set of values
+**     is compared against previous row. If they match, the new row
+**     is not distinct and control jumps to VM address addrRepeat. Otherwise,
+**     the VM program proceeds with processing the new row.
+**
+**     The returned value in this case is the register number of the first
+**     in an array of registers used to store the previous result row so that
+**     it can be compared to the next. The caller must ensure that this
+**     register is initialized to NULL.  (The fixDistinctOpenEph() routine
+**     will take care of this initialization.)
+**
+**   WHERE_DISTINCT_UNIQUE:
+**     In this case it has already been determined that the rows are distinct.
+**     No special action is required. The return value is zero.
+**
+** Parameter pEList is the list of expressions used to generated the
+** contents of each row. It is used by this routine to determine (a)
+** how many elements there are in the array of registers and (b) the
+** collation sequences that should be used for the comparisons if
+** eTnctType is WHERE_DISTINCT_ORDERED.
+*/
+static int codeDistinct(
   Parse *pParse,     /* Parsing and code generating context */
+  int eTnctType,     /* WHERE_DISTINCT_* value */
   int iTab,          /* A sorting index used to test for distinctness */
   int addrRepeat,    /* Jump to here if not distinct */
-  int N,             /* Number of elements */
-  int iMem           /* First element */
+  ExprList *pEList,  /* Expression for each element */
+  int regElem        /* First element */
 ){
-  Vdbe *v;
-  int r1;
+  int iRet = 0;
+  int nResultCol = pEList->nExpr;
+  Vdbe *v = pParse->pVdbe;
 
-  v = pParse->pVdbe;
-  r1 = sqlite3GetTempReg(pParse);
-  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
-  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
-  sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
-  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
-  sqlite3ReleaseTempReg(pParse, r1);
+  switch( eTnctType ){
+    case WHERE_DISTINCT_ORDERED: {
+      int i;
+      int iJump;              /* Jump destination */
+      int regPrev;            /* Previous row content */
+
+      /* Allocate space for the previous row */
+      iRet = regPrev = pParse->nMem+1;
+      pParse->nMem += nResultCol;
+
+      iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
+      for(i=0; i<nResultCol; i++){
+        CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
+        if( i<nResultCol-1 ){
+          sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i);
+          VdbeCoverage(v);
+        }else{
+          sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i);
+          VdbeCoverage(v);
+         }
+        sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
+        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
+      }
+      assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
+      sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
+      break;
+    }
+
+    case WHERE_DISTINCT_UNIQUE: {
+      /* nothing to do */
+      break;
+    }
+
+    default: {
+      int r1 = sqlite3GetTempReg(pParse);
+      sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol);
+      VdbeCoverage(v);
+      sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1);
+      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol);
+      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
+      sqlite3ReleaseTempReg(pParse, r1);
+      iRet = iTab;
+      break;
+    }
+  }
+
+  return iRet;
+}
+
+/*
+** This routine runs after codeDistinct().  It makes necessary
+** adjustments to the OP_OpenEphemeral opcode that the codeDistinct()
+** routine made use of.  This processing must be done separately since
+** sometimes codeDistinct is called before the OP_OpenEphemeral is actually
+** laid down.
+**
+** WHERE_DISTINCT_NOOP:
+** WHERE_DISTINCT_UNORDERED:
+**
+**     No adjustments necessary.  This function is a no-op.
+**
+** WHERE_DISTINCT_UNIQUE:
+**
+**     The ephemeral table is not needed.  So change the
+**     OP_OpenEphemeral opcode into an OP_Noop.
+**
+** WHERE_DISTINCT_ORDERED:
+**
+**     The ephemeral table is not needed.  But we do need register
+**     iVal to be initialized to NULL.  So change the OP_OpenEphemeral
+**     into an OP_Null on the iVal register.
+*/
+static void fixDistinctOpenEph(
+  Parse *pParse,     /* Parsing and code generating context */
+  int eTnctType,     /* WHERE_DISTINCT_* value */
+  int iVal,          /* Value returned by codeDistinct() */
+  int iOpenEphAddr   /* Address of OP_OpenEphemeral instruction for iTab */
+){
+  if( pParse->nErr==0
+   && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED)
+  ){
+    Vdbe *v = pParse->pVdbe;
+    sqlite3VdbeChangeToNoop(v, iOpenEphAddr);
+    if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
+      sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1);
+    }
+    if( eTnctType==WHERE_DISTINCT_ORDERED ){
+      /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
+      ** bit on the first register of the previous value.  This will cause the
+      ** OP_Ne added in codeDistinct() to always fail on the first iteration of
+      ** the loop even if the first row is all NULLs.  */
+      VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr);
+      pOp->opcode = OP_Null;
+      pOp->p1 = 1;
+      pOp->p2 = iVal;
+    }
+  }
 }
 
 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
@@ -131954,9 +135212,13 @@ static void selectExprDefer(
     struct ExprList_item *pItem = &pEList->a[i];
     if( pItem->u.x.iOrderByCol==0 ){
       Expr *pExpr = pItem->pExpr;
-      Table *pTab = pExpr->y.pTab;
-      if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
-       && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
+      Table *pTab;
+      if( pExpr->op==TK_COLUMN
+       && pExpr->iColumn>=0
+       && ALWAYS( ExprUseYTab(pExpr) )
+       && (pTab = pExpr->y.pTab)!=0
+       && IsOrdinaryTable(pTab)
+       && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
       ){
         int j;
         for(j=0; j<nDefer; j++){
@@ -131977,6 +135239,7 @@ static void selectExprDefer(
               Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
               if( pNew ){
                 pNew->iTable = pExpr->iTable;
+                assert( ExprUseYTab(pNew) );
                 pNew->y.pTab = pExpr->y.pTab;
                 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
                 pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
@@ -132161,59 +135424,11 @@ static void selectInnerLoop(
   ** part of the result.
   */
   if( hasDistinct ){
-    switch( pDistinct->eTnctType ){
-      case WHERE_DISTINCT_ORDERED: {
-        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
-        int iJump;              /* Jump destination */
-        int regPrev;            /* Previous row content */
-
-        /* Allocate space for the previous row */
-        regPrev = pParse->nMem+1;
-        pParse->nMem += nResultCol;
-
-        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
-        ** sets the MEM_Cleared bit on the first register of the
-        ** previous value.  This will cause the OP_Ne below to always
-        ** fail on the first iteration of the loop even if the first
-        ** row is all NULLs.
-        */
-        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
-        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
-        pOp->opcode = OP_Null;
-        pOp->p1 = 1;
-        pOp->p2 = regPrev;
-        pOp = 0;  /* Ensure pOp is not used after sqlite3VdbeAddOp() */
-
-        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
-        for(i=0; i<nResultCol; i++){
-          CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
-          if( i<nResultCol-1 ){
-            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
-            VdbeCoverage(v);
-          }else{
-            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
-            VdbeCoverage(v);
-           }
-          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
-          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
-        }
-        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
-        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
-        break;
-      }
-
-      case WHERE_DISTINCT_UNIQUE: {
-        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
-        break;
-      }
-
-      default: {
-        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
-        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
-                     regResult);
-        break;
-      }
-    }
+    int eType = pDistinct->eTnctType;
+    int iTab = pDistinct->tabTnct;
+    assert( nResultCol==p->pEList->nExpr );
+    iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
+    fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
     if( pSort==0 ){
       codeOffset(v, p->iOffset, iContinue);
     }
@@ -132460,7 +135675,7 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
     p->nRef = 1;
     memset(&p[1], 0, nExtra);
   }else{
-    sqlite3OomFault(db);
+    return (KeyInfo*)sqlite3OomFault(db);
   }
   return p;
 }
@@ -132631,6 +135846,9 @@ static void generateSortTail(
 
   iTab = pSort->iECursor;
   if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
+    if( eDest==SRT_Mem && p->iOffset ){
+      sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
+    }
     regRowid = 0;
     regRow = pDest->iSdst;
   }else{
@@ -132873,13 +136091,19 @@ static const char *columnTypeImpl(
         break;
       }
 
-      assert( pTab && pExpr->y.pTab==pTab );
+      assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
       if( pS ){
         /* The "table" is actually a sub-select or a view in the FROM clause
         ** of the SELECT statement. Return the declaration type and origin
         ** data for the result-set column of the sub-select.
         */
-        if( iCol>=0 && iCol<pS->pEList->nExpr ){
+        if( iCol<pS->pEList->nExpr
+#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
+         && iCol>=0
+#else
+         && ALWAYS(iCol>=0)
+#endif
+        ){
           /* If iCol is less than zero, then the expression requests the
           ** rowid of the sub-select or view. This expression is legal (see
           ** test case misc2.2.2) - it always evaluates to NULL.
@@ -132901,7 +136125,7 @@ static const char *columnTypeImpl(
           zType = "INTEGER";
           zOrigCol = "rowid";
         }else{
-          zOrigCol = pTab->aCol[iCol].zName;
+          zOrigCol = pTab->aCol[iCol].zCnName;
           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
         }
         zOrigTab = pTab->zName;
@@ -132927,9 +136151,11 @@ static const char *columnTypeImpl(
       ** statement.
       */
       NameContext sNC;
-      Select *pS = pExpr->x.pSelect;
-      Expr *p = pS->pEList->a[0].pExpr;
-      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
+      Select *pS;
+      Expr *p;
+      assert( ExprUseXSelect(pExpr) );
+      pS = pExpr->x.pSelect;
+      p = pS->pEList->a[0].pExpr;
       sNC.pSrcList = pS->pSrc;
       sNC.pNext = pNC;
       sNC.pParse = pNC->pParse;
@@ -133021,7 +136247,7 @@ static void generateColumnTypes(
 **                              then the result column name with the table name
 **                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
 */
-static void generateColumnNames(
+SQLITE_PRIVATE void sqlite3GenerateColumnNames(
   Parse *pParse,      /* Parser context */
   Select *pSelect     /* Generate column names for this SELECT statement */
 ){
@@ -133058,7 +136284,8 @@ static void generateColumnNames(
 
     assert( p!=0 );
     assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
-    assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
+    assert( p->op!=TK_COLUMN
+        || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
     if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){
       /* An AS clause always takes first priority */
       char *zName = pEList->a[i].zEName;
@@ -133073,7 +136300,7 @@ static void generateColumnNames(
       if( iCol<0 ){
         zCol = "rowid";
       }else{
-        zCol = pTab->aCol[iCol].zName;
+        zCol = pTab->aCol[iCol].zCnName;
       }
       if( fullName ){
         char *zName = 0;
@@ -133111,7 +136338,7 @@ static void generateColumnNames(
 ** and will break if those assumptions changes.  Hence, use extreme caution
 ** when modifying this routine to avoid breaking legacy.
 **
-** See Also: generateColumnNames()
+** See Also: sqlite3GenerateColumnNames()
 */
 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
   Parse *pParse,          /* Parsing context */
@@ -133154,11 +136381,14 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
         pColExpr = pColExpr->pRight;
         assert( pColExpr!=0 );
       }
-      if( pColExpr->op==TK_COLUMN && (pTab = pColExpr->y.pTab)!=0 ){
+      if( pColExpr->op==TK_COLUMN
+       && ALWAYS( ExprUseYTab(pColExpr) )
+       && (pTab = pColExpr->y.pTab)!=0
+      ){
         /* For columns use the column name name */
         int iCol = pColExpr->iColumn;
         if( iCol<0 ) iCol = pTab->iPKey;
-        zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
+        zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
       }else if( pColExpr->op==TK_ID ){
         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
         zName = pColExpr->u.zToken;
@@ -133186,7 +136416,7 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
       zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
     }
-    pCol->zName = zName;
+    pCol->zCnName = zName;
     pCol->hName = sqlite3StrIHash(zName);
     sqlite3ColumnPropertiesFromName(0, pCol);
     if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
@@ -133196,7 +136426,7 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
   sqlite3HashClear(&ht);
   if( db->mallocFailed ){
     for(j=0; j<i; j++){
-      sqlite3DbFree(db, aCol[j].zName);
+      sqlite3DbFree(db, aCol[j].zCnName);
     }
     sqlite3DbFree(db, aCol);
     *paCol = 0;
@@ -133240,7 +136470,7 @@ SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
   a = pSelect->pEList->a;
   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
     const char *zType;
-    int n, m;
+    i64 n, m;
     pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
     p = a[i].pExpr;
     zType = columnType(&sNC, p, 0, 0, 0);
@@ -133248,17 +136478,21 @@ SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
     pCol->affinity = sqlite3ExprAffinity(p);
     if( zType ){
       m = sqlite3Strlen30(zType);
-      n = sqlite3Strlen30(pCol->zName);
-      pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
-      if( pCol->zName ){
-        memcpy(&pCol->zName[n+1], zType, m+1);
+      n = sqlite3Strlen30(pCol->zCnName);
+      pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);
+      if( pCol->zCnName ){
+        memcpy(&pCol->zCnName[n+1], zType, m+1);
         pCol->colFlags |= COLFLAG_HASTYPE;
+      }else{
+        testcase( pCol->colFlags & COLFLAG_HASTYPE );
+        pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
       }
     }
     if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
     pColl = sqlite3ExprCollSeq(pParse, p);
-    if( pColl && pCol->zColl==0 ){
-      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
+    if( pColl ){
+      assert( pTab->pIndex==0 );
+      sqlite3ColumnSetColl(db, pCol, pColl->zName);
     }
   }
   pTab->szTabRow = 1; /* Any non-zero value works */
@@ -133422,7 +136656,7 @@ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
 */
 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
   ExprList *pOrderBy = p->pOrderBy;
-  int nOrderBy = p->pOrderBy->nExpr;
+  int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
   sqlite3 *db = pParse->db;
   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
   if( pRet ){
@@ -133494,7 +136728,7 @@ static void generateWithRecursiveQuery(
   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
-  Select *pSetup = p->pPrior;   /* The setup query */
+  Select *pSetup;               /* The setup query */
   Select *pFirstRec;            /* Left-most recursive term */
   int addrTop;                  /* Top of the loop */
   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
@@ -133578,7 +136812,6 @@ static void generateWithRecursiveQuery(
   ** iDistinct table.  pFirstRec is left pointing to the left-most
   ** recursive term of the CTE.
   */
-  pFirstRec = p;
   for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
     if( pFirstRec->selFlags & SF_Aggregate ){
       sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
@@ -133809,11 +137042,12 @@ static int multiSelect(
     switch( p->op ){
       case TK_ALL: {
         int addr = 0;
-        int nLimit;
+        int nLimit = 0;  /* Initialize to suppress harmless compiler warning */
         assert( !pPrior->pLimit );
         pPrior->iLimit = p->iLimit;
         pPrior->iOffset = p->iOffset;
         pPrior->pLimit = p->pLimit;
+        SELECTTRACE(1, pParse, p, ("multiSelect UNION ALL left...\n"));
         rc = sqlite3Select(pParse, pPrior, &dest);
         pPrior->pLimit = 0;
         if( rc ){
@@ -133831,6 +137065,7 @@ static int multiSelect(
           }
         }
         ExplainQueryPlan((pParse, 1, "UNION ALL"));
+        SELECTTRACE(1, pParse, p, ("multiSelect UNION ALL right...\n"));
         rc = sqlite3Select(pParse, p, &dest);
         testcase( rc!=SQLITE_OK );
         pDelete = p->pPrior;
@@ -133883,6 +137118,7 @@ static int multiSelect(
         */
         assert( !pPrior->pOrderBy );
         sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
+        SELECTTRACE(1, pParse, p, ("multiSelect EXCEPT/UNION left...\n"));
         rc = sqlite3Select(pParse, pPrior, &uniondest);
         if( rc ){
           goto multi_select_end;
@@ -133902,6 +137138,7 @@ static int multiSelect(
         uniondest.eDest = op;
         ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
                           sqlite3SelectOpName(p->op)));
+        SELECTTRACE(1, pParse, p, ("multiSelect EXCEPT/UNION right...\n"));
         rc = sqlite3Select(pParse, p, &uniondest);
         testcase( rc!=SQLITE_OK );
         assert( p->pOrderBy==0 );
@@ -133962,6 +137199,7 @@ static int multiSelect(
         /* Code the SELECTs to our left into temporary table "tab1".
         */
         sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
+        SELECTTRACE(1, pParse, p, ("multiSelect INTERSECT left...\n"));
         rc = sqlite3Select(pParse, pPrior, &intersectdest);
         if( rc ){
           goto multi_select_end;
@@ -133978,6 +137216,7 @@ static int multiSelect(
         intersectdest.iSDParm = tab2;
         ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
                           sqlite3SelectOpName(p->op)));
+        SELECTTRACE(1, pParse, p, ("multiSelect INTERSECT right...\n"));
         rc = sqlite3Select(pParse, p, &intersectdest);
         testcase( rc!=SQLITE_OK );
         pDelete = p->pPrior;
@@ -134038,6 +137277,7 @@ static int multiSelect(
     int nCol;                     /* Number of columns in result set */
 
     assert( p->pNext==0 );
+    assert( p->pEList!=0 );
     nCol = p->pEList->nExpr;
     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
     if( !pKeyInfo ){
@@ -134072,7 +137312,11 @@ static int multiSelect(
 multi_select_end:
   pDest->iSdst = dest.iSdst;
   pDest->nSdst = dest.nSdst;
-  sqlite3SelectDelete(db, pDelete);
+  if( pDelete ){
+    sqlite3ParserAddCleanup(pParse,
+        (void(*)(sqlite3*,void*))sqlite3SelectDelete,
+        pDelete);
+  }
   return rc;
 }
 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
@@ -134326,6 +137570,8 @@ static int multiSelectOrderBy(
 ){
   int i, j;             /* Loop counters */
   Select *pPrior;       /* Another SELECT immediately to our left */
+  Select *pSplit;       /* Left-most SELECT in the right-hand group */
+  int nSelect;          /* Number of SELECT statements in the compound */
   Vdbe *v;              /* Generate code to this VDBE */
   SelectDest destA;     /* Destination for coroutine A */
   SelectDest destB;     /* Destination for coroutine B */
@@ -134371,8 +137617,7 @@ static int multiSelectOrderBy(
   /* Patch up the ORDER BY clause
   */
   op = p->op;
-  pPrior = p->pPrior;
-  assert( pPrior->pOrderBy==0 );
+  assert( p->pPrior->pOrderBy==0 );
   pOrderBy = p->pOrderBy;
   assert( pOrderBy );
   nOrderBy = pOrderBy->nExpr;
@@ -134385,6 +137630,7 @@ static int multiSelectOrderBy(
     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
       struct ExprList_item *pItem;
       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
+        assert( pItem!=0 );
         assert( pItem->u.x.iOrderByCol>0 );
         if( pItem->u.x.iOrderByCol==i ) break;
       }
@@ -134411,6 +137657,7 @@ static int multiSelectOrderBy(
     struct ExprList_item *pItem;
     aPermute[0] = nOrderBy;
     for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
+      assert( pItem!=0 );
       assert( pItem->u.x.iOrderByCol>0 );
       assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
       aPermute[i] = pItem->u.x.iOrderByCol - 1;
@@ -134420,11 +137667,6 @@ static int multiSelectOrderBy(
     pKeyMerge = 0;
   }
 
-  /* Reattach the ORDER BY clause to the query.
-  */
-  p->pOrderBy = pOrderBy;
-  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
-
   /* Allocate a range of temporary registers and the KeyInfo needed
   ** for the logic that removes duplicate result rows when the
   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
@@ -134449,12 +137691,30 @@ static int multiSelectOrderBy(
 
   /* Separate the left and the right query from one another
   */
-  p->pPrior = 0;
+  nSelect = 1;
+  if( (op==TK_ALL || op==TK_UNION)
+   && OptimizationEnabled(db, SQLITE_BalancedMerge)
+  ){
+    for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
+      nSelect++;
+      assert( pSplit->pPrior->pNext==pSplit );
+    }
+  }
+  if( nSelect<=3 ){
+    pSplit = p;
+  }else{
+    pSplit = p;
+    for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
+  }
+  pPrior = pSplit->pPrior;
+  assert( pPrior!=0 );
+  pSplit->pPrior = 0;
   pPrior->pNext = 0;
+  assert( p->pOrderBy == pOrderBy );
+  assert( pOrderBy!=0 || db->mallocFailed );
+  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
-  if( pPrior->pPrior==0 ){
-    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
-  }
+  sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
 
   /* Compute the limit registers */
   computeLimitRegisters(pParse, p, labelEnd);
@@ -134605,11 +137865,13 @@ static int multiSelectOrderBy(
 
   /* Reassembly the compound query so that it will be freed correctly
   ** by the calling function */
-  if( p->pPrior ){
-    sqlite3SelectDelete(db, p->pPrior);
+  if( pSplit->pPrior ){
+    sqlite3SelectDelete(db, pSplit->pPrior);
   }
-  p->pPrior = pPrior;
-  pPrior->pNext = p;
+  pSplit->pPrior = pPrior;
+  pPrior->pNext = pSplit;
+  sqlite3ExprListDelete(db, pPrior->pOrderBy);
+  pPrior->pOrderBy = 0;
 
   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   **** subqueries ****/
@@ -134657,17 +137919,20 @@ static Expr *substExpr(
 ){
   if( pExpr==0 ) return 0;
   if( ExprHasProperty(pExpr, EP_FromJoin)
-   && pExpr->iRightJoinTable==pSubst->iTable
+   && pExpr->w.iRightJoinTable==pSubst->iTable
   ){
-    pExpr->iRightJoinTable = pSubst->iNewTable;
+    pExpr->w.iRightJoinTable = pSubst->iNewTable;
   }
   if( pExpr->op==TK_COLUMN
    && pExpr->iTable==pSubst->iTable
    && !ExprHasProperty(pExpr, EP_FixedCol)
   ){
+#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
     if( pExpr->iColumn<0 ){
       pExpr->op = TK_NULL;
-    }else{
+    }else
+#endif
+    {
       Expr *pNew;
       Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
       Expr ifNullRow;
@@ -134687,26 +137952,28 @@ static Expr *substExpr(
         }
         testcase( ExprHasProperty(pCopy, EP_Subquery) );
         pNew = sqlite3ExprDup(db, pCopy, 0);
-        if( pNew && pSubst->isLeftJoin ){
+        if( db->mallocFailed ){
+          sqlite3ExprDelete(db, pNew);
+          return pExpr;
+        }
+        if( pSubst->isLeftJoin ){
           ExprSetProperty(pNew, EP_CanBeNull);
         }
-        if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
-          sqlite3SetJoinExpr(pNew, pExpr->iRightJoinTable);
+        if( ExprHasProperty(pExpr,EP_FromJoin) ){
+          sqlite3SetJoinExpr(pNew, pExpr->w.iRightJoinTable);
         }
         sqlite3ExprDelete(db, pExpr);
         pExpr = pNew;
 
         /* Ensure that the expression now has an implicit collation sequence,
         ** just as it did when it was a column of a view or sub-query. */
-        if( pExpr ){
-          if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
-            CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
-            pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
-                (pColl ? pColl->zName : "BINARY")
-            );
-          }
-          ExprClearProperty(pExpr, EP_Collate);
+        if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
+          CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
+          pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
+              (pColl ? pColl->zName : "BINARY")
+          );
         }
+        ExprClearProperty(pExpr, EP_Collate);
       }
     }
   }else{
@@ -134715,7 +137982,7 @@ static Expr *substExpr(
     }
     pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
     pExpr->pRight = substExpr(pSubst, pExpr->pRight);
-    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+    if( ExprUseXSelect(pExpr) ){
       substSelect(pSubst, pExpr->x.pSelect, 1);
     }else{
       substExprList(pSubst, pExpr->x.pList);
@@ -134806,10 +138073,10 @@ static void recomputeColumnsUsed(
 ** new cursor number assigned, set an entry in the aCsrMap[] array
 ** to map the old cursor number to the new:
 **
-**     aCsrMap[iOld] = iNew;
+**     aCsrMap[iOld+1] = iNew;
 **
 ** The array is guaranteed by the caller to be large enough for all
-** existing cursor numbers in pSrc.
+** existing cursor numbers in pSrc.  aCsrMap[0] is the array size.
 **
 ** If pSrc contains any sub-selects, call this routine recursively
 ** on the FROM clause of each such sub-select, with iExcept set to -1.
@@ -134825,7 +138092,11 @@ static void srclistRenumberCursors(
   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
     if( i!=iExcept ){
       Select *p;
-      pItem->iCursor = aCsrMap[pItem->iCursor] = pParse->nTab++;
+      assert( pItem->iCursor < aCsrMap[0] );
+      if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
+        aCsrMap[pItem->iCursor+1] = pParse->nTab++;
+      }
+      pItem->iCursor = aCsrMap[pItem->iCursor+1];
       for(p=pItem->pSelect; p; p=p->pPrior){
         srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
       }
@@ -134833,18 +138104,28 @@ static void srclistRenumberCursors(
   }
 }
 
+/*
+** *piCursor is a cursor number.  Change it if it needs to be mapped.
+*/
+static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){
+  int *aCsrMap = pWalker->u.aiCol;
+  int iCsr = *piCursor;
+  if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){
+    *piCursor = aCsrMap[iCsr+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( op==TK_COLUMN || op==TK_IF_NULL_ROW ){
+    renumberCursorDoMapping(pWalker, &pExpr->iTable);
   }
-  if( ExprHasProperty(pExpr, EP_FromJoin) && aCsrMap[pExpr->iRightJoinTable] ){
-    pExpr->iRightJoinTable = aCsrMap[pExpr->iRightJoinTable];
+  if( ExprHasProperty(pExpr, EP_FromJoin) ){
+    renumberCursorDoMapping(pWalker, &pExpr->w.iRightJoinTable);
   }
   return WRC_Continue;
 }
@@ -135188,7 +138469,8 @@ static int flattenSubquery(
 
     if( pSrc->nSrc>1 ){
       if( pParse->nSelect>500 ) return 0;
-      aCsrMap = sqlite3DbMallocZero(db, pParse->nTab*sizeof(int));
+      aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
+      if( aCsrMap ) aCsrMap[0] = pParse->nTab;
     }
   }
 
@@ -135265,7 +138547,7 @@ static int flattenSubquery(
       p->pPrior = pPrior;
     }else{
       pNew->selId = ++pParse->nSelect;
-      if( aCsrMap && db->mallocFailed==0 ){
+      if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
         renumberCursors(pParse, pNew, iFrom, aCsrMap);
       }
       pNew->pPrior = pPrior;
@@ -135464,8 +138746,10 @@ static int flattenSubquery(
 typedef struct WhereConst WhereConst;
 struct WhereConst {
   Parse *pParse;   /* Parsing context */
+  u8 *pOomFault;   /* Pointer to pParse->db->mallocFailed */
   int nConst;      /* Number for COLUMN=CONSTANT terms */
   int nChng;       /* Number of times a constant is propagated */
+  int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
   Expr **apExpr;   /* [i*2] is COLUMN and [i*2+1] is VALUE */
 };
 
@@ -135504,6 +138788,9 @@ static void constInsert(
       return;  /* Already present.  Return without doing anything. */
     }
   }
+  if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
+    pConst->bHasAffBlob = 1;
+  }
 
   pConst->nConst++;
   pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
@@ -135524,7 +138811,7 @@ static void constInsert(
 */
 static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
   Expr *pRight, *pLeft;
-  if( pExpr==0 ) return;
+  if( NEVER(pExpr==0) ) return;
   if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
   if( pExpr->op==TK_AND ){
     findConstInWhere(pConst, pExpr->pRight);
@@ -135545,37 +138832,83 @@ static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
 }
 
 /*
-** This is a Walker expression callback.  pExpr is a candidate expression
-** to be replaced by a value.  If pExpr is equivalent to one of the
-** columns named in pWalker->u.pConst, then overwrite it with its
-** corresponding value.
+** This is a helper function for Walker callback propagateConstantExprRewrite().
+**
+** Argument pExpr is a candidate expression to be replaced by a value. If
+** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
+** then overwrite it with the corresponding value. Except, do not do so
+** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
+** is SQLITE_AFF_BLOB.
 */
-static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
+static int propagateConstantExprRewriteOne(
+  WhereConst *pConst,
+  Expr *pExpr,
+  int bIgnoreAffBlob
+){
   int i;
-  WhereConst *pConst;
+  if( pConst->pOomFault[0] ) return WRC_Prune;
   if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
   if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){
     testcase( ExprHasProperty(pExpr, EP_FixedCol) );
     testcase( ExprHasProperty(pExpr, EP_FromJoin) );
     return WRC_Continue;
   }
-  pConst = pWalker->u.pConst;
   for(i=0; i<pConst->nConst; i++){
     Expr *pColumn = pConst->apExpr[i*2];
     if( pColumn==pExpr ) continue;
     if( pColumn->iTable!=pExpr->iTable ) continue;
     if( pColumn->iColumn!=pExpr->iColumn ) continue;
+    if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
+      break;
+    }
     /* A match is found.  Add the EP_FixedCol property */
     pConst->nChng++;
     ExprClearProperty(pExpr, EP_Leaf);
     ExprSetProperty(pExpr, EP_FixedCol);
     assert( pExpr->pLeft==0 );
     pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
+    if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
     break;
   }
   return WRC_Prune;
 }
 
+/*
+** This is a Walker expression callback. pExpr is a node from the WHERE
+** clause of a SELECT statement. This function examines pExpr to see if
+** any substitutions based on the contents of pWalker->u.pConst should
+** be made to pExpr or its immediate children.
+**
+** A substitution is made if:
+**
+**   + pExpr is a column with an affinity other than BLOB that matches
+**     one of the columns in pWalker->u.pConst, or
+**
+**   + pExpr is a binary comparison operator (=, <=, >=, <, >) that
+**     uses an affinity other than TEXT and one of its immediate
+**     children is a column that matches one of the columns in
+**     pWalker->u.pConst.
+*/
+static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
+  WhereConst *pConst = pWalker->u.pConst;
+  assert( TK_GT==TK_EQ+1 );
+  assert( TK_LE==TK_EQ+2 );
+  assert( TK_LT==TK_EQ+3 );
+  assert( TK_GE==TK_EQ+4 );
+  if( pConst->bHasAffBlob ){
+    if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
+     || pExpr->op==TK_IS
+    ){
+      propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
+      if( pConst->pOomFault[0] ) return WRC_Prune;
+      if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
+        propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
+      }
+    }
+  }
+  return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
+}
+
 /*
 ** The WHERE-clause constant propagation optimization.
 **
@@ -135611,6 +138944,21 @@ static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
 ** routines know to generate the constant "123" instead of looking up the
 ** column value.  Also, to avoid collation problems, this optimization is
 ** only attempted if the "a=123" term uses the default BINARY collation.
+**
+** 2021-05-25 forum post 6a06202608: Another troublesome case is...
+**
+**    CREATE TABLE t1(x);
+**    INSERT INTO t1 VALUES(10.0);
+**    SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
+**
+** The query should return no rows, because the t1.x value is '10.0' not '10'
+** and '10.0' is not LIKE '10'.  But if we are not careful, the first WHERE
+** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
+** resulting in a false positive.  To avoid this, constant propagation for
+** columns with BLOB affinity is only allowed if the constant is used with
+** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
+** type conversions to occur.  See logic associated with the bHasAffBlob flag
+** for details.
 */
 static int propagateConstants(
   Parse *pParse,   /* The parsing context */
@@ -135620,10 +138968,12 @@ static int propagateConstants(
   Walker w;
   int nChng = 0;
   x.pParse = pParse;
+  x.pOomFault = &pParse->db->mallocFailed;
   do{
     x.nConst = 0;
     x.nChng = 0;
     x.apExpr = 0;
+    x.bHasAffBlob = 0;
     findConstInWhere(&x, p->pWhere);
     if( x.nConst ){
       memset(&w, 0, sizeof(w));
@@ -135743,8 +139093,7 @@ static int pushDownWhereTerms(
   Parse *pParse,        /* Parse context (for malloc() and error reporting) */
   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
   Expr *pWhere,         /* The WHERE clause of the outer query */
-  int iCursor,          /* Cursor number of the subquery */
-  int isLeftJoin        /* True if pSubq is the right term of a LEFT JOIN */
+  SrcItem *pSrc         /* The subquery term of the outer FROM clause */
 ){
   Expr *pNew;
   int nChng = 0;
@@ -135779,20 +139128,25 @@ static int pushDownWhereTerms(
     return 0; /* restriction (3) */
   }
   while( pWhere->op==TK_AND ){
-    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
-                                iCursor, isLeftJoin);
+    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrc);
     pWhere = pWhere->pLeft;
   }
+
+#if 0  /* Legacy code. Checks now done by sqlite3ExprIsTableConstraint() */
   if( isLeftJoin
    && (ExprHasProperty(pWhere,EP_FromJoin)==0
-         || pWhere->iRightJoinTable!=iCursor)
+         || pWhere->w.iRightJoinTable!=iCursor)
   ){
     return 0; /* restriction (4) */
   }
-  if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
+  if( ExprHasProperty(pWhere,EP_FromJoin)
+   && pWhere->w.iRightJoinTable!=iCursor
+  ){
     return 0; /* restriction (5) */
   }
-  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
+#endif
+
+  if( sqlite3ExprIsTableConstraint(pWhere, pSrc) ){
     nChng++;
     pSubq->selFlags |= SF_PushDown;
     while( pSubq ){
@@ -135800,8 +139154,8 @@ static int pushDownWhereTerms(
       pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
       unsetJoinExpr(pNew, -1);
       x.pParse = pParse;
-      x.iTable = iCursor;
-      x.iNewTable = iCursor;
+      x.iTable = pSrc->iCursor;
+      x.iNewTable = pSrc->iCursor;
       x.isLeftJoin = 0;
       x.pEList = pSubq->pEList;
       pNew = substExpr(&x, pNew);
@@ -135843,7 +139197,7 @@ static int pushDownWhereTerms(
 */
 static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
   int eRet = WHERE_ORDERBY_NORMAL;      /* Return value */
-  ExprList *pEList = pFunc->x.pList;    /* Arguments to agg function */
+  ExprList *pEList;                     /* Arguments to agg function */
   const char *zFunc;                    /* Name of aggregate function pFunc */
   ExprList *pOrderBy;
   u8 sortFlags = 0;
@@ -135851,6 +139205,8 @@ static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
   assert( *ppMinMax==0 );
   assert( pFunc->op==TK_AGG_FUNCTION );
   assert( !IsWindowFunc(pFunc) );
+  assert( ExprUseXList(pFunc) );
+  pEList = pFunc->x.pList;
   if( pEList==0
    || pEList->nExpr!=1
    || ExprHasProperty(pFunc, EP_WinFunc)
@@ -135858,6 +139214,7 @@ static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
   ){
     return eRet;
   }
+  assert( !ExprHasProperty(pFunc, EP_IntValue) );
   zFunc = pFunc->u.zToken;
   if( sqlite3StrICmp(zFunc, "min")==0 ){
     eRet = WHERE_ORDERBY_MIN;
@@ -135885,7 +139242,13 @@ static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
 **
 ** where table is a database table, not a sub-select or view. If the query
 ** does match this pattern, then a pointer to the Table object representing
-** <tbl> is returned. Otherwise, 0 is returned.
+** <tbl> is returned. Otherwise, NULL is returned.
+**
+** This routine checks to see if it is safe to use the count optimization.
+** A correct answer is still obtained (though perhaps more slowly) if
+** this routine returns NULL when it could have returned a table pointer.
+** But returning the pointer when NULL should have been returned can
+** result in incorrect answers and/or crashes.  So, when in doubt, return NULL.
 */
 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   Table *pTab;
@@ -135893,19 +139256,26 @@ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
 
   assert( !p->pGroupBy );
 
-  if( p->pWhere || p->pEList->nExpr!=1
-   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
+  if( p->pWhere
+   || p->pEList->nExpr!=1
+   || p->pSrc->nSrc!=1
+   || p->pSrc->a[0].pSelect
+   || pAggInfo->nFunc!=1
   ){
     return 0;
   }
   pTab = p->pSrc->a[0].pTab;
+  assert( pTab!=0 );
+  assert( !IsView(pTab) );
+  if( !IsOrdinaryTable(pTab) ) return 0;
   pExpr = p->pEList->a[0].pExpr;
-  assert( pTab && !pTab->pSelect && pExpr );
-
-  if( IsVirtual(pTab) ) return 0;
+  assert( pExpr!=0 );
   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
-  if( NEVER(pAggInfo->nFunc==0) ) return 0;
+  if( pExpr->pAggInfo!=pAggInfo ) return 0;
   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
+  assert( pAggInfo->aFunc[0].pFExpr==pExpr );
+  testcase( ExprHasProperty(pExpr, EP_Distinct) );
+  testcase( ExprHasProperty(pExpr, EP_WinFunc) );
   if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
 
   return pTab;
@@ -135934,6 +139304,7 @@ SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
     pParse->checkSchema = 1;
     return SQLITE_ERROR;
   }
+  assert( pFrom->fg.isCte==0 );
   pFrom->u2.pIBIndex = pIdx;
   return SQLITE_OK;
 }
@@ -136060,6 +139431,7 @@ static struct Cte *searchWith(
         return &p->a[i];
       }
     }
+    if( p->bView ) break;
   }
   return 0;
 }
@@ -136069,23 +139441,33 @@ static struct Cte *searchWith(
 **
 ** This routine pushes the WITH clause passed as the second argument
 ** onto the top of the stack. If argument bFree is true, then this
-** WITH clause will never be popped from the stack. In this case it
-** should be freed along with the Parse object. In other cases, when
+** WITH clause will never be popped from the stack but should instead
+** be freed along with the Parse object. In other cases, when
 ** bFree==0, the With object will be freed along with the SELECT
 ** statement with which it is associated.
+**
+** This routine returns a copy of pWith.  Or, if bFree is true and
+** the pWith object is destroyed immediately due to an OOM condition,
+** then this routine return NULL.
+**
+** If bFree is true, do not continue to use the pWith pointer after
+** calling this routine,  Instead, use only the return value.
 */
-SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
+SQLITE_PRIVATE With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
   if( pWith ){
-    assert( pParse->pWith!=pWith );
-    pWith->pOuter = pParse->pWith;
-    pParse->pWith = pWith;
     if( bFree ){
-      sqlite3ParserAddCleanup(pParse,
-         (void(*)(sqlite3*,void*))sqlite3WithDelete,
-         pWith);
-      testcase( pParse->earlyCleanup );
+      pWith = (With*)sqlite3ParserAddCleanup(pParse,
+                      (void(*)(sqlite3*,void*))sqlite3WithDelete,
+                      pWith);
+      if( pWith==0 ) return 0;
+    }
+    if( pParse->nErr==0 ){
+      assert( pParse->pWith!=pWith );
+      pWith->pOuter = pParse->pWith;
+      pParse->pWith = pWith;
     }
   }
+  return pWith;
 }
 
 /*
@@ -136115,11 +139497,24 @@ static int resolveFromTermToCte(
     /* There are no WITH clauses in the stack.  No match is possible */
     return 0;
   }
+  if( pParse->nErr ){
+    /* Prior errors might have left pParse->pWith in a goofy state, so
+    ** go no further. */
+    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;
   }
+  if( pFrom->fg.notCte ){
+    /* The FROM term is specifically excluded from matching a CTE.
+    **   (1)  It is part of a trigger that used to have zDatabase but had
+    **        zDatabase removed by sqlite3FixTriggerStep().
+    **   (2)  This is the first term in the FROM clause of an UPDATE.
+    */
+    return 0;
+  }
   pCte = searchWith(pParse->pWith, pFrom, &pWith);
   if( pCte ){
     sqlite3 *db = pParse->db;
@@ -136165,7 +139560,12 @@ static int resolveFromTermToCte(
     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
     if( db->mallocFailed ) return 2;
+    pFrom->pSelect->selFlags |= SF_CopyCte;
     assert( pFrom->pSelect );
+    if( pFrom->fg.isIndexedBy ){
+      sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
+      return 2;
+    }
     pFrom->fg.isCte = 1;
     pFrom->u2.pCteUse = pCteUse;
     pCteUse->nUse++;
@@ -136268,7 +139668,7 @@ static int resolveFromTermToCte(
 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
 ** names and other FROM clause elements.
 */
-static void selectPopWith(Walker *pWalker, Select *p){
+SQLITE_PRIVATE void sqlite3SelectPopWith(Walker *pWalker, Select *p){
   Parse *pParse = pWalker->pParse;
   if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
     With *pWith = findRightmost(p)->pWith;
@@ -136278,8 +139678,6 @@ static void selectPopWith(Walker *pWalker, Select *p){
     }
   }
 }
-#else
-#define selectPopWith 0
 #endif
 
 /*
@@ -136306,7 +139704,13 @@ SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
   sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
   pTab->iPKey = -1;
   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
-  pTab->tabFlags |= TF_Ephemeral;
+#ifndef SQLITE_ALLOW_ROWID_IN_VIEW
+  /* The usual case - do not allow ROWID on a subquery */
+  pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
+#else
+  pTab->tabFlags |= TF_Ephemeral;  /* Legacy compatibility mode */
+#endif
+
 
   return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
 }
@@ -136360,6 +139764,15 @@ static int selectExpander(Walker *pWalker, Select *p){
   }
   pTabList = p->pSrc;
   pEList = p->pEList;
+  if( pParse->pWith && (p->selFlags & SF_View) ){
+    if( p->pWith==0 ){
+      p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
+      if( p->pWith==0 ){
+        return WRC_Abort;
+      }
+    }
+    p->pWith->bView = 1;
+  }
   sqlite3WithPush(pParse, p->pWith, 0);
 
   /* Make sure cursor numbers have been assigned to all entries in
@@ -136407,29 +139820,31 @@ static int selectExpander(Walker *pWalker, Select *p){
         return WRC_Abort;
       }
 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
-      if( IsVirtual(pTab) || pTab->pSelect ){
+      if( !IsOrdinaryTable(pTab) ){
         i16 nCol;
         u8 eCodeOrig = pWalker->eCode;
         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
         assert( pFrom->pSelect==0 );
-        if( pTab->pSelect
-         && (db->flags & SQLITE_EnableView)==0
-         && pTab->pSchema!=db->aDb[1].pSchema
-        ){
-          sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
-            pTab->zName);
+        if( IsView(pTab) ){
+          if( (db->flags & SQLITE_EnableView)==0
+           && pTab->pSchema!=db->aDb[1].pSchema
+          ){
+            sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
+              pTab->zName);
+          }
+          pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
         }
 #ifndef SQLITE_OMIT_VIRTUALTABLE
-        if( IsVirtual(pTab)
+        else if( ALWAYS(IsVirtual(pTab))
          && pFrom->fg.fromDDL
-         && ALWAYS(pTab->pVTable!=0)
-         && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
+         && ALWAYS(pTab->u.vtab.p!=0)
+         && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
         ){
           sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
                                   pTab->zName);
         }
+        assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
 #endif
-        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
         nCol = pTab->nCol;
         pTab->nCol = -1;
         pWalker->eCode = 1;  /* Turn on Select.selId renumbering */
@@ -136448,7 +139863,8 @@ static int selectExpander(Walker *pWalker, Select *p){
 
   /* Process NATURAL keywords, and ON and USING clauses of joins.
   */
-  if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){
+  assert( db->mallocFailed==0 || pParse->nErr!=0 );
+  if( pParse->nErr || sqliteProcessJoin(pParse, p) ){
     return WRC_Abort;
   }
 
@@ -136529,7 +139945,7 @@ static int selectExpander(Walker *pWalker, Select *p){
             zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
           }
           for(j=0; j<pTab->nCol; j++){
-            char *zName = pTab->aCol[j].zName;
+            char *zName = pTab->aCol[j].zCnName;
             char *zColname;  /* The computed column name */
             char *zToFree;   /* Malloced string that needs to be freed */
             Token sColname;  /* Computed column name as a token */
@@ -136660,7 +140076,7 @@ static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
     sqlite3WalkSelect(&w, pSelect);
   }
   w.xSelectCallback = selectExpander;
-  w.xSelectCallback2 = selectPopWith;
+  w.xSelectCallback2 = sqlite3SelectPopWith;
   w.eCode = 0;
   sqlite3WalkSelect(&w, pSelect);
 }
@@ -136745,12 +140161,13 @@ SQLITE_PRIVATE void sqlite3SelectPrep(
   NameContext *pOuterNC  /* Name context for container */
 ){
   assert( p!=0 || pParse->db->mallocFailed );
+  assert( pParse->db->pParse==pParse );
   if( pParse->db->mallocFailed ) return;
   if( p->selFlags & SF_HasTypeInfo ) return;
   sqlite3SelectExpand(pParse, p);
-  if( pParse->nErr || pParse->db->mallocFailed ) return;
+  if( pParse->nErr ) return;
   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
-  if( pParse->nErr || pParse->db->mallocFailed ) return;
+  if( pParse->nErr ) return;
   sqlite3SelectAddTypeInfo(pParse, p);
 }
 
@@ -136767,8 +140184,10 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   int i;
   struct AggInfo_func *pFunc;
   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
+  assert( pParse->db->pParse==pParse );
+  assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
   if( nReg==0 ) return;
-  if( pParse->nErr || pParse->db->mallocFailed ) return;
+  if( pParse->nErr ) return;
 #ifdef SQLITE_DEBUG
   /* Verify that all AggInfo registers are within the range specified by
   ** AggInfo.mnReg..AggInfo.mxReg */
@@ -136786,15 +140205,17 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
     if( pFunc->iDistinct>=0 ){
       Expr *pE = pFunc->pFExpr;
-      assert( !ExprHasProperty(pE, EP_xIsSelect) );
+      assert( ExprUseXList(pE) );
       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
            "argument");
         pFunc->iDistinct = -1;
       }else{
         KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
-        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
-                          (char*)pKeyInfo, P4_KEYINFO);
+        pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
+            pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
+        ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
+                          pFunc->pFunc->zName));
       }
     }
   }
@@ -136809,8 +140230,9 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   int i;
   struct AggInfo_func *pF;
   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
-    ExprList *pList = pF->pFExpr->x.pList;
-    assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) );
+    ExprList *pList;
+    assert( ExprUseXList(pF->pFExpr) );
+    pList = pF->pFExpr->x.pList;
     sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
   }
@@ -136826,7 +140248,12 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
 ** registers if register regAcc contains 0. The caller will take care
 ** of setting and clearing regAcc.
 */
-static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
+static void updateAccumulator(
+  Parse *pParse,
+  int regAcc,
+  AggInfo *pAggInfo,
+  int eDistinctType
+){
   Vdbe *v = pParse->pVdbe;
   int i;
   int regHit = 0;
@@ -136839,9 +140266,10 @@ static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
     int nArg;
     int addrNext = 0;
     int regAgg;
-    ExprList *pList = pF->pFExpr->x.pList;
-    assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) );
+    ExprList *pList;
+    assert( ExprUseXList(pF->pFExpr) );
     assert( !IsWindowFunc(pF->pFExpr) );
+    pList = pF->pFExpr->x.pList;
     if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
       Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
       if( pAggInfo->nAccumulator
@@ -136872,13 +140300,12 @@ static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
       nArg = 0;
       regAgg = 0;
     }
-    if( pF->iDistinct>=0 ){
+    if( pF->iDistinct>=0 && pList ){
       if( addrNext==0 ){
         addrNext = sqlite3VdbeMakeLabel(pParse);
       }
-      testcase( nArg==0 );  /* Error condition */
-      testcase( nArg>1 );   /* Also an error */
-      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
+      pF->iDistinct = codeDistinct(pParse, eDistinctType,
+          pF->iDistinct, addrNext, pList, regAgg);
     }
     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
       CollSeq *pColl = 0;
@@ -136930,7 +140357,7 @@ static void explainSimpleCount(
 ){
   if( pParse->explain==2 ){
     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
-    sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
+    sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
         pTab->zName,
         bCover ? " USING COVERING INDEX " : "",
         bCover ? pIdx->zName : ""
@@ -136955,8 +140382,16 @@ static void explainSimpleCount(
 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
   if( pExpr->op!=TK_AND ){
     Select *pS = pWalker->u.pSelect;
+    /* This routine is called before the HAVING clause of the current
+    ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
+    ** here, it indicates that the expression is a correlated reference to a
+    ** column from an outer aggregate query, or an aggregate function that
+    ** belongs to an outer query. Do not move the expression to the WHERE
+    ** clause in this obscure case, as doing so may corrupt the outer Select
+    ** statements AggInfo structure.  */
     if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
      && ExprAlwaysFalse(pExpr)==0
+     && pExpr->pAggInfo==0
     ){
       sqlite3 *db = pWalker->pParse->db;
       Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
@@ -137080,7 +140515,9 @@ static int countOfViewOptimization(Parse *pParse, Select *p){
   if( p->pGroupBy ) return 0;
   pExpr = p->pEList->a[0].pExpr;
   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
+  assert( ExprUseUToken(pExpr) );
   if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
+  assert( ExprUseXList(pExpr) );
   if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
   if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
   pSub = p->pSrc->a[0].pSelect;
@@ -137173,10 +140610,12 @@ SQLITE_PRIVATE int sqlite3Select(
   u8 minMaxFlag;                 /* Flag for min/max queries */
 
   db = pParse->db;
+  assert( pParse==db->pParse );
   v = sqlite3GetVdbe(pParse);
-  if( p==0 || db->mallocFailed || pParse->nErr ){
+  if( p==0 || pParse->nErr ){
     return 1;
   }
+  assert( db->mallocFailed==0 );
   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
 #if SELECTTRACE_ENABLED
   SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
@@ -137211,9 +140650,10 @@ SQLITE_PRIVATE int sqlite3Select(
     p->selFlags |= SF_NoopOrderBy;
   }
   sqlite3SelectPrep(pParse, p, 0);
-  if( pParse->nErr || db->mallocFailed ){
+  if( pParse->nErr ){
     goto select_end;
   }
+  assert( db->mallocFailed==0 );
   assert( p->pEList!=0 );
 #if SELECTTRACE_ENABLED
   if( sqlite3SelectTrace & 0x104 ){
@@ -137222,11 +140662,16 @@ SQLITE_PRIVATE int sqlite3Select(
   }
 #endif
 
-  /* If the SF_UpdateFrom flag is set, then this function is being called
+  /* If the SF_UFSrcCheck flag is set, then this function is being called
   ** as part of populating the temp table for an UPDATE...FROM statement.
   ** 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 ){
+  ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
+  **
+  ** Postgres disallows this case too. The reason is that some other
+  ** systems handle this case differently, and not all the same way,
+  ** which is just confusing. To avoid this, we follow PG's lead and
+  ** disallow it altogether.  */
+  if( p->selFlags & SF_UFSrcCheck ){
     SrcItem *p0 = &p->pSrc->a[0];
     for(i=1; i<p->pSrc->nSrc; i++){
       SrcItem *p1 = &p->pSrc->a[i];
@@ -137238,16 +140683,21 @@ SQLITE_PRIVATE int sqlite3Select(
         goto select_end;
       }
     }
+
+    /* Clear the SF_UFSrcCheck flag. The check has already been performed,
+    ** and leaving this flag set can cause errors if a compound sub-query
+    ** in p->pSrc is flattened into this query and this function called
+    ** again as part of compound SELECT processing.  */
+    p->selFlags &= ~SF_UFSrcCheck;
   }
 
   if( pDest->eDest==SRT_Output ){
-    generateColumnNames(pParse, p);
+    sqlite3GenerateColumnNames(pParse, p);
   }
 
 #ifndef SQLITE_OMIT_WINDOWFUNC
-  rc = sqlite3WindowRewrite(pParse, p);
-  if( rc ){
-    assert( db->mallocFailed || pParse->nErr>0 );
+  if( sqlite3WindowRewrite(pParse, p) ){
+    assert( pParse->nErr );
     goto select_end;
   }
 #if SELECTTRACE_ENABLED
@@ -137310,6 +140760,39 @@ SQLITE_PRIVATE int sqlite3Select(
     if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
     assert( pSub->pGroupBy==0 );
 
+    /* If a FROM-clause subquery has an ORDER BY clause that is not
+    ** really doing anything, then delete it now so that it does not
+    ** interfere with query flattening.  See the discussion at
+    ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
+    **
+    ** Beware of these cases where the ORDER BY clause may not be safely
+    ** omitted:
+    **
+    **    (1)   There is also a LIMIT clause
+    **    (2)   The subquery was added to help with window-function
+    **          processing
+    **    (3)   The subquery is in the FROM clause of an UPDATE
+    **    (4)   The outer query uses an aggregate function other than
+    **          the built-in count(), min(), or max().
+    **    (5)   The ORDER BY isn't going to accomplish anything because
+    **          one of:
+    **            (a)  The outer query has a different ORDER BY clause
+    **            (b)  The subquery is part of a join
+    **          See forum post 062d576715d277c8
+    */
+    if( pSub->pOrderBy!=0
+     && (p->pOrderBy!=0 || pTabList->nSrc>1)      /* Condition (5) */
+     && pSub->pLimit==0                           /* Condition (1) */
+     && (pSub->selFlags & SF_OrderByReqd)==0      /* Condition (2) */
+     && (p->selFlags & SF_OrderByReqd)==0         /* Condition (3) and (4) */
+     && OptimizationEnabled(db, SQLITE_OmitOrderBy)
+    ){
+      SELECTTRACE(0x100,pParse,p,
+                ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
+      sqlite3ExprListDelete(db, pSub->pOrderBy);
+      pSub->pOrderBy = 0;
+    }
+
     /* If the outer query contains a "complex" result set (that is,
     ** if the result set of the outer query uses functions or subqueries)
     ** and if the subquery contains an ORDER BY clause and if
@@ -137372,7 +140855,8 @@ SQLITE_PRIVATE int sqlite3Select(
   ** as the equivalent optimization will be handled by query planner in
   ** sqlite3WhereBegin().
   */
-  if( pTabList->nSrc>1
+  if( p->pWhere!=0
+   && p->pWhere->op==TK_AND
    && OptimizationEnabled(db, SQLITE_PropagateConst)
    && propagateConstants(pParse, p)
   ){
@@ -137435,19 +140919,8 @@ SQLITE_PRIVATE int sqlite3Select(
     pSub = pItem->pSelect;
     if( pSub==0 ) continue;
 
-    /* The code for a subquery should only be generated once, though it is
-    ** technically harmless for it to be generated multiple times. The
-    ** following assert() will detect if something changes to cause
-    ** the same subquery to be coded multiple times, as a signal to the
-    ** developers to try to optimize the situation.
-    **
-    ** Update 2019-07-24:
-    ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.
-    ** The dbsqlfuzz fuzzer found a case where the same subquery gets
-    ** coded twice.  So this assert() now becomes a testcase().  It should
-    ** be very rare, though.
-    */
-    testcase( pItem->addrFillSub!=0 );
+    /* The code for a subquery should only be generated once. */
+    assert( pItem->addrFillSub==0 );
 
     /* Increment Parse.nHeight by the height of the largest expression
     ** tree referred to by this, the parent select. The child select
@@ -137462,9 +140935,9 @@ SQLITE_PRIVATE int sqlite3Select(
     ** 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)
+     && (pItem->fg.isCte==0
+         || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
+     && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem)
     ){
 #if SELECTTRACE_ENABLED
       if( sqlite3SelectTrace & 0x100 ){
@@ -137503,10 +140976,10 @@ SQLITE_PRIVATE int sqlite3Select(
 
       pItem->regReturn = ++pParse->nMem;
       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
-      VdbeComment((v, "%s", pItem->pTab->zName));
+      VdbeComment((v, "%!S", pItem));
       pItem->addrFillSub = addrTop;
       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
-      ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
+      ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
       sqlite3Select(pParse, pSub, &dest);
       pItem->pTab->nRowLogEst = pSub->nSelectRow;
       pItem->fg.viaCoroutine = 1;
@@ -137523,6 +140996,7 @@ SQLITE_PRIVATE int sqlite3Select(
       sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
       if( pItem->iCursor!=pCteUse->iCur ){
         sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
+        VdbeComment((v, "%!S", pItem));
       }
       pSub->nSelectRow = pCteUse->nRowEst;
     }else if( (pPrior = isSelfJoinView(pTabList, pItem))!=0 ){
@@ -137534,14 +141008,13 @@ SQLITE_PRIVATE int sqlite3Select(
       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
+      /* Materialize 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;
 
-      testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */
       pItem->regReturn = ++pParse->nMem;
       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
       pItem->addrFillSub = topAddr+1;
@@ -137550,17 +141023,17 @@ SQLITE_PRIVATE int sqlite3Select(
         ** a trigger, then we only need to compute the value of the subquery
         ** once. */
         onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
-        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
+        VdbeComment((v, "materialize %!S", pItem));
       }else{
-        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
+        VdbeNoopComment((v, "materialize %!S", pItem));
       }
       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
-      ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
+      ExplainQueryPlan((pParse, 1, "MATERIALIZE %!S", pItem));
       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));
+      VdbeComment((v, "end %!S", pItem));
       sqlite3VdbeChangeP1(v, topAddr, retAddr);
       sqlite3ClearTempRegCache(pParse);
       if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
@@ -137699,7 +141172,7 @@ SQLITE_PRIVATE int sqlite3Select(
     /* Begin the database scan. */
     SELECTTRACE(1,pParse,p,("WhereBegin\n"));
     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
-                               p->pEList, wctrlFlags, p->nSelectRow);
+                               p->pEList, p, wctrlFlags, p->nSelectRow);
     if( pWInfo==0 ) goto select_end;
     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
@@ -137861,7 +141334,7 @@ SQLITE_PRIVATE int sqlite3Select(
     }
     for(i=0; i<pAggInfo->nFunc; i++){
       Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
-      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
+      assert( ExprUseXList(pExpr) );
       sNC.ncFlags |= NC_InAggFunc;
       sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
 #ifndef SQLITE_OMIT_WINDOWFUNC
@@ -137910,6 +141383,22 @@ SQLITE_PRIVATE int sqlite3Select(
       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
       int addrReset;      /* Subroutine for resetting the accumulator */
       int regReset;       /* Return address register for reset subroutine */
+      ExprList *pDistinct = 0;
+      u16 distFlag = 0;
+      int eDist = WHERE_DISTINCT_NOOP;
+
+      if( pAggInfo->nFunc==1
+       && pAggInfo->aFunc[0].iDistinct>=0
+       && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
+       && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
+       && pAggInfo->aFunc[0].pFExpr->x.pList!=0
+      ){
+        Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
+        pExpr = sqlite3ExprDup(db, pExpr, 0);
+        pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
+        pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
+        distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
+      }
 
       /* If there is a GROUP BY clause we might need a sorting index to
       ** implement it.  Allocate that sorting index now.  If it turns out
@@ -137946,10 +141435,14 @@ SQLITE_PRIVATE int sqlite3Select(
       */
       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
       SELECTTRACE(1,pParse,p,("WhereBegin\n"));
-      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
-          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
+      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
+          0, (WHERE_GROUPBY|(orderByGrp ? WHERE_SORTBYGROUP : 0)|distFlag), 0
       );
-      if( pWInfo==0 ) goto select_end;
+      if( pWInfo==0 ){
+        sqlite3ExprListDelete(db, pDistinct);
+        goto select_end;
+      }
+      eDist = sqlite3WhereIsDistinct(pWInfo);
       SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
         /* The optimizer is able to deliver rows in group by order so
@@ -138067,7 +141560,7 @@ SQLITE_PRIVATE int sqlite3Select(
       ** the current row
       */
       sqlite3VdbeJumpHere(v, addr1);
-      updateAccumulator(pParse, iUseFlag, pAggInfo);
+      updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
       VdbeComment((v, "indicate data in accumulator"));
 
@@ -138081,6 +141574,7 @@ SQLITE_PRIVATE int sqlite3Select(
         sqlite3WhereEnd(pWInfo);
         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
       }
+      sqlite3ExprListDelete(db, pDistinct);
 
       /* Output the final row of result
       */
@@ -138124,6 +141618,10 @@ SQLITE_PRIVATE int sqlite3Select(
       VdbeComment((v, "indicate accumulator empty"));
       sqlite3VdbeAddOp1(v, OP_Return, regReset);
 
+      if( eDist!=WHERE_DISTINCT_NOOP ){
+        struct AggInfo_func *pF = &pAggInfo->aFunc[0];
+        fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
+      }
     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
     else {
       Table *pTab;
@@ -138187,6 +141685,9 @@ SQLITE_PRIVATE int sqlite3Select(
         explainSimpleCount(pParse, pTab, pBest);
       }else{
         int regAcc = 0;           /* "populate accumulators" flag */
+        ExprList *pDistinct = 0;
+        u16 distFlag = 0;
+        int eDist;
 
         /* If there are accumulator registers but no min() or max() functions
         ** without FILTER clauses, allocate register regAcc. Register regAcc
@@ -138210,6 +141711,10 @@ SQLITE_PRIVATE int sqlite3Select(
             regAcc = ++pParse->nMem;
             sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
           }
+        }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
+          assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
+          pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
+          distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
         }
 
         /* This case runs if the aggregate has no GROUP BY clause.  The
@@ -138229,12 +141734,18 @@ SQLITE_PRIVATE int sqlite3Select(
 
         SELECTTRACE(1,pParse,p,("WhereBegin\n"));
         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
-                                   0, minMaxFlag, 0);
+                                   pDistinct, 0, minMaxFlag|distFlag, 0);
         if( pWInfo==0 ){
           goto select_end;
         }
         SELECTTRACE(1,pParse,p,("WhereBegin returns\n"));
-        updateAccumulator(pParse, regAcc, pAggInfo);
+        eDist = sqlite3WhereIsDistinct(pWInfo);
+        updateAccumulator(pParse, regAcc, pAggInfo, eDist);
+        if( eDist!=WHERE_DISTINCT_NOOP ){
+          struct AggInfo_func *pF = &pAggInfo->aFunc[0];
+          fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
+        }
+
         if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
         if( minMaxFlag ){
           sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
@@ -138279,6 +141790,8 @@ SQLITE_PRIVATE int sqlite3Select(
   ** successful coding of the SELECT.
   */
 select_end:
+  assert( db->mallocFailed==0 || db->mallocFailed==1 );
+  assert( db->mallocFailed==0 || pParse->nErr!=0 );
   sqlite3ExprListDelete(db, pMinMaxOrderBy);
 #ifdef SQLITE_DEBUG
   if( pAggInfo && !db->mallocFailed ){
@@ -138569,29 +142082,41 @@ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   }
   pTmpSchema = pParse->db->aDb[1].pSchema;
   p = sqliteHashFirst(&pTmpSchema->trigHash);
-  if( p==0 ){
-    return pTab->pTrigger;
-  }
   pList = pTab->pTrigger;
-  if( pTmpSchema!=pTab->pSchema ){
-    while( p ){
-      Trigger *pTrig = (Trigger *)sqliteHashData(p);
-      if( pTrig->pTabSchema==pTab->pSchema
-       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
-      ){
-        pTrig->pNext = pList;
-        pList = pTrig;
-      }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);
+  while( p ){
+    Trigger *pTrig = (Trigger *)sqliteHashData(p);
+    if( pTrig->pTabSchema==pTab->pSchema
+     && pTrig->table
+     && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
+     && pTrig->pTabSchema!=pTmpSchema
+    ){
+      pTrig->pNext = pList;
+      pList = pTrig;
+    }else if( pTrig->op==TK_RETURNING
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+              && pParse->db->pVtabCtx==0
+#endif
+    ){
+      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);
   }
+#if 0
+  if( pList ){
+    Trigger *pX;
+    printf("Triggers for %s:", pTab->zName);
+    for(pX=pList; pX; pX=pX->pNext){
+      printf(" %s", pX->zName);
+    }
+    printf("\n");
+    fflush(stdout);
+  }
+#endif
   return pList;
 }
 
@@ -138719,14 +142244,14 @@ SQLITE_PRIVATE void sqlite3BeginTrigger(
   /* INSTEAD of triggers are only for views and views only support INSTEAD
   ** of triggers.
   */
-  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
+  if( IsView(pTab) && tr_tm!=TK_INSTEAD ){
     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
-        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
+        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName->a);
     goto trigger_orphan_error;
   }
-  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
+  if( !IsView(pTab) && tr_tm==TK_INSTEAD ){
     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
-        " trigger on table: %S", pTableName, 0);
+        " trigger on table: %S", pTableName->a);
     goto trigger_orphan_error;
   }
 
@@ -138861,7 +142386,7 @@ SQLITE_PRIVATE void sqlite3FinishTrigger(
     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
     testcase( z==0 );
     sqlite3NestedParse(pParse,
-       "INSERT INTO %Q." DFLT_SCHEMA_TABLE
+       "INSERT INTO %Q." LEGACY_SCHEMA_TABLE
        " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
        db->aDb[iDb].zDbSName, zName,
        pTrig->table, z);
@@ -138946,6 +142471,7 @@ static TriggerStep *triggerStepAllocate(
   sqlite3 *db = pParse->db;
   TriggerStep *pTriggerStep;
 
+  if( pParse->nErr ) return 0;
   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
   if( pTriggerStep ){
     char *z = (char*)&pTriggerStep[1];
@@ -139123,7 +142649,7 @@ SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr)
   }
   if( !pTrigger ){
     if( !noErr ){
-      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
+      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName->a);
     }else{
       sqlite3CodeVerifyNamedSchema(pParse, zDb);
     }
@@ -139175,7 +142701,7 @@ SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   */
   if( (v = sqlite3GetVdbe(pParse))!=0 ){
     sqlite3NestedParse(pParse,
-       "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'",
+       "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'",
        db->aDb[iDb].zDbSName, pTrigger->zName
     );
     sqlite3ChangeCookie(pParse, iDb);
@@ -139377,11 +142903,11 @@ static ExprList *sqlite3ExpandReturning(
       for(jj=0; jj<pTab->nCol; jj++){
         Expr *pNewExpr;
         if( IsHiddenColumn(pTab->aCol+jj) ) continue;
-        pNewExpr = sqlite3Expr(db, TK_ID, pTab->aCol[jj].zName);
+        pNewExpr = sqlite3Expr(db, TK_ID, pTab->aCol[jj].zCnName);
         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->zEName = sqlite3DbStrDup(db, pTab->aCol[jj].zCnName);
           pItem->eEName = ENAME_NAME;
         }
       }
@@ -139395,15 +142921,6 @@ static ExprList *sqlite3ExpandReturning(
       }
     }
   }
-  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;
 }
 
@@ -139419,15 +142936,32 @@ static void codeReturningTrigger(
   int regIn            /* The first in an array of registers */
 ){
   Vdbe *v = pParse->pVdbe;
+  sqlite3 *db = pParse->db;
   ExprList *pNew;
   Returning *pReturning;
+  Select sSelect;
+  SrcList sFrom;
 
   assert( v!=0 );
   assert( pParse->bReturning );
+  assert( db->pParse==pParse );
   pReturning = pParse->u1.pReturning;
   assert( pTrigger == &(pReturning->retTrig) );
+  memset(&sSelect, 0, sizeof(sSelect));
+  memset(&sFrom, 0, sizeof(sFrom));
+  sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
+  sSelect.pSrc = &sFrom;
+  sFrom.nSrc = 1;
+  sFrom.a[0].pTab = pTab;
+  sFrom.a[0].iCursor = -1;
+  sqlite3SelectPrep(pParse, &sSelect, 0);
+  if( pParse->nErr==0 ){
+    assert( db->mallocFailed==0 );
+    sqlite3GenerateColumnNames(pParse, &sSelect);
+  }
+  sqlite3ExprListDelete(db, sSelect.pEList);
   pNew = sqlite3ExpandReturning(pParse, pReturning->pReturnEL, pTab);
-  if( pNew ){
+  if( !db->mallocFailed ){
     NameContext sNC;
     memset(&sNC, 0, sizeof(sNC));
     if( pReturning->nRetCol==0 ){
@@ -139439,23 +142973,30 @@ static void codeReturningTrigger(
     sNC.ncFlags = NC_UBaseReg;
     pParse->eTriggerOp = pTrigger->op;
     pParse->pTriggerTab = pTab;
-    if( sqlite3ResolveExprListNames(&sNC, pNew)==SQLITE_OK ){
+    if( sqlite3ResolveExprListNames(&sNC, pNew)==SQLITE_OK
+     && ALWAYS(!db->mallocFailed)
+    ){
       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);
+        Expr *pCol = pNew->a[i].pExpr;
+        assert( pCol!=0 ); /* Due to !db->mallocFailed ~9 lines above */
+        sqlite3ExprCodeFactorable(pParse, pCol, reg+i);
+        if( sqlite3ExprAffinity(pCol)==SQLITE_AFF_REAL ){
+          sqlite3VdbeAddOp1(v, OP_RealAffinity, 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;
   }
+  sqlite3ExprListDelete(db, pNew);
+  pParse->eTriggerOp = 0;
+  pParse->pTriggerTab = 0;
 }
 
 
@@ -139597,8 +143138,8 @@ static TriggerPrg *codeRowTrigger(
   Vdbe *v;                    /* Temporary VM */
   NameContext sNC;            /* Name context for sub-vdbe */
   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
-  Parse *pSubParse;           /* Parse context for sub-vdbe */
   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
+  Parse sSubParse;            /* Parse context for sub-vdbe */
 
   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   assert( pTop->pVdbe );
@@ -139620,19 +143161,17 @@ static TriggerPrg *codeRowTrigger(
 
   /* Allocate and populate a new Parse context to use for coding the
   ** trigger sub-program.  */
-  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
-  if( !pSubParse ) return 0;
+  sqlite3ParseObjectInit(&sSubParse, db);
   memset(&sNC, 0, sizeof(sNC));
-  sNC.pParse = pSubParse;
-  pSubParse->db = db;
-  pSubParse->pTriggerTab = pTab;
-  pSubParse->pToplevel = pTop;
-  pSubParse->zAuthContext = pTrigger->zName;
-  pSubParse->eTriggerOp = pTrigger->op;
-  pSubParse->nQueryLoop = pParse->nQueryLoop;
-  pSubParse->disableVtab = pParse->disableVtab;
-
-  v = sqlite3GetVdbe(pSubParse);
+  sNC.pParse = &sSubParse;
+  sSubParse.pTriggerTab = pTab;
+  sSubParse.pToplevel = pTop;
+  sSubParse.zAuthContext = pTrigger->zName;
+  sSubParse.eTriggerOp = pTrigger->op;
+  sSubParse.nQueryLoop = pParse->nQueryLoop;
+  sSubParse.disableVtab = pParse->disableVtab;
+
+  v = sqlite3GetVdbe(&sSubParse);
   if( v ){
     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
       pTrigger->zName, onErrorText(orconf),
@@ -139655,17 +143194,17 @@ static TriggerPrg *codeRowTrigger(
     ** OP_Halt inserted at the end of the program.  */
     if( pTrigger->pWhen ){
       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
-      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
-       && db->mallocFailed==0
+      if( db->mallocFailed==0
+       && SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
       ){
-        iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
-        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
+        iEndTrigger = sqlite3VdbeMakeLabel(&sSubParse);
+        sqlite3ExprIfFalse(&sSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
       }
       sqlite3ExprDelete(db, pWhen);
     }
 
     /* Code the trigger program into the sub-vdbe. */
-    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
+    codeTriggerProgram(&sSubParse, pTrigger->step_list, orconf);
 
     /* Insert an OP_Halt at the end of the sub-program. */
     if( iEndTrigger ){
@@ -139673,23 +143212,24 @@ static TriggerPrg *codeRowTrigger(
     }
     sqlite3VdbeAddOp0(v, OP_Halt);
     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
+    transferParseError(pParse, &sSubParse);
 
-    transferParseError(pParse, pSubParse);
-    if( db->mallocFailed==0 && pParse->nErr==0 ){
+    if( pParse->nErr==0 ){
+      assert( db->mallocFailed==0 );
       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
     }
-    pProgram->nMem = pSubParse->nMem;
-    pProgram->nCsr = pSubParse->nTab;
+    pProgram->nMem = sSubParse.nMem;
+    pProgram->nCsr = sSubParse.nTab;
     pProgram->token = (void *)pTrigger;
-    pPrg->aColmask[0] = pSubParse->oldmask;
-    pPrg->aColmask[1] = pSubParse->newmask;
+    pPrg->aColmask[0] = sSubParse.oldmask;
+    pPrg->aColmask[1] = sSubParse.newmask;
     sqlite3VdbeDelete(v);
+  }else{
+    transferParseError(pParse, &sSubParse);
   }
 
-  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
-  sqlite3ParserReset(pSubParse);
-  sqlite3StackFree(db, pSubParse);
-
+  assert( !sSubParse.pTriggerPrg && !sSubParse.nMaxArg );
+  sqlite3ParseObjectReset(&sSubParse);
   return pPrg;
 }
 
@@ -139722,6 +143262,7 @@ static TriggerPrg *getRowTrigger(
   /* If an existing TriggerPrg could not be located, create a new one. */
   if( !pPrg ){
     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
+    pParse->db->errByteOffset = -1;
   }
 
   return pPrg;
@@ -139744,7 +143285,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   TriggerPrg *pPrg;
   pPrg = getRowTrigger(pParse, p, pTab, orconf);
-  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
+  assert( pPrg || pParse->nErr );
 
   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   ** is a pointer to the sub-vdbe containing the trigger program.  */
@@ -139975,13 +143516,14 @@ static void updateVirtualTable(
 */
 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   assert( pTab!=0 );
-  if( !pTab->pSelect ){
+  if( !IsView(pTab) ){
     sqlite3_value *pValue = 0;
     u8 enc = ENC(sqlite3VdbeDb(v));
     Column *pCol = &pTab->aCol[i];
-    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
+    VdbeComment((v, "%s.%s", pTab->zName, pCol->zCnName));
     assert( i<pTab->nCol );
-    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
+    sqlite3ValueFromExpr(sqlite3VdbeDb(v),
+                         sqlite3ColumnExpr(pTab,pCol), enc,
                          pCol->affinity, &pValue);
     if( pValue ){
       sqlite3VdbeAppendP4(v, pValue, P4_MEM);
@@ -140135,6 +143677,7 @@ static void updateFromSelect(
 
   assert( pTabList->nSrc>1 );
   if( pSrc ){
+    pSrc->a[0].fg.notCte = 1;
     pSrc->a[0].iCursor = -1;
     pSrc->a[0].pTab->nTabRef--;
     pSrc->a[0].pTab = 0;
@@ -140150,7 +143693,7 @@ static void updateFromSelect(
       pList = sqlite3ExprListAppend(pParse, pList, pNew);
     }
     eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
-  }else if( pTab->pSelect ){
+  }else if( IsView(pTab) ){
     for(i=0; i<pTab->nCol; i++){
       pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
     }
@@ -140164,7 +143707,8 @@ static void updateFromSelect(
     }
 #endif
   }
-  if( ALWAYS(pChanges) ){
+  assert( pChanges!=0 || pParse->db->mallocFailed );
+  if( pChanges ){
     for(i=0; i<pChanges->nExpr; i++){
       pList = sqlite3ExprListAppend(pParse, pList,
           sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
@@ -140172,8 +143716,9 @@ static void updateFromSelect(
     }
   }
   pSelect = sqlite3SelectNew(pParse, pList,
-      pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UpdateFrom|SF_IncludeHidden, pLimit2
+      pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UFSrcCheck|SF_IncludeHidden, pLimit2
   );
+  if( pSelect ) pSelect->selFlags |= SF_OrderByReqd;
   sqlite3SelectDestInit(&dest, eDest, iEph);
   dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
   sqlite3Select(pParse, pSelect, &dest);
@@ -140258,9 +143803,11 @@ SQLITE_PRIVATE void sqlite3Update(
 
   memset(&sContext, 0, sizeof(sContext));
   db = pParse->db;
-  if( pParse->nErr || db->mallocFailed ){
+  assert( db->pParse==pParse );
+  if( pParse->nErr ){
     goto update_cleanup;
   }
+  assert( db->mallocFailed==0 );
 
   /* Locate the table which we want to update.
   */
@@ -140273,7 +143820,7 @@ SQLITE_PRIVATE void sqlite3Update(
   */
 #ifndef SQLITE_OMIT_TRIGGER
   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
-  isView = pTab->pSelect!=0;
+  isView = IsView(pTab);
   assert( pTrigger || tmask==0 );
 #else
 # define pTrigger 0
@@ -140362,13 +143909,16 @@ SQLITE_PRIVATE void sqlite3Update(
   */
   chngRowid = chngPk = 0;
   for(i=0; i<pChanges->nExpr; i++){
+    u8 hCol = sqlite3StrIHash(pChanges->a[i].zEName);
     /* If this is an UPDATE with a FROM clause, do not resolve expressions
     ** here. The call to sqlite3Select() below will do that. */
     if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
       goto update_cleanup;
     }
     for(j=0; j<pTab->nCol; j++){
-      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){
+      if( pTab->aCol[j].hName==hCol
+       && sqlite3StrICmp(pTab->aCol[j].zCnName, pChanges->a[i].zEName)==0
+      ){
         if( j==pTab->iPKey ){
           chngRowid = 1;
           pRowidExpr = pChanges->a[i].pExpr;
@@ -140382,7 +143932,7 @@ SQLITE_PRIVATE void sqlite3Update(
           testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
           sqlite3ErrorMsg(pParse,
              "cannot UPDATE generated column \"%s\"",
-             pTab->aCol[j].zName);
+             pTab->aCol[j].zCnName);
           goto update_cleanup;
         }
 #endif
@@ -140406,7 +143956,7 @@ SQLITE_PRIVATE void sqlite3Update(
     {
       int rc;
       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
-                            j<0 ? "ROWID" : pTab->aCol[j].zName,
+                            j<0 ? "ROWID" : pTab->aCol[j].zCnName,
                             db->aDb[iDb].zDbSName);
       if( rc==SQLITE_DENY ){
         goto update_cleanup;
@@ -140438,8 +143988,10 @@ SQLITE_PRIVATE void sqlite3Update(
       for(i=0; i<pTab->nCol; i++){
         if( aXRef[i]>=0 ) continue;
         if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
-        if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt,
-                                               aXRef, chngRowid) ){
+        if( sqlite3ExprReferencesUpdatedColumn(
+                sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
+                 aXRef, chngRowid)
+        ){
           aXRef[i] = 99999;
           bProgress = 1;
         }
@@ -140627,7 +144179,7 @@ SQLITE_PRIVATE void sqlite3Update(
       if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
         flags |= WHERE_ONEPASS_MULTIROW;
       }
-      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags,iIdxCur);
+      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,0,0,flags,iIdxCur);
       if( pWInfo==0 ) goto update_cleanup;
 
       /* A one-pass strategy that might update more than one row may not
@@ -140714,7 +144266,12 @@ SQLITE_PRIVATE void sqlite3Update(
 
     /* Top of the update loop */
     if( eOnePass!=ONEPASS_OFF ){
-      if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
+      if( aiCurOnePass[0]!=iDataCur
+       && aiCurOnePass[1]!=iDataCur
+#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
+       && !isView
+#endif
+      ){
         assert( pPk );
         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
         VdbeCoverage(v);
@@ -141022,9 +144579,7 @@ SQLITE_PRIVATE void sqlite3Update(
   ** that information.
   */
   if( regRowCount ){
-    sqlite3VdbeAddOp2(v, OP_ChngCntRow, regRowCount, 1);
-    sqlite3VdbeSetNumCols(v, 1);
-    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
+    sqlite3CodeChangeCount(v, regRowCount, "rows updated");
   }
 
 update_cleanup:
@@ -141146,7 +144701,9 @@ static void updateVirtualTable(
     regRowid = ++pParse->nMem;
 
     /* Start scanning the virtual table */
-    pWInfo = sqlite3WhereBegin(pParse, pSrc,pWhere,0,0,WHERE_ONEPASS_DESIRED,0);
+    pWInfo = sqlite3WhereBegin(
+        pParse, pSrc, pWhere, 0, 0, 0, WHERE_ONEPASS_DESIRED, 0
+    );
     if( pWInfo==0 ) return;
 
     /* Populate the argument registers. */
@@ -141526,7 +145083,7 @@ SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
         k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
         sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
         VdbeComment((v, "%s.%s", pIdx->zName,
-                    pTab->aCol[pPk->aiColumn[i]].zName));
+                    pTab->aCol[pPk->aiColumn[i]].zCnName));
       }
       sqlite3VdbeVerifyAbortable(v, OE_Abort);
       i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
@@ -141708,8 +145265,8 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
   Btree *pTemp;           /* The temporary database we vacuum into */
   u32 saved_mDbFlags;     /* Saved value of db->mDbFlags */
   u64 saved_flags;        /* Saved value of db->flags */
-  int saved_nChange;      /* Saved value of db->nChange */
-  int saved_nTotalChange; /* Saved value of db->nTotalChange */
+  i64 saved_nChange;      /* Saved value of db->nChange */
+  i64 saved_nTotalChange; /* Saved value of db->nTotalChange */
   u32 saved_openFlags;    /* Saved value of db->openFlags */
   u8 saved_mTrace;        /* Saved trace settings */
   Db *pDb = 0;            /* Database to detach at end of vacuum */
@@ -141807,7 +145364,9 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
 
   /* Do not attempt to change the page size for a WAL database */
   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
-                                               ==PAGER_JOURNALMODE_WAL ){
+                                               ==PAGER_JOURNALMODE_WAL
+   && pOut==0
+  ){
     db->nextPagesize = 0;
   }
 
@@ -142156,7 +145715,7 @@ SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   VTable *pVtab;
   assert( IsVirtual(pTab) );
-  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
+  for(pVtab=pTab->u.vtab.p; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   return pVtab;
 }
 
@@ -142169,7 +145728,8 @@ SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
 
   assert( db );
   assert( pVTab->nRef>0 );
-  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
+  assert( db->eOpenState==SQLITE_STATE_OPEN
+       || db->eOpenState==SQLITE_STATE_ZOMBIE );
 
   pVTab->nRef--;
   if( pVTab->nRef==0 ){
@@ -142184,21 +145744,24 @@ SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
 
 /*
 ** Table p is a virtual table. This function moves all elements in the
-** p->pVTable list to the sqlite3.pDisconnect lists of their associated
+** p->u.vtab.p list to the sqlite3.pDisconnect lists of their associated
 ** database connections to be disconnected at the next opportunity.
 ** Except, if argument db is not NULL, then the entry associated with
-** connection db is left in the p->pVTable list.
+** connection db is left in the p->u.vtab.p list.
 */
 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   VTable *pRet = 0;
-  VTable *pVTable = p->pVTable;
-  p->pVTable = 0;
+  VTable *pVTable;
+
+  assert( IsVirtual(p) );
+  pVTable = p->u.vtab.p;
+  p->u.vtab.p = 0;
 
   /* Assert that the mutex (if any) associated with the BtShared database
   ** that contains table p is held by the caller. See header comments
   ** above function sqlite3VtabUnlockList() for an explanation of why
   ** this makes it safe to access the sqlite3.pDisconnect list of any
-  ** database connection that may have an entry in the p->pVTable list.
+  ** database connection that may have an entry in the p->u.vtab.p list.
   */
   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
 
@@ -142208,7 +145771,7 @@ static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
     assert( db2 );
     if( db2==db ){
       pRet = pVTable;
-      p->pVTable = pRet;
+      p->u.vtab.p = pRet;
       pRet->pNext = 0;
     }else{
       pVTable->pNext = db2->pDisconnect;
@@ -142236,7 +145799,7 @@ SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
   assert( sqlite3BtreeHoldsAllMutexes(db) );
   assert( sqlite3_mutex_held(db->mutex) );
 
-  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
+  for(ppVTab=&p->u.vtab.p; *ppVTab; ppVTab=&(*ppVTab)->pNext){
     if( (*ppVTab)->db==db  ){
       VTable *pVTab = *ppVTab;
       *ppVTab = pVTab->pNext;
@@ -142299,37 +145862,41 @@ SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
 ** database connection.
 */
 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
+  assert( IsVirtual(p) );
   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
-  if( p->azModuleArg ){
+  if( p->u.vtab.azArg ){
     int i;
-    for(i=0; i<p->nModuleArg; i++){
-      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
+    for(i=0; i<p->u.vtab.nArg; i++){
+      if( i!=1 ) sqlite3DbFree(db, p->u.vtab.azArg[i]);
     }
-    sqlite3DbFree(db, p->azModuleArg);
+    sqlite3DbFree(db, p->u.vtab.azArg);
   }
 }
 
 /*
-** Add a new module argument to pTable->azModuleArg[].
+** Add a new module argument to pTable->u.vtab.azArg[].
 ** The string is not copied - the pointer is stored.  The
 ** string will be freed automatically when the table is
 ** deleted.
 */
 static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){
-  sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg);
+  sqlite3_int64 nBytes;
   char **azModuleArg;
   sqlite3 *db = pParse->db;
-  if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
+
+  assert( IsVirtual(pTable) );
+  nBytes = sizeof(char *)*(2+pTable->u.vtab.nArg);
+  if( pTable->u.vtab.nArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
     sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
   }
-  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
+  azModuleArg = sqlite3DbRealloc(db, pTable->u.vtab.azArg, nBytes);
   if( azModuleArg==0 ){
     sqlite3DbFree(db, zArg);
   }else{
-    int i = pTable->nModuleArg++;
+    int i = pTable->u.vtab.nArg++;
     azModuleArg[i] = zArg;
     azModuleArg[i+1] = 0;
-    pTable->azModuleArg = azModuleArg;
+    pTable->u.vtab.azArg = azModuleArg;
   }
 }
 
@@ -142352,10 +145919,11 @@ SQLITE_PRIVATE void sqlite3VtabBeginParse(
   pTable = pParse->pNewTable;
   if( pTable==0 ) return;
   assert( 0==pTable->pIndex );
+  pTable->eTabType = TABTYP_VTAB;
 
   db = pParse->db;
 
-  assert( pTable->nModuleArg==0 );
+  assert( pTable->u.vtab.nArg==0 );
   addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName));
   addModuleArgument(pParse, pTable, 0);
   addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
@@ -142372,11 +145940,11 @@ SQLITE_PRIVATE void sqlite3VtabBeginParse(
   ** sqlite_schema table, has already been made by sqlite3StartTable().
   ** The second call, to obtain permission to create the table, is made now.
   */
-  if( pTable->azModuleArg ){
+  if( pTable->u.vtab.azArg ){
     int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
     assert( iDb>=0 ); /* The database the table is being created in */
     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
-            pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
+            pTable->u.vtab.azArg[0], pParse->db->aDb[iDb].zDbSName);
   }
 #endif
 }
@@ -142404,9 +145972,10 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   sqlite3 *db = pParse->db;         /* The database connection */
 
   if( pTab==0 ) return;
+  assert( IsVirtual(pTab) );
   addArgumentToVtab(pParse);
   pParse->sArg.z = 0;
-  if( pTab->nModuleArg<1 ) return;
+  if( pTab->u.vtab.nArg<1 ) return;
 
   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   ** first time (in other words if the virtual table is actually being
@@ -142439,7 +146008,7 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
     */
     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
     sqlite3NestedParse(pParse,
-      "UPDATE %Q." DFLT_SCHEMA_TABLE " "
+      "UPDATE %Q." LEGACY_SCHEMA_TABLE " "
          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
        "WHERE rowid=#%d",
       db->aDb[iDb].zDbSName,
@@ -142459,18 +146028,14 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
     iReg = ++pParse->nMem;
     sqlite3VdbeLoadString(v, iReg, pTab->zName);
     sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
-  }
-
-  /* If we are rereading the sqlite_schema table create the in-memory
-  ** record of the table. The xConnect() method is not called until
-  ** the first time the virtual table is used in an SQL statement. This
-  ** allows a schema that contains virtual tables to be loaded before
-  ** the required virtual table implementations are registered.  */
-  else {
+  }else{
+    /* If we are rereading the sqlite_schema table create the in-memory
+    ** record of the table. */
     Table *pOld;
     Schema *pSchema = pTab->pSchema;
     const char *zName = pTab->zName;
-    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
+    assert( zName!=0 );
+    sqlite3MarkAllShadowTablesOf(db, pTab);
     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
     if( pOld ){
       sqlite3OomFault(db);
@@ -142521,13 +146086,16 @@ static int vtabCallConstructor(
   VtabCtx sCtx;
   VTable *pVTable;
   int rc;
-  const char *const*azArg = (const char *const*)pTab->azModuleArg;
-  int nArg = pTab->nModuleArg;
+  const char *const*azArg;
+  int nArg = pTab->u.vtab.nArg;
   char *zErr = 0;
   char *zModuleName;
   int iDb;
   VtabCtx *pCtx;
 
+  assert( IsVirtual(pTab) );
+  azArg = (const char *const*)pTab->u.vtab.azArg;
+
   /* Check that the virtual-table is not already being initialized */
   for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
     if( pCtx->pTab==pTab ){
@@ -142554,7 +146122,7 @@ static int vtabCallConstructor(
   pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;
 
   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
-  pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
+  pTab->u.vtab.azArg[1] = db->aDb[iDb].zDbSName;
 
   /* Invoke the virtual table constructor */
   assert( &db->pVtabCtx );
@@ -142593,12 +146161,12 @@ static int vtabCallConstructor(
       int iCol;
       u16 oooHidden = 0;
       /* If everything went according to plan, link the new VTable structure
-      ** into the linked list headed by pTab->pVTable. Then loop through the
+      ** into the linked list headed by pTab->u.vtab.p. Then loop through the
       ** columns of the table to see if any of them contain the token "hidden".
       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
       ** the type string.  */
-      pVTable->pNext = pTab->pVTable;
-      pTab->pVTable = pVTable;
+      pVTable->pNext = pTab->u.vtab.p;
+      pTab->u.vtab.p = pVTable;
 
       for(iCol=0; iCol<pTab->nCol; iCol++){
         char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
@@ -142651,16 +146219,17 @@ SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   int rc;
 
   assert( pTab );
-  if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
+  assert( IsVirtual(pTab) );
+  if( sqlite3GetVTable(db, pTab) ){
     return SQLITE_OK;
   }
 
   /* Locate the required virtual table module */
-  zMod = pTab->azModuleArg[0];
+  zMod = pTab->u.vtab.azArg[0];
   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
 
   if( !pMod ){
-    const char *zModule = pTab->azModuleArg[0];
+    const char *zModule = pTab->u.vtab.azArg[0];
     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
     rc = SQLITE_ERROR;
   }else{
@@ -142723,10 +146292,10 @@ SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab,
   const char *zMod;
 
   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
-  assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
+  assert( pTab && IsVirtual(pTab) && !pTab->u.vtab.p );
 
   /* Locate the required virtual table module */
-  zMod = pTab->azModuleArg[0];
+  zMod = pTab->u.vtab.azArg[0];
   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
 
   /* If the module has been registered and includes a Create method,
@@ -142761,8 +146330,8 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   VtabCtx *pCtx;
   int rc = SQLITE_OK;
   Table *pTab;
-  char *zErr = 0;
   Parse sParse;
+  int initBusy;
 
 #ifdef SQLITE_ENABLE_API_ARMOR
   if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
@@ -142779,20 +146348,27 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   pTab = pCtx->pTab;
   assert( IsVirtual(pTab) );
 
-  memset(&sParse, 0, sizeof(sParse));
+  sqlite3ParseObjectInit(&sParse, db);
   sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
-  sParse.db = db;
+  sParse.disableTriggers = 1;
+  /* We should never be able to reach this point while loading the
+  ** schema.  Nevertheless, defend against that (turn off db->init.busy)
+  ** in case a bug arises. */
+  assert( db->init.busy==0 );
+  initBusy = db->init.busy;
+  db->init.busy = 0;
   sParse.nQueryLoop = 1;
-  if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
-   && sParse.pNewTable
-   && !db->mallocFailed
-   && !sParse.pNewTable->pSelect
-   && !IsVirtual(sParse.pNewTable)
+  if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable)
+   && ALWAYS(sParse.pNewTable!=0)
+   && ALWAYS(!db->mallocFailed)
+   && IsOrdinaryTable(sParse.pNewTable)
   ){
+    assert( sParse.zErrMsg==0 );
     if( !pTab->aCol ){
       Table *pNew = sParse.pNewTable;
       Index *pIdx;
       pTab->aCol = pNew->aCol;
+      sqlite3ExprListDelete(db, pNew->u.tab.pDfltList);
       pTab->nNVCol = pTab->nCol = pNew->nCol;
       pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
       pNew->nCol = 0;
@@ -142817,8 +146393,9 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
     }
     pCtx->bDeclared = 1;
   }else{
-    sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
-    sqlite3DbFree(db, zErr);
+    sqlite3ErrorWithMsg(db, SQLITE_ERROR,
+          (sParse.zErrMsg ? "%s" : 0), sParse.zErrMsg);
+    sqlite3DbFree(db, sParse.zErrMsg);
     rc = SQLITE_ERROR;
   }
   sParse.eParseMode = PARSE_MODE_NORMAL;
@@ -142827,7 +146404,8 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
     sqlite3VdbeFinalize(sParse.pVdbe);
   }
   sqlite3DeleteTable(db, sParse.pNewTable);
-  sqlite3ParserReset(&sParse);
+  sqlite3ParseObjectReset(&sParse);
+  db->init.busy = initBusy;
 
   assert( (rc&0xff)==rc );
   rc = sqlite3ApiExit(db, rc);
@@ -142847,10 +146425,13 @@ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab
   Table *pTab;
 
   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
-  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
+  if( ALWAYS(pTab!=0)
+   && ALWAYS(IsVirtual(pTab))
+   && ALWAYS(pTab->u.vtab.p!=0)
+  ){
     VTable *p;
     int (*xDestroy)(sqlite3_vtab *);
-    for(p=pTab->pVTable; p; p=p->pNext){
+    for(p=pTab->u.vtab.p; p; p=p->pNext){
       assert( p->pVtab );
       if( p->pVtab->nRef>0 ){
         return SQLITE_LOCKED;
@@ -142864,9 +146445,9 @@ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab
     rc = xDestroy(p->pVtab);
     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
     if( rc==SQLITE_OK ){
-      assert( pTab->pVTable==p && p->pNext==0 );
+      assert( pTab->u.vtab.p==p && p->pNext==0 );
       p->pVtab = 0;
-      pTab->pVTable = 0;
+      pTab->u.vtab.p = 0;
       sqlite3VtabUnlock(p);
     }
     sqlite3DeleteTable(db, pTab);
@@ -143080,6 +146661,7 @@ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   /* Check to see the left operand is a column in a virtual table */
   if( NEVER(pExpr==0) ) return pDef;
   if( pExpr->op!=TK_COLUMN ) return pDef;
+  assert( ExprUseYTab(pExpr) );
   pTab = pExpr->y.pTab;
   if( pTab==0 ) return pDef;
   if( !IsVirtual(pTab) ) return pDef;
@@ -143154,8 +146736,9 @@ SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
 /*
 ** Check to see if virtual table module pMod can be have an eponymous
 ** virtual table instance.  If it can, create one if one does not already
-** exist. Return non-zero if the eponymous virtual table instance exists
-** when this routine returns, and return zero if it does not exist.
+** exist. Return non-zero if either the eponymous virtual table instance
+** exists when this routine returns or if an attempt to create it failed
+** and an error message was left in pParse.
 **
 ** An eponymous virtual table instance is one that is named after its
 ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
@@ -143182,9 +146765,11 @@ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
   }
   pMod->pEpoTab = pTab;
   pTab->nTabRef = 1;
+  pTab->eTabType = TABTYP_VTAB;
   pTab->pSchema = db->aDb[0].pSchema;
-  assert( pTab->nModuleArg==0 );
+  assert( pTab->u.vtab.nArg==0 );
   pTab->iPKey = -1;
+  pTab->tabFlags |= TF_Eponymous;
   addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
   addModuleArgument(pParse, pTab, 0);
   addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
@@ -143193,7 +146778,6 @@ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
     sqlite3ErrorMsg(pParse, "%s", zErr);
     sqlite3DbFree(db, zErr);
     sqlite3VtabEponymousTableClear(db, pMod);
-    return 0;
   }
   return 1;
 }
@@ -143372,6 +146956,7 @@ struct WhereLevel {
   u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
   int addrLikeRep;      /* LIKE range processing address */
 #endif
+  int regFilter;        /* Bloom filter */
   u8 iFrom;             /* Which entry in the FROM clause */
   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
   int p1, p2;           /* Operands of the opcode used to end the loop */
@@ -143386,7 +146971,7 @@ struct WhereLevel {
         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
       } *aInLoop;           /* Information about each nested IN operator */
     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
-    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
+    Index *pCoveringIdx;  /* Possible covering index for WHERE_MULTI_OR */
   } u;
   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
   Bitmask notReady;          /* FROM entries not usable at this level */
@@ -143430,10 +147015,12 @@ struct WhereLoop {
     } btree;
     struct {               /* Information for virtual tables */
       int idxNum;            /* Index number */
-      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
+      u32 needFree : 1;      /* True if sqlite3_free(idxStr) is needed */
+      u32 bOmitOffset : 1;   /* True to let virtual table handle offset */
       i8 isOrdered;          /* True if satisfies ORDER BY */
       u16 omitMask;          /* Terms that may be omitted */
       char *idxStr;          /* Index identifier string */
+      u32 mHandleIn;         /* Terms to handle as IN(...) instead of == */
     } vtab;
   } u;
   u32 wsFlags;          /* WHERE_* flags describing the plan */
@@ -143577,7 +147164,7 @@ struct WhereTerm {
 #define TERM_COPIED     0x0008 /* Has a child */
 #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 */
+#define TERM_OK         0x0040 /* Used during OR-clause processing */
 #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 */
@@ -143590,6 +147177,7 @@ struct WhereTerm {
 #else
 #  define TERM_HIGHTRUTH  0      /* Only used with STAT4 */
 #endif
+#define TERM_SLICE      0x8000 /* One slice of a row-value/vector comparison */
 
 /*
 ** An instance of the WhereScan object is used as an iterator for locating
@@ -143600,11 +147188,11 @@ struct WhereScan {
   WhereClause *pWC;          /* WhereClause currently being scanned */
   const char *zCollName;     /* Required collating sequence, if not NULL */
   Expr *pIdxExpr;            /* Search for this index expression */
-  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
-  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
-  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
-  u32 opMask;                /* Acceptable operators */
   int k;                     /* Resume scanning at this->pWC->a[this->k] */
+  u32 opMask;                /* Acceptable operators */
+  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
+  unsigned char iEquiv;      /* Current slot in aiCur[] and aiColumn[] */
+  unsigned char nEquiv;      /* Number of entries in aiCur[] and aiColumn[] */
   int aiCur[11];             /* Cursors in the equivalence class */
   i16 aiColumn[11];          /* Corresponding column number in the eq-class */
 };
@@ -143628,6 +147216,7 @@ struct WhereClause {
   u8 hasOr;                /* True if any a[].eOperator is WO_OR */
   int nTerm;               /* Number of terms */
   int nSlot;               /* Number of entries in a[] */
+  int nBase;               /* Number of terms through the last non-Virtual */
   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
 #if defined(SQLITE_SMALL_STACK)
   WhereTerm aStatic[1];    /* Initial static space for a[] */
@@ -143685,11 +147274,6 @@ struct WhereMaskSet {
   int ix[BMS];                  /* Cursor assigned to each bit */
 };
 
-/*
-** Initialize a WhereMaskSet object
-*/
-#define initMaskSet(P)  (P)->n=0
-
 /*
 ** This object is a convenience wrapper holding all information needed
 ** to construct WhereLoop objects for a particular query.
@@ -143697,7 +147281,6 @@ struct WhereMaskSet {
 struct WhereLoopBuilder {
   WhereInfo *pWInfo;        /* Information about this WHERE */
   WhereClause *pWC;         /* WHERE clause terms */
-  ExprList *pOrderBy;       /* ORDER BY clause */
   WhereLoop *pNew;          /* Template WhereLoop */
   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
 #ifdef SQLITE_ENABLE_STAT4
@@ -143765,6 +147348,9 @@ struct WhereInfo {
   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
   ExprList *pResultSet;     /* Result set of the query */
   Expr *pWhere;             /* The complete WHERE clause */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+  Select *pLimit;           /* Used to access LIMIT expr/registers for vtabs */
+#endif
   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
   int iContinue;            /* Jump here to continue with next record */
   int iBreak;               /* Jump here to break out of the loop */
@@ -143818,8 +147404,14 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
 );
+SQLITE_PRIVATE int sqlite3WhereExplainBloomFilter(
+  const Parse *pParse,            /* Parse context */
+  const WhereInfo *pWInfo,        /* WHERE clause */
+  const WhereLevel *pLevel        /* Bloom filter on this level */
+);
 #else
 # define sqlite3WhereExplainOneScan(u,v,w,x) 0
+# define sqlite3WhereExplainBloomFilter(u,v,w) 0
 #endif /* SQLITE_OMIT_EXPLAIN */
 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
@@ -143844,6 +147436,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
 SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
+SQLITE_PRIVATE void sqlite3WhereAddLimit(WhereClause*, Select*);
 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
@@ -143911,6 +147504,10 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*);
 #define WHERE_IN_EARLYOUT  0x00040000  /* Perhaps quit IN loops early */
 #define WHERE_BIGNULL_SORT 0x00080000  /* Column nEq of index is BIGNULL */
 #define WHERE_IN_SEEKSCAN  0x00100000  /* Seek-scan optimization for IN */
+#define WHERE_TRANSCONS    0x00200000  /* Uses a transitive constraint */
+#define WHERE_BLOOMFILTER  0x00400000  /* Consider using a Bloom-filter */
+#define WHERE_SELFCULL     0x00800000  /* nOut reduced by extra WHERE terms */
+#define WHERE_OMIT_OFFSET  0x01000000  /* Set offset counter to zero */
 
 #endif /* !defined(SQLITE_WHEREINT_H) */
 
@@ -143926,7 +147523,7 @@ static const char *explainIndexColumnName(Index *pIdx, int i){
   i = pIdx->aiColumn[i];
   if( i==XN_EXPR ) return "<expr>";
   if( i==XN_ROWID ) return "rowid";
-  return pIdx->pTable->aCol[i].zName;
+  return pIdx->pTable->aCol[i].zCnName;
 }
 
 /*
@@ -144045,16 +147642,8 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
 
     sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
-    sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
-    if( pItem->pSelect ){
-      sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId);
-    }else{
-      sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
-    }
-
-    if( pItem->zAlias ){
-      sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
-    }
+    str.printfFlags = SQLITE_PRINTF_INTERNAL;
+    sqlite3_str_appendf(&str, "%s %S", isSearch ? "SEARCH" : "SCAN", pItem);
     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
       const char *zFmt = 0;
       Index *pIdx;
@@ -144081,19 +147670,27 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
         explainIndexRange(&str, pLoop);
       }
     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
-      const char *zRangeOp;
+      char cRangeOp;
+#if 0  /* Better output, but breaks many tests */
+      const Table *pTab = pItem->pTab;
+      const char *zRowid = pTab->iPKey>=0 ? pTab->aCol[pTab->iPKey].zCnName:
+                              "rowid";
+#else
+      const char *zRowid = "rowid";
+#endif
+      sqlite3_str_appendf(&str, " USING INTEGER PRIMARY KEY (%s", zRowid);
       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
-        zRangeOp = "=";
+        cRangeOp = '=';
       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
-        zRangeOp = ">? AND rowid<";
+        sqlite3_str_appendf(&str, ">? AND %s", zRowid);
+        cRangeOp = '<';
       }else if( flags&WHERE_BTM_LIMIT ){
-        zRangeOp = ">";
+        cRangeOp = '>';
       }else{
         assert( flags&WHERE_TOP_LIMIT);
-        zRangeOp = "<";
+        cRangeOp = '<';
       }
-      sqlite3_str_appendf(&str,
-          " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
+      sqlite3_str_appendf(&str, "%c?)", cRangeOp);
     }
 #ifndef SQLITE_OMIT_VIRTUALTABLE
     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
@@ -144116,6 +147713,56 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
   }
   return ret;
 }
+
+/*
+** Add a single OP_Explain opcode that describes a Bloom filter.
+**
+** Or if not processing EXPLAIN QUERY PLAN and not in a SQLITE_DEBUG and/or
+** SQLITE_ENABLE_STMT_SCANSTATUS build, then OP_Explain opcodes are not
+** required and this routine is a no-op.
+**
+** If an OP_Explain opcode is added to the VM, its address is returned.
+** Otherwise, if no OP_Explain is coded, zero is returned.
+*/
+SQLITE_PRIVATE int sqlite3WhereExplainBloomFilter(
+  const Parse *pParse,               /* Parse context */
+  const WhereInfo *pWInfo,           /* WHERE clause */
+  const WhereLevel *pLevel           /* Bloom filter on this level */
+){
+  int ret = 0;
+  SrcItem *pItem = &pWInfo->pTabList->a[pLevel->iFrom];
+  Vdbe *v = pParse->pVdbe;      /* VM being constructed */
+  sqlite3 *db = pParse->db;     /* Database handle */
+  char *zMsg;                   /* Text to add to EQP output */
+  int i;                        /* Loop counter */
+  WhereLoop *pLoop;             /* The where loop */
+  StrAccum str;                 /* EQP output string */
+  char zBuf[100];               /* Initial space for EQP output string */
+
+  sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
+  str.printfFlags = SQLITE_PRINTF_INTERNAL;
+  sqlite3_str_appendf(&str, "BLOOM FILTER ON %S (", pItem);
+  pLoop = pLevel->pWLoop;
+  if( pLoop->wsFlags & WHERE_IPK ){
+    const Table *pTab = pItem->pTab;
+    if( pTab->iPKey>=0 ){
+      sqlite3_str_appendf(&str, "%s=?", pTab->aCol[pTab->iPKey].zCnName);
+    }else{
+      sqlite3_str_appendf(&str, "rowid=?");
+    }
+  }else{
+    for(i=pLoop->nSkip; i<pLoop->u.btree.nEq; i++){
+      const char *z = explainIndexColumnName(pLoop->u.btree.pIndex, i);
+      if( i>pLoop->nSkip ) sqlite3_str_append(&str, " AND ", 5);
+      sqlite3_str_appendf(&str, "%s=?", z);
+    }
+  }
+  sqlite3_str_append(&str, ")", 1);
+  zMsg = sqlite3StrAccumFinish(&str);
+  ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
+                          pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
+  return ret;
+}
 #endif /* SQLITE_OMIT_EXPLAIN */
 
 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
@@ -144202,6 +147849,12 @@ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
     }else{
       pTerm->wtFlags |= TERM_CODED;
     }
+#ifdef WHERETRACE_ENABLED
+    if( sqlite3WhereTrace & 0x20000 ){
+      sqlite3DebugPrintf("DISABLE-");
+      sqlite3WhereTermPrint(pTerm, (int)(pTerm - (pTerm->pWC->a)));
+    }
+#endif
     if( pTerm->iParent<0 ) break;
     pTerm = &pTerm->pWC->a[pTerm->iParent];
     assert( pTerm!=0 );
@@ -144315,16 +147968,23 @@ static Expr *removeUnindexableInClauseTerms(
   Expr *pNew;
   pNew = sqlite3ExprDup(db, pX, 0);
   if( db->mallocFailed==0 ){
-    ExprList *pOrigRhs = pNew->x.pSelect->pEList;  /* Original unmodified RHS */
-    ExprList *pOrigLhs = pNew->pLeft->x.pList;     /* Original unmodified LHS */
+    ExprList *pOrigRhs;         /* Original unmodified RHS */
+    ExprList *pOrigLhs;         /* Original unmodified LHS */
     ExprList *pRhs = 0;         /* New RHS after modifications */
     ExprList *pLhs = 0;         /* New LHS after mods */
     int i;                      /* Loop counter */
     Select *pSelect;            /* Pointer to the SELECT on the RHS */
 
+    assert( ExprUseXSelect(pNew) );
+    pOrigRhs = pNew->x.pSelect->pEList;
+    assert( pNew->pLeft!=0 );
+    assert( ExprUseXList(pNew->pLeft) );
+    pOrigLhs = pNew->pLeft->x.pList;
     for(i=iEq; i<pLoop->nLTerm; i++){
       if( pLoop->aLTerm[i]->pExpr==pX ){
-        int iField = pLoop->aLTerm[i]->u.x.iField - 1;
+        int iField;
+        assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
+        iField = pLoop->aLTerm[i]->u.x.iField - 1;
         if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
         pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
         pOrigRhs->a[iField].pExpr = 0;
@@ -144439,7 +148099,7 @@ static int codeEqualityTerm(
     }
 
     iTab = 0;
-    if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
+    if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
       eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
     }else{
       sqlite3 *db = pParse->db;
@@ -144461,8 +148121,8 @@ static int codeEqualityTerm(
     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
     VdbeCoverageIf(v, bRev);
     VdbeCoverageIf(v, !bRev);
-    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
 
+    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
     pLoop->wsFlags |= WHERE_IN_ABLE;
     if( pLevel->u.in.nIn==0 ){
       pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
@@ -144519,7 +148179,22 @@ static int codeEqualityTerm(
     sqlite3DbFree(pParse->db, aiMap);
 #endif
   }
-  disableTerm(pLevel, pTerm);
+
+  /* As an optimization, try to disable the WHERE clause term that is
+  ** driving the index as it will always be true.  The correct answer is
+  ** obtained regardless, but we might get the answer with fewer CPU cycles
+  ** by omitting the term.
+  **
+  ** But do not disable the term unless we are certain that the term is
+  ** not a transitive constraint.  For an example of where that does not
+  ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
+  */
+  if( (pLevel->pWLoop->wsFlags & WHERE_TRANSCONS)==0
+   || (pTerm->eOperator & WO_EQUIV)==0
+  ){
+    disableTerm(pLevel, pTerm);
+  }
+
   return iReg;
 }
 
@@ -144605,11 +148280,13 @@ static int codeAllEqualityTerms(
 
   if( nSkip ){
     int iIdxCur = pLevel->iIdxCur;
+    sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1);
     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
     VdbeCoverageIf(v, bRev==0);
     VdbeCoverageIf(v, bRev!=0);
     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
     j = sqlite3VdbeAddOp0(v, OP_Goto);
+    assert( pLevel->addrSkip==0 );
     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
                             iIdxCur, 0, regBase, nSkip);
     VdbeCoverageIf(v, bRev==0);
@@ -144639,9 +148316,12 @@ static int codeAllEqualityTerms(
         sqlite3ReleaseTempReg(pParse, regBase);
         regBase = r1;
       }else{
-        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
+        sqlite3VdbeAddOp2(v, OP_Copy, r1, regBase+j);
       }
     }
+  }
+  for(j=nSkip; j<nEq; j++){
+    pTerm = pLoop->aLTerm[j];
     if( pTerm->eOperator & WO_IN ){
       if( pTerm->pExpr->flags & EP_xIsSelect ){
         /* No affinity ever needs to be (or should be) applied to a value
@@ -144656,7 +148336,8 @@ static int codeAllEqualityTerms(
         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
         VdbeCoverage(v);
       }
-      if( zAff ){
+      if( pParse->nErr==0 ){
+        assert( pParse->db->mallocFailed==0 );
         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
           zAff[j] = SQLITE_AFF_BLOB;
         }
@@ -144846,7 +148527,7 @@ static void codeCursorHint(
   sWalker.pParse = pParse;
   sWalker.u.pCCurHint = &sHint;
   pWC = &pWInfo->sWC;
-  for(i=0; i<pWC->nTerm; i++){
+  for(i=0; i<pWC->nBase; i++){
     pTerm = &pWC->a[i];
     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
     if( pTerm->prereqAll & pLevel->notReady ) continue;
@@ -144876,7 +148557,7 @@ static void codeCursorHint(
     if( pTabItem->fg.jointype & JT_LEFT ){
       Expr *pExpr = pTerm->pExpr;
       if( !ExprHasProperty(pExpr, EP_FromJoin)
-       || pExpr->iRightJoinTable!=pTabItem->iCursor
+       || pExpr->w.iRightJoinTable!=pTabItem->iCursor
       ){
         sWalker.eCode = 0;
         sWalker.xExprCallback = codeCursorHintIsOrFunction;
@@ -144988,7 +148669,7 @@ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
   assert( nReg>0 );
   if( p && sqlite3ExprIsVector(p) ){
 #ifndef SQLITE_OMIT_SUBQUERY
-    if( (p->flags & EP_xIsSelect) ){
+    if( ExprUseXSelect(p) ){
       Vdbe *v = pParse->pVdbe;
       int iSelect;
       assert( p->op==TK_SELECT );
@@ -144998,14 +148679,16 @@ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
 #endif
     {
       int i;
-      ExprList *pList = p->x.pList;
+      const ExprList *pList;
+      assert( ExprUseXList(p) );
+      pList = p->x.pList;
       assert( nReg<=pList->nExpr );
       for(i=0; i<nReg; i++){
         sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
       }
     }
   }else{
-    assert( nReg==1 );
+    assert( nReg==1 || pParse->nErr );
     sqlite3ExprCode(pParse, p, iReg);
   }
 }
@@ -145046,15 +148729,16 @@ static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){
 static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
   IdxExprTrans *pX = p->u.pIdxTrans;
   if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
+    pExpr = sqlite3ExprSkipCollate(pExpr);
     preserveExpr(pX, pExpr);
     pExpr->affExpr = sqlite3ExprAffinity(pExpr);
     pExpr->op = TK_COLUMN;
     pExpr->iTable = pX->iIdxCur;
     pExpr->iColumn = pX->iIdxCol;
-    pExpr->y.pTab = 0;
     testcase( ExprHasProperty(pExpr, EP_Skip) );
     testcase( ExprHasProperty(pExpr, EP_Unlikely) );
-    ExprClearProperty(pExpr, EP_Skip|EP_Unlikely);
+    ExprClearProperty(pExpr, EP_Skip|EP_Unlikely|EP_WinFunc|EP_Subrtn);
+    pExpr->y.pTab = 0;
     return WRC_Prune;
   }else{
     return WRC_Continue;
@@ -145069,7 +148753,7 @@ static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){
   if( pExpr->op==TK_COLUMN ){
     IdxExprTrans *pX = p->u.pIdxTrans;
     if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){
-      assert( pExpr->y.pTab!=0 );
+      assert( ExprUseYTab(pExpr) && pExpr->y.pTab!=0 );
       preserveExpr(pX, pExpr);
       pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn);
       pExpr->iTable = pX->iIdxCur;
@@ -145117,15 +148801,16 @@ static void whereIndexExprTrans(
   for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){
     i16 iRef = pIdx->aiColumn[iIdxCol];
     if( iRef==XN_EXPR ){
-      assert( aColExpr->a[iIdxCol].pExpr!=0 );
+      assert( aColExpr!=0 && aColExpr->a[iIdxCol].pExpr!=0 );
       x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
       if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue;
       w.xExprCallback = whereIndexExprTransNode;
 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
     }else if( iRef>=0
        && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0
-       && (pTab->aCol[iRef].zColl==0
-           || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0)
+       && ((pTab->aCol[iRef].colFlags & COLFLAG_HASCOLL)==0
+           || sqlite3StrICmp(sqlite3ColumnColl(&pTab->aCol[iRef]),
+                                               sqlite3StrBINARY)==0)
     ){
       /* Check to see if there are direct references to generated columns
       ** that are contained in the index.  Pulling the generated column
@@ -145174,6 +148859,68 @@ static void whereApplyPartialIndexConstraints(
   }
 }
 
+/*
+** This routine is called right after An OP_Filter has been generated and
+** before the corresponding index search has been performed.  This routine
+** checks to see if there are additional Bloom filters in inner loops that
+** can be checked prior to doing the index lookup.  If there are available
+** inner-loop Bloom filters, then evaluate those filters now, before the
+** index lookup.  The idea is that a Bloom filter check is way faster than
+** an index lookup, and the Bloom filter might return false, meaning that
+** the index lookup can be skipped.
+**
+** We know that an inner loop uses a Bloom filter because it has the
+** WhereLevel.regFilter set.  If an inner-loop Bloom filter is checked,
+** then clear the WhereLevel.regFilter value to prevent the Bloom filter
+** from being checked a second time when the inner loop is evaluated.
+*/
+static SQLITE_NOINLINE void filterPullDown(
+  Parse *pParse,       /* Parsing context */
+  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
+  int iLevel,          /* Which level of pWInfo->a[] should be coded */
+  int addrNxt,         /* Jump here to bypass inner loops */
+  Bitmask notReady     /* Loops that are not ready */
+){
+  while( ++iLevel < pWInfo->nLevel ){
+    WhereLevel *pLevel = &pWInfo->a[iLevel];
+    WhereLoop *pLoop = pLevel->pWLoop;
+    if( pLevel->regFilter==0 ) continue;
+    if( pLevel->pWLoop->nSkip ) continue;
+    /*         ,--- Because sqlite3ConstructBloomFilter() has will not have set
+    **  vvvvv--'    pLevel->regFilter if this were true. */
+    if( NEVER(pLoop->prereq & notReady) ) continue;
+    assert( pLevel->addrBrk==0 );
+    pLevel->addrBrk = addrNxt;
+    if( pLoop->wsFlags & WHERE_IPK ){
+      WhereTerm *pTerm = pLoop->aLTerm[0];
+      int regRowid;
+      assert( pTerm!=0 );
+      assert( pTerm->pExpr!=0 );
+      testcase( pTerm->wtFlags & TERM_VIRTUAL );
+      regRowid = sqlite3GetTempReg(pParse);
+      regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid);
+      sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
+                           addrNxt, regRowid, 1);
+      VdbeCoverage(pParse->pVdbe);
+    }else{
+      u16 nEq = pLoop->u.btree.nEq;
+      int r1;
+      char *zStartAff;
+
+      assert( pLoop->wsFlags & WHERE_INDEXED );
+      assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
+      r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff);
+      codeApplyAffinity(pParse, r1, nEq, zStartAff);
+      sqlite3DbFree(pParse->db, zStartAff);
+      sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
+                           addrNxt, r1, nEq);
+      VdbeCoverage(pParse->pVdbe);
+    }
+    pLevel->regFilter = 0;
+    pLevel->addrBrk = 0;
+  }
+}
+
 /*
 ** Generate code for the start of the iLevel-th loop in the WHERE clause
 ** implementation described by pWInfo.
@@ -145276,7 +149023,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     int iReg;   /* P3 Value for OP_VFilter */
     int addrNotFound;
     int nConstraint = pLoop->nLTerm;
-    int iIn;    /* Counter for IN constraints */
 
     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
     addrNotFound = pLevel->addrBrk;
@@ -145285,11 +149031,27 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       pTerm = pLoop->aLTerm[j];
       if( NEVER(pTerm==0) ) continue;
       if( pTerm->eOperator & WO_IN ){
-        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
-        addrNotFound = pLevel->addrNxt;
+        if( SMASKBIT32(j) & pLoop->u.vtab.mHandleIn ){
+          int iTab = pParse->nTab++;
+          int iCache = ++pParse->nMem;
+          sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab);
+          sqlite3VdbeAddOp3(v, OP_VInitIn, iTab, iTarget, iCache);
+        }else{
+          codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
+          addrNotFound = pLevel->addrNxt;
+        }
       }else{
         Expr *pRight = pTerm->pExpr->pRight;
         codeExprOrVector(pParse, pRight, iTarget, 1);
+        if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET
+         && pLoop->u.vtab.bOmitOffset
+        ){
+          assert( pTerm->eOperator==WO_AUX );
+          assert( pWInfo->pLimit!=0 );
+          assert( pWInfo->pLimit->iOffset>0 );
+          sqlite3VdbeAddOp2(v, OP_Integer, 0, pWInfo->pLimit->iOffset);
+          VdbeComment((v,"Zero OFFSET counter"));
+        }
       }
     }
     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
@@ -145305,40 +149067,55 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     pLevel->p1 = iCur;
     pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
-    iIn = pLevel->u.in.nIn;
-    for(j=nConstraint-1; j>=0; j--){
+    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
+
+    for(j=0; j<nConstraint; j++){
       pTerm = pLoop->aLTerm[j];
-      if( (pTerm->eOperator & WO_IN)!=0 ) iIn--;
       if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
         disableTerm(pLevel, pTerm);
-      }else if( (pTerm->eOperator & WO_IN)!=0
-        && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1
+        continue;
+      }
+      if( (pTerm->eOperator & WO_IN)!=0
+       && (SMASKBIT32(j) & pLoop->u.vtab.mHandleIn)==0
+       && !db->mallocFailed
       ){
         Expr *pCompare;  /* The comparison operator */
         Expr *pRight;    /* RHS of the comparison */
         VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
+        int iIn;         /* IN loop corresponding to the j-th constraint */
 
         /* Reload the constraint value into reg[iReg+j+2].  The same value
         ** was loaded into the same register prior to the OP_VFilter, but
         ** the xFilter implementation might have changed the datatype or
-        ** encoding of the value in the register, so it *must* be reloaded. */
-        assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
-        if( !db->mallocFailed ){
-          assert( iIn>=0 && iIn<pLevel->u.in.nIn );
+        ** encoding of the value in the register, so it *must* be reloaded.
+        */
+        for(iIn=0; ALWAYS(iIn<pLevel->u.in.nIn); iIn++){
           pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
-          assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
-          assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
-          assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
-          testcase( pOp->opcode==OP_Rowid );
-          sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
+          if( (pOp->opcode==OP_Column && pOp->p3==iReg+j+2)
+           || (pOp->opcode==OP_Rowid && pOp->p2==iReg+j+2)
+          ){
+            testcase( pOp->opcode==OP_Rowid );
+            sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
+            break;
+          }
         }
 
         /* Generate code that will continue to the next row if
-        ** the IN constraint is not satisfied */
+        ** the IN constraint is not satisfied
+        */
         pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
-        assert( pCompare!=0 || db->mallocFailed );
-        if( pCompare ){
-          pCompare->pLeft = pTerm->pExpr->pLeft;
+        if( !db->mallocFailed ){
+          int iFld = pTerm->u.x.iField;
+          Expr *pLeft = pTerm->pExpr->pLeft;
+          assert( pLeft!=0 );
+          if( iFld>0 ){
+            assert( pLeft->op==TK_VECTOR );
+            assert( ExprUseXList(pLeft) );
+            assert( iFld<=pLeft->x.pList->nExpr );
+            pCompare->pLeft = pLeft->x.pList->a[iFld-1].pExpr;
+          }else{
+            pCompare->pLeft = pLeft;
+          }
           pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
           if( pRight ){
             pRight->iTable = iReg+j+2;
@@ -145347,11 +149124,11 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
             );
           }
           pCompare->pLeft = 0;
-          sqlite3ExprDelete(db, pCompare);
         }
+        sqlite3ExprDelete(db, pCompare);
       }
     }
-    assert( iIn==0 || db->mallocFailed );
+
     /* These registers need to be preserved in case there is an IN operator
     ** loop.  So we could deallocate the registers here (and potentially
     ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
@@ -145379,12 +149156,15 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
     addrNxt = pLevel->addrNxt;
+    if( pLevel->regFilter ){
+      sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
+                           iRowidReg, 1);
+      VdbeCoverage(v);
+      filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
+    }
     sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
     VdbeCoverage(v);
     pLevel->op = OP_Noop;
-    if( (pTerm->prereqAll & pLevel->notReady)==0 ){
-      pTerm->wtFlags |= TERM_CODED;
-    }
   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
   ){
@@ -145632,9 +149412,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     ** a forward order scan on a descending index, interchange the
     ** start and end terms (pRangeStart and pRangeEnd).
     */
-    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
-     || (bRev && pIdx->nKeyCol==nEq)
-    ){
+    if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) ){
       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
       SWAP(u8, bSeekPastNull, bStopAtNull);
       SWAP(u8, nBtm, nTop);
@@ -145709,6 +149487,12 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
         VdbeComment((v, "NULL-scan pass ctr"));
       }
+      if( pLevel->regFilter ){
+        sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
+                             regBase, nEq);
+        VdbeCoverage(v);
+        filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
+      }
 
       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
       assert( op!=0 );
@@ -145757,8 +149541,19 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     ** range (if any).
     */
     nConstraint = nEq;
+    assert( pLevel->p2==0 );
     if( pRangeEnd ){
       Expr *pRight = pRangeEnd->pExpr->pRight;
+      if( addrSeekScan ){
+        /* For a seek-scan that has a range on the lowest term of the index,
+        ** we have to make the top of the loop be code that sets the end
+        ** condition of the range.  Otherwise, the OP_SeekScan might jump
+        ** over that initialization, leaving the range-end value set to the
+        ** range-start value, resulting in a wrong answer.
+        ** See ticket 5981a8c041a3c2f3 (2021-11-02).
+        */
+        pLevel->p2 = sqlite3VdbeCurrentAddr(v);
+      }
       codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
       whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
@@ -145792,7 +149587,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     sqlite3DbFree(db, zEndAff);
 
     /* Top of the loop body */
-    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
+    if( pLevel->p2==0 ) pLevel->p2 = sqlite3VdbeCurrentAddr(v);
 
     /* Check if the index cursor is past the end of the range. */
     if( nConstraint ){
@@ -146025,7 +149820,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
 
     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
-    ** Then for every term xN, evaluate as the subexpression: xN AND z
+    ** Then for every term xN, evaluate as the subexpression: xN AND y
     ** That way, terms in y that are factored into the disjunction will
     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
     **
@@ -146037,6 +149832,20 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     ** This optimization also only applies if the (x1 OR x2 OR ...) term
     ** is not contained in the ON clause of a LEFT JOIN.
     ** See ticket http://www.sqlite.org/src/info/f2369304e4
+    **
+    ** 2022-02-04:  Do not push down slices of a row-value comparison.
+    ** In other words, "w" or "y" may not be a slice of a vector.  Otherwise,
+    ** the initialization of the right-hand operand of the vector comparison
+    ** might not occur, or might occur only in an OR branch that is not
+    ** taken.  dbsqlfuzz 80a9fade844b4fb43564efc972bcb2c68270f5d1.
+    **
+    ** 2022-03-03:  Do not push down expressions that involve subqueries.
+    ** The subquery might get coded as a subroutine.  Any table-references
+    ** in the subquery might be resolved to index-references for the index on
+    ** the OR branch in which the subroutine is coded.  But if the subroutine
+    ** is invoked from a different OR branch that uses a different index, such
+    ** index-references will not work.  tag-20220303a
+    ** https://sqlite.org/forum/forumpost/36937b197273d403
     */
     if( pWC->nTerm>1 ){
       int iTerm;
@@ -146045,9 +149854,12 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         if( &pWC->a[iTerm] == pTerm ) continue;
         testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
         testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
-        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
+        testcase( pWC->a[iTerm].wtFlags & TERM_SLICE );
+        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED|TERM_SLICE))!=0 ){
+          continue;
+        }
         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
-        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
+        if( ExprHasProperty(pExpr, EP_Subquery) ) continue;  /* tag-20220303a */
         pExpr = sqlite3ExprDup(db, pExpr, 0);
         pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);
       }
@@ -146055,7 +149867,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         /* The extra 0x10000 bit on the opcode is masked off and does not
         ** become part of the new Expr.op.  However, it does make the
         ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
-        ** prevents sqlite3PExpr() from implementing AND short-circuit
+        ** prevents sqlite3PExpr() from applying the AND short-circuit
         ** optimization, which we do not want here. */
         pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
       }
@@ -146071,10 +149883,16 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
+        Expr *pDelete;                  /* Local copy of OR clause term */
         int jmp1 = 0;                   /* Address of jump operation */
         testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0
                && !ExprHasProperty(pOrExpr, EP_FromJoin)
         ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
+        pDelete = pOrExpr = sqlite3ExprDup(db, pOrExpr, 0);
+        if( db->mallocFailed ){
+          sqlite3ExprDelete(db, pDelete);
+          continue;
+        }
         if( pAndExpr ){
           pAndExpr->pLeft = pOrExpr;
           pOrExpr = pAndExpr;
@@ -146082,9 +149900,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         /* Loop through table entries that match term pOrTerm. */
         ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
-        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
+        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 0,
                                       WHERE_OR_SUBCLAUSE, iCovCur);
-        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
+        assert( pSubWInfo || pParse->nErr );
         if( pSubWInfo ){
           WhereLoop *pSubLoop;
           int addrExplain = sqlite3WhereExplainOneScan(
@@ -146189,10 +150007,14 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
           sqlite3WhereEnd(pSubWInfo);
           ExplainQueryPlanPop(pParse);
         }
+        sqlite3ExprDelete(db, pDelete);
       }
     }
     ExplainQueryPlanPop(pParse);
-    pLevel->u.pCovidx = pCov;
+    assert( pLevel->pWLoop==pLoop );
+    assert( (pLoop->wsFlags & WHERE_MULTI_OR)!=0 );
+    assert( (pLoop->wsFlags & WHERE_IN_ABLE)==0 );
+    pLevel->u.pCoveringIdx = pCov;
     if( pCov ) pLevel->iIdxCur = iCovCur;
     if( pAndExpr ){
       pAndExpr->pLeft = 0;
@@ -146319,7 +150141,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
   ** the implied "t1.a=123" constraint.
   */
-  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
+  for(pTerm=pWC->a, j=pWC->nBase; j>0; j--, pTerm++){
     Expr *pE, sEAlt;
     WhereTerm *pAlt;
     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
@@ -146336,12 +150158,13 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
 #endif
     assert( !ExprHasProperty(pE, EP_FromJoin) );
     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
+    assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
     pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
                     WO_EQ|WO_IN|WO_IS, 0);
     if( pAlt==0 ) continue;
     if( pAlt->wtFlags & (TERM_CODED) ) continue;
     if( (pAlt->eOperator & WO_IN)
-     && (pAlt->pExpr->flags & EP_xIsSelect)
+     && ExprUseXSelect(pAlt->pExpr)
      && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
     ){
       continue;
@@ -146353,6 +150176,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     sEAlt = *pAlt->pExpr;
     sEAlt.pLeft = pE->pLeft;
     sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
+    pAlt->wtFlags |= TERM_CODED;
   }
 
   /* For a LEFT OUTER JOIN, generate code that will record the fact that
@@ -146362,7 +150186,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
     VdbeComment((v, "record LEFT JOIN hit"));
-    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
+    for(pTerm=pWC->a, j=0; j<pWC->nBase; j++, pTerm++){
       testcase( pTerm->wtFlags & TERM_VIRTUAL );
       testcase( pTerm->wtFlags & TERM_CODED );
       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
@@ -146473,6 +150297,7 @@ static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   }
   pTerm = &pWC->a[idx = pWC->nTerm++];
+  if( (wtFlags & TERM_VIRTUAL)==0 ) pWC->nBase = pWC->nTerm;
   if( p && ExprHasProperty(p, EP_Unlikely) ){
     pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
   }else{
@@ -146589,6 +150414,7 @@ static int isLikeOrGlob(
 #ifdef SQLITE_EBCDIC
   if( *pnoCase ) return 0;
 #endif
+  assert( ExprUseXList(pExpr) );
   pList = pExpr->x.pList;
   pLeft = pList->a[1].pExpr;
 
@@ -146604,7 +150430,8 @@ static int isLikeOrGlob(
     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   }else if( op==TK_STRING ){
-    z = (u8*)pRight->u.zToken;
+    assert( !ExprHasProperty(pRight, EP_IntValue) );
+     z = (u8*)pRight->u.zToken;
   }
   if( z ){
 
@@ -146633,7 +150460,9 @@ static int isLikeOrGlob(
       pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
       if( pPrefix ){
         int iFrom, iTo;
-        char *zNew = pPrefix->u.zToken;
+        char *zNew;
+        assert( !ExprHasProperty(pPrefix, EP_IntValue) );
+        zNew = pPrefix->u.zToken;
         zNew[cnt] = 0;
         for(iFrom=iTo=0; iFrom<cnt; iFrom++){
           if( zNew[iFrom]==wc[3] ) iFrom++;
@@ -146657,7 +150486,9 @@ static int isLikeOrGlob(
         */
         if( pLeft->op!=TK_COLUMN
          || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
-         || IsVirtual(pLeft->y.pTab)  /* Value might be numeric */
+         || (ALWAYS( ExprUseYTab(pLeft) )
+             && pLeft->y.pTab
+             && IsVirtual(pLeft->y.pTab))  /* Might be numeric */
         ){
           int isNum;
           double rDummy;
@@ -146685,6 +150516,7 @@ static int isLikeOrGlob(
       if( op==TK_VARIABLE ){
         Vdbe *v = pParse->pVdbe;
         sqlite3VdbeSetVarmask(v, pRight->iColumn);
+        assert( !ExprHasProperty(pRight, EP_IntValue) );
         if( *pisComplete && pRight->u.zToken[1] ){
           /* If the rhs of the LIKE expression is a variable, and the current
           ** value of the variable means there is no need to invoke the LIKE
@@ -146758,6 +150590,7 @@ static int isAuxiliaryVtabOperator(
     Expr *pCol;                     /* Column reference */
     int i;
 
+    assert( ExprUseXList(pExpr) );
     pList = pExpr->x.pList;
     if( pList==0 || pList->nExpr!=2 ){
       return 0;
@@ -146771,9 +150604,11 @@ static int isAuxiliaryVtabOperator(
     **       MATCH(expression,vtab_column)
     */
     pCol = pList->a[1].pExpr;
+    assert( pCol->op!=TK_COLUMN || ExprUseYTab(pCol) );
     testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
     if( ExprIsVtab(pCol) ){
       for(i=0; i<ArraySize(aOp); i++){
+        assert( !ExprHasProperty(pExpr, EP_IntValue) );
         if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
           *peOp2 = aOp[i].eOp2;
           *ppRight = pList->a[0].pExpr;
@@ -146794,6 +150629,7 @@ static int isAuxiliaryVtabOperator(
     ** with function names in an arbitrary case.
     */
     pCol = pList->a[0].pExpr;
+    assert( pCol->op!=TK_COLUMN || ExprUseYTab(pCol) );
     testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
     if( ExprIsVtab(pCol) ){
       sqlite3_vtab *pVtab;
@@ -146803,6 +150639,7 @@ static int isAuxiliaryVtabOperator(
       pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
       assert( pVtab!=0 );
       assert( pVtab->pModule!=0 );
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       pMod = (sqlite3_module *)pVtab->pModule;
       if( pMod->xFindFunction!=0 ){
         i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
@@ -146818,10 +150655,12 @@ static int isAuxiliaryVtabOperator(
     int res = 0;
     Expr *pLeft = pExpr->pLeft;
     Expr *pRight = pExpr->pRight;
+    assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
     testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 );
     if( ExprIsVtab(pLeft) ){
       res++;
     }
+    assert( pRight==0 || pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
     testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 );
     if( pRight && ExprIsVtab(pRight) ){
       res++;
@@ -146845,7 +150684,7 @@ static int isAuxiliaryVtabOperator(
 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   if( pDerived ){
     pDerived->flags |= pBase->flags & EP_FromJoin;
-    pDerived->iRightJoinTable = pBase->iRightJoinTable;
+    pDerived->w.iRightJoinTable = pBase->w.iRightJoinTable;
   }
 }
 
@@ -146905,6 +150744,7 @@ static void whereCombineDisjuncts(
   int op;                /* Operator for the combined expression */
   int idxNew;            /* Index in pWC of the next virtual term */
 
+  if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return;
   if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
   if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
   if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
@@ -147073,6 +150913,7 @@ static void exprAnalyzeOrTerm(
         pOrTerm->u.pAndInfo = pAndInfo;
         pOrTerm->wtFlags |= TERM_ANDINFO;
         pOrTerm->eOperator = WO_AND;
+        pOrTerm->leftCursor = -1;
         pAndWC = &pAndInfo->wc;
         memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
         sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
@@ -147115,11 +150956,10 @@ static void exprAnalyzeOrTerm(
   ** empty.
   */
   pOrInfo->indexable = indexable;
+  pTerm->eOperator = WO_OR;
+  pTerm->leftCursor = -1;
   if( indexable ){
-    pTerm->eOperator = WO_OR;
     pWC->hasOr = 1;
-  }else{
-    pTerm->eOperator = WO_OR;
   }
 
   /* For a two-way OR, attempt to implementation case 2.
@@ -147174,7 +151014,7 @@ static void exprAnalyzeOrTerm(
       pOrTerm = pOrWc->a;
       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
         assert( pOrTerm->eOperator & WO_EQ );
-        pOrTerm->wtFlags &= ~TERM_OR_OK;
+        pOrTerm->wtFlags &= ~TERM_OK;
         if( pOrTerm->leftCursor==iCursor ){
           /* This is the 2-bit case and we are on the second iteration and
           ** current term is from the first iteration.  So skip this term. */
@@ -147192,6 +151032,7 @@ static void exprAnalyzeOrTerm(
           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
           continue;
         }
+        assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
         iColumn = pOrTerm->u.x.leftColumn;
         iCursor = pOrTerm->leftCursor;
         pLeft = pOrTerm->pExpr->pLeft;
@@ -147212,8 +151053,9 @@ static void exprAnalyzeOrTerm(
       okToChngToIN = 1;
       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
         assert( pOrTerm->eOperator & WO_EQ );
+        assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
         if( pOrTerm->leftCursor!=iCursor ){
-          pOrTerm->wtFlags &= ~TERM_OR_OK;
+          pOrTerm->wtFlags &= ~TERM_OK;
         }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR
                && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
         )){
@@ -147229,7 +151071,7 @@ static void exprAnalyzeOrTerm(
           if( affRight!=0 && affRight!=affLeft ){
             okToChngToIN = 0;
           }else{
-            pOrTerm->wtFlags |= TERM_OR_OK;
+            pOrTerm->wtFlags |= TERM_OK;
           }
         }
       }
@@ -147246,8 +151088,9 @@ static void exprAnalyzeOrTerm(
       Expr *pNew;            /* The complete IN operator */
 
       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
-        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
+        if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue;
         assert( pOrTerm->eOperator & WO_EQ );
+        assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
         assert( pOrTerm->leftCursor==iCursor );
         assert( pOrTerm->u.x.leftColumn==iColumn );
         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
@@ -147260,12 +151103,12 @@ static void exprAnalyzeOrTerm(
       if( pNew ){
         int idxNew;
         transferJoinMarkings(pNew, pExpr);
-        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
+        assert( ExprUseXList(pNew) );
         pNew->x.pList = pList;
         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
         testcase( idxNew==0 );
         exprAnalyze(pSrc, pWC, idxNew);
-        /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
+        /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where reused */
         markTermAsChild(pWC, idxNew, idxTerm);
       }else{
         sqlite3ExprListDelete(db, pList);
@@ -147388,7 +151231,9 @@ static int exprMightBeIndexed(
   assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
   assert( op<=TK_GE );
   if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
+    assert( ExprUseXList(pExpr) );
     pExpr = pExpr->x.pList->a[0].pExpr;
+
   }
 
   if( pExpr->op==TK_COLUMN ){
@@ -147401,276 +151246,6 @@ static int exprMightBeIndexed(
   return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
 }
 
-/*
-** 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
@@ -147714,30 +151289,47 @@ static void exprAnalyze(
   if( db->mallocFailed ){
     return;
   }
+  assert( pWC->nTerm > idxTerm );
   pTerm = &pWC->a[idxTerm];
   pMaskSet = &pWInfo->sMaskSet;
   pExpr = pTerm->pExpr;
+  assert( pExpr!=0 ); /* Because malloc() has not failed */
   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
+  pMaskSet->bVarSelect = 0;
   prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
   op = pExpr->op;
   if( op==TK_IN ){
     assert( pExpr->pRight==0 );
     if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
-    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+    if( ExprUseXSelect(pExpr) ){
       pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
     }else{
       pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
     }
-  }else if( op==TK_ISNULL ){
-    pTerm->prereqRight = 0;
+    prereqAll = prereqLeft | pTerm->prereqRight;
   }else{
     pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
+    if( pExpr->pLeft==0
+     || ExprHasProperty(pExpr, EP_xIsSelect|EP_IfNullRow)
+     || pExpr->x.pList!=0
+    ){
+      prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
+    }else{
+      prereqAll = prereqLeft | pTerm->prereqRight;
+    }
   }
-  pMaskSet->bVarSelect = 0;
-  prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
   if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
+
+#ifdef SQLITE_DEBUG
+  if( prereqAll!=sqlite3WhereExprUsageNN(pMaskSet, pExpr) ){
+    printf("\n*** Incorrect prereqAll computed for:\n");
+    sqlite3TreeViewExpr(0,pExpr,0);
+    abort();
+  }
+#endif
+
   if( ExprHasProperty(pExpr, EP_FromJoin) ){
-    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
+    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->w.iRightJoinTable);
     prereqAll |= x;
     extraRight = x-1;  /* ON clause terms may not be used with an index
                        ** on left table of a LEFT JOIN.  Ticket #3015 */
@@ -147759,17 +151351,20 @@ static void exprAnalyze(
     if( pTerm->u.x.iField>0 ){
       assert( op==TK_IN );
       assert( pLeft->op==TK_VECTOR );
+      assert( ExprUseXList(pLeft) );
       pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr;
     }
 
     if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
       pTerm->leftCursor = aiCurCol[0];
+      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
       pTerm->u.x.leftColumn = aiCurCol[1];
       pTerm->eOperator = operatorMask(op) & opMask;
     }
     if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
     if( pRight
      && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
+     && !ExprHasProperty(pRight, EP_FixedCol)
     ){
       WhereTerm *pNew;
       Expr *pDup;
@@ -147800,12 +151395,18 @@ static void exprAnalyze(
       }
       pNew->wtFlags |= exprCommute(pParse, pDup);
       pNew->leftCursor = aiCurCol[0];
+      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
       pNew->u.x.leftColumn = aiCurCol[1];
       testcase( (prereqLeft | extraRight) != prereqLeft );
       pNew->prereqRight = prereqLeft | extraRight;
       pNew->prereqAll = prereqAll;
       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
-    }else if( op==TK_ISNULL && 0==sqlite3ExprCanBeNull(pLeft) ){
+    }else
+    if( op==TK_ISNULL
+     && !ExprHasProperty(pExpr,EP_FromJoin)
+     && 0==sqlite3ExprCanBeNull(pLeft)
+    ){
+      assert( !ExprHasProperty(pExpr, EP_IntValue) );
       pExpr->op = TK_TRUEFALSE;
       pExpr->u.zToken = "false";
       ExprSetProperty(pExpr, EP_IsFalse);
@@ -147831,9 +151432,11 @@ static void exprAnalyze(
   ** BETWEEN term is skipped.
   */
   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
-    ExprList *pList = pExpr->x.pList;
+    ExprList *pList;
     int i;
     static const u8 ops[] = {TK_GE, TK_LE};
+    assert( ExprUseXList(pExpr) );
+    pList = pExpr->x.pList;
     assert( pList!=0 );
     assert( pList->nExpr==2 );
     for(i=0; i<2; i++){
@@ -147862,16 +151465,6 @@ static void exprAnalyze(
     pTerm = &pWC->a[idxTerm];
   }
 #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.
@@ -147936,8 +151529,12 @@ static void exprAnalyze(
     const char *zCollSeqName;     /* Name of collating sequence */
     const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
 
+    assert( ExprUseXList(pExpr) );
     pLeft = pExpr->x.pList->a[1].pExpr;
     pStr2 = sqlite3ExprDup(db, pStr1, 0);
+    assert( pStr1==0 || !ExprHasProperty(pStr1, EP_IntValue) );
+    assert( pStr2==0 || !ExprHasProperty(pStr2, EP_IntValue) );
+
 
     /* Convert the lower bound to upper-case and the upper bound to
     ** lower-case (upper-case is less than lower-case in ASCII) so that
@@ -148000,7 +151597,10 @@ static void exprAnalyze(
   ** no longer used.
   **
   ** This is only required if at least one side of the comparison operation
-  ** is not a sub-select.  */
+  ** is not a sub-select.
+  **
+  ** tag-20220128a
+  */
   if( (pExpr->op==TK_EQ || pExpr->op==TK_IS)
    && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
    && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
@@ -148012,12 +151612,12 @@ static void exprAnalyze(
     for(i=0; i<nLeft; i++){
       int idxNew;
       Expr *pNew;
-      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
-      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
+      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i, nLeft);
+      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i, nLeft);
 
       pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
       transferJoinMarkings(pNew, pExpr);
-      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
+      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC|TERM_SLICE);
       exprAnalyze(pSrc, pWC, idxNew);
     }
     pTerm = &pWC->a[idxTerm];
@@ -148037,6 +151637,7 @@ static void exprAnalyze(
   else if( pExpr->op==TK_IN
    && pTerm->u.x.iField==0
    && pExpr->pLeft->op==TK_VECTOR
+   && ALWAYS( ExprUseXSelect(pExpr) )
    && pExpr->x.pSelect->pPrior==0
 #ifndef SQLITE_OMIT_WINDOWFUNC
    && pExpr->x.pSelect->pWin==0
@@ -148046,7 +151647,7 @@ static void exprAnalyze(
     int i;
     for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
       int idxNew;
-      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
+      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL|TERM_SLICE);
       pWC->a[idxNew].u.x.iField = i+1;
       exprAnalyze(pSrc, pWC, idxNew);
       markTermAsChild(pWC, idxNew, idxTerm);
@@ -148079,7 +151680,7 @@ static void exprAnalyze(
             0, sqlite3ExprDup(db, pRight, 0));
         if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
           ExprSetProperty(pNewExpr, EP_FromJoin);
-          pNewExpr->iRightJoinTable = pExpr->iRightJoinTable;
+          pNewExpr->w.iRightJoinTable = pExpr->w.iRightJoinTable;
         }
         idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
         testcase( idxNew==0 );
@@ -148142,6 +151743,113 @@ SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
   }
 }
 
+/*
+** Add either a LIMIT (if eMatchOp==SQLITE_INDEX_CONSTRAINT_LIMIT) or
+** OFFSET (if eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET) term to the
+** where-clause passed as the first argument. The value for the term
+** is found in register iReg.
+**
+** In the common case where the value is a simple integer
+** (example: "LIMIT 5 OFFSET 10") then the expression codes as a
+** TK_INTEGER so that it will be available to sqlite3_vtab_rhs_value().
+** If not, then it codes as a TK_REGISTER expression.
+*/
+static void whereAddLimitExpr(
+  WhereClause *pWC,   /* Add the constraint to this WHERE clause */
+  int iReg,           /* Register that will hold value of the limit/offset */
+  Expr *pExpr,        /* Expression that defines the limit/offset */
+  int iCsr,           /* Cursor to which the constraint applies */
+  int eMatchOp        /* SQLITE_INDEX_CONSTRAINT_LIMIT or _OFFSET */
+){
+  Parse *pParse = pWC->pWInfo->pParse;
+  sqlite3 *db = pParse->db;
+  Expr *pNew;
+  int iVal = 0;
+
+  if( sqlite3ExprIsInteger(pExpr, &iVal) && iVal>=0 ){
+    Expr *pVal = sqlite3Expr(db, TK_INTEGER, 0);
+    if( pVal==0 ) return;
+    ExprSetProperty(pVal, EP_IntValue);
+    pVal->u.iValue = iVal;
+    pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
+  }else{
+    Expr *pVal = sqlite3Expr(db, TK_REGISTER, 0);
+    if( pVal==0 ) return;
+    pVal->iTable = iReg;
+    pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal);
+  }
+  if( pNew ){
+    WhereTerm *pTerm;
+    int idx;
+    idx = whereClauseInsert(pWC, pNew, TERM_DYNAMIC|TERM_VIRTUAL);
+    pTerm = &pWC->a[idx];
+    pTerm->leftCursor = iCsr;
+    pTerm->eOperator = WO_AUX;
+    pTerm->eMatchOp = eMatchOp;
+  }
+}
+
+/*
+** Possibly add terms corresponding to the LIMIT and OFFSET clauses of the
+** SELECT statement passed as the second argument. These terms are only
+** added if:
+**
+**   1. The SELECT statement has a LIMIT clause, and
+**   2. The SELECT statement is not an aggregate or DISTINCT query, and
+**   3. The SELECT statement has exactly one object in its from clause, and
+**      that object is a virtual table, and
+**   4. There are no terms in the WHERE clause that will not be passed
+**      to the virtual table xBestIndex method.
+**   5. The ORDER BY clause, if any, will be made available to the xBestIndex
+**      method.
+**
+** LIMIT and OFFSET terms are ignored by most of the planner code. They
+** exist only so that they may be passed to the xBestIndex method of the
+** single virtual table in the FROM clause of the SELECT.
+*/
+SQLITE_PRIVATE void sqlite3WhereAddLimit(WhereClause *pWC, Select *p){
+  assert( p==0 || (p->pGroupBy==0 && (p->selFlags & SF_Aggregate)==0) );
+  if( (p && p->pLimit)                                          /* 1 */
+   && (p->selFlags & (SF_Distinct|SF_Aggregate))==0             /* 2 */
+   && (p->pSrc->nSrc==1 && IsVirtual(p->pSrc->a[0].pTab))       /* 3 */
+  ){
+    ExprList *pOrderBy = p->pOrderBy;
+    int iCsr = p->pSrc->a[0].iCursor;
+    int ii;
+
+    /* Check condition (4). Return early if it is not met. */
+    for(ii=0; ii<pWC->nTerm; ii++){
+      if( pWC->a[ii].wtFlags & TERM_CODED ){
+        /* This term is a vector operation that has been decomposed into
+        ** other, subsequent terms.  It can be ignored. See tag-20220128a */
+        assert( pWC->a[ii].wtFlags & TERM_VIRTUAL );
+        assert( pWC->a[ii].eOperator==0 );
+        continue;
+      }
+      if( pWC->a[ii].leftCursor!=iCsr ) return;
+    }
+
+    /* Check condition (5). Return early if it is not met. */
+    if( pOrderBy ){
+      for(ii=0; ii<pOrderBy->nExpr; ii++){
+        Expr *pExpr = pOrderBy->a[ii].pExpr;
+        if( pExpr->op!=TK_COLUMN ) return;
+        if( pExpr->iTable!=iCsr ) return;
+        if( pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_BIGNULL ) return;
+      }
+    }
+
+    /* All conditions are met. Add the terms to the where-clause object. */
+    assert( p->pLimit->op==TK_LIMIT );
+    whereAddLimitExpr(pWC, p->iLimit, p->pLimit->pLeft,
+                      iCsr, SQLITE_INDEX_CONSTRAINT_LIMIT);
+    if( p->iOffset>0 ){
+      whereAddLimitExpr(pWC, p->iOffset, p->pLimit->pRight,
+                        iCsr, SQLITE_INDEX_CONSTRAINT_OFFSET);
+    }
+  }
+}
+
 /*
 ** Initialize a preallocated WhereClause structure.
 */
@@ -148153,6 +151861,7 @@ SQLITE_PRIVATE void sqlite3WhereClauseInit(
   pWC->hasOr = 0;
   pWC->pOuter = 0;
   pWC->nTerm = 0;
+  pWC->nBase = 0;
   pWC->nSlot = ArraySize(pWC->aStatic);
   pWC->a = pWC->aStatic;
 }
@@ -148163,17 +151872,34 @@ SQLITE_PRIVATE void sqlite3WhereClauseInit(
 ** sqlite3WhereClauseInit().
 */
 SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
-  int i;
-  WhereTerm *a;
   sqlite3 *db = pWC->pWInfo->pParse->db;
-  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
-    if( a->wtFlags & TERM_DYNAMIC ){
-      sqlite3ExprDelete(db, a->pExpr);
+  assert( pWC->nTerm>=pWC->nBase );
+  if( pWC->nTerm>0 ){
+    WhereTerm *a = pWC->a;
+    WhereTerm *aLast = &pWC->a[pWC->nTerm-1];
+#ifdef SQLITE_DEBUG
+    int i;
+    /* Verify that every term past pWC->nBase is virtual */
+    for(i=pWC->nBase; i<pWC->nTerm; i++){
+      assert( (pWC->a[i].wtFlags & TERM_VIRTUAL)!=0 );
     }
-    if( a->wtFlags & TERM_ORINFO ){
-      whereOrInfoDelete(db, a->u.pOrInfo);
-    }else if( a->wtFlags & TERM_ANDINFO ){
-      whereAndInfoDelete(db, a->u.pAndInfo);
+#endif
+    while(1){
+      assert( a->eMatchOp==0 || a->eOperator==WO_AUX );
+      if( a->wtFlags & TERM_DYNAMIC ){
+        sqlite3ExprDelete(db, a->pExpr);
+      }
+      if( a->wtFlags & (TERM_ORINFO|TERM_ANDINFO) ){
+        if( a->wtFlags & TERM_ORINFO ){
+          assert( (a->wtFlags & TERM_ANDINFO)==0 );
+          whereOrInfoDelete(db, a->u.pOrInfo);
+        }else{
+          assert( (a->wtFlags & TERM_ANDINFO)!=0 );
+          whereAndInfoDelete(db, a->u.pAndInfo);
+        }
+      }
+      if( a==aLast ) break;
+      a++;
     }
   }
   if( pWC->a!=pWC->aStatic ){
@@ -148186,28 +151912,52 @@ SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
 ** These routines walk (recursively) an expression tree and generate
 ** a bitmask indicating which tables are used in that expression
 ** tree.
+**
+** sqlite3WhereExprUsage(MaskSet, Expr) ->
+**
+**       Return a Bitmask of all tables referenced by Expr.  Expr can be
+**       be NULL, in which case 0 is returned.
+**
+** sqlite3WhereExprUsageNN(MaskSet, Expr) ->
+**
+**       Same as sqlite3WhereExprUsage() except that Expr must not be
+**       NULL.  The "NN" suffix on the name stands for "Not Null".
+**
+** sqlite3WhereExprListUsage(MaskSet, ExprList) ->
+**
+**       Return a Bitmask of all tables referenced by every expression
+**       in the expression list ExprList.  ExprList can be NULL, in which
+**       case 0 is returned.
+**
+** sqlite3WhereExprUsageFull(MaskSet, ExprList) ->
+**
+**       Internal use only.  Called only by sqlite3WhereExprUsageNN() for
+**       complex expressions that require pushing register values onto
+**       the stack.  Many calls to sqlite3WhereExprUsageNN() do not need
+**       the more complex analysis done by this routine.  Hence, the
+**       computations done by this routine are broken out into a separate
+**       "no-inline" function to avoid the stack push overhead in the
+**       common case where it is not needed.
 */
-SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
+static SQLITE_NOINLINE Bitmask sqlite3WhereExprUsageFull(
+  WhereMaskSet *pMaskSet,
+  Expr *p
+){
   Bitmask mask;
-  if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
-    return sqlite3WhereGetMask(pMaskSet, p->iTable);
-  }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
-    assert( p->op!=TK_IF_NULL_ROW );
-    return 0;
-  }
   mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
   if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
   if( p->pRight ){
     mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
     assert( p->x.pList==0 );
-  }else if( ExprHasProperty(p, EP_xIsSelect) ){
+  }else if( ExprUseXSelect(p) ){
     if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
     mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
   }else if( p->x.pList ){
     mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
   }
 #ifndef SQLITE_OMIT_WINDOWFUNC
-  if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){
+  if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && ExprUseYWin(p) ){
+    assert( p->y.pWin!=0 );
     mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
     mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
     mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
@@ -148215,6 +151965,15 @@ SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
 #endif
   return mask;
 }
+SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
+  if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
+    return sqlite3WhereGetMask(pMaskSet, p->iTable);
+  }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
+    assert( p->op!=TK_IF_NULL_ROW );
+    return 0;
+  }
+  return sqlite3WhereExprUsageFull(pMaskSet, p);
+}
 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
   return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
 }
@@ -148282,7 +152041,9 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
     if( pColRef==0 ) return;
     pColRef->iTable = pItem->iCursor;
     pColRef->iColumn = k++;
+    assert( ExprUseYTab(pColRef) );
     pColRef->y.pTab = pTab;
+    pItem->colUsed |= sqlite3ExprColUsed(pColRef);
     pRhs = sqlite3PExpr(pParse, TK_UPLUS,
         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
     pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
@@ -148327,8 +152088,14 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
 */
 typedef struct HiddenIndexInfo HiddenIndexInfo;
 struct HiddenIndexInfo {
-  WhereClause *pWC;   /* The Where clause being analyzed */
-  Parse *pParse;      /* The parsing context */
+  WhereClause *pWC;        /* The Where clause being analyzed */
+  Parse *pParse;           /* The parsing context */
+  int eDistinct;           /* Value to return from sqlite3_vtab_distinct() */
+  u32 mIn;                 /* Mask of terms that are <col> IN (...) */
+  u32 mHandleIn;           /* Terms that vtab will handle as <col> IN (...) */
+  sqlite3_value *aRhs[1];  /* RHS values for constraints. MUST BE LAST
+                           ** because extra space is allocated to hold up
+                           ** to nTerm such values */
 };
 
 /* Forward declaration of methods */
@@ -148531,7 +152298,12 @@ whereOrInsert_done:
 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
   int i;
   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
-  for(i=0; i<pMaskSet->n; i++){
+  assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 );
+  assert( iCursor>=-1 );
+  if( pMaskSet->ix[0]==iCursor ){
+    return 1;
+  }
+  for(i=1; i<pMaskSet->n; i++){
     if( pMaskSet->ix[i]==iCursor ){
       return MASKBIT(i);
     }
@@ -148558,7 +152330,9 @@ static void createMask(WhereMaskSet *pMaskSet, int iCursor){
 */
 static Expr *whereRightSubexprIsColumn(Expr *p){
   p = sqlite3ExprSkipCollateAndLikely(p->pRight);
-  if( ALWAYS(p!=0) && p->op==TK_COLUMN ) return p;
+  if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
+    return p;
+  }
   return 0;
 }
 
@@ -148581,8 +152355,10 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
     iColumn = pScan->aiColumn[pScan->iEquiv-1];
     iCur = pScan->aiCur[pScan->iEquiv-1];
     assert( pWC!=0 );
+    assert( iCur>=0 );
     do{
       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
+        assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 || pTerm->leftCursor<0 );
         if( pTerm->leftCursor==iCur
          && pTerm->u.x.leftColumn==iColumn
          && (iColumn!=XN_EXPR
@@ -148624,7 +152400,8 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
               }
             }
             if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
-             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
+             && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
+             && pX->op==TK_COLUMN
              && pX->iTable==pScan->aiCur[0]
              && pX->iColumn==pScan->aiColumn[0]
             ){
@@ -148633,6 +152410,18 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
             }
             pScan->pWC = pWC;
             pScan->k = k+1;
+#ifdef WHERETRACE_ENABLED
+            if( sqlite3WhereTrace & 0x20000 ){
+              int ii;
+              sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d",
+                 pTerm, pScan->nEquiv);
+              for(ii=0; ii<pScan->nEquiv; ii++){
+                sqlite3DebugPrintf(" {%d:%d}",
+                   pScan->aiCur[ii], pScan->aiColumn[ii]);
+              }
+              sqlite3DebugPrintf("\n");
+            }
+#endif
             return pTerm;
           }
         }
@@ -148699,16 +152488,16 @@ static WhereTerm *whereScanInit(
   if( pIdx ){
     int j = iColumn;
     iColumn = pIdx->aiColumn[j];
-    if( iColumn==XN_EXPR ){
-      pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
-      pScan->zCollName = pIdx->azColl[j];
-      pScan->aiColumn[0] = XN_EXPR;
-      return whereScanInitIndexExpr(pScan);
-    }else if( iColumn==pIdx->pTable->iPKey ){
+    if( iColumn==pIdx->pTable->iPKey ){
       iColumn = XN_ROWID;
     }else if( iColumn>=0 ){
       pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
       pScan->zCollName = pIdx->azColl[j];
+    }else if( iColumn==XN_EXPR ){
+      pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
+      pScan->zCollName = pIdx->azColl[j];
+      pScan->aiColumn[0] = XN_EXPR;
+      return whereScanInitIndexExpr(pScan);
     }
   }else if( iColumn==XN_EXPR ){
     return 0;
@@ -148789,7 +152578,7 @@ static int findIndexCol(
   for(i=0; i<pList->nExpr; i++){
     Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
     if( ALWAYS(p!=0)
-     && p->op==TK_COLUMN
+     && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
      && p->iColumn==pIdx->aiColumn[iCol]
      && p->iTable==iBase
     ){
@@ -148854,7 +152643,8 @@ static int isDistinctRedundant(
   for(i=0; i<pDistinct->nExpr; i++){
     Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
     if( NEVER(p==0) ) continue;
-    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
+    if( p->op!=TK_COLUMN && p->op!=TK_AGG_COLUMN ) continue;
+    if( p->iTable==iBase && p->iColumn<0 ) return 1;
   }
 
   /* Loop through all indices on the table, checking each to see if it makes
@@ -148872,6 +152662,7 @@ static int isDistinctRedundant(
   */
   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
     if( !IsUniqueIndex(pIdx) ) continue;
+    if( pIdx->pPartIdxWhere ) continue;
     for(i=0; i<pIdx->nKeyCol; i++){
       if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
         if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
@@ -148926,14 +152717,14 @@ static void translateColumnToCopy(
       pOp->p2 = pOp->p3;
       pOp->p3 = 0;
     }else if( pOp->opcode==OP_Rowid ){
-      if( iAutoidxCur ){
-        pOp->opcode = OP_Sequence;
-        pOp->p1 = iAutoidxCur;
-      }else{
+      pOp->opcode = OP_Sequence;
+      pOp->p1 = iAutoidxCur;
+#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
+      if( iAutoidxCur==0 ){
         pOp->opcode = OP_Null;
-        pOp->p1 = 0;
         pOp->p3 = 0;
       }
+#endif
     }
   }
 }
@@ -148949,12 +152740,14 @@ static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
   int i;
   if( !sqlite3WhereTrace ) return;
   for(i=0; i<p->nConstraint; i++){
-    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
+    sqlite3DebugPrintf(
+       "  constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",
        i,
        p->aConstraint[i].iColumn,
        p->aConstraint[i].iTermOffset,
        p->aConstraint[i].op,
-       p->aConstraint[i].usable);
+       p->aConstraint[i].usable,
+       sqlite3_vtab_collation(p,i));
   }
   for(i=0; i<p->nOrderBy; i++){
     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
@@ -148990,9 +152783,9 @@ static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
 ** index existed.
 */
 static int termCanDriveIndex(
-  WhereTerm *pTerm,              /* WHERE clause term to check */
-  SrcItem *pSrc,                 /* Table we are trying to access */
-  Bitmask notReady               /* Tables in outer loops of the join */
+  const WhereTerm *pTerm,        /* WHERE clause term to check */
+  const SrcItem *pSrc,           /* Table we are trying to access */
+  const Bitmask notReady         /* Tables in outer loops of the join */
 ){
   char aff;
   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
@@ -149007,6 +152800,7 @@ static int termCanDriveIndex(
     return 0;
   }
   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
+  assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
   if( pTerm->u.x.leftColumn<0 ) return 0;
   aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
@@ -149022,11 +152816,11 @@ static int termCanDriveIndex(
 ** and to set up the WhereLevel object pLevel so that the code generator
 ** makes use of the automatic index.
 */
-static void constructAutomaticIndex(
+static SQLITE_NOINLINE void constructAutomaticIndex(
   Parse *pParse,              /* The parsing context */
-  WhereClause *pWC,           /* The WHERE clause */
-  SrcItem *pSrc,              /* The FROM clause term to get the next index */
-  Bitmask notReady,           /* Mask of cursors that are not available */
+  const WhereClause *pWC,     /* The WHERE clause */
+  const SrcItem *pSrc,        /* The FROM clause term to get the next index */
+  const Bitmask notReady,     /* Mask of cursors that are not available */
   WhereLevel *pLevel          /* Write new index here */
 ){
   int nKeyCol;                /* Number of columns in the constructed index */
@@ -149068,25 +152862,27 @@ static void constructAutomaticIndex(
   idxCols = 0;
   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
     Expr *pExpr = pTerm->pExpr;
-    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
-         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
-         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
-    if( pLoop->prereq==0
-     && (pTerm->wtFlags & TERM_VIRTUAL)==0
-     && !ExprHasProperty(pExpr, EP_FromJoin)
-     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
+    /* Make the automatic index a partial index if there are terms in the
+    ** WHERE clause (or the ON clause of a LEFT join) that constrain which
+    ** rows of the target table (pSrc) that can be used. */
+    if( (pTerm->wtFlags & TERM_VIRTUAL)==0
+     && sqlite3ExprIsTableConstraint(pExpr, pSrc)
+    ){
       pPartial = sqlite3ExprAnd(pParse, pPartial,
                                 sqlite3ExprDup(pParse->db, pExpr, 0));
     }
     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
-      int iCol = pTerm->u.x.leftColumn;
-      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
+      int iCol;
+      Bitmask cMask;
+      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
+      iCol = pTerm->u.x.leftColumn;
+      cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
       testcase( iCol==BMS );
       testcase( iCol==BMS-1 );
       if( !sentWarning ){
         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
             "automatic index on %s(%s)", pTable->zName,
-            pTable->aCol[iCol].zName);
+            pTable->aCol[iCol].zCnName);
         sentWarning = 1;
       }
       if( (idxCols & cMask)==0 ){
@@ -149098,7 +152894,7 @@ static void constructAutomaticIndex(
       }
     }
   }
-  assert( nKeyCol>0 );
+  assert( nKeyCol>0 || pParse->db->mallocFailed );
   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
                      | WHERE_AUTO_INDEX;
@@ -149132,8 +152928,11 @@ static void constructAutomaticIndex(
   idxCols = 0;
   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
-      int iCol = pTerm->u.x.leftColumn;
-      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
+      int iCol;
+      Bitmask cMask;
+      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
+      iCol = pTerm->u.x.leftColumn;
+      cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
       testcase( iCol==BMS-1 );
       testcase( iCol==BMS );
       if( (idxCols & cMask)==0 ){
@@ -149175,6 +152974,10 @@ static void constructAutomaticIndex(
   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
   VdbeComment((v, "for %s", pTable->zName));
+  if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ){
+    pLevel->regFilter = ++pParse->nMem;
+    sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
+  }
 
   /* Fill the automatic index with content */
   pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
@@ -149197,6 +153000,10 @@ static void constructAutomaticIndex(
   regBase = sqlite3GenerateIndexKey(
       pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
   );
+  if( pLevel->regFilter ){
+    sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
+                         regBase, pLoop->u.btree.nEq);
+  }
   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
@@ -149223,22 +153030,149 @@ end_auto_index_create:
 }
 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
 
+/*
+** Generate bytecode that will initialize a Bloom filter that is appropriate
+** for pLevel.
+**
+** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER
+** flag set, initialize a Bloomfilter for them as well.  Except don't do
+** this recursive initialization if the SQLITE_BloomPulldown optimization has
+** been turned off.
+**
+** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared
+** from the loop, but the regFilter value is set to a register that implements
+** the Bloom filter.  When regFilter is positive, the
+** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter
+** and skip the subsequence B-Tree seek if the Bloom filter indicates that
+** no matching rows exist.
+**
+** This routine may only be called if it has previously been determined that
+** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit
+** is set.
+*/
+static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
+  WhereInfo *pWInfo,    /* The WHERE clause */
+  int iLevel,           /* Index in pWInfo->a[] that is pLevel */
+  WhereLevel *pLevel,   /* Make a Bloom filter for this FROM term */
+  Bitmask notReady      /* Loops that are not ready */
+){
+  int addrOnce;                        /* Address of opening OP_Once */
+  int addrTop;                         /* Address of OP_Rewind */
+  int addrCont;                        /* Jump here to skip a row */
+  const WhereTerm *pTerm;              /* For looping over WHERE clause terms */
+  const WhereTerm *pWCEnd;             /* Last WHERE clause term */
+  Parse *pParse = pWInfo->pParse;      /* Parsing context */
+  Vdbe *v = pParse->pVdbe;             /* VDBE under construction */
+  WhereLoop *pLoop = pLevel->pWLoop;   /* The loop being coded */
+  int iCur;                            /* Cursor for table getting the filter */
+
+  assert( pLoop!=0 );
+  assert( v!=0 );
+  assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
+
+  addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+  do{
+    const SrcItem *pItem;
+    const Table *pTab;
+    u64 sz;
+    sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
+    addrCont = sqlite3VdbeMakeLabel(pParse);
+    iCur = pLevel->iTabCur;
+    pLevel->regFilter = ++pParse->nMem;
+
+    /* The Bloom filter is a Blob held in a register.  Initialize it
+    ** to zero-filled blob of at least 80K bits, but maybe more if the
+    ** estimated size of the table is larger.  We could actually
+    ** measure the size of the table at run-time using OP_Count with
+    ** P3==1 and use that value to initialize the blob.  But that makes
+    ** testing complicated.  By basing the blob size on the value in the
+    ** sqlite_stat1 table, testing is much easier.
+    */
+    pItem = &pWInfo->pTabList->a[pLevel->iFrom];
+    assert( pItem!=0 );
+    pTab = pItem->pTab;
+    assert( pTab!=0 );
+    sz = sqlite3LogEstToInt(pTab->nRowLogEst);
+    if( sz<10000 ){
+      sz = 10000;
+    }else if( sz>10000000 ){
+      sz = 10000000;
+    }
+    sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
+
+    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
+    pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
+    for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
+      Expr *pExpr = pTerm->pExpr;
+      if( (pTerm->wtFlags & TERM_VIRTUAL)==0
+       && sqlite3ExprIsTableConstraint(pExpr, pItem)
+      ){
+        sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
+      }
+    }
+    if( pLoop->wsFlags & WHERE_IPK ){
+      int r1 = sqlite3GetTempReg(pParse);
+      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
+      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
+      sqlite3ReleaseTempReg(pParse, r1);
+    }else{
+      Index *pIdx = pLoop->u.btree.pIndex;
+      int n = pLoop->u.btree.nEq;
+      int r1 = sqlite3GetTempRange(pParse, n);
+      int jj;
+      for(jj=0; jj<n; jj++){
+        int iCol = pIdx->aiColumn[jj];
+        assert( pIdx->pTable==pItem->pTab );
+        sqlite3ExprCodeGetColumnOfTable(v, pIdx->pTable, iCur, iCol,r1+jj);
+      }
+      sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
+      sqlite3ReleaseTempRange(pParse, r1, n);
+    }
+    sqlite3VdbeResolveLabel(v, addrCont);
+    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
+    VdbeCoverage(v);
+    sqlite3VdbeJumpHere(v, addrTop);
+    pLoop->wsFlags &= ~WHERE_BLOOMFILTER;
+    if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break;
+    while( ++iLevel < pWInfo->nLevel ){
+      const SrcItem *pTabItem;
+      pLevel = &pWInfo->a[iLevel];
+      pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
+      if( pTabItem->fg.jointype & JT_LEFT ) continue;
+      pLoop = pLevel->pWLoop;
+      if( NEVER(pLoop==0) ) continue;
+      if( pLoop->prereq & notReady ) continue;
+      if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN))
+                 ==WHERE_BLOOMFILTER
+      ){
+        /* This is a candidate for bloom-filter pull-down (early evaluation).
+        ** The test that WHERE_COLUMN_IN is omitted is important, as we are
+        ** not able to do early evaluation of bloom filters that make use of
+        ** the IN operator */
+        break;
+      }
+    }
+  }while( iLevel < pWInfo->nLevel );
+  sqlite3VdbeJumpHere(v, addrOnce);
+}
+
+
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 /*
 ** Allocate and populate an sqlite3_index_info structure. It is the
 ** responsibility of the caller to eventually release the structure
-** by passing the pointer returned by this function to sqlite3_free().
+** by passing the pointer returned by this function to freeIndexInfo().
 */
 static sqlite3_index_info *allocateIndexInfo(
-  Parse *pParse,                  /* The parsing context */
+  WhereInfo *pWInfo,              /* The WHERE clause */
   WhereClause *pWC,               /* The WHERE clause being analyzed */
   Bitmask mUnusable,              /* Ignore terms with these prereqs */
   SrcItem *pSrc,                  /* The FROM clause term that is the vtab */
-  ExprList *pOrderBy,             /* The ORDER BY clause */
   u16 *pmNoOmit                   /* Mask of terms not to omit */
 ){
   int i, j;
   int nTerm;
+  Parse *pParse = pWInfo->pParse;
   struct sqlite3_index_constraint *pIdxCons;
   struct sqlite3_index_orderby *pIdxOrderBy;
   struct sqlite3_index_constraint_usage *pUsage;
@@ -149247,10 +153181,21 @@ static sqlite3_index_info *allocateIndexInfo(
   int nOrderBy;
   sqlite3_index_info *pIdxInfo;
   u16 mNoOmit = 0;
+  const Table *pTab;
+  int eDistinct = 0;
+  ExprList *pOrderBy = pWInfo->pOrderBy;
 
-  /* Count the number of possible WHERE clause constraints referring
-  ** to this virtual table */
+  assert( pSrc!=0 );
+  pTab = pSrc->pTab;
+  assert( pTab!=0 );
+  assert( IsVirtual(pTab) );
+
+  /* Find all WHERE clause constraints referring to this virtual table.
+  ** Mark each term with the TERM_OK flag.  Set nTerm to the number of
+  ** terms found.
+  */
   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
+    pTerm->wtFlags &= ~TERM_OK;
     if( pTerm->leftCursor != pSrc->iCursor ) continue;
     if( pTerm->prereqRight & mUnusable ) continue;
     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
@@ -149260,8 +153205,21 @@ static sqlite3_index_info *allocateIndexInfo(
     testcase( pTerm->eOperator & WO_ALL );
     if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
     if( pTerm->wtFlags & TERM_VNULL ) continue;
-    assert( pTerm->u.x.leftColumn>=(-1) );
+
+    assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
+    assert( pTerm->u.x.leftColumn>=XN_ROWID );
+    assert( pTerm->u.x.leftColumn<pTab->nCol );
+
+    /* tag-20191211-002: WHERE-clause constraints are not useful to the
+    ** right-hand table of a LEFT JOIN.  See tag-20191211-001 for the
+    ** equivalent restriction for ordinary tables. */
+    if( (pSrc->fg.jointype & JT_LEFT)!=0
+     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
+    ){
+      continue;
+    }
     nTerm++;
+    pTerm->wtFlags |= TERM_OK;
   }
 
   /* If the ORDER BY clause contains only columns in the current
@@ -149273,11 +153231,47 @@ static sqlite3_index_info *allocateIndexInfo(
     int n = pOrderBy->nExpr;
     for(i=0; i<n; i++){
       Expr *pExpr = pOrderBy->a[i].pExpr;
-      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
+      Expr *pE2;
+
+      /* Skip over constant terms in the ORDER BY clause */
+      if( sqlite3ExprIsConstant(pExpr) ){
+        continue;
+      }
+
+      /* Virtual tables are unable to deal with NULLS FIRST */
       if( pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL ) break;
+
+      /* First case - a direct column references without a COLLATE operator */
+      if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){
+        assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumn<pTab->nCol );
+        continue;
+      }
+
+      /* 2nd case - a column reference with a COLLATE operator.  Only match
+      ** of the COLLATE operator matches the collation of the column. */
+      if( pExpr->op==TK_COLLATE
+       && (pE2 = pExpr->pLeft)->op==TK_COLUMN
+       && pE2->iTable==pSrc->iCursor
+      ){
+        const char *zColl;  /* The collating sequence name */
+        assert( !ExprHasProperty(pExpr, EP_IntValue) );
+        assert( pExpr->u.zToken!=0 );
+        assert( pE2->iColumn>=XN_ROWID && pE2->iColumn<pTab->nCol );
+        pExpr->iColumn = pE2->iColumn;
+        if( pE2->iColumn<0 ) continue;  /* Collseq does not matter for rowid */
+        zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]);
+        if( zColl==0 ) zColl = sqlite3StrBINARY;
+        if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue;
+      }
+
+      /* No matches cause a break out of the loop */
+      break;
     }
-    if( i==n){
+    if( i==n ){
       nOrderBy = n;
+      if( (pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY)) ){
+        eDistinct = 1 + ((pWInfo->wctrlFlags & WHERE_DISTINCTBY)!=0);
+      }
     }
   }
 
@@ -149285,46 +153279,35 @@ static sqlite3_index_info *allocateIndexInfo(
   */
   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
-                           + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
+                           + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden)
+                           + sizeof(sqlite3_value*)*nTerm );
   if( pIdxInfo==0 ){
     sqlite3ErrorMsg(pParse, "out of memory");
     return 0;
   }
   pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
-  pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
+  pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm];
   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
-  pIdxInfo->nOrderBy = nOrderBy;
   pIdxInfo->aConstraint = pIdxCons;
   pIdxInfo->aOrderBy = pIdxOrderBy;
   pIdxInfo->aConstraintUsage = pUsage;
   pHidden->pWC = pWC;
   pHidden->pParse = pParse;
+  pHidden->eDistinct = eDistinct;
+  pHidden->mIn = 0;
   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
     u16 op;
-    if( pTerm->leftCursor != pSrc->iCursor ) continue;
-    if( pTerm->prereqRight & mUnusable ) continue;
-    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
-    testcase( pTerm->eOperator & WO_IN );
-    testcase( pTerm->eOperator & WO_IS );
-    testcase( pTerm->eOperator & WO_ISNULL );
-    testcase( pTerm->eOperator & WO_ALL );
-    if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
-    if( pTerm->wtFlags & TERM_VNULL ) continue;
-
-    /* tag-20191211-002: WHERE-clause constraints are not useful to the
-    ** right-hand table of a LEFT JOIN.  See tag-20191211-001 for the
-    ** equivalent restriction for ordinary tables. */
-    if( (pSrc->fg.jointype & JT_LEFT)!=0
-     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
-    ){
-      continue;
-    }
-    assert( pTerm->u.x.leftColumn>=(-1) );
+    if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
     pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
     pIdxCons[j].iTermOffset = i;
     op = pTerm->eOperator & WO_ALL;
-    if( op==WO_IN ) op = WO_EQ;
+    if( op==WO_IN ){
+      if( (pTerm->wtFlags & TERM_SLICE)==0 ){
+        pHidden->mIn |= SMASKBIT32(j);
+      }
+      op = WO_EQ;
+    }
     if( op==WO_AUX ){
       pIdxCons[j].op = pTerm->eMatchOp;
     }else if( op & (WO_ISNULL|WO_IS) ){
@@ -149357,17 +153340,42 @@ static sqlite3_index_info *allocateIndexInfo(
 
     j++;
   }
+  assert( j==nTerm );
   pIdxInfo->nConstraint = j;
-  for(i=0; i<nOrderBy; i++){
+  for(i=j=0; i<nOrderBy; i++){
     Expr *pExpr = pOrderBy->a[i].pExpr;
-    pIdxOrderBy[i].iColumn = pExpr->iColumn;
-    pIdxOrderBy[i].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC;
+    if( sqlite3ExprIsConstant(pExpr) ) continue;
+    assert( pExpr->op==TK_COLUMN
+         || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
+              && pExpr->iColumn==pExpr->pLeft->iColumn) );
+    pIdxOrderBy[j].iColumn = pExpr->iColumn;
+    pIdxOrderBy[j].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC;
+    j++;
   }
+  pIdxInfo->nOrderBy = j;
 
   *pmNoOmit = mNoOmit;
   return pIdxInfo;
 }
 
+/*
+** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
+** and possibly modified by xBestIndex methods.
+*/
+static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
+  HiddenIndexInfo *pHidden;
+  int i;
+  assert( pIdxInfo!=0 );
+  pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
+  assert( pHidden->pParse!=0 );
+  assert( pHidden->pParse->db==db );
+  for(i=0; i<pIdxInfo->nConstraint; i++){
+    sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
+    pHidden->aRhs[i] = 0;
+  }
+  sqlite3DbFree(db, pIdxInfo);
+}
+
 /*
 ** The table object reference passed as the second argument to this function
 ** must represent a virtual table. This function invokes the xBestIndex()
@@ -149389,7 +153397,9 @@ static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   int rc;
 
   whereTraceIndexInfoInputs(p);
+  pParse->db->nSchemaLock++;
   rc = pVtab->pModule->xBestIndex(pVtab, p);
+  pParse->db->nSchemaLock--;
   whereTraceIndexInfoOutputs(p);
 
   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
@@ -150083,6 +154093,7 @@ SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
     if( pTerm->wtFlags & TERM_CODED  ) zType[3] = 'C';
     if( pTerm->eOperator & WO_SINGLE ){
+      assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
       sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
                        pTerm->leftCursor, pTerm->u.x.leftColumn);
     }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
@@ -150100,7 +154111,7 @@ SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
       sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
         pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
     }
-    if( pTerm->u.x.iField ){
+    if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){
       sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
     }
     if( pTerm->iParent>=0 ){
@@ -150162,9 +154173,9 @@ SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
     sqlite3_free(z);
   }
   if( p->wsFlags & WHERE_SKIPSCAN ){
-    sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
+    sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
   }else{
-    sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
+    sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm);
   }
   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
@@ -150235,7 +154246,7 @@ static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
   whereLoopClearUnion(db, pTo);
   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
-    memset(&pTo->u, 0, sizeof(pTo->u));
+    memset(pTo, 0, WHERE_LOOP_XFER_SZ);
     return SQLITE_NOMEM_BKPT;
   }
   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
@@ -150264,7 +154275,8 @@ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   assert( pWInfo!=0 );
   for(i=0; i<pWInfo->nLevel; i++){
     WhereLevel *pLevel = &pWInfo->a[i];
-    if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
+    if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE)!=0 ){
+      assert( (pLevel->pWLoop->wsFlags & WHERE_MULTI_OR)==0 );
       sqlite3DbFree(db, pLevel->u.in.aInLoop);
     }
   }
@@ -150278,10 +154290,22 @@ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   sqlite3DbFreeNN(db, pWInfo);
 }
 
+/* Undo all Expr node modifications
+*/
+static void whereUndoExprMods(WhereInfo *pWInfo){
+  while( pWInfo->pExprMods ){
+    WhereExprMod *p = pWInfo->pExprMods;
+    pWInfo->pExprMods = p->pNext;
+    memcpy(p->pExpr, &p->orig, sizeof(p->orig));
+    sqlite3DbFree(pWInfo->pParse->db, p);
+  }
+}
+
 /*
 ** Return TRUE if all of the following are true:
 **
-**   (1)  X has the same or lower cost that Y
+**   (1)  X has the same or lower cost, or returns the same or fewer rows,
+**        than Y.
 **   (2)  X uses fewer WHERE clause terms than Y
 **   (3)  Every WHERE clause term used by X is also used by Y
 **   (4)  X skips at least as many columns as Y
@@ -150304,11 +154328,8 @@ static int whereLoopCheaperProperSubset(
   if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
     return 0; /* X is not a subset of Y */
   }
+  if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0;
   if( pY->nSkip > pX->nSkip ) return 0;
-  if( pX->rRun >= pY->rRun ){
-    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
-    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
-  }
   for(i=pX->nLTerm-1; i>=0; i--){
     if( pX->aLTerm[i]==0 ) continue;
     for(j=pY->nLTerm-1; j>=0; j--){
@@ -150324,8 +154345,8 @@ static int whereLoopCheaperProperSubset(
 }
 
 /*
-** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
-** that:
+** Try to adjust the cost and number of output rows of WhereLoop pTemplate
+** upwards or downwards so that:
 **
 **   (1) pTemplate costs less than any other WhereLoops that are a proper
 **       subset of pTemplate
@@ -150346,16 +154367,20 @@ static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
       /* Adjust pTemplate cost downward so that it is cheaper than its
       ** subset p. */
       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
-                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
-      pTemplate->rRun = p->rRun;
-      pTemplate->nOut = p->nOut - 1;
+                       pTemplate->rRun, pTemplate->nOut,
+                       MIN(p->rRun, pTemplate->rRun),
+                       MIN(p->nOut - 1, pTemplate->nOut)));
+      pTemplate->rRun = MIN(p->rRun, pTemplate->rRun);
+      pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut);
     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
       /* Adjust pTemplate cost upward so that it is costlier than p since
       ** pTemplate is a proper subset of p */
       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
-                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
-      pTemplate->rRun = p->rRun;
-      pTemplate->nOut = p->nOut + 1;
+                       pTemplate->rRun, pTemplate->nOut,
+                       MAX(p->rRun, pTemplate->rRun),
+                       MAX(p->nOut + 1, pTemplate->nOut)));
+      pTemplate->rRun = MAX(p->rRun, pTemplate->rRun);
+      pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut);
     }
   }
 }
@@ -150610,11 +154635,11 @@ static void whereLoopOutputAdjust(
   LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
 
   assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
-  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
+  for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){
     assert( pTerm!=0 );
-    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
-    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
+    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
+    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue;
     for(j=pLoop->nLTerm-1; j>=0; j--){
       pX = pLoop->aLTerm[j];
       if( pX==0 ) continue;
@@ -150622,6 +154647,22 @@ static void whereLoopOutputAdjust(
       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
     }
     if( j<0 ){
+      if( pLoop->maskSelf==pTerm->prereqAll ){
+        /* If there are extra terms in the WHERE clause not used by an index
+        ** that depend only on the table being scanned, and that will tend to
+        ** cause many rows to be omitted, then mark that table as
+        ** "self-culling".
+        **
+        ** 2022-03-24:  Self-culling only applies if either the extra terms
+        ** are straight comparison operators that are non-true with NULL
+        ** operand, or if the loop is not a LEFT JOIN.
+        */
+        if( (pTerm->eOperator & 0x3f)!=0
+         || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0
+        ){
+          pLoop->wsFlags |= WHERE_SELFCULL;
+        }
+      }
       if( pTerm->truthProb<=0 ){
         /* If a truth probability is specified using the likelihood() hints,
         ** then use the probability provided by the application. */
@@ -150649,7 +154690,9 @@ static void whereLoopOutputAdjust(
       }
     }
   }
-  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
+  if( pLoop->nOut > nRow-iReduce ){
+    pLoop->nOut = nRow - iReduce;
+  }
 }
 
 /*
@@ -150686,9 +154729,12 @@ static int whereRangeVectorLen(
     char aff;                     /* Comparison affinity */
     char idxaff = 0;              /* Indexed columns affinity */
     CollSeq *pColl;               /* Comparison collation sequence */
-    Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
-    Expr *pRhs = pTerm->pExpr->pRight;
-    if( pRhs->flags & EP_xIsSelect ){
+    Expr *pLhs, *pRhs;
+
+    assert( ExprUseXList(pTerm->pExpr->pLeft) );
+    pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
+    pRhs = pTerm->pExpr->pRight;
+    if( ExprUseXSelect(pRhs) ){
       pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
     }else{
       pRhs = pRhs->x.pList->a[i].pExpr;
@@ -150783,6 +154829,8 @@ static int whereLoopAddBtreeIndex(
   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
 
   assert( pNew->u.btree.nEq<pProbe->nColumn );
+  assert( pNew->u.btree.nEq<pProbe->nKeyCol
+       || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
 
   saved_nEq = pNew->u.btree.nEq;
   saved_nBtm = pNew->u.btree.nBtm;
@@ -150847,7 +154895,7 @@ static int whereLoopAddBtreeIndex(
 
     if( eOp & WO_IN ){
       Expr *pExpr = pTerm->pExpr;
-      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
+      if( ExprUseXSelect(pExpr) ){
         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
         int i;
         nIn = 46;  assert( 46==sqlite3LogEst(25) );
@@ -150865,7 +154913,7 @@ static int whereLoopAddBtreeIndex(
         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
       }
       if( pProbe->hasStat1 && rLogSize>=10 ){
-        LogEst M, logK, safetyMargin;
+        LogEst M, logK, x;
         /* Let:
         **   N = the total number of rows in the table
         **   K = the number of entries on the RHS of the IN operator
@@ -150888,16 +154936,25 @@ static int whereLoopAddBtreeIndex(
         */
         M = pProbe->aiRowLogEst[saved_nEq];
         logK = estLog(nIn);
-        safetyMargin = 10;  /* TUNING: extra weight for indexed IN */
-        if( M + logK + safetyMargin < nIn + rLogSize ){
+        /* TUNING      v-----  10 to bias toward indexed IN */
+        x = M + logK + 10 - (nIn + rLogSize);
+        if( x>=0 ){
           WHERETRACE(0x40,
-            ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
-             saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
+            ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) "
+             "prefers indexed lookup\n",
+             saved_nEq, M, logK, nIn, rLogSize, x));
+        }else if( nInMul<2 && OptimizationEnabled(db, SQLITE_SeekScan) ){
+          WHERETRACE(0x40,
+            ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
+             " nInMul=%d) prefers skip-scan\n",
+             saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
           pNew->wsFlags |= WHERE_IN_SEEKSCAN;
         }else{
           WHERETRACE(0x40,
-            ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
-             saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
+            ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
+             " nInMul=%d) prefers normal scan\n",
+             saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
+          continue;
         }
       }
       pNew->wsFlags |= WHERE_COLUMN_IN;
@@ -150916,6 +154973,7 @@ static int whereLoopAddBtreeIndex(
           pNew->wsFlags |= WHERE_UNQ_WANTED;
         }
       }
+      if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
     }else if( eOp & WO_ISNULL ){
       pNew->wsFlags |= WHERE_COLUMN_NULL;
     }else if( eOp & (WO_GT|WO_GE) ){
@@ -150977,8 +155035,8 @@ static int whereLoopAddBtreeIndex(
         tRowcnt nOut = 0;
         if( nInMul==0
          && pProbe->nSample
-         && pNew->u.btree.nEq<=pProbe->nSampleCol
-         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
+         && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol)
+         && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr))
          && OptimizationEnabled(db, SQLITE_Stat4)
         ){
           Expr *pExpr = pTerm->pExpr;
@@ -151059,6 +155117,8 @@ static int whereLoopAddBtreeIndex(
 
     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
      && pNew->u.btree.nEq<pProbe->nColumn
+     && (pNew->u.btree.nEq<pProbe->nKeyCol ||
+           pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)
     ){
       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
     }
@@ -151177,9 +155237,10 @@ static int whereUsablePartialIndex(
   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
     Expr *pExpr;
     pExpr = pTerm->pExpr;
-    if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
+    if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->w.iRightJoinTable==iTab)
      && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin))
      && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
+     && (pTerm->wtFlags & TERM_VNULL)==0
     ){
       return 1;
     }
@@ -151239,7 +155300,6 @@ static int whereLoopAddBtree(
   int iSortIdx = 1;           /* Index number */
   int b;                      /* A boolean value */
   LogEst rSize;               /* number of rows in the table */
-  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
   WhereClause *pWC;           /* The parsed WHERE clause */
   Table *pTab;                /* Table being queried */
 
@@ -151252,6 +155312,7 @@ static int whereLoopAddBtree(
   assert( !IsVirtual(pSrc->pTab) );
 
   if( pSrc->fg.isIndexedBy ){
+    assert( pSrc->fg.isCte==0 );
     /* An INDEXED BY clause specifies a particular index to use */
     pProbe = pSrc->u2.pIBIndex;
   }else if( !HasRowid(pTab) ){
@@ -151282,7 +155343,6 @@ static int whereLoopAddBtree(
     pProbe = &sPk;
   }
   rSize = pTab->nRowLogEst;
-  rLogSize = estLog(rSize);
 
 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   /* Automatic indexes */
@@ -151296,8 +155356,10 @@ static int whereLoopAddBtree(
    && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
   ){
     /* Generate auto-index WhereLoops */
+    LogEst rLogSize;         /* Logarithm of the number of rows in the table */
     WhereTerm *pTerm;
     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
+    rLogSize = estLog(rSize);
     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
       if( pTerm->prereqRight & pNew->maskSelf ) continue;
       if( termCanDriveIndex(pTerm, pSrc, 0) ){
@@ -151315,7 +155377,7 @@ static int whereLoopAddBtree(
         ** those objects, since there is no opportunity to add schema
         ** indexes on subqueries and views. */
         pNew->rSetup = rLogSize + rSize;
-        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
+        if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){
           pNew->rSetup += 28;
         }else{
           pNew->rSetup -= 10;
@@ -151477,6 +155539,15 @@ static int whereLoopAddBtree(
 
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 
+/*
+** Return true if pTerm is a virtual table LIMIT or OFFSET term.
+*/
+static int isLimitTerm(WhereTerm *pTerm){
+  assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
+  return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
+      && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
+}
+
 /*
 ** Argument pIdxInfo is already populated with all constraints that may
 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
@@ -151504,9 +155575,11 @@ static int whereLoopAddVirtualOne(
   u16 mExclude,                   /* Exclude terms using these operators */
   sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
   u16 mNoOmit,                    /* Do not omit these constraints */
-  int *pbIn                       /* OUT: True if plan uses an IN(...) op */
+  int *pbIn,                      /* OUT: True if plan uses an IN(...) op */
+  int *pbRetryLimit               /* OUT: Retry without LIMIT/OFFSET */
 ){
   WhereClause *pWC = pBuilder->pWC;
+  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
   struct sqlite3_index_constraint *pIdxCons;
   struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
   int i;
@@ -151529,6 +155602,7 @@ static int whereLoopAddVirtualOne(
     pIdxCons->usable = 0;
     if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
      && (pTerm->eOperator & mExclude)==0
+     && (pbRetryLimit || !isLimitTerm(pTerm))
     ){
       pIdxCons->usable = 1;
     }
@@ -151544,6 +155618,7 @@ static int whereLoopAddVirtualOne(
   pIdxInfo->estimatedRows = 25;
   pIdxInfo->idxFlags = 0;
   pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
+  pHidden->mHandleIn = 0;
 
   /* Invoke the virtual table xBestIndex() method */
   rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
@@ -151561,8 +155636,8 @@ static int whereLoopAddVirtualOne(
 
   mxTerm = -1;
   assert( pNew->nLSlot>=nConstraint );
-  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
-  pNew->u.vtab.omitMask = 0;
+  memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
+  memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   for(i=0; i<nConstraint; i++, pIdxCons++){
     int iTerm;
@@ -151596,8 +155671,13 @@ static int whereLoopAddVirtualOne(
         }else{
           testcase( i!=iTerm );
         }
+        if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
+          pNew->u.vtab.bOmitOffset = 1;
+        }
       }
-      if( (pTerm->eOperator & WO_IN)!=0 ){
+      if( SMASKBIT32(i) & pHidden->mHandleIn ){
+        pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
+      }else if( (pTerm->eOperator & WO_IN)!=0 ){
         /* A virtual table that is constrained by an IN clause may not
         ** consume the ORDER BY clause because (1) the order of IN terms
         ** is not necessarily related to the order of output terms and
@@ -151607,6 +155687,21 @@ static int whereLoopAddVirtualOne(
         pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
         *pbIn = 1; assert( (mExclude & WO_IN)==0 );
       }
+
+      if( isLimitTerm(pTerm) && *pbIn ){
+        /* If there is an IN(...) term handled as an == (separate call to
+        ** xFilter for each value on the RHS of the IN) and a LIMIT or
+        ** OFFSET term handled as well, the plan is unusable. Set output
+        ** variable *pbRetryLimit to true to tell the caller to retry with
+        ** LIMIT and OFFSET disabled. */
+        if( pIdxInfo->needToFreeIdxStr ){
+          sqlite3_free(pIdxInfo->idxStr);
+          pIdxInfo->idxStr = 0;
+          pIdxInfo->needToFreeIdxStr = 0;
+        }
+        *pbRetryLimit = 1;
+        return SQLITE_OK;
+      }
     }
   }
 
@@ -151651,11 +155746,19 @@ static int whereLoopAddVirtualOne(
 }
 
 /*
-** If this function is invoked from within an xBestIndex() callback, it
-** returns a pointer to a buffer containing the name of the collation
-** sequence associated with element iCons of the sqlite3_index_info.aConstraint
-** array. Or, if iCons is out of range or there is no active xBestIndex
-** call, return NULL.
+** Return the collating sequence for a constraint passed into xBestIndex.
+**
+** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
+** This routine depends on there being a HiddenIndexInfo structure immediately
+** following the sqlite3_index_info structure.
+**
+** Return a pointer to the collation name:
+**
+**    1. If there is an explicit COLLATE operator on the constaint, return it.
+**
+**    2. Else, if the column has an alternative collation, return that.
+**
+**    3. Otherwise, return "BINARY".
 */
 SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
   HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
@@ -151672,6 +155775,88 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int
   return zRet;
 }
 
+/*
+** Return true if constraint iCons is really an IN(...) constraint, or
+** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
+** or clear (if bHandle==0) the flag to handle it using an iterator.
+*/
+SQLITE_API int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){
+  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
+  u32 m = SMASKBIT32(iCons);
+  if( m & pHidden->mIn ){
+    if( bHandle==0 ){
+      pHidden->mHandleIn &= ~m;
+    }else if( bHandle>0 ){
+      pHidden->mHandleIn |= m;
+    }
+    return 1;
+  }
+  return 0;
+}
+
+/*
+** This interface is callable from within the xBestIndex callback only.
+**
+** If possible, set (*ppVal) to point to an object containing the value
+** on the right-hand-side of constraint iCons.
+*/
+SQLITE_API int sqlite3_vtab_rhs_value(
+  sqlite3_index_info *pIdxInfo,   /* Copy of first argument to xBestIndex */
+  int iCons,                      /* Constraint for which RHS is wanted */
+  sqlite3_value **ppVal           /* Write value extracted here */
+){
+  HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
+  sqlite3_value *pVal = 0;
+  int rc = SQLITE_OK;
+  if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
+    rc = SQLITE_MISUSE; /* EV: R-30545-25046 */
+  }else{
+    if( pH->aRhs[iCons]==0 ){
+      WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
+      rc = sqlite3ValueFromExpr(
+          pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
+          SQLITE_AFF_BLOB, &pH->aRhs[iCons]
+      );
+      testcase( rc!=SQLITE_OK );
+    }
+    pVal = pH->aRhs[iCons];
+  }
+  *ppVal = pVal;
+
+  if( rc==SQLITE_OK && pVal==0 ){  /* IMP: R-19933-32160 */
+    rc = SQLITE_NOTFOUND;          /* IMP: R-36424-56542 */
+  }
+
+  return rc;
+}
+
+/*
+** Return true if ORDER BY clause may be handled as DISTINCT.
+*/
+SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
+  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
+  assert( pHidden->eDistinct==0
+       || pHidden->eDistinct==1
+       || pHidden->eDistinct==2 );
+  return pHidden->eDistinct;
+}
+
+#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
+    && !defined(SQLITE_OMIT_VIRTUALTABLE)
+/*
+** Cause the prepared statement that is associated with a call to
+** xBestIndex to open write transactions on all attached schemas.
+** This is used by the (built-in) sqlite_dbpage virtual table.
+*/
+SQLITE_PRIVATE void sqlite3VtabWriteAll(sqlite3_index_info *pIdxInfo){
+  HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
+  Parse *pParse = pHidden->pParse;
+  int nDb = pParse->db->nDb;
+  int i;
+  for(i=0; i<nDb; i++) sqlite3BeginWriteOperation(pParse, 0, i);
+}
+#endif
+
 /*
 ** Add all WhereLoop objects for a table of the join identified by
 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
@@ -151713,6 +155898,7 @@ static int whereLoopAddVirtual(
   WhereLoop *pNew;
   Bitmask mBest;               /* Tables used by best possible plan */
   u16 mNoOmit;
+  int bRetry = 0;              /* True to retry with LIMIT/OFFSET disabled */
 
   assert( (mPrereq & mUnusable)==0 );
   pWInfo = pBuilder->pWInfo;
@@ -151721,8 +155907,7 @@ static int whereLoopAddVirtual(
   pNew = pBuilder->pNew;
   pSrc = &pWInfo->pTabList->a[pNew->iTab];
   assert( IsVirtual(pSrc->pTab) );
-  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
-      &mNoOmit);
+  p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit);
   if( p==0 ) return SQLITE_NOMEM_BKPT;
   pNew->rSetup = 0;
   pNew->wsFlags = WHERE_VIRTUALTABLE;
@@ -151730,14 +155915,22 @@ static int whereLoopAddVirtual(
   pNew->u.vtab.needFree = 0;
   nConstraint = p->nConstraint;
   if( whereLoopResize(pParse->db, pNew, nConstraint) ){
-    sqlite3DbFree(pParse->db, p);
+    freeIndexInfo(pParse->db, p);
     return SQLITE_NOMEM_BKPT;
   }
 
   /* First call xBestIndex() with all constraints usable. */
   WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
   WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
-  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
+  rc = whereLoopAddVirtualOne(
+      pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry
+  );
+  if( bRetry ){
+    assert( rc==SQLITE_OK );
+    rc = whereLoopAddVirtualOne(
+        pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0
+    );
+  }
 
   /* If the call to xBestIndex() with all terms enabled produced a plan
   ** that does not require any source tables (IOW: a plan with mBest==0)
@@ -151755,7 +155948,7 @@ static int whereLoopAddVirtual(
     if( bIn ){
       WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
       rc = whereLoopAddVirtualOne(
-          pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
+          pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0);
       assert( bIn==0 );
       mBestNoIn = pNew->prereq & ~mPrereq;
       if( mBestNoIn==0 ){
@@ -151782,7 +155975,7 @@ static int whereLoopAddVirtual(
       WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
                        (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
       rc = whereLoopAddVirtualOne(
-          pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
+          pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn, 0);
       if( pNew->prereq==mPrereq ){
         seenZero = 1;
         if( bIn==0 ) seenZeroNoIN = 1;
@@ -151795,7 +155988,7 @@ static int whereLoopAddVirtual(
     if( rc==SQLITE_OK && seenZero==0 ){
       WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
       rc = whereLoopAddVirtualOne(
-          pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
+          pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0);
       if( bIn==0 ) seenZeroNoIN = 1;
     }
 
@@ -151805,12 +155998,12 @@ static int whereLoopAddVirtual(
     if( rc==SQLITE_OK && seenZeroNoIN==0 ){
       WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
       rc = whereLoopAddVirtualOne(
-          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
+          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
     }
   }
 
   if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
-  sqlite3DbFreeNN(pParse->db, p);
+  freeIndexInfo(pParse->db, p);
   WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
   return rc;
 }
@@ -151854,7 +156047,6 @@ static int whereLoopAddOr(
       int i, j;
 
       sSubBuild = *pBuilder;
-      sSubBuild.pOrderBy = 0;
       sSubBuild.pOrSet = &sCur;
 
       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
@@ -151866,6 +156058,7 @@ static int whereLoopAddOr(
           tempWC.pOuter = pWC;
           tempWC.op = TK_AND;
           tempWC.nTerm = 1;
+          tempWC.nBase = 1;
           tempWC.a = pOrTerm;
           sSubBuild.pWC = &tempWC;
         }else{
@@ -151890,7 +156083,9 @@ static int whereLoopAddOr(
         if( rc==SQLITE_OK ){
           rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
         }
-        assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 );
+        assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0
+                || rc==SQLITE_NOMEM );
+        testcase( rc==SQLITE_NOMEM && sCur.n>0 );
         testcase( rc==SQLITE_DONE );
         if( sCur.n==0 ){
           sSum.n = 0;
@@ -152119,7 +156314,7 @@ static i8 wherePathSatisfiesOrderBy(
       if( MASKBIT(i) & obSat ) continue;
       pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
       if( NEVER(pOBExpr==0) ) continue;
-      if( pOBExpr->op!=TK_COLUMN ) continue;
+      if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
       if( pOBExpr->iTable!=iCur ) continue;
       pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
                        ~ready, eqOpMask, 0);
@@ -152159,6 +156354,10 @@ static i8 wherePathSatisfiesOrderBy(
         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
         assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
                           || !HasRowid(pIndex->pTable));
+        /* All relevant terms of the index must also be non-NULL in order
+        ** for isOrderDistinct to be true.  So the isOrderDistint value
+        ** computed here might be a false positive.  Corrections will be
+        ** made at tag-20210426-1 below */
         isOrderDistinct = IsUniqueIndex(pIndex)
                           && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
       }
@@ -152226,14 +156425,18 @@ static i8 wherePathSatisfiesOrderBy(
         }
 
         /* An unconstrained column that might be NULL means that this
-        ** WhereLoop is not well-ordered
+        ** WhereLoop is not well-ordered.  tag-20210426-1
         */
-        if( isOrderDistinct
-         && iColumn>=0
-         && j>=pLoop->u.btree.nEq
-         && pIndex->pTable->aCol[iColumn].notNull==0
-        ){
-          isOrderDistinct = 0;
+        if( isOrderDistinct ){
+          if( iColumn>=0
+           && j>=pLoop->u.btree.nEq
+           && pIndex->pTable->aCol[iColumn].notNull==0
+          ){
+            isOrderDistinct = 0;
+          }
+          if( iColumn==XN_EXPR ){
+            isOrderDistinct = 0;
+          }
         }
 
         /* Find the ORDER BY term that corresponds to the j-th column
@@ -152248,7 +156451,7 @@ static i8 wherePathSatisfiesOrderBy(
           if( NEVER(pOBExpr==0) ) continue;
           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
           if( iColumn>=XN_ROWID ){
-            if( pOBExpr->op!=TK_COLUMN ) continue;
+            if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
             if( pOBExpr->iTable!=iCur ) continue;
             if( pOBExpr->iColumn!=iColumn ) continue;
           }else{
@@ -152327,7 +156530,7 @@ static i8 wherePathSatisfiesOrderBy(
   if( obSat==obDone ) return (i8)nOrderBy;
   if( !isOrderDistinct ){
     for(i=nOrderBy-1; i>0; i--){
-      Bitmask m = MASKBIT(i) - 1;
+      Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
       if( (obSat&m)==m ) return i;
     }
     return 0;
@@ -152417,7 +156620,7 @@ static LogEst whereSortingCost(
   }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
     /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
     ** reduces the number of output rows by a factor of 2 */
-    if( nRow>10 ) nRow -= 10;  assert( 10==sqlite3LogEst(2) );
+    if( nRow>10 ){ nRow -= 10;  assert( 10==sqlite3LogEst(2) ); }
   }
   rSortCost += estLog(nRow);
   return rSortCost;
@@ -152837,6 +157040,7 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
   int j;
   Table *pTab;
   Index *pIdx;
+  WhereScan scan;
 
   pWInfo = pBuilder->pWInfo;
   if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
@@ -152850,7 +157054,8 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
   pLoop = pBuilder->pNew;
   pLoop->wsFlags = 0;
   pLoop->nSkip = 0;
-  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
+  pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
+  while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
   if( pTerm ){
     testcase( pTerm->eOperator & WO_IS );
     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
@@ -152869,7 +157074,8 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
       ) continue;
       opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
       for(j=0; j<pIdx->nKeyCol; j++){
-        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
+        pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx);
+        while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
         if( pTerm==0 ) break;
         testcase( pTerm->eOperator & WO_IS );
         pLoop->aLTerm[j] = pTerm;
@@ -152898,8 +157104,14 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
     }
+    if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
 #ifdef SQLITE_DEBUG
     pLoop->cId = '0';
+#endif
+#ifdef WHERETRACE_ENABLED
+    if( sqlite3WhereTrace ){
+      sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
+    }
 #endif
     return 1;
   }
@@ -152954,6 +157166,150 @@ static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
 # define WHERETRACE_ALL_LOOPS(W,C)
 #endif
 
+/* Attempt to omit tables from a join that do not affect the result.
+** For a table to not affect the result, the following must be true:
+**
+**   1) The query must not be an aggregate.
+**   2) The table must be the RHS of a LEFT JOIN.
+**   3) Either the query must be DISTINCT, or else the ON or USING clause
+**      must contain a constraint that limits the scan of the table to
+**      at most a single row.
+**   4) The table must not be referenced by any part of the query apart
+**      from its own USING or ON clause.
+**
+** For example, given:
+**
+**     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
+**     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
+**     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
+**
+** then table t2 can be omitted from the following:
+**
+**     SELECT v1, v3 FROM t1
+**       LEFT JOIN t2 ON (t1.ipk=t2.ipk)
+**       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
+**
+** or from:
+**
+**     SELECT DISTINCT v1, v3 FROM t1
+**       LEFT JOIN t2
+**       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
+*/
+static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
+  WhereInfo *pWInfo,
+  Bitmask notReady
+){
+  int i;
+  Bitmask tabUsed;
+
+  /* Preconditions checked by the caller */
+  assert( pWInfo->nLevel>=2 );
+  assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
+
+  /* These two preconditions checked by the caller combine to guarantee
+  ** condition (1) of the header comment */
+  assert( pWInfo->pResultSet!=0 );
+  assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
+
+  tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
+  if( pWInfo->pOrderBy ){
+    tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
+  }
+  for(i=pWInfo->nLevel-1; i>=1; i--){
+    WhereTerm *pTerm, *pEnd;
+    SrcItem *pItem;
+    WhereLoop *pLoop;
+    pLoop = pWInfo->a[i].pWLoop;
+    pItem = &pWInfo->pTabList->a[pLoop->iTab];
+    if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
+    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
+     && (pLoop->wsFlags & WHERE_ONEROW)==0
+    ){
+      continue;
+    }
+    if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
+    pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
+    for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
+      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
+        if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
+         || pTerm->pExpr->w.iRightJoinTable!=pItem->iCursor
+        ){
+          break;
+        }
+      }
+    }
+    if( pTerm<pEnd ) continue;
+    WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
+    notReady &= ~pLoop->maskSelf;
+    for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
+      if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
+        pTerm->wtFlags |= TERM_CODED;
+      }
+    }
+    if( i!=pWInfo->nLevel-1 ){
+      int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
+      memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
+    }
+    pWInfo->nLevel--;
+    assert( pWInfo->nLevel>0 );
+  }
+  return notReady;
+}
+
+/*
+** Check to see if there are any SEARCH loops that might benefit from
+** using a Bloom filter.  Consider a Bloom filter if:
+**
+**   (1)  The SEARCH happens more than N times where N is the number
+**        of rows in the table that is being considered for the Bloom
+**        filter.
+**   (2)  Some searches are expected to find zero rows.  (This is determined
+**        by the WHERE_SELFCULL flag on the term.)
+**   (3)  Bloom-filter processing is not disabled.  (Checked by the
+**        caller.)
+**   (4)  The size of the table being searched is known by ANALYZE.
+**
+** This block of code merely checks to see if a Bloom filter would be
+** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
+** WhereLoop.  The implementation of the Bloom filter comes further
+** down where the code for each WhereLoop is generated.
+*/
+static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
+  const WhereInfo *pWInfo
+){
+  int i;
+  LogEst nSearch;
+
+  assert( pWInfo->nLevel>=2 );
+  assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
+  nSearch = pWInfo->a[0].pWLoop->nOut;
+  for(i=1; i<pWInfo->nLevel; i++){
+    WhereLoop *pLoop = pWInfo->a[i].pWLoop;
+    const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ);
+    if( (pLoop->wsFlags & reqFlags)==reqFlags
+     /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
+     && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
+    ){
+      SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
+      Table *pTab = pItem->pTab;
+      pTab->tabFlags |= TF_StatsUsed;
+      if( nSearch > pTab->nRowLogEst
+       && (pTab->tabFlags & TF_HasStat1)!=0
+      ){
+        testcase( pItem->fg.jointype & JT_LEFT );
+        pLoop->wsFlags |= WHERE_BLOOMFILTER;
+        pLoop->wsFlags &= ~WHERE_IDX_ONLY;
+        WHERETRACE(0xffff, (
+           "-> use Bloom-filter on loop %c because there are ~%.1e "
+           "lookups into %s which has only ~%.1e rows\n",
+           pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
+           (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
+      }
+    }
+    nSearch += pLoop->nOut;
+  }
+}
+
 /*
 ** Generate the beginning of the loop used for WHERE clause processing.
 ** The return value is a pointer to an opaque structure that contains
@@ -153048,6 +157404,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   Expr *pWhere,           /* The WHERE clause */
   ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
   ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
+  Select *pLimit,         /* Use this LIMIT/OFFSET clause, if any */
   u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
   int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
                           ** If WHERE_USE_LIMIT, then the limit amount */
@@ -153082,13 +157439,6 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
-  sWLB.pOrderBy = pOrderBy;
-
-  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
-  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
-  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
-    wctrlFlags &= ~WHERE_WANT_DISTINCT;
-  }
 
   /* The number of tables in the FROM clause is limited by the number of
   ** bits in a Bitmask
@@ -153131,11 +157481,18 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   pWInfo->wctrlFlags = wctrlFlags;
   pWInfo->iLimit = iAuxArg;
   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+  pWInfo->pLimit = pLimit;
+#endif
   memset(&pWInfo->nOBSat, 0,
          offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
   memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
   assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
   pMaskSet = &pWInfo->sMaskSet;
+  pMaskSet->n = 0;
+  pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
+                         ** a valid cursor number, to avoid an initial
+                         ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
   sWLB.pWInfo = pWInfo;
   sWLB.pWC = &pWInfo->sWC;
   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
@@ -153148,7 +157505,6 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   /* Split the WHERE clause into separate subexpressions where each
   ** subexpression is separated by an AND operator.
   */
-  initMaskSet(pMaskSet);
   sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
   sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
 
@@ -153156,7 +157512,9 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   */
   if( nTabList==0 ){
     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
-    if( wctrlFlags & WHERE_WANT_DISTINCT ){
+    if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0
+     && OptimizationEnabled(db, SQLITE_DistinctOpt)
+    ){
       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
     }
     ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
@@ -153194,6 +157552,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
 
   /* Analyze all of the subexpressions. */
   sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
+  sqlite3WhereAddLimit(&pWInfo->sWC, pLimit);
   if( db->mallocFailed ) goto whereBeginError;
 
   /* Special case: WHERE terms that do not refer to any tables in the join
@@ -153207,7 +157566,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   **   FROM ... WHERE random()>0;           -- eval random() once per row
   **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall
   */
-  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
+  for(ii=0; ii<sWLB.pWC->nBase; ii++){
     WhereTerm *pT = &sWLB.pWC->a[ii];
     if( pT->wtFlags & TERM_VIRTUAL ) continue;
     if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
@@ -153217,7 +157576,12 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   }
 
   if( wctrlFlags & WHERE_WANT_DISTINCT ){
-    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
+    if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
+      /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
+      ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
+      wctrlFlags &= ~WHERE_WANT_DISTINCT;
+      pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
+    }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
       /* The DISTINCT marking is pointless.  Ignore it. */
       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
     }else if( pOrderBy==0 ){
@@ -153288,9 +157652,10 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
      pWInfo->revMask = ALLBITS;
   }
-  if( pParse->nErr || db->mallocFailed ){
+  if( pParse->nErr ){
     goto whereBeginError;
   }
+  assert( db->mallocFailed==0 );
 #ifdef WHERETRACE_ENABLED
   if( sqlite3WhereTrace ){
     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
@@ -153318,83 +157683,36 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   }
 #endif
 
-  /* Attempt to omit tables from the join that do not affect the result.
-  ** For a table to not affect the result, the following must be true:
-  **
-  **   1) The query must not be an aggregate.
-  **   2) The table must be the RHS of a LEFT JOIN.
-  **   3) Either the query must be DISTINCT, or else the ON or USING clause
-  **      must contain a constraint that limits the scan of the table to
-  **      at most a single row.
-  **   4) The table must not be referenced by any part of the query apart
-  **      from its own USING or ON clause.
-  **
-  ** For example, given:
-  **
-  **     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
-  **     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
-  **     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
-  **
-  ** then table t2 can be omitted from the following:
-  **
-  **     SELECT v1, v3 FROM t1
-  **       LEFT JOIN t2 ON (t1.ipk=t2.ipk)
-  **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
-  **
-  ** or from:
+  /* Attempt to omit tables from a join that do not affect the result.
+  ** See the comment on whereOmitNoopJoin() for further information.
   **
-  **     SELECT DISTINCT v1, v3 FROM t1
-  **       LEFT JOIN t2
-  **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
+  ** This query optimization is factored out into a separate "no-inline"
+  ** procedure to keep the sqlite3WhereBegin() procedure from becoming
+  ** too large.  If sqlite3WhereBegin() becomes too large, that prevents
+  ** some C-compiler optimizers from in-lining the
+  ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
+  ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
   */
   notReady = ~(Bitmask)0;
   if( pWInfo->nLevel>=2
-   && pResultSet!=0               /* guarantees condition (1) above */
+   && pResultSet!=0                         /* these two combine to guarantee */
+   && 0==(wctrlFlags & WHERE_AGG_DISTINCT)  /* condition (1) above */
    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
   ){
-    int i;
-    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
-    if( sWLB.pOrderBy ){
-      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
-    }
-    for(i=pWInfo->nLevel-1; i>=1; i--){
-      WhereTerm *pTerm, *pEnd;
-      SrcItem *pItem;
-      pLoop = pWInfo->a[i].pWLoop;
-      pItem = &pWInfo->pTabList->a[pLoop->iTab];
-      if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
-      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
-       && (pLoop->wsFlags & WHERE_ONEROW)==0
-      ){
-        continue;
-      }
-      if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
-      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
-      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
-        if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
-          if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
-           || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
-          ){
-            break;
-          }
-        }
-      }
-      if( pTerm<pEnd ) continue;
-      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
-      notReady &= ~pLoop->maskSelf;
-      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
-        if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
-          pTerm->wtFlags |= TERM_CODED;
-        }
-      }
-      if( i!=pWInfo->nLevel-1 ){
-        int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
-        memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
-      }
-      pWInfo->nLevel--;
-      nTabList--;
-    }
+    notReady = whereOmitNoopJoin(pWInfo, notReady);
+    nTabList = pWInfo->nLevel;
+    assert( nTabList>0 );
+  }
+
+  /* Check to see if there are any SEARCH loops that might benefit from
+  ** using a Bloom filter.
+  */
+  if( pWInfo->nLevel>=2
+   && OptimizationEnabled(db, SQLITE_BloomFilter)
+  ){
+    whereCheckIfBloomFilterIsUseful(pWInfo);
   }
+
 #if defined(WHERETRACE_ENABLED)
   if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
     sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
@@ -153455,7 +157773,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
     pTab = pTabItem->pTab;
     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
     pLoop = pLevel->pWLoop;
-    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
+    if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
       /* Do nothing */
     }else
 #ifndef SQLITE_OMIT_VIRTUALTABLE
@@ -153481,6 +157799,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
       if( pWInfo->eOnePass==ONEPASS_OFF
        && pTab->nCol<BMS
        && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
+       && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
       ){
         /* If we know that only a prefix of the record will be used,
         ** it is advantageous to reduce the "column count" field in
@@ -153580,15 +157899,20 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   for(ii=0; ii<nTabList; ii++){
     int addrExplain;
     int wsFlags;
+    if( pParse->nErr ) goto whereBeginError;
     pLevel = &pWInfo->a[ii];
     wsFlags = pLevel->pWLoop->wsFlags;
+    if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
+      if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
-    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
-      constructAutomaticIndex(pParse, &pWInfo->sWC,
-                &pTabList->a[pLevel->iFrom], notReady, pLevel);
+        constructAutomaticIndex(pParse, &pWInfo->sWC,
+                  &pTabList->a[pLevel->iFrom], notReady, pLevel);
+#endif
+      }else{
+        sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
+      }
       if( db->mallocFailed ) goto whereBeginError;
     }
-#endif
     addrExplain = sqlite3WhereExplainOneScan(
         pParse, pTabList, pLevel, wctrlFlags
     );
@@ -153608,6 +157932,8 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   /* Jump here if malloc fails */
 whereBeginError:
   if( pWInfo ){
+    testcase( pWInfo->pExprMods!=0 );
+    whereUndoExprMods(pWInfo);
     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
     whereInfoFree(db, pWInfo);
   }
@@ -153634,6 +157960,26 @@ whereBeginError:
   }
 #endif
 
+#ifdef SQLITE_DEBUG
+/*
+** Return true if cursor iCur is opened by instruction k of the
+** bytecode.  Used inside of assert() only.
+*/
+static int cursorIsOpen(Vdbe *v, int iCur, int k){
+  while( k>=0 ){
+    VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
+    if( pOp->p1!=iCur ) continue;
+    if( pOp->opcode==OP_Close ) return 0;
+    if( pOp->opcode==OP_OpenRead ) return 1;
+    if( pOp->opcode==OP_OpenWrite ) return 1;
+    if( pOp->opcode==OP_OpenDup ) return 1;
+    if( pOp->opcode==OP_OpenAutoindex ) return 1;
+    if( pOp->opcode==OP_OpenEphemeral ) return 1;
+  }
+  return 0;
+}
+#endif /* SQLITE_DEBUG */
+
 /*
 ** Generate the end of the WHERE loop.  See comments on
 ** sqlite3WhereBegin() for additional information.
@@ -153699,11 +158045,13 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
     }else{
       sqlite3VdbeResolveLabel(v, pLevel->addrCont);
     }
-    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
+    if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
       struct InLoop *pIn;
       int j;
       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
+        assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
+                 || pParse->db->mallocFailed );
         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
         if( pIn->eEndLoopOp!=OP_Noop ){
           if( pIn->nPrefix ){
@@ -153728,6 +158076,11 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
                   sqlite3VdbeCurrentAddr(v)+2,
                   pIn->iBase, pIn->nPrefix);
               VdbeCoverage(v);
+              /* Retarget the OP_IsNull against the left operand of IN so
+              ** it jumps past the OP_IfNoHope.  This is because the
+              ** OP_IsNull also bypasses the OP_Affinity opcode that is
+              ** required by OP_IfNoHope. */
+              sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
             }
           }
           sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
@@ -153761,8 +158114,14 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
       }
       if( (ws & WHERE_INDEXED)
-       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
+       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
       ){
+        if( ws & WHERE_MULTI_OR ){
+          Index *pIx = pLevel->u.pCoveringIdx;
+          int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
+          sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
+          sqlite3VdbeSetP4KeyInfo(pParse, pIx);
+        }
         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
       }
       if( pLevel->op==OP_Return ){
@@ -153809,7 +158168,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
     ** created for the ONEPASS optimization.
     */
     if( (pTab->tabFlags & TF_Ephemeral)==0
-     && pTab->pSelect==0
+     && !IsView(pTab)
      && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
     ){
       int ws = pLoop->wsFlags;
@@ -153839,7 +158198,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
       pIdx = pLoop->u.btree.pIndex;
     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
-      pIdx = pLevel->u.pCovidx;
+      pIdx = pLevel->u.pCoveringIdx;
     }
     if( pIdx
      && !db->mallocFailed
@@ -153862,7 +158221,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
 #endif
       pOp = sqlite3VdbeGetOp(v, k);
       pLastOp = pOp + (last - k);
-      assert( pOp<pLastOp || (pParse->nErr>0 && pOp==pLastOp) );
+      assert( pOp<=pLastOp );
       do{
         if( pOp->p1!=pLevel->iTabCur ){
           /* no-op */
@@ -153873,6 +158232,11 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
         ){
           int x = pOp->p2;
           assert( pIdx->pTable==pTab );
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+          if( pOp->opcode==OP_Offset ){
+            /* Do not need to translate the column number */
+          }else
+#endif
           if( !HasRowid(pTab) ){
             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
             x = pPk->aiColumn[x];
@@ -153886,9 +158250,22 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
             pOp->p2 = x;
             pOp->p1 = pLevel->iIdxCur;
             OpcodeRewriteTrace(db, k, pOp);
+          }else{
+            /* Unable to translate the table reference into an index
+            ** reference.  Verify that this is harmless - that the
+            ** table being referenced really is open.
+            */
+#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
+            assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
+                 || cursorIsOpen(v,pOp->p1,k)
+                 || pOp->opcode==OP_Offset
+            );
+#else
+            assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
+                 || cursorIsOpen(v,pOp->p1,k)
+            );
+#endif
           }
-          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
-              || pWInfo->eOnePass );
         }else if( pOp->opcode==OP_Rowid ){
           pOp->p1 = pLevel->iIdxCur;
           pOp->opcode = OP_IdxRowid;
@@ -153907,16 +158284,9 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
     }
   }
 
-  /* Undo all Expr node modifications */
-  while( pWInfo->pExprMods ){
-    WhereExprMod *p = pWInfo->pExprMods;
-    pWInfo->pExprMods = p->pNext;
-    memcpy(p->pExpr, &p->orig, sizeof(p->orig));
-    sqlite3DbFree(db, p);
-  }
-
   /* Final cleanup
   */
+  if( pWInfo->pExprMods ) whereUndoExprMods(pWInfo);
   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   whereInfoFree(db, pWInfo);
   return;
@@ -154507,7 +158877,7 @@ static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
 /* Window functions that use all window interfaces: xStep, xFinal,
 ** xValue, and xInverse */
 #define WINDOWFUNCALL(name,nArg,extra) {                                   \
-  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
+  nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,  \
   name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc,               \
   name ## InvFunc, name ## Name, {0}                                       \
 }
@@ -154515,7 +158885,7 @@ static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
 /* Window functions that are implemented using bytecode and thus have
 ** no-op routines for their methods */
 #define WINDOWFUNCNOOP(name,nArg,extra) {                                  \
-  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
+  nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,  \
   noopStepFunc, noopValueFunc, noopValueFunc,                              \
   noopStepFunc, name ## Name, {0}                                          \
 }
@@ -154524,7 +158894,7 @@ static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
 ** same routine for xFinalize and xValue and which never call
 ** xInverse. */
 #define WINDOWFUNCX(name,nArg,extra) {                                     \
-  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
+  nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,  \
   name ## StepFunc, name ## ValueFunc, name ## ValueFunc,                  \
   noopStepFunc, name ## Name, {0}                                          \
 }
@@ -154714,6 +159084,7 @@ static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
     case TK_AGG_FUNCTION:
     case TK_COLUMN: {
       int iCol = -1;
+      if( pParse->db->mallocFailed ) return WRC_Abort;
       if( p->pSub ){
         int i;
         for(i=0; i<p->pSub->nExpr; i++){
@@ -154823,14 +159194,17 @@ static ExprList *exprListAppendList(
     int i;
     int nInit = pList ? pList->nExpr : 0;
     for(i=0; i<pAppend->nExpr; i++){
-      Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
+      sqlite3 *db = pParse->db;
+      Expr *pDup = sqlite3ExprDup(db, pAppend->a[i].pExpr, 0);
       assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
-      if( bIntToNull && pDup ){
+      if( db->mallocFailed ){
+        sqlite3ExprDelete(db, pDup);
+        break;
+      }
+      if( bIntToNull ){
         int iDummy;
         Expr *pSub;
-        for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){
-          assert( pSub );
-        }
+        pSub = sqlite3ExprSkipCollateAndLikely(pDup);
         if( sqlite3ExprIsInteger(pSub, &iDummy) ){
           pSub->op = TK_NULL;
           pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
@@ -154861,6 +159235,15 @@ static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
   return WRC_Continue;
 }
 
+static int disallowAggregatesInOrderByCb(Walker *pWalker, Expr *pExpr){
+  if( pExpr->op==TK_AGG_FUNCTION && pExpr->pAggInfo==0 ){
+    assert( !ExprHasProperty(pExpr, EP_IntValue) );
+     sqlite3ErrorMsg(pWalker->pParse,
+         "misuse of aggregate: %s()", pExpr->u.zToken);
+  }
+  return WRC_Continue;
+}
+
 /*
 ** If the SELECT statement passed as the second argument does not invoke
 ** any SQL window functions, this function is a no-op. Otherwise, it
@@ -154870,7 +159253,11 @@ static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
 */
 SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
   int rc = SQLITE_OK;
-  if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
+  if( p->pWin
+   && p->pPrior==0
+   && ALWAYS((p->selFlags & SF_WinRewrite)==0)
+   && ALWAYS(!IN_RENAME_OBJECT)
+  ){
     Vdbe *v = sqlite3GetVdbe(pParse);
     sqlite3 *db = pParse->db;
     Select *pSub = 0;             /* The subquery */
@@ -154894,6 +159281,11 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
     }
     sqlite3AggInfoPersistWalkerInit(&w, pParse);
     sqlite3WalkSelect(&w, p);
+    if( (p->selFlags & SF_Aggregate)==0 ){
+      w.xExprCallback = disallowAggregatesInOrderByCb;
+      w.xSelectCallback = 0;
+      sqlite3WalkExprList(&w, p->pOrderBy);
+    }
 
     p->pSrc = 0;
     p->pWhere = 0;
@@ -154938,7 +159330,10 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
     ** window function - one for the accumulator, another for interim
     ** results.  */
     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
-      ExprList *pArgs = pWin->pOwner->x.pList;
+      ExprList *pArgs;
+      assert( ExprUseXList(pWin->pOwner) );
+      assert( pWin->pFunc!=0 );
+      pArgs = pWin->pOwner->x.pList;
       if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
         selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
         pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
@@ -154975,11 +159370,14 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
        ("New window-function subquery in FROM clause of (%u/%p)\n",
        p->selId, p));
     p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
+    assert( pSub!=0 || p->pSrc==0 ); /* Due to db->mallocFailed test inside
+                                     ** of sqlite3DbMallocRawNN() called from
+                                     ** sqlite3SrcListAppend() */
     if( p->pSrc ){
       Table *pTab2;
       p->pSrc->a[0].pSelect = pSub;
       sqlite3SrcListAssignCursors(pParse, p->pSrc);
-      pSub->selFlags |= SF_Expanded;
+      pSub->selFlags |= SF_Expanded|SF_OrderByReqd;
       pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
       pSub->selFlags |= (selFlags & SF_Aggregate);
       if( pTab2==0 ){
@@ -155002,15 +159400,14 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
       sqlite3SelectDelete(db, pSub);
     }
     if( db->mallocFailed ) rc = SQLITE_NOMEM;
-    sqlite3DbFree(db, pTab);
-  }
 
-  if( rc ){
-    if( pParse->nErr==0 ){
-      assert( pParse->db->mallocFailed );
-      sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
-    }
+    /* Defer deleting the temporary table pTab because if an error occurred,
+    ** there could still be references to that table embedded in the
+    ** result-set or ORDER BY clause of the SELECT statement p.  */
+    sqlite3ParserAddCleanup(pParse, sqlite3DbFree, pTab);
   }
+
+  assert( rc==SQLITE_OK || pParse->nErr!=0 );
   return rc;
 }
 
@@ -155251,7 +159648,12 @@ SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){
 ** different, or 2 if it cannot be determined if the objects are identical
 ** or not. Identical window objects can be processed in a single scan.
 */
-SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
+SQLITE_PRIVATE int sqlite3WindowCompare(
+  const Parse *pParse,
+  const Window *p1,
+  const Window *p2,
+  int bFilter
+){
   int res;
   if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
   if( p1->eFrmType!=p2->eFrmType ) return 1;
@@ -155323,8 +159725,11 @@ SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
       **   regApp+1: integer value used to ensure keys are unique
       **   regApp+2: output of MakeRecord
       */
-      ExprList *pList = pWin->pOwner->x.pList;
-      KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
+      ExprList *pList;
+      KeyInfo *pKeyInfo;
+      assert( ExprUseXList(pWin->pOwner) );
+      pList = pWin->pOwner->x.pList;
+      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
       pWin->csrApp = pParse->nTab++;
       pWin->regApp = pParse->nMem+1;
       pParse->nMem += 3;
@@ -155412,7 +159817,9 @@ static void windowCheckValue(Parse *pParse, int reg, int eCond){
 ** with the object passed as the only argument to this function.
 */
 static int windowArgCount(Window *pWin){
-  ExprList *pList = pWin->pOwner->x.pList;
+  const ExprList *pList;
+  assert( ExprUseXList(pWin->pOwner) );
+  pList = pWin->pOwner->x.pList;
   return (pList ? pList->nExpr : 0);
 }
 
@@ -155490,6 +159897,7 @@ struct WindowCodeArg {
   int regGosub;              /* Register used with OP_Gosub(addrGosub) */
   int regArg;                /* First in array of accumulator registers */
   int eDelete;               /* See above */
+  int regRowid;
 
   WindowCsrAndReg start;
   WindowCsrAndReg current;
@@ -155596,6 +160004,7 @@ static void windowAggStep(
       int addrIf = 0;
       if( pWin->pFilter ){
         int regTmp;
+        assert( ExprUseXList(pWin->pOwner) );
         assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
         assert( pWin->bExprArgs || nArg  ||pWin->pOwner->x.pList==0 );
         regTmp = sqlite3GetTempReg(pParse);
@@ -155606,16 +160015,17 @@ static void windowAggStep(
       }
 
       if( pWin->bExprArgs ){
-        int iStart = sqlite3VdbeCurrentAddr(v);
-        VdbeOp *pOp, *pEnd;
+        int iOp = sqlite3VdbeCurrentAddr(v);
+        int iEnd;
 
+        assert( ExprUseXList(pWin->pOwner) );
         nArg = pWin->pOwner->x.pList->nExpr;
         regArg = sqlite3GetTempRange(pParse, nArg);
         sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
 
-        pEnd = sqlite3VdbeGetOp(v, -1);
-        for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){
-          if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
+        for(iEnd=sqlite3VdbeCurrentAddr(v); iOp<iEnd; iOp++){
+          VdbeOp *pOp = sqlite3VdbeGetOp(v, iOp);
+          if( pOp->opcode==OP_Column && pOp->p1==pMWin->iEphCsr ){
             pOp->p1 = csr;
           }
         }
@@ -155623,6 +160033,7 @@ static void windowAggStep(
       if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
         CollSeq *pColl;
         assert( nArg>0 );
+        assert( ExprUseXList(pWin->pOwner) );
         pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
         sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
       }
@@ -155808,6 +160219,7 @@ static void windowReturnOneRow(WindowCodeArg *p){
 
     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
       FuncDef *pFunc = pWin->pFunc;
+      assert( ExprUseXList(pWin->pOwner) );
       if( pFunc->zName==nth_valueName
        || pFunc->zName==first_valueName
       ){
@@ -155973,7 +160385,7 @@ static void windowIfNewPeer(
 **   if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
 **
 ** A special type of arithmetic is used such that if csr1.peerVal is not
-** a numeric type (real or integer), then the result of the addition addition
+** a numeric type (real or integer), then the result of the addition
 ** or subtraction is a a copy of csr1.peerVal.
 */
 static void windowCodeRangeTest(
@@ -155992,8 +160404,13 @@ static void windowCodeRangeTest(
   int regString = ++pParse->nMem;           /* Reg. for constant value '' */
   int arith = OP_Add;                       /* OP_Add or OP_Subtract */
   int addrGe;                               /* Jump destination */
+  int addrDone = sqlite3VdbeMakeLabel(pParse);   /* Address past OP_Ge */
   CollSeq *pColl;
 
+  /* Read the peer-value from each cursor into a register */
+  windowReadPeerValues(p, csr1, reg1);
+  windowReadPeerValues(p, csr2, reg2);
+
   assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
   assert( pOrderBy && pOrderBy->nExpr==1 );
   if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
@@ -156005,34 +160422,11 @@ static void windowCodeRangeTest(
     arith = OP_Subtract;
   }
 
-  /* Read the peer-value from each cursor into a register */
-  windowReadPeerValues(p, csr1, reg1);
-  windowReadPeerValues(p, csr2, reg2);
-
   VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
       reg1, (arith==OP_Add ? "+" : "-"), regVal,
       ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
   ));
 
-  /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
-  ** This block adds (or subtracts for DESC) the numeric value in regVal
-  ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
-  ** then leave reg1 as it is. In pseudo-code, this is implemented as:
-  **
-  **   if( reg1>='' ) goto addrGe;
-  **   reg1 = reg1 +/- regVal
-  **   addrGe:
-  **
-  ** Since all strings and blobs are greater-than-or-equal-to an empty string,
-  ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
-  ** then the arithmetic is performed, but since adding or subtracting from
-  ** NULL is always NULL anyway, this case is handled as required too.  */
-  sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
-  addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
-  VdbeCoverage(v);
-  sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
-  sqlite3VdbeJumpHere(v, addrGe);
-
   /* If the BIGNULL flag is set for the ORDER BY, then it is required to
   ** consider NULL values to be larger than all other values, instead of
   ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
@@ -156069,16 +160463,38 @@ static void windowCodeRangeTest(
         break;
       default: assert( op==OP_Lt ); /* no-op */ break;
     }
-    sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
+    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
 
     /* This block runs if reg1 is not NULL, but reg2 is. */
     sqlite3VdbeJumpHere(v, addr);
     sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
     if( op==OP_Gt || op==OP_Ge ){
-      sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);
+      sqlite3VdbeChangeP2(v, -1, addrDone);
     }
   }
 
+  /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
+  ** This block adds (or subtracts for DESC) the numeric value in regVal
+  ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
+  ** then leave reg1 as it is. In pseudo-code, this is implemented as:
+  **
+  **   if( reg1>='' ) goto addrGe;
+  **   reg1 = reg1 +/- regVal
+  **   addrGe:
+  **
+  ** Since all strings and blobs are greater-than-or-equal-to an empty string,
+  ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
+  ** then the arithmetic is performed, but since adding or subtracting from
+  ** NULL is always NULL anyway, this case is handled as required too.  */
+  sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
+  addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
+  VdbeCoverage(v);
+  if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
+    sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
+  }
+  sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
+  sqlite3VdbeJumpHere(v, addrGe);
+
   /* Compare registers reg2 and reg1, taking the jump if required. Note that
   ** control skips over this test if the BIGNULL flag is set and either
   ** reg1 or reg2 contain a NULL value.  */
@@ -156086,6 +160502,7 @@ static void windowCodeRangeTest(
   pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
   sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ);
   sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
+  sqlite3VdbeResolveLabel(v, addrDone);
 
   assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
   testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
@@ -156161,16 +160578,24 @@ static int windowCodeOp(
   /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
   ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
   ** start cursor does not advance past the end cursor within the
-  ** temporary table. It otherwise might, if (a>b).  */
+  ** temporary table. It otherwise might, if (a>b). Also ensure that,
+  ** if the input cursor is still finding new rows, that the end
+  ** cursor does not go past it to EOF. */
   if( pMWin->eStart==pMWin->eEnd && regCountdown
-   && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
+   && pMWin->eFrmType==TK_RANGE
   ){
     int regRowid1 = sqlite3GetTempReg(pParse);
     int regRowid2 = sqlite3GetTempReg(pParse);
-    sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
-    sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
-    sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
-    VdbeCoverage(v);
+    if( op==WINDOW_AGGINVERSE ){
+      sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
+      sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
+      sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
+      VdbeCoverage(v);
+    }else if( p->regRowid ){
+      sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid1);
+      sqlite3VdbeAddOp3(v, OP_Ge, p->regRowid, lblDone, regRowid1);
+      VdbeCoverageNeverNull(v);
+    }
     sqlite3ReleaseTempReg(pParse, regRowid1);
     sqlite3ReleaseTempReg(pParse, regRowid2);
     assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
@@ -156667,7 +161092,6 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
   int addrEmpty;                  /* Address of OP_Rewind in flush: */
   int regNew;                     /* Array of registers holding new input row */
   int regRecord;                  /* regNew array in record form */
-  int regRowid;                   /* Rowid for regRecord in eph table */
   int regNewPeer = 0;             /* Peer values for new row (part of regNew) */
   int regPeer = 0;                /* Peer values for current row */
   int regFlushPart = 0;           /* Register for "Gosub flush_partition" */
@@ -156739,7 +161163,7 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
   regNew = pParse->nMem+1;
   pParse->nMem += nInput;
   regRecord = ++pParse->nMem;
-  regRowid = ++pParse->nMem;
+  s.regRowid = ++pParse->nMem;
 
   /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
   ** clause, allocate registers to store the results of evaluating each
@@ -156795,9 +161219,9 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
   }
 
   /* Insert the new row into the ephemeral table */
-  sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
-  sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
-  addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
+  sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, s.regRowid);
+  sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, s.regRowid);
+  addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, s.regRowid);
   VdbeCoverageNeverNull(v);
 
   /* This block is run for the first row of each partition */
@@ -156915,6 +161339,7 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
     sqlite3VdbeJumpHere(v, addrGosubFlush);
   }
 
+  s.regRowid = 0;
   addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
   VdbeCoverage(v);
   if( pMWin->eEnd==TK_PRECEDING ){
@@ -157130,10 +161555,7 @@ static void updateDeleteLimitError(
   }
 
 
-  /* 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
-  ** that created the expression.
-  */
+  /* Construct a new Expr object from a single token */
   static Expr *tokenExpr(Parse *pParse, int op, Token t){
     Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
     if( p ){
@@ -157144,15 +161566,16 @@ static void updateDeleteLimitError(
       ExprClearVVAProperties(p);
       p->iAgg = -1;
       p->pLeft = p->pRight = 0;
-      p->x.pList = 0;
       p->pAggInfo = 0;
-      p->y.pTab = 0;
+      memset(&p->x, 0, sizeof(p->x));
+      memset(&p->y, 0, sizeof(p->y));
       p->op2 = 0;
       p->iTable = 0;
       p->iColumn = 0;
       p->u.zToken = (char*)&p[1];
       memcpy(p->u.zToken, t.z, t.n);
       p->u.zToken[t.n] = 0;
+      p->w.iOfst = (int)(t.z - pParse->zTail);
       if( sqlite3Isquote(p->u.zToken[0]) ){
         sqlite3DequoteExpr(p);
       }
@@ -157232,8 +161655,8 @@ static void updateDeleteLimitError(
 #define TK_LP                             22
 #define TK_RP                             23
 #define TK_AS                             24
-#define TK_WITHOUT                        25
-#define TK_COMMA                          26
+#define TK_COMMA                          25
+#define TK_WITHOUT                        26
 #define TK_ABORT                          27
 #define TK_ACTION                         28
 #define TK_AFTER                          29
@@ -157319,77 +161742,79 @@ static void updateDeleteLimitError(
 #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
+#define TK_PTR                            112
+#define TK_COLLATE                        113
+#define TK_BITNOT                         114
+#define TK_ON                             115
+#define TK_INDEXED                        116
+#define TK_STRING                         117
+#define TK_JOIN_KW                        118
+#define TK_CONSTRAINT                     119
+#define TK_DEFAULT                        120
+#define TK_NULL                           121
+#define TK_PRIMARY                        122
+#define TK_UNIQUE                         123
+#define TK_CHECK                          124
+#define TK_REFERENCES                     125
+#define TK_AUTOINCR                       126
+#define TK_INSERT                         127
+#define TK_DELETE                         128
+#define TK_UPDATE                         129
+#define TK_SET                            130
+#define TK_DEFERRABLE                     131
+#define TK_FOREIGN                        132
+#define TK_DROP                           133
+#define TK_UNION                          134
+#define TK_ALL                            135
+#define TK_EXCEPT                         136
+#define TK_INTERSECT                      137
+#define TK_SELECT                         138
+#define TK_VALUES                         139
+#define TK_DISTINCT                       140
+#define TK_DOT                            141
+#define TK_FROM                           142
+#define TK_JOIN                           143
+#define TK_USING                          144
+#define TK_ORDER                          145
+#define TK_GROUP                          146
+#define TK_HAVING                         147
+#define TK_LIMIT                          148
+#define TK_WHERE                          149
+#define TK_RETURNING                      150
+#define TK_INTO                           151
+#define TK_NOTHING                        152
+#define TK_FLOAT                          153
+#define TK_BLOB                           154
+#define TK_INTEGER                        155
+#define TK_VARIABLE                       156
+#define TK_CASE                           157
+#define TK_WHEN                           158
+#define TK_THEN                           159
+#define TK_ELSE                           160
+#define TK_INDEX                          161
+#define TK_ALTER                          162
+#define TK_ADD                            163
+#define TK_WINDOW                         164
+#define TK_OVER                           165
+#define TK_FILTER                         166
+#define TK_COLUMN                         167
+#define TK_AGG_FUNCTION                   168
+#define TK_AGG_COLUMN                     169
+#define TK_TRUEFALSE                      170
+#define TK_ISNOT                          171
+#define TK_FUNCTION                       172
+#define TK_UMINUS                         173
+#define TK_UPLUS                          174
+#define TK_TRUTH                          175
+#define TK_REGISTER                       176
+#define TK_VECTOR                         177
+#define TK_SELECT_COLUMN                  178
+#define TK_IF_NULL_ROW                    179
+#define TK_ASTERISK                       180
+#define TK_SPAN                           181
+#define TK_ERROR                          182
+#define TK_SPACE                          183
+#define TK_ILLEGAL                        184
 #endif
 /**************** End token definitions ***************************************/
 
@@ -157449,29 +161874,30 @@ static void updateDeleteLimitError(
 #endif
 /************* Begin control #defines *****************************************/
 #define YYCODETYPE unsigned short int
-#define YYNOCODE 316
+#define YYNOCODE 319
 #define YYACTIONTYPE unsigned short int
 #define YYWILDCARD 101
 #define sqlite3ParserTOKENTYPE Token
 typedef union {
   int yyinit;
   sqlite3ParserTOKENTYPE yy0;
-  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;
+  TriggerStep* yy33;
+  Window* yy41;
+  Select* yy47;
+  SrcList* yy131;
+  struct TrigEvent yy180;
+  struct {int value; int mask;} yy231;
+  IdList* yy254;
+  u32 yy285;
+  ExprList* yy322;
+  Cte* yy385;
+  int yy394;
+  Upsert* yy444;
+  u8 yy516;
+  With* yy521;
+  const char* yy522;
+  Expr* yy528;
+  struct FrameBound yy595;
 } YYMINORTYPE;
 #ifndef YYSTACKDEPTH
 #define YYSTACKDEPTH 100
@@ -157487,18 +161913,18 @@ typedef union {
 #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
 #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
 #define YYFALLBACK 1
-#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
+#define YYNSTATE             574
+#define YYNRULE              402
+#define YYNRULE_WITH_ACTION  340
+#define YYNTOKEN             185
+#define YY_MAX_SHIFT         573
+#define YY_MIN_SHIFTREDUCE   831
+#define YY_MAX_SHIFTREDUCE   1232
+#define YY_ERROR_ACTION      1233
+#define YY_ACCEPT_ACTION     1234
+#define YY_NO_ACTION         1235
+#define YY_MIN_REDUCE        1236
+#define YY_MAX_REDUCE        1637
 /************* End control #defines *******************************************/
 #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
 
@@ -157565,600 +161991,612 @@ typedef union {
 **  yy_default[]       Default action for each state.
 **
 *********** Begin parsing tables **********************************************/
-#define YY_ACTTAB_COUNT (2020)
+#define YY_ACTTAB_COUNT (2070)
 static const YYACTIONTYPE yy_action[] = {
- /*     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,
+ /*     0 */   566, 1307,  566, 1286,  201,  201,  566,  116,  112,  222,
+ /*    10 */   566, 1307,  377,  566,  116,  112,  222,  397,  408,  409,
+ /*    20 */  1260,  378, 1269,   41,   41,   41,   41, 1412, 1517,   71,
+ /*    30 */    71,  967, 1258,   41,   41,  491,   71,   71,  272,  968,
+ /*    40 */   298,  476,  298,  123,  124,  114, 1210, 1210, 1044, 1047,
+ /*    50 */  1036, 1036,  121,  121,  122,  122,  122,  122,  543,  409,
+ /*    60 */  1234,    1,    1,  573,    2, 1238,  548,  116,  112,  222,
+ /*    70 */   309,  480,  142,  548, 1272,  524,  116,  112,  222, 1320,
+ /*    80 */   417,  523,  547,  123,  124,  114, 1210, 1210, 1044, 1047,
+ /*    90 */  1036, 1036,  121,  121,  122,  122,  122,  122,  424,  116,
+ /*   100 */   112,  222,  120,  120,  120,  120,  119,  119,  118,  118,
+ /*   110 */   118,  117,  113,  444,  277,  277,  277,  277,  560,  560,
+ /*   120 */   560, 1558,  376, 1560, 1186,  375, 1157,  563, 1157,  563,
+ /*   130 */   409, 1558,  537,  252,  219, 1553,   99,  141,  449,    6,
+ /*   140 */   365,  233,  120,  120,  120,  120,  119,  119,  118,  118,
+ /*   150 */   118,  117,  113,  444,  123,  124,  114, 1210, 1210, 1044,
+ /*   160 */  1047, 1036, 1036,  121,  121,  122,  122,  122,  122,  138,
+ /*   170 */   289, 1186, 1546,  448,  118,  118,  118,  117,  113,  444,
+ /*   180 */   125, 1186, 1187, 1188,  144,  465,  334,  566,  150,  127,
+ /*   190 */   444,  122,  122,  122,  122,  115,  120,  120,  120,  120,
+ /*   200 */   119,  119,  118,  118,  118,  117,  113,  444,  454,  419,
+ /*   210 */    13,   13,  215,  120,  120,  120,  120,  119,  119,  118,
+ /*   220 */   118,  118,  117,  113,  444,  422,  308,  557, 1186, 1187,
+ /*   230 */  1188,  441,  440,  409, 1271,  122,  122,  122,  122,  120,
+ /*   240 */   120,  120,  120,  119,  119,  118,  118,  118,  117,  113,
+ /*   250 */   444, 1543,   98, 1033, 1033, 1045, 1048,  123,  124,  114,
+ /*   260 */  1210, 1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,
+ /*   270 */   122,  122,  566,  406,  405, 1186,  566,  409, 1217,  319,
+ /*   280 */  1217,   80,   81,  120,  120,  120,  120,  119,  119,  118,
+ /*   290 */   118,  118,  117,  113,  444,   70,   70, 1186, 1604,   71,
+ /*   300 */    71,  123,  124,  114, 1210, 1210, 1044, 1047, 1036, 1036,
+ /*   310 */   121,  121,  122,  122,  122,  122,  120,  120,  120,  120,
+ /*   320 */   119,  119,  118,  118,  118,  117,  113,  444, 1037,  210,
+ /*   330 */  1186,  365, 1186, 1187, 1188,  245,  548,  399,  504,  501,
+ /*   340 */   500,  108,  558,  138,    4,  516,  933,  433,  499,  217,
+ /*   350 */   514,  522,  352,  879, 1186, 1187, 1188,  383,  561,  566,
+ /*   360 */   120,  120,  120,  120,  119,  119,  118,  118,  118,  117,
+ /*   370 */   113,  444,  277,  277,   16,   16, 1598,  441,  440,  153,
+ /*   380 */   409,  445,   13,   13, 1279,  563, 1214, 1186, 1187, 1188,
+ /*   390 */  1003, 1216,  264,  555, 1574,  186,  566,  427,  138, 1215,
+ /*   400 */   308,  557,  472,  138,  123,  124,  114, 1210, 1210, 1044,
+ /*   410 */  1047, 1036, 1036,  121,  121,  122,  122,  122,  122,   55,
+ /*   420 */    55,  413, 1023,  507, 1217, 1186, 1217,  474,  106,  106,
+ /*   430 */  1312, 1312, 1186,  171,  566,  384,  107,  380,  445,  568,
+ /*   440 */   567,  430, 1543, 1013,  332,  549,  565,  263,  280,  360,
+ /*   450 */   510,  355,  509,  250,  491,  308,  557,   71,   71,  351,
+ /*   460 */   308,  557,  374,  120,  120,  120,  120,  119,  119,  118,
+ /*   470 */   118,  118,  117,  113,  444, 1013, 1013, 1015, 1016,   27,
+ /*   480 */   277,  277, 1186, 1187, 1188, 1152,  566,  528,  409, 1186,
+ /*   490 */  1187, 1188,  348,  563,  548, 1260,  533,  517, 1152, 1516,
+ /*   500 */   317, 1152,  285,  550,  485,  569,  566,  569,  482,   51,
+ /*   510 */    51,  207,  123,  124,  114, 1210, 1210, 1044, 1047, 1036,
+ /*   520 */  1036,  121,  121,  122,  122,  122,  122,  171, 1412,   13,
+ /*   530 */    13,  409,  277,  277, 1186,  505,  119,  119,  118,  118,
+ /*   540 */   118,  117,  113,  444,  429,  563,  518,  220,  515, 1552,
+ /*   550 */   365,  546, 1186,    6,  532,  123,  124,  114, 1210, 1210,
+ /*   560 */  1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,  122,
+ /*   570 */   145,  120,  120,  120,  120,  119,  119,  118,  118,  118,
+ /*   580 */   117,  113,  444,  245,  566,  474,  504,  501,  500,  566,
+ /*   590 */  1481, 1186, 1187, 1188, 1310, 1310,  499, 1186,  149,  425,
+ /*   600 */  1186,  480,  409,  274,  365,  952,  872,   56,   56, 1186,
+ /*   610 */  1187, 1188,   71,   71,  120,  120,  120,  120,  119,  119,
+ /*   620 */   118,  118,  118,  117,  113,  444,  123,  124,  114, 1210,
+ /*   630 */  1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,
+ /*   640 */   122,  409,  541, 1552,   83,  865,   98,    6,  928,  529,
+ /*   650 */   848,  543,  151,  927, 1186, 1187, 1188, 1186, 1187, 1188,
+ /*   660 */   290, 1543,  187, 1633,  395,  123,  124,  114, 1210, 1210,
+ /*   670 */  1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,  122,
+ /*   680 */   566,  954,  566,  453,  953,  120,  120,  120,  120,  119,
+ /*   690 */   119,  118,  118,  118,  117,  113,  444, 1152,  221, 1186,
+ /*   700 */   331,  453,  452,   13,   13,   13,   13, 1003,  365,  463,
+ /*   710 */  1152,  193,  409, 1152,  382, 1543, 1170,   32,  297,  474,
+ /*   720 */   195, 1527,    5,  952,  120,  120,  120,  120,  119,  119,
+ /*   730 */   118,  118,  118,  117,  113,  444,  123,  124,  114, 1210,
+ /*   740 */  1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,
+ /*   750 */   122,  409, 1067,  419, 1186, 1024, 1186, 1187, 1188, 1186,
+ /*   760 */   419,  332,  460,  320,  544, 1545,  442,  442,  442,  566,
+ /*   770 */     3,  117,  113,  444,  453,  123,  124,  114, 1210, 1210,
+ /*   780 */  1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,  122,
+ /*   790 */  1473,  566,   15,   15,  293,  120,  120,  120,  120,  119,
+ /*   800 */   119,  118,  118,  118,  117,  113,  444, 1186,  566, 1486,
+ /*   810 */  1412, 1186, 1187, 1188,   13,   13, 1186, 1187, 1188, 1544,
+ /*   820 */   271,  271,  409,  286,  308,  557, 1008, 1486, 1488,  196,
+ /*   830 */   288,   71,   71,  563,  120,  120,  120,  120,  119,  119,
+ /*   840 */   118,  118,  118,  117,  113,  444,  123,  124,  114, 1210,
+ /*   850 */  1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,
+ /*   860 */   122,  409,  201, 1087, 1186, 1187, 1188, 1324,  304, 1529,
+ /*   870 */   388,  278,  278,  450,  564,  402,  922,  922,  566,  563,
+ /*   880 */   566,  426,  491,  480,  563,  123,  124,  114, 1210, 1210,
+ /*   890 */  1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,  122,
+ /*   900 */  1486,   71,   71,   13,   13,  120,  120,  120,  120,  119,
+ /*   910 */   119,  118,  118,  118,  117,  113,  444,  566,  545,  566,
+ /*   920 */  1577,  573,    2, 1238, 1092, 1092,  488, 1480,  309, 1525,
+ /*   930 */   142,  324,  409,  836,  837,  838,  312, 1320,  305,  363,
+ /*   940 */    43,   43,   57,   57,  120,  120,  120,  120,  119,  119,
+ /*   950 */   118,  118,  118,  117,  113,  444,  123,  124,  114, 1210,
+ /*   960 */  1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,
+ /*   970 */   122,   12,  277,  277,  566, 1152,  409,  572,  428, 1238,
+ /*   980 */   465,  334,  296,  474,  309,  563,  142,  249, 1152,  308,
+ /*   990 */   557, 1152,  321, 1320,  323,  491,  455,   71,   71,  233,
+ /*  1000 */   283,  101,  114, 1210, 1210, 1044, 1047, 1036, 1036,  121,
+ /*  1010 */   121,  122,  122,  122,  122,  120,  120,  120,  120,  119,
+ /*  1020 */   119,  118,  118,  118,  117,  113,  444, 1108,  277,  277,
+ /*  1030 */  1412,  448,  394, 1230,  439,  277,  277,  248,  247,  246,
+ /*  1040 */  1319,  563, 1109,  313,  198,  294,  491, 1318,  563,  464,
+ /*  1050 */   566, 1427,  394, 1130, 1023,  233,  414, 1110,  295,  120,
+ /*  1060 */   120,  120,  120,  119,  119,  118,  118,  118,  117,  113,
+ /*  1070 */   444, 1014,  104,   71,   71, 1013,  322,  496,  908,  566,
+ /*  1080 */   277,  277,  277,  277, 1108, 1261,  415,  448,  909,  361,
+ /*  1090 */  1571, 1315,  409,  563,  952,  563,    9,  202,  255, 1109,
+ /*  1100 */   316,  487,   44,   44,  249,  559,  415, 1013, 1013, 1015,
+ /*  1110 */   443, 1231,  409, 1603, 1110,  897,  123,  124,  114, 1210,
+ /*  1120 */  1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,
+ /*  1130 */   122, 1231,  409, 1207,  215,  554,  123,  124,  114, 1210,
+ /*  1140 */  1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,
+ /*  1150 */   122, 1131, 1631,  470, 1631,  255,  123,  111,  114, 1210,
+ /*  1160 */  1210, 1044, 1047, 1036, 1036,  121,  121,  122,  122,  122,
+ /*  1170 */   122, 1131, 1632,  414, 1632,  120,  120,  120,  120,  119,
+ /*  1180 */   119,  118,  118,  118,  117,  113,  444,  221,  209,  351,
+ /*  1190 */  1207, 1207,  147, 1426,  491,  120,  120,  120,  120,  119,
+ /*  1200 */   119,  118,  118,  118,  117,  113,  444, 1256,  539,  519,
+ /*  1210 */   888,  551,  952,   12,  566,  120,  120,  120,  120,  119,
+ /*  1220 */   119,  118,  118,  118,  117,  113,  444,  538,  566,  860,
+ /*  1230 */  1129,  361, 1571,  346, 1356,  409, 1163,   58,   58,  339,
+ /*  1240 */  1355,  508,  277,  277,  277,  277,  277,  277, 1207,  889,
+ /*  1250 */  1129,   59,   59,  459,  363,  563,  566,  563,   96,  563,
+ /*  1260 */   124,  114, 1210, 1210, 1044, 1047, 1036, 1036,  121,  121,
+ /*  1270 */   122,  122,  122,  122,  566, 1412,  566,  281, 1186,   60,
+ /*  1280 */    60,  110,  392,  392,  391,  266,  389,  860, 1163,  845,
+ /*  1290 */   566,  481,  566,  436,  341, 1152,  344,   61,   61,   62,
+ /*  1300 */    62,  967,  227, 1550,  315,  431,  540,    6, 1152,  968,
+ /*  1310 */   566, 1152,  314,   45,   45,   46,   46,  512,  120,  120,
+ /*  1320 */   120,  120,  119,  119,  118,  118,  118,  117,  113,  444,
+ /*  1330 */   416,  173, 1532,   47,   47, 1186, 1187, 1188,  108,  558,
+ /*  1340 */   325,    4,  229, 1551,  928,  566,  437,    6,  566,  927,
+ /*  1350 */   164,  566, 1290,  137, 1190,  561,  566, 1549,  566, 1089,
+ /*  1360 */   566,    6,  566, 1089,  531,  566,  868,    8,   49,   49,
+ /*  1370 */   228,   50,   50,  566,   63,   63,  566,  457,  445,   64,
+ /*  1380 */    64,   65,   65,   14,   14,   66,   66,  407,  129,  129,
+ /*  1390 */   555,  566,  458,  566, 1505,  486,   67,   67,  566,   52,
+ /*  1400 */    52,  546,  407,  467,  535,  410,  226, 1023,  566,  534,
+ /*  1410 */   308,  557, 1190,  407,   68,   68,   69,   69,  566, 1023,
+ /*  1420 */   566,   53,   53,  868, 1014,  106,  106,  525, 1013,  566,
+ /*  1430 */  1504,  159,  159,  107,  451,  445,  568,  567,  471,  307,
+ /*  1440 */  1013,  160,  160,   76,   76,  566, 1548,  466,  407,  407,
+ /*  1450 */     6, 1225,   54,   54,  478,  276,  219,  566,  887,  886,
+ /*  1460 */  1013, 1013, 1015,   84,  206, 1206,  230,  282,   72,   72,
+ /*  1470 */   329,  483, 1013, 1013, 1015, 1016,   27, 1576, 1174,  447,
+ /*  1480 */   130,  130,  281,  148,  105,   38,  103,  392,  392,  391,
+ /*  1490 */   266,  389,  566, 1126,  845,  396,  566,  108,  558,  566,
+ /*  1500 */     4,  311,  566,   30,   17,  566,  279,  227,  566,  315,
+ /*  1510 */   108,  558,  468,    4,  561,   73,   73,  314,  566,  157,
+ /*  1520 */   157,  566,  131,  131,  526,  132,  132,  561,  128,  128,
+ /*  1530 */   566,  158,  158,  566,   31,  291,  566,  445,  330,  521,
+ /*  1540 */    98,  152,  152,  420,  136,  136, 1005,  229,  254,  555,
+ /*  1550 */   445,  479,  336,  135,  135,  164,  133,  133,  137,  134,
+ /*  1560 */   134,  875,  555,  535,  566,  473,  566,  254,  536,  475,
+ /*  1570 */   335,  254,   98,  894,  895,  228,  535,  566, 1023,  566,
+ /*  1580 */  1074,  534,  210,  232,  106,  106, 1352,   75,   75,   77,
+ /*  1590 */    77, 1023,  107,  340,  445,  568,  567,  106,  106, 1013,
+ /*  1600 */    74,   74,   42,   42,  566,  107,  343,  445,  568,  567,
+ /*  1610 */   410,  497, 1013,  251,  359,  308,  557, 1135,  349,  875,
+ /*  1620 */    98, 1070,  345,  251,  358, 1591,  347,   48,   48, 1017,
+ /*  1630 */  1303, 1013, 1013, 1015, 1016,   27, 1289, 1287, 1074,  451,
+ /*  1640 */   961,  925,  254,  110, 1013, 1013, 1015, 1016,   27, 1174,
+ /*  1650 */   447,  970,  971,  281,  108,  558, 1288,    4,  392,  392,
+ /*  1660 */   391,  266,  389, 1343, 1086,  845, 1086, 1085,  858, 1085,
+ /*  1670 */   146,  561,  926,  354,  110,  303,  364,  553,  227, 1364,
+ /*  1680 */   315,  108,  558, 1411,    4, 1339,  492, 1017,  314, 1350,
+ /*  1690 */  1565,  552, 1417, 1268,  445,  204, 1259, 1247,  561, 1246,
+ /*  1700 */  1248, 1584,  269, 1336,  367,  369,  555,  371,   11,  212,
+ /*  1710 */   393,  225, 1393,  284, 1398,  456,  287,  327,  229,  328,
+ /*  1720 */   292,  445, 1386,  216,  333, 1403,  164,  477,  373,  137,
+ /*  1730 */  1402,  400,  502,  555, 1286, 1023,  357, 1477,  199, 1587,
+ /*  1740 */   211,  106,  106,  932, 1476, 1225,  228,  556,  175,  107,
+ /*  1750 */   200,  445,  568,  567,  258,  387, 1013, 1524, 1522,  223,
+ /*  1760 */  1222,  418, 1023,   83,  208,   79,   82,  184,  106,  106,
+ /*  1770 */  1482,  169,  177,  461,  179,  462,  107, 1399,  445,  568,
+ /*  1780 */   567,  410,  180, 1013,  495,  181,  308,  557, 1013, 1013,
+ /*  1790 */  1015, 1016,   27,  182,   35,  235,  100,  558,  398,    4,
+ /*  1800 */    96, 1405, 1404,   36,  484,  469, 1407,  188,  401, 1471,
+ /*  1810 */   451,   89, 1493,  561,  239, 1013, 1013, 1015, 1016,   27,
+ /*  1820 */   490,  338,  270,  241,  192,  342,  493,  242,  403, 1249,
+ /*  1830 */   243,  511,  432, 1297, 1306,   91,  445, 1305, 1304,  879,
+ /*  1840 */   217,  434,  435, 1570, 1276, 1602,  520, 1601,  555,  301,
+ /*  1850 */   527,  404, 1275,  302,  356, 1274, 1600,   95, 1347,  366,
+ /*  1860 */  1296,  362, 1348,  368,  256,  257, 1556, 1555,  438, 1346,
+ /*  1870 */   370,  126, 1345,   10, 1371,  546,  381, 1023,  102, 1457,
+ /*  1880 */    97,  530,   34,  106,  106,  570, 1180,  372,  265, 1329,
+ /*  1890 */   379,  107,  203,  445,  568,  567, 1328,  385, 1013, 1370,
+ /*  1900 */   386,  267,  268,  571, 1244,  161, 1239,  162, 1509, 1510,
+ /*  1910 */  1508,  143, 1507,  299,  832,  213,  214,   78,  446,  205,
+ /*  1920 */   310,  306,  163,  224, 1084,  140, 1082,  318,  165,  176,
+ /*  1930 */  1013, 1013, 1015, 1016,   27,  178, 1206,  231,  911,  234,
+ /*  1940 */   326, 1098,  183,  421,  166,  167,  411,  185,   85,  423,
+ /*  1950 */   412,   86,  174,   87,  168,   88, 1101,  236, 1097,  237,
+ /*  1960 */   154,   18,  238,  254,  337, 1219,  489, 1090,  240,  190,
+ /*  1970 */    37,  847,  189,  494,  358,  244,  350,  506,  191,  877,
+ /*  1980 */    90,  498,   19,   20,  503,   92,  353,  890,  300,  170,
+ /*  1990 */   155,   93,  513,   94, 1168,  156, 1050, 1137,   39,  218,
+ /*  2000 */   273,  275, 1136,  960,  194,  955,  110, 1154, 1158,  253,
+ /*  2010 */     7, 1162, 1156,   21,   22, 1161, 1142,   23,   24,   25,
+ /*  2020 */    33,  542,   26,  260,  197,   98, 1065, 1051, 1049, 1053,
+ /*  2030 */  1107, 1054, 1106,  259,   28,   40,  562, 1018,  859,  109,
+ /*  2040 */    29,  921,  390, 1176,  172,  139, 1175, 1235,  261, 1235,
+ /*  2050 */  1235, 1235, 1235, 1235, 1235, 1235, 1235,  262, 1235, 1235,
+ /*  2060 */  1235, 1235, 1235, 1235, 1235, 1235, 1235, 1235, 1593, 1592,
 };
 static const YYCODETYPE yy_lookahead[] = {
- /*     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,  191,  117,  191,  210,   19,  152,
- /*   460 */   153,  154,   23,  295,  102,  103,  104,  105,  106,  107,
- /*   470 */   108,  109,  110,  111,  112,  266,  213,  214,  213,  214,
- /*   480 */   142,   81,   43,   44,   45,   46,   47,   48,   49,   50,
- /*   490 */    51,   52,   53,   54,   55,   56,   57,  301,  102,  103,
- /*   500 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  106,
- /*   510 */   107,  118,   59,  250,  121,  122,  123,  280,   76,  119,
- /*   520 */   236,  237,  259,  306,  131,   72,   59,  310,   19,   87,
- /*   530 */   283,   89,   23,  249,   92,  288,   22,  137,  138,   22,
- /*   540 */   275,  102,  103,  104,  105,  106,  107,  108,  109,  110,
- /*   550 */   111,  112,   43,   44,   45,   46,   47,   48,   49,   50,
- /*   560 */    51,   52,   53,   54,   55,   56,   57,   19,  115,  116,
- /*   570 */   117,   23,  186,   59,  188,  108,   59,  241,  191,  193,
- /*   580 */    26,  195,  115,  116,  117,  191,  144,  251,  202,   22,
- /*   590 */   100,   43,   44,   45,   46,   47,   48,   49,   50,   51,
- /*   600 */    52,   53,   54,   55,   56,   57,  116,  213,  214,  191,
- /*   610 */   120,  102,  103,  104,  105,  106,  107,  108,  109,  110,
- /*   620 */   111,  112,  236,  237,  306,  238,   59,   26,  310,  115,
- /*   630 */   116,  117,  115,  116,  117,  249,  246,   19,  248,  106,
- /*   640 */   107,   23,  152,  153,  154,   46,   47,   48,   49,  263,
- /*   650 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
- /*   660 */   112,   43,   44,   45,   46,   47,   48,   49,   50,   51,
- /*   670 */    52,   53,   54,   55,   56,   57,   19,   76,  298,  299,
- /*   680 */    23,  295,  115,  116,  117,  152,  191,  154,  301,   73,
- /*   690 */    89,  137,  138,   92,   22,  191,  144,   22,  191,  191,
- /*   700 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   710 */    53,   54,   55,   56,   57,  163,  191,  213,  214,  120,
- /*   720 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
- /*   730 */   112,   59,  228,  191,   59,  191,  236,  237,  213,  214,
- /*   740 */    11,   59,  126,  127,  128,  238,   19,   26,  191,  249,
- /*   750 */    23,  164,  165,  228,  191,  213,  214,  213,  214,  102,
- /*   760 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
- /*   770 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   780 */    53,   54,   55,   56,   57,   19,  241,  115,  116,  117,
- /*   790 */   115,  116,  117,  191,  250,  238,  251,  115,  116,  117,
- /*   800 */   157,   23,  159,  191,   26,  191,  111,  112,  301,   43,
- /*   810 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
- /*   820 */    54,   55,   56,   57,  142,  213,  214,  213,  214,  102,
- /*   830 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
- /*   840 */   228,  191,  228,  191,  191,  207,  208,  209,  126,  127,
- /*   850 */   128,  133,  289,  135,  136,   19,  127,  128,  301,    7,
- /*   860 */     8,    9,  141,  213,  214,  213,  214,  265,  102,  103,
- /*   870 */   104,  105,  106,  107,  108,  109,  110,  111,  112,   43,
- /*   880 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
- /*   890 */    54,   55,   56,   57,  191,  117,  191,   22,   23,   19,
- /*   900 */   250,   26,  250,  191,  223,  191,  126,  127,  128,  205,
- /*   910 */   206,  205,  206,  260,   21,  202,  213,  214,  213,  214,
- /*   920 */   142,  270,  208,  209,  158,   45,   46,   47,   48,   49,
- /*   930 */    50,   51,   52,   53,   54,   55,   56,   57,  102,  103,
- /*   940 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  236,
- /*   950 */   237,   12,  191,  250,   76,  250,  191,   22,   23,  308,
- /*   960 */   309,   26,  249,  202,  191,  191,   27,   89,  191,  202,
- /*   970 */    92,  202,  260,   80,  213,  214,  101,  203,  213,  214,
- /*   980 */    22,   42,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   990 */   110,  111,  112,  228,  158,  281,  108,  236,  237,  225,
- /*  1000 */   191,  227,   63,  236,  237,  236,  237,  191,  235,  191,
- /*  1010 */   249,  250,   73,  241,   19,  122,  249,   59,  249,   24,
- /*  1020 */   259,   29,  134,  251,  191,   33,   22,  139,   24,  213,
- /*  1030 */   214,  213,  214,  191,   19,  210,  101,  191,   43,   44,
- /*  1040 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,
- /*  1050 */    55,   56,   57,  160,   19,  213,  214,   65,   43,   44,
- /*  1060 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,
- /*  1070 */    55,   56,   57,  191,  116,   22,  191,   24,   43,   44,
- /*  1080 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,
- /*  1090 */    55,   56,   57,  191,  261,  213,  214,  102,  103,  104,
- /*  1100 */   105,  106,  107,  108,  109,  110,  111,  112,   59,   19,
- /*  1110 */   191,  265,   59,  288,  191,  213,  214,  102,  103,  104,
- /*  1120 */   105,  106,  107,  108,  109,  110,  111,  112,   35,  191,
- /*  1130 */    66,  191,  213,  214,  191,  270,   46,  102,  103,  104,
- /*  1140 */   105,  106,  107,  108,  109,  110,  111,  112,  191,   85,
- /*  1150 */   265,  213,  214,  213,  214,  106,  107,   19,   94,   66,
- /*  1160 */   137,  138,  191,  114,  115,  116,  117,   74,  119,  116,
- /*  1170 */   213,  214,  202,  308,  309,  306,  127,  191,  235,  310,
- /*  1180 */    59,  191,   44,   45,   46,   47,   48,   49,   50,   51,
- /*  1190 */    52,   53,   54,   55,   56,   57,  191,   76,  196,  213,
- /*  1200 */   214,  152,   12,  154,  114,  191,  236,  237,   87,  145,
- /*  1210 */    89,   19,   20,   92,   22,   22,   23,   27,  191,  249,
- /*  1220 */   130,  202,  129,  202,  191,  235,  306,  152,   36,  154,
- /*  1230 */   310,  191,   42,  191,  191,  191,  115,  116,  117,  191,
- /*  1240 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
- /*  1250 */   112,   59,   99,   63,  191,  236,  237,  236,  237,  191,
- /*  1260 */   289,  213,  214,   71,  191,  144,  261,  191,  249,  191,
- /*  1270 */   249,   19,   20,   81,   22,  235,  213,  214,  235,  191,
- /*  1280 */   278,  213,  214,  191,  282,  132,  213,  214,   36,  213,
- /*  1290 */   214,  191,  100,  191,  101,  191,  191,  191,  106,  107,
- /*  1300 */    48,  213,  214,  261,  191,  113,  191,  115,  116,  117,
- /*  1310 */   191,   59,  120,  213,  214,  213,  214,  213,  214,  213,
- /*  1320 */   214,   22,   23,   71,  237,   59,  213,  214,  191,  137,
- /*  1330 */   138,  191,  213,  214,  191,  191,  249,   85,  191,  261,
- /*  1340 */   191,   26,   90,   15,  152,  153,  154,  155,  156,   19,
- /*  1350 */   213,  214,  100,  213,  214,  191,  213,  214,  106,  107,
- /*  1360 */   213,  214,  213,  214,  191,  113,  261,  115,  116,  117,
- /*  1370 */   253,  254,  120,  229,  191,  191,  191,  213,  214,  191,
- /*  1380 */   306,  289,  116,   26,  310,  191,  213,  214,   60,   19,
- /*  1390 */   296,  297,   24,  191,   46,  191,  213,  214,  213,  214,
- /*  1400 */   101,  213,  214,  191,  152,  153,  154,  155,  156,    0,
- /*  1410 */     1,    2,  191,  229,    5,  213,  214,  213,  214,   10,
- /*  1420 */    11,   12,   13,   14,    1,    2,   17,  191,    5,   19,
- /*  1430 */    20,  191,   22,   10,   11,   12,   13,   14,  191,   30,
- /*  1440 */    17,   32,  241,  148,  149,  115,   36,  191,  241,   40,
- /*  1450 */   191,   26,  251,   30,  191,   32,  141,   22,  251,    5,
- /*  1460 */   213,  214,  114,   40,   10,   11,   12,   13,   14,   59,
- /*  1470 */   134,   17,  213,  214,  191,  139,  213,  214,  191,   70,
- /*  1480 */   191,   71,  125,  191,   30,  115,   32,   78,   53,  191,
- /*  1490 */    81,  191,  191,   70,   40,   85,  213,  214,  191,   22,
- /*  1500 */    90,   78,  213,  214,   81,  213,  214,   98,  140,  120,
- /*  1510 */   100,  213,  214,  213,  214,   23,  106,  107,   26,  130,
- /*  1520 */   191,   98,  191,  113,   70,  115,  116,  117,   23,   22,
- /*  1530 */   120,   26,   78,   19,  191,   81,   19,   20,   61,   22,
- /*  1540 */   191,  132,  213,  214,  213,  214,  137,  138,   59,  191,
- /*  1550 */   191,  191,   98,   36,  128,  132,  213,  214,  128,   59,
- /*  1560 */   137,  138,  152,  153,  154,  155,  156,   83,   84,  144,
- /*  1570 */   161,  213,  214,  213,  214,   23,   59,  151,   26,   23,
- /*  1580 */    23,  151,   26,   26,  161,   59,  132,   23,   71,  191,
- /*  1590 */    26,  137,  138,  119,  120,   23,   19,   20,   26,   22,
- /*  1600 */   223,   23,   85,   23,   26,  116,   26,   90,  191,    7,
- /*  1610 */     8,   97,  152,   36,  154,  161,  116,  100,   23,   23,
- /*  1620 */   191,   26,   26,  106,  107,  191,   23,  223,   23,   26,
- /*  1630 */   113,   26,  115,  116,  117,   23,   59,  120,   26,  191,
- /*  1640 */   191,  191,  116,  255,  191,  252,  191,  140,   71,  191,
- /*  1650 */   315,  233,  191,  191,  191,  191,  191,  191,  191,  191,
- /*  1660 */   191,  285,  284,  239,  252,  252,  252,  252,  240,  152,
- /*  1670 */   153,  154,  155,  156,  189,  294,  268,  100,  242,  268,
- /*  1680 */   264,  211,  290,  106,  107,  108,  264,  256,  256,  243,
- /*  1690 */   113,  290,  115,  116,  117,  268,  217,  120,  226,  243,
- /*  1700 */   222,  268,  216,   19,   20,  246,   22,  216,  256,  216,
- /*  1710 */   194,   60,   38,  242,  277,  294,  240,  242,  198,  246,
- /*  1720 */    36,  140,  198,  198,   19,   20,  150,   22,  149,  152,
- /*  1730 */   153,  154,  155,  156,  294,  291,  291,  280,   22,   43,
- /*  1740 */   231,   36,   18,   59,  234,  234,  234,  234,  267,  269,
- /*  1750 */    18,  198,  197,  231,  148,   71,  269,  269,  243,  231,
- /*  1760 */   198,  243,  267,  197,   59,  157,  243,  198,   62,  287,
- /*  1770 */   243,  197,   22,  198,  114,   64,   71,  218,  218,  197,
- /*  1780 */   286,  198,  197,  215,  100,  215,  215,  224,   22,  125,
- /*  1790 */   106,  107,  164,   24,  221,  112,  143,  113,  302,  115,
- /*  1800 */   116,  117,  218,  215,  120,  100,  217,  221,  215,  215,
- /*  1810 */   309,  106,  107,  215,  224,  279,  279,  218,  113,  258,
- /*  1820 */   115,  116,  117,  114,  257,  120,   91,  198,   82,  147,
- /*  1830 */   144,   22,  274,  314,  198,  314,  152,  153,  154,  155,
- /*  1840 */   156,  276,  157,  146,  145,  258,   25,  247,  257,  201,
- /*  1850 */   258,   26,  200,   13,  257,  244,  246,  152,  153,  154,
- /*  1860 */   155,  156,  258,  262,  257,  247,  245,  243,  192,  192,
- /*  1870 */     6,  262,  204,  210,  219,  210,  210,  190,  190,  190,
- /*  1880 */   210,  219,  204,  211,  211,  210,    4,    3,   22,  162,
- /*  1890 */    15,   23,   16,   23,  204,  138,  129,  150,   26,  141,
- /*  1900 */    20,   24,  143,   16,    1,  141,  129,  129,   61,   53,
- /*  1910 */    37,  150,  297,  300,  300,   53,   53,  129,   53,  115,
- /*  1920 */    34,  140,    1,    5,   22,  114,   68,   26,  160,   68,
- /*  1930 */    75,   41,  140,  114,   24,   20,   19,  130,  124,   23,
- /*  1940 */    96,   22,   22,   37,   22,   67,   22,   59,   67,   24,
- /*  1950 */    22,   28,   67,   23,  148,   22,   97,   23,   23,   23,
- /*  1960 */   140,   23,   22,   26,   23,   23,  115,   22,  142,   26,
- /*  1970 */    75,   88,   75,   34,   23,   86,   44,   22,   34,   26,
- /*  1980 */    34,   34,   34,   34,   93,   24,   26,   23,   34,   23,
- /*  1990 */    23,   23,   23,   11,   23,   22,   26,   22,   22,   15,
- /*  2000 */    23,   23,   22,   22,    1,   26,   23,  140,  134,  140,
- /*  2010 */     1,  140,  316,  316,  316,  316,  316,  316,  316,  140,
- /*  2020 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2030 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2040 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2050 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2060 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2070 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2080 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2090 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2100 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2110 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2120 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2130 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2140 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2150 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2160 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2170 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2180 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2190 */   316,  316,  316,  316,  316,  316,  316,  316,  316,  316,
- /*  2200 */   316,  316,  316,
+ /*     0 */   193,  223,  193,  225,  193,  193,  193,  274,  275,  276,
+ /*    10 */   193,  233,  219,  193,  274,  275,  276,  206,  206,   19,
+ /*    20 */   193,  219,  216,  216,  217,  216,  217,  193,  295,  216,
+ /*    30 */   217,   31,  205,  216,  217,  193,  216,  217,  213,   39,
+ /*    40 */   228,  193,  230,   43,   44,   45,   46,   47,   48,   49,
+ /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  193,   19,
+ /*    60 */   185,  186,  187,  188,  189,  190,  253,  274,  275,  276,
+ /*    70 */   195,  193,  197,  253,  216,  262,  274,  275,  276,  204,
+ /*    80 */   238,  204,  262,   43,   44,   45,   46,   47,   48,   49,
+ /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  264,  274,
+ /*   100 */   275,  276,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   110 */   110,  111,  112,  113,  239,  240,  239,  240,  210,  211,
+ /*   120 */   212,  314,  315,  314,   59,  316,   86,  252,   88,  252,
+ /*   130 */    19,  314,  315,  256,  257,  309,   25,   72,  296,  313,
+ /*   140 */   193,  266,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   150 */   110,  111,  112,  113,   43,   44,   45,   46,   47,   48,
+ /*   160 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   81,
+ /*   170 */   292,   59,  307,  298,  108,  109,  110,  111,  112,  113,
+ /*   180 */    69,  116,  117,  118,   72,  128,  129,  193,  241,   22,
+ /*   190 */   113,   54,   55,   56,   57,   58,  102,  103,  104,  105,
+ /*   200 */   106,  107,  108,  109,  110,  111,  112,  113,  120,  193,
+ /*   210 */   216,  217,   25,  102,  103,  104,  105,  106,  107,  108,
+ /*   220 */   109,  110,  111,  112,  113,  231,  138,  139,  116,  117,
+ /*   230 */   118,  106,  107,   19,  216,   54,   55,   56,   57,  102,
+ /*   240 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
+ /*   250 */   113,  304,   25,   46,   47,   48,   49,   43,   44,   45,
+ /*   260 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
+ /*   270 */    56,   57,  193,  106,  107,   59,  193,   19,  153,  263,
+ /*   280 */   155,   67,   24,  102,  103,  104,  105,  106,  107,  108,
+ /*   290 */   109,  110,  111,  112,  113,  216,  217,   59,  230,  216,
+ /*   300 */   217,   43,   44,   45,   46,   47,   48,   49,   50,   51,
+ /*   310 */    52,   53,   54,   55,   56,   57,  102,  103,  104,  105,
+ /*   320 */   106,  107,  108,  109,  110,  111,  112,  113,  121,  142,
+ /*   330 */    59,  193,  116,  117,  118,  119,  253,  204,  122,  123,
+ /*   340 */   124,   19,   20,   81,   22,  262,  108,   19,  132,  165,
+ /*   350 */   166,  193,   24,  126,  116,  117,  118,  278,   36,  193,
+ /*   360 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
+ /*   370 */   112,  113,  239,  240,  216,  217,  215,  106,  107,  241,
+ /*   380 */    19,   59,  216,  217,  223,  252,  115,  116,  117,  118,
+ /*   390 */    73,  120,   26,   71,  193,   22,  193,  231,   81,  128,
+ /*   400 */   138,  139,  269,   81,   43,   44,   45,   46,   47,   48,
+ /*   410 */    49,   50,   51,   52,   53,   54,   55,   56,   57,  216,
+ /*   420 */   217,  198,  100,   95,  153,   59,  155,  193,  106,  107,
+ /*   430 */   235,  236,   59,  193,  193,  249,  114,  251,  116,  117,
+ /*   440 */   118,  113,  304,  121,  127,  204,  193,  119,  120,  121,
+ /*   450 */   122,  123,  124,  125,  193,  138,  139,  216,  217,  131,
+ /*   460 */   138,  139,  193,  102,  103,  104,  105,  106,  107,  108,
+ /*   470 */   109,  110,  111,  112,  113,  153,  154,  155,  156,  157,
+ /*   480 */   239,  240,  116,  117,  118,   76,  193,  193,   19,  116,
+ /*   490 */   117,  118,   23,  252,  253,  193,   87,  204,   89,  238,
+ /*   500 */   193,   92,  268,  262,  281,  203,  193,  205,  285,  216,
+ /*   510 */   217,  150,   43,   44,   45,   46,   47,   48,   49,   50,
+ /*   520 */    51,   52,   53,   54,   55,   56,   57,  193,  193,  216,
+ /*   530 */   217,   19,  239,  240,   59,   23,  106,  107,  108,  109,
+ /*   540 */   110,  111,  112,  113,  231,  252,  253,  193,  308,  309,
+ /*   550 */   193,  145,   59,  313,  145,   43,   44,   45,   46,   47,
+ /*   560 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
+ /*   570 */   164,  102,  103,  104,  105,  106,  107,  108,  109,  110,
+ /*   580 */   111,  112,  113,  119,  193,  193,  122,  123,  124,  193,
+ /*   590 */   283,  116,  117,  118,  235,  236,  132,   59,  241,  264,
+ /*   600 */    59,  193,   19,   23,  193,   25,   23,  216,  217,  116,
+ /*   610 */   117,  118,  216,  217,  102,  103,  104,  105,  106,  107,
+ /*   620 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
+ /*   630 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*   640 */    57,   19,  308,  309,  151,   23,   25,  313,  135,  253,
+ /*   650 */    21,  193,  241,  140,  116,  117,  118,  116,  117,  118,
+ /*   660 */   268,  304,   22,  301,  302,   43,   44,   45,   46,   47,
+ /*   670 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
+ /*   680 */   193,  143,  193,  193,  143,  102,  103,  104,  105,  106,
+ /*   690 */   107,  108,  109,  110,  111,  112,  113,   76,  118,   59,
+ /*   700 */   292,  211,  212,  216,  217,  216,  217,   73,  193,   80,
+ /*   710 */    89,   25,   19,   92,  193,  304,   23,   22,  231,  193,
+ /*   720 */   231,  193,   22,  143,  102,  103,  104,  105,  106,  107,
+ /*   730 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
+ /*   740 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*   750 */    57,   19,  123,  193,   59,   23,  116,  117,  118,   59,
+ /*   760 */   193,  127,  128,  129,  306,  307,  210,  211,  212,  193,
+ /*   770 */    22,  111,  112,  113,  284,   43,   44,   45,   46,   47,
+ /*   780 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
+ /*   790 */   161,  193,  216,  217,  268,  102,  103,  104,  105,  106,
+ /*   800 */   107,  108,  109,  110,  111,  112,  113,   59,  193,  193,
+ /*   810 */   193,  116,  117,  118,  216,  217,  116,  117,  118,  304,
+ /*   820 */   239,  240,   19,  263,  138,  139,   23,  211,  212,  231,
+ /*   830 */   263,  216,  217,  252,  102,  103,  104,  105,  106,  107,
+ /*   840 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
+ /*   850 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*   860 */    57,   19,  193,   11,  116,  117,  118,  240,  253,  193,
+ /*   870 */   201,  239,  240,  193,  134,  206,  136,  137,  193,  252,
+ /*   880 */   193,  264,  193,  193,  252,   43,   44,   45,   46,   47,
+ /*   890 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
+ /*   900 */   284,  216,  217,  216,  217,  102,  103,  104,  105,  106,
+ /*   910 */   107,  108,  109,  110,  111,  112,  113,  193,  231,  193,
+ /*   920 */   187,  188,  189,  190,  127,  128,  129,  238,  195,  193,
+ /*   930 */   197,   16,   19,    7,    8,    9,  193,  204,  253,  193,
+ /*   940 */   216,  217,  216,  217,  102,  103,  104,  105,  106,  107,
+ /*   950 */   108,  109,  110,  111,  112,  113,   43,   44,   45,   46,
+ /*   960 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*   970 */    57,  213,  239,  240,  193,   76,   19,  188,  232,  190,
+ /*   980 */   128,  129,  292,  193,  195,  252,  197,   46,   89,  138,
+ /*   990 */   139,   92,   77,  204,   79,  193,  269,  216,  217,  266,
+ /*  1000 */   204,  159,   45,   46,   47,   48,   49,   50,   51,   52,
+ /*  1010 */    53,   54,   55,   56,   57,  102,  103,  104,  105,  106,
+ /*  1020 */   107,  108,  109,  110,  111,  112,  113,   12,  239,  240,
+ /*  1030 */   193,  298,   22,   23,  253,  239,  240,  127,  128,  129,
+ /*  1040 */   238,  252,   27,  193,  286,  204,  193,  204,  252,  291,
+ /*  1050 */   193,  273,   22,   23,  100,  266,  115,   42,  268,  102,
+ /*  1060 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
+ /*  1070 */   113,  117,  159,  216,  217,  121,  161,   19,   63,  193,
+ /*  1080 */   239,  240,  239,  240,   12,  208,  209,  298,   73,  311,
+ /*  1090 */   312,  238,   19,  252,   25,  252,   22,   24,   24,   27,
+ /*  1100 */   193,  264,  216,  217,   46,  208,  209,  153,  154,  155,
+ /*  1110 */   253,  101,   19,   23,   42,   25,   43,   44,   45,   46,
+ /*  1120 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*  1130 */    57,  101,   19,   59,   25,   63,   43,   44,   45,   46,
+ /*  1140 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*  1150 */    57,   22,   23,  115,   25,   24,   43,   44,   45,   46,
+ /*  1160 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*  1170 */    57,   22,   23,  115,   25,  102,  103,  104,  105,  106,
+ /*  1180 */   107,  108,  109,  110,  111,  112,  113,  118,  150,  131,
+ /*  1190 */    59,  117,   22,  273,  193,  102,  103,  104,  105,  106,
+ /*  1200 */   107,  108,  109,  110,  111,  112,  113,  204,   66,  204,
+ /*  1210 */    35,  204,  143,  213,  193,  102,  103,  104,  105,  106,
+ /*  1220 */   107,  108,  109,  110,  111,  112,  113,   85,  193,   59,
+ /*  1230 */   101,  311,  312,   16,  193,   19,   94,  216,  217,  238,
+ /*  1240 */   193,   66,  239,  240,  239,  240,  239,  240,  117,   74,
+ /*  1250 */   101,  216,  217,  193,  193,  252,  193,  252,  149,  252,
+ /*  1260 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
+ /*  1270 */    54,   55,   56,   57,  193,  193,  193,    5,   59,  216,
+ /*  1280 */   217,   25,   10,   11,   12,   13,   14,  117,  146,   17,
+ /*  1290 */   193,  291,  193,  232,   77,   76,   79,  216,  217,  216,
+ /*  1300 */   217,   31,   30,  309,   32,  130,   87,  313,   89,   39,
+ /*  1310 */   193,   92,   40,  216,  217,  216,  217,  108,  102,  103,
+ /*  1320 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  113,
+ /*  1330 */   299,  300,  193,  216,  217,  116,  117,  118,   19,   20,
+ /*  1340 */   193,   22,   70,  309,  135,  193,  264,  313,  193,  140,
+ /*  1350 */    78,  193,  226,   81,   59,   36,  193,  309,  193,   29,
+ /*  1360 */   193,  313,  193,   33,  145,  193,   59,   48,  216,  217,
+ /*  1370 */    98,  216,  217,  193,  216,  217,  193,  244,   59,  216,
+ /*  1380 */   217,  216,  217,  216,  217,  216,  217,  254,  216,  217,
+ /*  1390 */    71,  193,  244,  193,  193,   65,  216,  217,  193,  216,
+ /*  1400 */   217,  145,  254,  244,   85,  133,   15,  100,  193,   90,
+ /*  1410 */   138,  139,  117,  254,  216,  217,  216,  217,  193,  100,
+ /*  1420 */   193,  216,  217,  116,  117,  106,  107,   19,  121,  193,
+ /*  1430 */   193,  216,  217,  114,  162,  116,  117,  118,  244,  244,
+ /*  1440 */   121,  216,  217,  216,  217,  193,  309,  129,  254,  254,
+ /*  1450 */   313,   60,  216,  217,   19,  256,  257,  193,  120,  121,
+ /*  1460 */   153,  154,  155,  149,  150,   25,   24,   99,  216,  217,
+ /*  1470 */   152,  193,  153,  154,  155,  156,  157,    0,    1,    2,
+ /*  1480 */   216,  217,    5,   22,  158,   24,  160,   10,   11,   12,
+ /*  1490 */    13,   14,  193,   23,   17,   25,  193,   19,   20,  193,
+ /*  1500 */    22,  133,  193,   22,   22,  193,   22,   30,  193,   32,
+ /*  1510 */    19,   20,  129,   22,   36,  216,  217,   40,  193,  216,
+ /*  1520 */   217,  193,  216,  217,  116,  216,  217,   36,  216,  217,
+ /*  1530 */   193,  216,  217,  193,   53,  152,  193,   59,   23,   19,
+ /*  1540 */    25,  216,  217,   61,  216,  217,   23,   70,   25,   71,
+ /*  1550 */    59,  116,  193,  216,  217,   78,  216,  217,   81,  216,
+ /*  1560 */   217,   59,   71,   85,  193,   23,  193,   25,   90,   23,
+ /*  1570 */    23,   25,   25,    7,    8,   98,   85,  193,  100,  193,
+ /*  1580 */    59,   90,  142,  141,  106,  107,  193,  216,  217,  216,
+ /*  1590 */   217,  100,  114,  193,  116,  117,  118,  106,  107,  121,
+ /*  1600 */   216,  217,  216,  217,  193,  114,  193,  116,  117,  118,
+ /*  1610 */   133,   23,  121,   25,  121,  138,  139,   97,   23,  117,
+ /*  1620 */    25,   23,  193,   25,  131,  141,  193,  216,  217,   59,
+ /*  1630 */   193,  153,  154,  155,  156,  157,  226,  193,  117,  162,
+ /*  1640 */    23,   23,   25,   25,  153,  154,  155,  156,  157,    1,
+ /*  1650 */     2,   83,   84,    5,   19,   20,  226,   22,   10,   11,
+ /*  1660 */    12,   13,   14,  258,  153,   17,  155,  153,   23,  155,
+ /*  1670 */    25,   36,   23,  193,   25,  255,  193,  236,   30,  193,
+ /*  1680 */    32,   19,   20,  193,   22,  193,  288,  117,   40,  193,
+ /*  1690 */   318,  193,  193,  193,   59,  242,  193,  193,   36,  193,
+ /*  1700 */   193,  193,  287,  255,  255,  255,   71,  255,  243,  214,
+ /*  1710 */   191,  297,  267,  245,  271,  259,  259,  293,   70,  246,
+ /*  1720 */   246,   59,  267,  229,  245,  271,   78,  293,  259,   81,
+ /*  1730 */   271,  271,  220,   71,  225,  100,  219,  219,  249,  196,
+ /*  1740 */   243,  106,  107,  108,  219,   60,   98,  280,  297,  114,
+ /*  1750 */   249,  116,  117,  118,  141,  245,  121,  200,  200,  297,
+ /*  1760 */    38,  200,  100,  151,  150,  294,  294,   22,  106,  107,
+ /*  1770 */   283,   43,  234,   18,  237,  200,  114,  272,  116,  117,
+ /*  1780 */   118,  133,  237,  121,   18,  237,  138,  139,  153,  154,
+ /*  1790 */   155,  156,  157,  237,  270,  199,   19,   20,  246,   22,
+ /*  1800 */   149,  272,  272,  270,  200,  246,  234,  234,  246,  246,
+ /*  1810 */   162,  158,  290,   36,  199,  153,  154,  155,  156,  157,
+ /*  1820 */    62,  289,  200,  199,   22,  200,  221,  199,  221,  200,
+ /*  1830 */   199,  115,   64,  227,  218,   22,   59,  218,  218,  126,
+ /*  1840 */   165,   24,  113,  312,  218,  224,  305,  224,   71,  282,
+ /*  1850 */   144,  221,  220,  282,  218,  218,  218,  115,  261,  260,
+ /*  1860 */   227,  221,  261,  260,  200,   91,  317,  317,   82,  261,
+ /*  1870 */   260,  148,  261,   22,  265,  145,  200,  100,  158,  277,
+ /*  1880 */   147,  146,   25,  106,  107,  202,   13,  260,  194,  250,
+ /*  1890 */   249,  114,  248,  116,  117,  118,  250,  247,  121,  265,
+ /*  1900 */   246,  194,    6,  192,  192,  207,  192,  207,  213,  213,
+ /*  1910 */   213,  222,  213,  222,    4,  214,  214,  213,    3,   22,
+ /*  1920 */   163,  279,  207,   15,   23,   16,   23,  139,  130,  151,
+ /*  1930 */   153,  154,  155,  156,  157,  142,   25,   24,   20,  144,
+ /*  1940 */    16,    1,  142,   61,  130,  130,  303,  151,   53,   37,
+ /*  1950 */   303,   53,  300,   53,  130,   53,  116,   34,    1,  141,
+ /*  1960 */     5,   22,  115,   25,  161,   75,   41,   68,  141,  115,
+ /*  1970 */    24,   20,   68,   19,  131,  125,   23,   96,   22,   59,
+ /*  1980 */    22,   67,   22,   22,   67,   22,   24,   28,   67,   37,
+ /*  1990 */    23,  149,   22,   25,   23,   23,   23,   23,   22,  141,
+ /*  2000 */    23,   23,   97,  116,   22,  143,   25,   88,   75,   34,
+ /*  2010 */    44,   75,   86,   34,   34,   93,   23,   34,   34,   34,
+ /*  2020 */    22,   24,   34,   22,   25,   25,   23,   23,   23,   23,
+ /*  2030 */    23,   11,   23,   25,   22,   22,   25,   23,   23,   22,
+ /*  2040 */    22,  135,   15,    1,   25,   23,    1,  319,  141,  319,
+ /*  2050 */   319,  319,  319,  319,  319,  319,  319,  141,  319,  319,
+ /*  2060 */   319,  319,  319,  319,  319,  319,  319,  319,  141,  141,
+ /*  2070 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2080 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2090 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2100 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2110 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2120 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2130 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2140 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2150 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2160 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2170 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2180 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2190 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2200 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2210 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2220 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2230 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2240 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
+ /*  2250 */   319,  319,  319,  319,  319,
 };
-#define YY_SHIFT_COUNT    (569)
+#define YY_SHIFT_COUNT    (573)
 #define YY_SHIFT_MIN      (0)
-#define YY_SHIFT_MAX      (2009)
+#define YY_SHIFT_MAX      (2045)
 static const unsigned short int yy_shift_ofst[] = {
- /*     0 */  1423, 1409, 1454, 1192, 1192,   36, 1252, 1410, 1517, 1684,
- /*    10 */  1684, 1684,  292,    0,    0,  180, 1015, 1684, 1684, 1684,
- /*    20 */  1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684,
- /*    30 */  1049, 1049, 1121, 1121,   54,  400,   36,   36,   36,   36,
- /*    40 */    36,   40,  110,  219,  289,  396,  439,  509,  548,  618,
- /*    50 */   657,  727,  766,  836,  995, 1015, 1015, 1015, 1015, 1015,
- /*    60 */  1015, 1015, 1015, 1015, 1015, 1015, 1015, 1015, 1015, 1015,
- /*    70 */  1015, 1015, 1015, 1035, 1015, 1138,  880,  880, 1577, 1684,
- /*    80 */  1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684,
- /*    90 */  1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684,
- /*   100 */  1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684, 1684,
- /*   110 */  1684, 1684, 1684, 1705, 1684, 1684, 1684, 1684, 1684, 1684,
- /*   120 */  1684, 1684, 1684, 1684, 1684, 1684, 1684,  146,   84,   84,
- /*   130 */    84,   84,   84,  362,  269,  125,   97,  453,   66,   66,
- /*   140 */   893, 1090,   66,   66,  533,  533,   66,  554,  554,  554,
- /*   150 */   554,  192,  587,  587,  695,   25, 2020, 2020,  290,  290,
- /*   160 */   290,  200,  514,  514,  514,  514,  939,  939,  442,  875,
- /*   170 */   935,   66,   66,   66,   66,   66,   66,   66,   66,   66,
- /*   180 */    66,   66,   66,   66,   66,   66,   66,   66,   66,   66,
- /*   190 */    66,  601,  601,   66,  729,  878,  878, 1266, 1266,  552,
- /*   200 */  1023, 2020, 2020, 2020, 2020, 2020, 2020, 2020,  307,  490,
- /*   210 */   490,  567,  393,  517,  467,  672,  242,  682,  675,   66,
- /*   220 */    66,   66,   66,   66,   66,   66,   66,   66,   66,  616,
- /*   230 */    66,   66,   66,   66,   66,   66,   66,   66,   66,   66,
- /*   240 */    66,   66, 1093, 1093, 1093,   66,   66,   66,  778,   66,
- /*   250 */    66,   66, 1053, 1064,   66,   66, 1190,   66,   66,   66,
- /*   260 */    66,   66,   66,   66,   66,  722,  992,  718,  253,  253,
- /*   270 */   253,  253,  338,  718,  718,  888,  403,  852, 1328,  254,
- /*   280 */  1295,  721, 1330, 1295, 1330, 1370,  234,  254,  254,  234,
- /*   290 */   254,  721, 1370, 1357, 1492, 1348,  385,  385,  385, 1330,
- /*   300 */  1425, 1425,  643, 1315, 1336, 1004, 1651, 1651, 1581, 1581,
- /*   310 */  1674, 1674, 1581, 1576, 1579, 1716, 1696, 1724, 1724, 1724,
- /*   320 */  1724, 1581, 1732, 1606, 1579, 1579, 1606, 1716, 1696, 1606,
- /*   330 */  1696, 1606, 1581, 1732, 1608, 1706, 1581, 1732, 1750, 1581,
- /*   340 */  1732, 1581, 1732, 1750, 1660, 1660, 1660, 1711, 1766, 1766,
- /*   350 */  1750, 1660, 1664, 1660, 1711, 1660, 1660, 1628, 1769, 1683,
- /*   360 */  1683, 1750, 1653, 1709, 1653, 1709, 1653, 1709, 1653, 1709,
- /*   370 */  1581, 1735, 1735, 1746, 1746, 1682, 1686, 1809, 1581, 1685,
- /*   380 */  1682, 1697, 1699, 1606, 1821, 1825, 1840, 1840, 1864, 1864,
- /*   390 */  1864, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020,
- /*   400 */  2020, 2020, 2020, 2020, 2020, 2020,  599,  223, 1193, 1299,
- /*   410 */   228,  780,  958, 1505, 1153, 1435, 1368, 1426, 1430, 1552,
- /*   420 */  1477, 1556, 1557, 1564, 1572, 1578, 1580, 1489, 1474, 1602,
- /*   430 */  1389, 1514, 1500, 1595, 1596, 1484, 1603, 1075, 1460, 1605,
- /*   440 */  1612, 1526, 1507, 1882, 1884, 1866, 1727, 1875, 1876, 1868,
- /*   450 */  1870, 1757, 1747, 1767, 1872, 1872, 1877, 1758, 1880, 1759,
- /*   460 */  1887, 1903, 1764, 1777, 1872, 1778, 1847, 1873, 1872, 1761,
- /*   470 */  1856, 1862, 1863, 1865, 1788, 1804, 1886, 1781, 1921, 1918,
- /*   480 */  1902, 1811, 1768, 1858, 1901, 1861, 1855, 1890, 1792, 1819,
- /*   490 */  1910, 1915, 1917, 1807, 1814, 1919, 1878, 1920, 1922, 1916,
- /*   500 */  1924, 1881, 1888, 1925, 1844, 1923, 1928, 1885, 1906, 1930,
- /*   510 */  1806, 1933, 1934, 1935, 1936, 1937, 1938, 1940, 1859, 1820,
- /*   520 */  1941, 1942, 1851, 1939, 1945, 1826, 1943, 1944, 1946, 1947,
- /*   530 */  1948, 1883, 1895, 1889, 1932, 1897, 1891, 1949, 1951, 1955,
- /*   540 */  1961, 1953, 1960, 1954, 1964, 1943, 1966, 1967, 1968, 1969,
- /*   550 */  1970, 1971, 1973, 1982, 1975, 1976, 1977, 1978, 1980, 1981,
- /*   560 */  1979, 1874, 1867, 1869, 1871, 1879, 1983, 1984, 2003, 2009,
+ /*     0 */  1648, 1477, 1272,  322,  322,  262, 1319, 1478, 1491, 1662,
+ /*    10 */  1662, 1662,  317,    0,    0,  214, 1093, 1662, 1662, 1662,
+ /*    20 */  1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662,
+ /*    30 */   271,  271, 1219, 1219,  216,   88,  262,  262,  262,  262,
+ /*    40 */   262,   40,  111,  258,  361,  469,  512,  583,  622,  693,
+ /*    50 */   732,  803,  842,  913, 1073, 1093, 1093, 1093, 1093, 1093,
+ /*    60 */  1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093,
+ /*    70 */  1093, 1093, 1093, 1113, 1093, 1216,  957,  957, 1635, 1662,
+ /*    80 */  1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662,
+ /*    90 */  1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662,
+ /*   100 */  1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662,
+ /*   110 */  1662, 1662, 1662, 1662, 1777, 1662, 1662, 1662, 1662, 1662,
+ /*   120 */  1662, 1662, 1662, 1662, 1662, 1662, 1662, 1662,  137,  181,
+ /*   130 */   181,  181,  181,  181,   94,  430,   66,   65,  112,  366,
+ /*   140 */   475,  475,  629, 1058,  475,  475,  125,  125,  475,  686,
+ /*   150 */   686,  686,  660,  686,   57,  184,  184,   77,   77, 2070,
+ /*   160 */  2070,  328,  328,  328,  493,  373,  373,  373,  373, 1015,
+ /*   170 */  1015,  409,  366, 1129, 1149,  475,  475,  475,  475,  475,
+ /*   180 */   475,  475,  475,  475,  475,  475,  475,  475,  475,  475,
+ /*   190 */   475,  475,  475,  475,  475,  621,  621,  475,  852,  899,
+ /*   200 */   899, 1295, 1295,  406,  851, 2070, 2070, 2070, 2070, 2070,
+ /*   210 */  2070, 2070, 1307,  954,  954,  640,  464,  695,  238,  700,
+ /*   220 */   538,  541,  748,  475,  475,  475,  475,  475,  475,  475,
+ /*   230 */   475,  475,  475,  634,  475,  475,  475,  475,  475,  475,
+ /*   240 */   475,  475,  475,  475,  475,  475, 1175, 1175, 1175,  475,
+ /*   250 */   475,  475,  580,  475,  475,  475, 1074, 1142,  475,  475,
+ /*   260 */  1072,  475,  475,  475,  475,  475,  475,  475,  475,  797,
+ /*   270 */  1330,  740, 1131, 1131, 1131, 1131, 1069,  740,  740, 1209,
+ /*   280 */   167,  926, 1391, 1038, 1314,  187, 1408, 1314, 1408, 1435,
+ /*   290 */  1109, 1038, 1038, 1109, 1038,  187, 1435,  227, 1090,  941,
+ /*   300 */  1270, 1270, 1270, 1408, 1256, 1256, 1326, 1440,  513, 1461,
+ /*   310 */  1685, 1685, 1613, 1613, 1722, 1722, 1613, 1612, 1614, 1745,
+ /*   320 */  1728, 1755, 1755, 1755, 1755, 1613, 1766, 1651, 1614, 1614,
+ /*   330 */  1651, 1745, 1728, 1651, 1728, 1651, 1613, 1766, 1653, 1758,
+ /*   340 */  1613, 1766, 1802, 1613, 1766, 1613, 1766, 1802, 1716, 1716,
+ /*   350 */  1716, 1768, 1813, 1813, 1802, 1716, 1713, 1716, 1768, 1716,
+ /*   360 */  1716, 1675, 1817, 1729, 1729, 1802, 1706, 1742, 1706, 1742,
+ /*   370 */  1706, 1742, 1706, 1742, 1613, 1774, 1774, 1786, 1786, 1723,
+ /*   380 */  1730, 1851, 1613, 1720, 1723, 1733, 1735, 1651, 1857, 1873,
+ /*   390 */  1873, 1896, 1896, 1896, 2070, 2070, 2070, 2070, 2070, 2070,
+ /*   400 */  2070, 2070, 2070, 2070, 2070, 2070, 2070, 2070, 2070,  207,
+ /*   410 */   915, 1010, 1030, 1217,  910, 1170, 1470, 1368, 1481, 1442,
+ /*   420 */  1318, 1383, 1515, 1482, 1523, 1542, 1546, 1547, 1588, 1595,
+ /*   430 */  1502, 1338, 1566, 1493, 1520, 1521, 1598, 1617, 1568, 1618,
+ /*   440 */  1511, 1514, 1645, 1649, 1570, 1484, 1910, 1915, 1897, 1757,
+ /*   450 */  1908, 1909, 1901, 1903, 1788, 1778, 1798, 1911, 1911, 1913,
+ /*   460 */  1793, 1918, 1795, 1924, 1940, 1800, 1814, 1911, 1815, 1882,
+ /*   470 */  1912, 1911, 1796, 1895, 1898, 1900, 1902, 1824, 1840, 1923,
+ /*   480 */  1818, 1957, 1955, 1939, 1847, 1803, 1899, 1938, 1904, 1890,
+ /*   490 */  1925, 1827, 1854, 1946, 1951, 1954, 1843, 1850, 1956, 1914,
+ /*   500 */  1958, 1960, 1953, 1961, 1917, 1920, 1962, 1881, 1959, 1963,
+ /*   510 */  1921, 1952, 1967, 1842, 1970, 1971, 1972, 1973, 1968, 1974,
+ /*   520 */  1976, 1905, 1858, 1977, 1978, 1887, 1975, 1982, 1862, 1981,
+ /*   530 */  1979, 1980, 1983, 1984, 1919, 1933, 1926, 1966, 1936, 1922,
+ /*   540 */  1985, 1993, 1998, 1997, 1999, 2000, 1988, 2003, 1981, 2004,
+ /*   550 */  2005, 2006, 2007, 2008, 2009, 2001, 2020, 2012, 2013, 2014,
+ /*   560 */  2015, 2017, 2018, 2011, 1906, 1907, 1916, 1927, 1928, 2019,
+ /*   570 */  2022, 2027, 2042, 2045,
 };
-#define YY_REDUCE_COUNT (405)
-#define YY_REDUCE_MIN   (-265)
-#define YY_REDUCE_MAX   (1690)
+#define YY_REDUCE_COUNT (408)
+#define YY_REDUCE_MIN   (-267)
+#define YY_REDUCE_MAX   (1715)
 static const short yy_reduce_ofst[] = {
- /*     0 */   111,  168,  386,  761, -176, -174, -191, -189, -181, -178,
- /*    10 */   176,  263,   44, -207, -204, -265, -139, -114,  158,  504,
- /*    20 */   525,  544,  612,  614,  650,  652,  765,  265,  703,  705,
- /*    30 */    70,  714, -187,  127,  774,  713,  767,  769,  970, 1019,
- /*    40 */  1021, -255, -255, -255, -255, -255, -255, -255, -255, -255,
- /*    50 */  -255, -255, -255, -255, -255, -255, -255, -255, -255, -255,
- /*    60 */  -255, -255, -255, -255, -255, -255, -255, -255, -255, -255,
- /*    70 */  -255, -255, -255, -255, -255, -255, -255, -255,  394,  542,
- /*    80 */   816,  818,  842,  882,  902,  919,  938,  940,  957,  986,
- /*    90 */  1048, 1063, 1068, 1073, 1076, 1088, 1100, 1102, 1104, 1106,
- /*   100 */  1113, 1119, 1137, 1140, 1143, 1147, 1149, 1164, 1173, 1183,
- /*   110 */  1185, 1188, 1202, 1204, 1247, 1259, 1263, 1283, 1289, 1292,
- /*   120 */  1298, 1300, 1329, 1331, 1343, 1358, 1360, -255, -255, -255,
- /*   130 */  -255, -255, -255, -255, -255,  196, -255,  387, -177,  507,
- /*   140 */  1002, -219,  557,  -93, -167,  638, -121,  284,  500,  284,
- /*   150 */   500,  247,  651,  865, -255, -255, -255, -255,  -85,  -85,
- /*   160 */   -85,  237,  171,  602,  846,  885, -212, -203,  217,  380,
- /*   170 */   380,  -23,  161,  653,  712,  773,  943,  990, 1040,  563,
- /*   180 */   833,  971, 1005, 1042, 1092, 1078, 1043, 1144, 1184, -186,
- /*   190 */  1105,  318,  869,    7,  825,  920, 1074,  704,  706,  390,
- /*   200 */  1087, 1094,  336,  545,  772, 1201, 1117, 1207, -179, -137,
- /*   210 */  -112,  -13,   18,  112,  197,  418,  495,  508,  777,  809,
- /*   220 */   923, 1014, 1027, 1033, 1044, 1115, 1194, 1212, 1221,  209,
- /*   230 */  1236, 1240, 1256, 1287, 1301, 1307, 1349, 1359, 1398, 1417,
- /*   240 */  1429, 1434,  681, 1377, 1404, 1448, 1449, 1450, 1388, 1453,
- /*   250 */  1455, 1458, 1393, 1335, 1461, 1462, 1418, 1463,  197, 1464,
- /*   260 */  1465, 1466, 1467, 1468, 1469, 1376, 1378, 1424, 1412, 1413,
- /*   270 */  1414, 1415, 1388, 1424, 1424, 1428, 1470, 1485, 1381, 1408,
- /*   280 */  1416, 1436, 1431, 1422, 1432, 1392, 1446, 1411, 1427, 1456,
- /*   290 */  1433, 1471, 1401, 1479, 1472, 1478, 1486, 1491, 1493, 1452,
- /*   300 */  1459, 1473, 1437, 1475, 1476, 1516, 1421, 1440, 1520, 1524,
- /*   310 */  1444, 1445, 1525, 1457, 1480, 1481, 1509, 1510, 1511, 1512,
- /*   320 */  1513, 1553, 1555, 1515, 1487, 1488, 1518, 1495, 1522, 1523,
- /*   330 */  1528, 1527, 1562, 1566, 1482, 1494, 1569, 1574, 1559, 1575,
- /*   340 */  1582, 1583, 1585, 1560, 1568, 1570, 1571, 1563, 1573, 1586,
- /*   350 */  1584, 1588, 1589, 1593, 1590, 1594, 1598, 1501, 1496, 1536,
- /*   360 */  1537, 1599, 1561, 1567, 1587, 1591, 1592, 1597, 1604, 1607,
- /*   370 */  1629, 1519, 1521, 1601, 1609, 1600, 1610, 1558, 1636, 1565,
- /*   380 */  1618, 1621, 1611, 1624, 1648, 1652, 1676, 1677, 1687, 1688,
- /*   390 */  1689, 1613, 1614, 1615, 1668, 1663, 1665, 1666, 1670, 1678,
- /*   400 */  1655, 1662, 1672, 1673, 1675, 1690,
+ /*     0 */  -125,  733,  789,  241,  293, -123, -193, -191, -183, -187,
+ /*    10 */  -180,   83,  133, -207, -198, -267, -175,   -6,  166,  313,
+ /*    20 */   487,  396,  489,  598,  615,  685,  687,   79,  781,  857,
+ /*    30 */   490,  616,  240,  334, -188,  796,  841,  843, 1003, 1005,
+ /*    40 */  1007, -260, -260, -260, -260, -260, -260, -260, -260, -260,
+ /*    50 */  -260, -260, -260, -260, -260, -260, -260, -260, -260, -260,
+ /*    60 */  -260, -260, -260, -260, -260, -260, -260, -260, -260, -260,
+ /*    70 */  -260, -260, -260, -260, -260, -260, -260, -260,  158,  203,
+ /*    80 */   391,  576,  724,  726,  886, 1021, 1035, 1063, 1081, 1083,
+ /*    90 */  1097, 1099, 1117, 1152, 1155, 1158, 1163, 1165, 1167, 1169,
+ /*   100 */  1172, 1180, 1183, 1198, 1200, 1205, 1215, 1225, 1227, 1236,
+ /*   110 */  1252, 1264, 1299, 1303, 1306, 1309, 1312, 1315, 1325, 1328,
+ /*   120 */  1337, 1340, 1343, 1371, 1373, 1384, 1386, 1411, -260, -260,
+ /*   130 */  -260, -260, -260, -260, -260, -260, -260,  -53,  138,  302,
+ /*   140 */  -158,  357,  223, -222,  411,  458,  -92,  556,  669,  581,
+ /*   150 */   632,  581, -260,  632,  758,  778,  920, -260, -260, -260,
+ /*   160 */  -260,  161,  161,  161,  307,  234,  392,  526,  790,  195,
+ /*   170 */   359, -174, -173,  362,  362, -189,   16,  560,  567,  261,
+ /*   180 */   689,  802,  853, -122, -166,  408,  335,  617,  690,  837,
+ /*   190 */  1001,  746, 1061,  515, 1082,  994, 1034, -135, 1000, 1048,
+ /*   200 */  1137,  877,  897,  186,  627, 1031, 1133, 1148, 1159, 1194,
+ /*   210 */  1199, 1195, -194, -142,   18, -152,   68,  201,  253,  269,
+ /*   220 */   294,  354,  521,  528,  676,  680,  736,  743,  850,  907,
+ /*   230 */  1041, 1047, 1060,  727, 1139, 1147, 1201, 1237, 1278, 1359,
+ /*   240 */  1393, 1400, 1413, 1429, 1433, 1437, 1126, 1410, 1430, 1444,
+ /*   250 */  1480, 1483, 1405, 1486, 1490, 1492, 1420, 1372, 1496, 1498,
+ /*   260 */  1441, 1499,  253, 1500, 1503, 1504, 1506, 1507, 1508, 1398,
+ /*   270 */  1415, 1453, 1448, 1449, 1450, 1452, 1405, 1453, 1453, 1465,
+ /*   280 */  1495, 1519, 1414, 1443, 1445, 1468, 1456, 1455, 1457, 1424,
+ /*   290 */  1473, 1454, 1459, 1474, 1460, 1479, 1434, 1512, 1494, 1509,
+ /*   300 */  1517, 1518, 1525, 1469, 1489, 1501, 1467, 1510, 1497, 1543,
+ /*   310 */  1451, 1462, 1557, 1558, 1471, 1472, 1561, 1487, 1505, 1524,
+ /*   320 */  1538, 1537, 1545, 1548, 1556, 1575, 1596, 1552, 1529, 1530,
+ /*   330 */  1559, 1533, 1572, 1562, 1573, 1563, 1604, 1615, 1522, 1532,
+ /*   340 */  1622, 1624, 1605, 1625, 1628, 1629, 1631, 1607, 1616, 1619,
+ /*   350 */  1620, 1606, 1621, 1623, 1630, 1626, 1632, 1636, 1633, 1637,
+ /*   360 */  1638, 1531, 1541, 1567, 1571, 1640, 1597, 1599, 1601, 1603,
+ /*   370 */  1608, 1610, 1611, 1627, 1664, 1549, 1550, 1609, 1634, 1639,
+ /*   380 */  1641, 1602, 1676, 1642, 1646, 1644, 1650, 1654, 1683, 1694,
+ /*   390 */  1707, 1711, 1712, 1714, 1643, 1647, 1652, 1698, 1695, 1696,
+ /*   400 */  1697, 1699, 1700, 1689, 1691, 1701, 1702, 1704, 1715,
 };
 static const YYACTIONTYPE yy_default[] = {
- /*     0 */  1623, 1623, 1623, 1453, 1223, 1332, 1223, 1223, 1223, 1453,
- /*    10 */  1453, 1453, 1223, 1362, 1362, 1506, 1254, 1223, 1223, 1223,
- /*    20 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1452, 1223, 1223,
- /*    30 */  1223, 1223, 1541, 1541, 1223, 1223, 1223, 1223, 1223, 1223,
- /*    40 */  1223, 1223, 1371, 1223, 1378, 1223, 1223, 1223, 1223, 1223,
- /*    50 */  1454, 1455, 1223, 1223, 1223, 1505, 1507, 1470, 1385, 1384,
- /*    60 */  1383, 1382, 1488, 1349, 1376, 1369, 1373, 1448, 1449, 1447,
- /*    70 */  1451, 1455, 1454, 1223, 1372, 1419, 1433, 1418, 1223, 1223,
- /*    80 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*    90 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   100 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   110 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   120 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1427, 1432, 1438,
- /*   130 */  1431, 1428, 1421, 1420, 1422, 1223, 1423, 1223, 1223, 1223,
- /*   140 */  1244, 1296, 1223, 1223, 1223, 1223, 1223, 1525, 1524, 1223,
- /*   150 */  1223, 1254, 1413, 1412, 1424, 1425, 1435, 1434, 1513, 1576,
- /*   160 */  1575, 1471, 1223, 1223, 1223, 1223, 1223, 1223, 1541, 1223,
- /*   170 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   180 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   190 */  1223, 1541, 1541, 1223, 1254, 1541, 1541, 1250, 1250, 1356,
- /*   200 */  1223, 1520, 1323, 1323, 1323, 1323, 1332, 1323, 1223, 1223,
- /*   210 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   220 */  1223, 1223, 1223, 1510, 1508, 1223, 1223, 1223, 1223, 1223,
- /*   230 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   240 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   250 */  1223, 1223, 1328, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   260 */  1223, 1223, 1223, 1223, 1570, 1223, 1483, 1310, 1328, 1328,
- /*   270 */  1328, 1328, 1330, 1311, 1309, 1322, 1255, 1230, 1615, 1388,
- /*   280 */  1377, 1329, 1351, 1377, 1351, 1612, 1375, 1388, 1388, 1375,
- /*   290 */  1388, 1329, 1612, 1271, 1592, 1266, 1362, 1362, 1362, 1351,
- /*   300 */  1356, 1356, 1450, 1329, 1322, 1223, 1615, 1615, 1337, 1337,
- /*   310 */  1614, 1614, 1337, 1471, 1599, 1397, 1299, 1305, 1305, 1305,
- /*   320 */  1305, 1337, 1241, 1375, 1599, 1599, 1375, 1397, 1299, 1375,
- /*   330 */  1299, 1375, 1337, 1241, 1487, 1609, 1337, 1241, 1461, 1337,
- /*   340 */  1241, 1337, 1241, 1461, 1297, 1297, 1297, 1286, 1223, 1223,
- /*   350 */  1461, 1297, 1271, 1297, 1286, 1297, 1297, 1559, 1223, 1465,
- /*   360 */  1465, 1461, 1355, 1350, 1355, 1350, 1355, 1350, 1355, 1350,
- /*   370 */  1337, 1551, 1551, 1365, 1365, 1370, 1356, 1456, 1337, 1223,
- /*   380 */  1370, 1368, 1366, 1375, 1247, 1289, 1573, 1573, 1569, 1569,
- /*   390 */  1569, 1620, 1620, 1520, 1585, 1254, 1254, 1254, 1254, 1585,
- /*   400 */  1273, 1273, 1255, 1255, 1254, 1585, 1223, 1223, 1223, 1223,
- /*   410 */  1223, 1223, 1580, 1223, 1515, 1472, 1341, 1223, 1223, 1223,
- /*   420 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   430 */  1223, 1526, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   440 */  1223, 1223, 1402, 1223, 1226, 1517, 1223, 1223, 1223, 1223,
- /*   450 */  1223, 1223, 1223, 1223, 1379, 1380, 1342, 1223, 1223, 1223,
- /*   460 */  1223, 1223, 1223, 1223, 1394, 1223, 1223, 1223, 1389, 1223,
- /*   470 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1611, 1223, 1223,
- /*   480 */  1223, 1223, 1223, 1223, 1486, 1485, 1223, 1223, 1339, 1223,
- /*   490 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   500 */  1223, 1223, 1269, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   510 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   520 */  1223, 1223, 1223, 1223, 1223, 1223, 1367, 1223, 1223, 1223,
- /*   530 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   540 */  1223, 1556, 1357, 1223, 1223, 1602, 1223, 1223, 1223, 1223,
- /*   550 */  1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223,
- /*   560 */  1596, 1313, 1404, 1223, 1403, 1407, 1223, 1235, 1223, 1223,
+ /*     0 */  1637, 1637, 1637, 1466, 1233, 1344, 1233, 1233, 1233, 1466,
+ /*    10 */  1466, 1466, 1233, 1374, 1374, 1519, 1266, 1233, 1233, 1233,
+ /*    20 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1465, 1233, 1233,
+ /*    30 */  1233, 1233, 1554, 1554, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*    40 */  1233, 1233, 1383, 1233, 1390, 1233, 1233, 1233, 1233, 1233,
+ /*    50 */  1467, 1468, 1233, 1233, 1233, 1518, 1520, 1483, 1397, 1396,
+ /*    60 */  1395, 1394, 1501, 1361, 1388, 1381, 1385, 1461, 1462, 1460,
+ /*    70 */  1464, 1468, 1467, 1233, 1384, 1431, 1445, 1430, 1233, 1233,
+ /*    80 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*    90 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   100 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   110 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   120 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1439, 1444,
+ /*   130 */  1451, 1443, 1440, 1433, 1432, 1434, 1435, 1233, 1233, 1257,
+ /*   140 */  1233, 1233, 1254, 1308, 1233, 1233, 1233, 1233, 1233, 1538,
+ /*   150 */  1537, 1233, 1436, 1233, 1266, 1425, 1424, 1448, 1437, 1447,
+ /*   160 */  1446, 1526, 1590, 1589, 1484, 1233, 1233, 1233, 1233, 1233,
+ /*   170 */  1233, 1554, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   180 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   190 */  1233, 1233, 1233, 1233, 1233, 1554, 1554, 1233, 1266, 1554,
+ /*   200 */  1554, 1262, 1262, 1368, 1233, 1533, 1335, 1335, 1335, 1335,
+ /*   210 */  1344, 1335, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   220 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1523, 1521, 1233,
+ /*   230 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   240 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   250 */  1233, 1233, 1233, 1233, 1233, 1233, 1340, 1233, 1233, 1233,
+ /*   260 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1583, 1233,
+ /*   270 */  1496, 1322, 1340, 1340, 1340, 1340, 1342, 1323, 1321, 1334,
+ /*   280 */  1267, 1240, 1629, 1400, 1389, 1341, 1363, 1389, 1363, 1626,
+ /*   290 */  1387, 1400, 1400, 1387, 1400, 1341, 1626, 1283, 1606, 1278,
+ /*   300 */  1374, 1374, 1374, 1363, 1368, 1368, 1463, 1341, 1334, 1233,
+ /*   310 */  1629, 1629, 1349, 1349, 1628, 1628, 1349, 1484, 1613, 1409,
+ /*   320 */  1311, 1317, 1317, 1317, 1317, 1349, 1251, 1387, 1613, 1613,
+ /*   330 */  1387, 1409, 1311, 1387, 1311, 1387, 1349, 1251, 1500, 1623,
+ /*   340 */  1349, 1251, 1474, 1349, 1251, 1349, 1251, 1474, 1309, 1309,
+ /*   350 */  1309, 1298, 1233, 1233, 1474, 1309, 1283, 1309, 1298, 1309,
+ /*   360 */  1309, 1572, 1233, 1478, 1478, 1474, 1367, 1362, 1367, 1362,
+ /*   370 */  1367, 1362, 1367, 1362, 1349, 1564, 1564, 1377, 1377, 1382,
+ /*   380 */  1368, 1469, 1349, 1233, 1382, 1380, 1378, 1387, 1301, 1586,
+ /*   390 */  1586, 1582, 1582, 1582, 1634, 1634, 1533, 1599, 1266, 1266,
+ /*   400 */  1266, 1266, 1599, 1285, 1285, 1267, 1267, 1266, 1599, 1233,
+ /*   410 */  1233, 1233, 1233, 1233, 1233, 1594, 1233, 1528, 1485, 1353,
+ /*   420 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   430 */  1233, 1233, 1233, 1233, 1539, 1233, 1233, 1233, 1233, 1233,
+ /*   440 */  1233, 1233, 1233, 1233, 1233, 1414, 1233, 1236, 1530, 1233,
+ /*   450 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1391, 1392, 1354,
+ /*   460 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1406, 1233, 1233,
+ /*   470 */  1233, 1401, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   480 */  1625, 1233, 1233, 1233, 1233, 1233, 1233, 1499, 1498, 1233,
+ /*   490 */  1233, 1351, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   500 */  1233, 1233, 1233, 1233, 1233, 1281, 1233, 1233, 1233, 1233,
+ /*   510 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   520 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1379,
+ /*   530 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   540 */  1233, 1233, 1233, 1233, 1569, 1369, 1233, 1233, 1616, 1233,
+ /*   550 */  1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233,
+ /*   560 */  1233, 1233, 1233, 1610, 1325, 1416, 1233, 1415, 1419, 1255,
+ /*   570 */  1233, 1245, 1233, 1233,
 };
 /********** End of lemon-generated parsing tables *****************************/
 
@@ -158203,8 +162641,8 @@ static const YYCODETYPE yyFallback[] = {
     0,  /*         LP => nothing */
     0,  /*         RP => nothing */
     0,  /*         AS => nothing */
-   59,  /*    WITHOUT => ID */
     0,  /*      COMMA => nothing */
+   59,  /*    WITHOUT => ID */
    59,  /*      ABORT => ID */
    59,  /*     ACTION => ID */
    59,  /*      AFTER => ID */
@@ -158290,6 +162728,7 @@ static const YYCODETYPE yyFallback[] = {
     0,  /*      SLASH => nothing */
     0,  /*        REM => nothing */
     0,  /*     CONCAT => nothing */
+    0,  /*        PTR => nothing */
     0,  /*    COLLATE => nothing */
     0,  /*     BITNOT => nothing */
     0,  /*         ON => nothing */
@@ -158359,6 +162798,7 @@ static const YYCODETYPE yyFallback[] = {
     0,  /* IF_NULL_ROW => nothing */
     0,  /*   ASTERISK => nothing */
     0,  /*       SPAN => nothing */
+    0,  /*      ERROR => nothing */
     0,  /*      SPACE => nothing */
     0,  /*    ILLEGAL => nothing */
 };
@@ -158412,9 +162852,9 @@ struct yyParser {
 };
 typedef struct yyParser yyParser;
 
+/* #include <assert.h> */
 #ifndef NDEBUG
 /* #include <stdio.h> */
-/* #include <assert.h> */
 static FILE *yyTraceFILE = 0;
 static char *yyTracePrompt = 0;
 #endif /* NDEBUG */
@@ -158474,8 +162914,8 @@ static const char *const yyTokenName[] = {
   /*   22 */ "LP",
   /*   23 */ "RP",
   /*   24 */ "AS",
-  /*   25 */ "WITHOUT",
-  /*   26 */ "COMMA",
+  /*   25 */ "COMMA",
+  /*   26 */ "WITHOUT",
   /*   27 */ "ABORT",
   /*   28 */ "ACTION",
   /*   29 */ "AFTER",
@@ -158561,210 +163001,213 @@ static const char *const yyTokenName[] = {
   /*  109 */ "SLASH",
   /*  110 */ "REM",
   /*  111 */ "CONCAT",
-  /*  112 */ "COLLATE",
-  /*  113 */ "BITNOT",
-  /*  114 */ "ON",
-  /*  115 */ "INDEXED",
-  /*  116 */ "STRING",
-  /*  117 */ "JOIN_KW",
-  /*  118 */ "CONSTRAINT",
-  /*  119 */ "DEFAULT",
-  /*  120 */ "NULL",
-  /*  121 */ "PRIMARY",
-  /*  122 */ "UNIQUE",
-  /*  123 */ "CHECK",
-  /*  124 */ "REFERENCES",
-  /*  125 */ "AUTOINCR",
-  /*  126 */ "INSERT",
-  /*  127 */ "DELETE",
-  /*  128 */ "UPDATE",
-  /*  129 */ "SET",
-  /*  130 */ "DEFERRABLE",
-  /*  131 */ "FOREIGN",
-  /*  132 */ "DROP",
-  /*  133 */ "UNION",
-  /*  134 */ "ALL",
-  /*  135 */ "EXCEPT",
-  /*  136 */ "INTERSECT",
-  /*  137 */ "SELECT",
-  /*  138 */ "VALUES",
-  /*  139 */ "DISTINCT",
-  /*  140 */ "DOT",
-  /*  141 */ "FROM",
-  /*  142 */ "JOIN",
-  /*  143 */ "USING",
-  /*  144 */ "ORDER",
-  /*  145 */ "GROUP",
-  /*  146 */ "HAVING",
-  /*  147 */ "LIMIT",
-  /*  148 */ "WHERE",
-  /*  149 */ "RETURNING",
-  /*  150 */ "INTO",
-  /*  151 */ "NOTHING",
-  /*  152 */ "FLOAT",
-  /*  153 */ "BLOB",
-  /*  154 */ "INTEGER",
-  /*  155 */ "VARIABLE",
-  /*  156 */ "CASE",
-  /*  157 */ "WHEN",
-  /*  158 */ "THEN",
-  /*  159 */ "ELSE",
-  /*  160 */ "INDEX",
-  /*  161 */ "ALTER",
-  /*  162 */ "ADD",
-  /*  163 */ "WINDOW",
-  /*  164 */ "OVER",
-  /*  165 */ "FILTER",
-  /*  166 */ "COLUMN",
-  /*  167 */ "AGG_FUNCTION",
-  /*  168 */ "AGG_COLUMN",
-  /*  169 */ "TRUEFALSE",
-  /*  170 */ "ISNOT",
-  /*  171 */ "FUNCTION",
-  /*  172 */ "UMINUS",
-  /*  173 */ "UPLUS",
-  /*  174 */ "TRUTH",
-  /*  175 */ "REGISTER",
-  /*  176 */ "VECTOR",
-  /*  177 */ "SELECT_COLUMN",
-  /*  178 */ "IF_NULL_ROW",
-  /*  179 */ "ASTERISK",
-  /*  180 */ "SPAN",
-  /*  181 */ "SPACE",
-  /*  182 */ "ILLEGAL",
-  /*  183 */ "input",
-  /*  184 */ "cmdlist",
-  /*  185 */ "ecmd",
-  /*  186 */ "cmdx",
-  /*  187 */ "explain",
-  /*  188 */ "cmd",
-  /*  189 */ "transtype",
-  /*  190 */ "trans_opt",
-  /*  191 */ "nm",
-  /*  192 */ "savepoint_opt",
-  /*  193 */ "create_table",
-  /*  194 */ "create_table_args",
-  /*  195 */ "createkw",
-  /*  196 */ "temp",
-  /*  197 */ "ifnotexists",
-  /*  198 */ "dbnm",
-  /*  199 */ "columnlist",
-  /*  200 */ "conslist_opt",
-  /*  201 */ "table_options",
-  /*  202 */ "select",
-  /*  203 */ "columnname",
-  /*  204 */ "carglist",
-  /*  205 */ "typetoken",
-  /*  206 */ "typename",
-  /*  207 */ "signed",
-  /*  208 */ "plus_num",
-  /*  209 */ "minus_num",
-  /*  210 */ "scanpt",
-  /*  211 */ "scantok",
-  /*  212 */ "ccons",
-  /*  213 */ "term",
-  /*  214 */ "expr",
-  /*  215 */ "onconf",
-  /*  216 */ "sortorder",
-  /*  217 */ "autoinc",
-  /*  218 */ "eidlist_opt",
-  /*  219 */ "refargs",
-  /*  220 */ "defer_subclause",
-  /*  221 */ "generated",
-  /*  222 */ "refarg",
-  /*  223 */ "refact",
-  /*  224 */ "init_deferred_pred_opt",
-  /*  225 */ "conslist",
-  /*  226 */ "tconscomma",
-  /*  227 */ "tcons",
-  /*  228 */ "sortlist",
-  /*  229 */ "eidlist",
-  /*  230 */ "defer_subclause_opt",
-  /*  231 */ "orconf",
-  /*  232 */ "resolvetype",
-  /*  233 */ "raisetype",
-  /*  234 */ "ifexists",
-  /*  235 */ "fullname",
-  /*  236 */ "selectnowith",
-  /*  237 */ "oneselect",
-  /*  238 */ "wqlist",
-  /*  239 */ "multiselect_op",
-  /*  240 */ "distinct",
-  /*  241 */ "selcollist",
-  /*  242 */ "from",
-  /*  243 */ "where_opt",
-  /*  244 */ "groupby_opt",
-  /*  245 */ "having_opt",
-  /*  246 */ "orderby_opt",
-  /*  247 */ "limit_opt",
-  /*  248 */ "window_clause",
-  /*  249 */ "values",
-  /*  250 */ "nexprlist",
-  /*  251 */ "sclp",
-  /*  252 */ "as",
-  /*  253 */ "seltablist",
-  /*  254 */ "stl_prefix",
-  /*  255 */ "joinop",
-  /*  256 */ "indexed_opt",
-  /*  257 */ "on_opt",
-  /*  258 */ "using_opt",
-  /*  259 */ "exprlist",
-  /*  260 */ "xfullname",
-  /*  261 */ "idlist",
-  /*  262 */ "nulls",
-  /*  263 */ "with",
-  /*  264 */ "where_opt_ret",
-  /*  265 */ "setlist",
-  /*  266 */ "insert_cmd",
-  /*  267 */ "idlist_opt",
-  /*  268 */ "upsert",
-  /*  269 */ "returning",
-  /*  270 */ "filter_over",
-  /*  271 */ "likeop",
-  /*  272 */ "between_op",
-  /*  273 */ "in_op",
-  /*  274 */ "paren_exprlist",
-  /*  275 */ "case_operand",
-  /*  276 */ "case_exprlist",
-  /*  277 */ "case_else",
-  /*  278 */ "uniqueflag",
-  /*  279 */ "collate",
-  /*  280 */ "vinto",
-  /*  281 */ "nmnum",
-  /*  282 */ "trigger_decl",
-  /*  283 */ "trigger_cmd_list",
-  /*  284 */ "trigger_time",
-  /*  285 */ "trigger_event",
-  /*  286 */ "foreach_clause",
-  /*  287 */ "when_clause",
-  /*  288 */ "trigger_cmd",
-  /*  289 */ "trnm",
-  /*  290 */ "tridxby",
-  /*  291 */ "database_kw_opt",
-  /*  292 */ "key_opt",
-  /*  293 */ "add_column_fullname",
-  /*  294 */ "kwcolumn_opt",
-  /*  295 */ "create_vtab",
-  /*  296 */ "vtabarglist",
-  /*  297 */ "vtabarg",
-  /*  298 */ "vtabargtoken",
-  /*  299 */ "lp",
-  /*  300 */ "anylist",
-  /*  301 */ "wqitem",
-  /*  302 */ "wqas",
-  /*  303 */ "windowdefn_list",
-  /*  304 */ "windowdefn",
-  /*  305 */ "window",
-  /*  306 */ "frame_opt",
-  /*  307 */ "part_opt",
-  /*  308 */ "filter_clause",
-  /*  309 */ "over_clause",
-  /*  310 */ "range_or_rows",
-  /*  311 */ "frame_bound",
-  /*  312 */ "frame_bound_s",
-  /*  313 */ "frame_bound_e",
-  /*  314 */ "frame_exclude_opt",
-  /*  315 */ "frame_exclude",
+  /*  112 */ "PTR",
+  /*  113 */ "COLLATE",
+  /*  114 */ "BITNOT",
+  /*  115 */ "ON",
+  /*  116 */ "INDEXED",
+  /*  117 */ "STRING",
+  /*  118 */ "JOIN_KW",
+  /*  119 */ "CONSTRAINT",
+  /*  120 */ "DEFAULT",
+  /*  121 */ "NULL",
+  /*  122 */ "PRIMARY",
+  /*  123 */ "UNIQUE",
+  /*  124 */ "CHECK",
+  /*  125 */ "REFERENCES",
+  /*  126 */ "AUTOINCR",
+  /*  127 */ "INSERT",
+  /*  128 */ "DELETE",
+  /*  129 */ "UPDATE",
+  /*  130 */ "SET",
+  /*  131 */ "DEFERRABLE",
+  /*  132 */ "FOREIGN",
+  /*  133 */ "DROP",
+  /*  134 */ "UNION",
+  /*  135 */ "ALL",
+  /*  136 */ "EXCEPT",
+  /*  137 */ "INTERSECT",
+  /*  138 */ "SELECT",
+  /*  139 */ "VALUES",
+  /*  140 */ "DISTINCT",
+  /*  141 */ "DOT",
+  /*  142 */ "FROM",
+  /*  143 */ "JOIN",
+  /*  144 */ "USING",
+  /*  145 */ "ORDER",
+  /*  146 */ "GROUP",
+  /*  147 */ "HAVING",
+  /*  148 */ "LIMIT",
+  /*  149 */ "WHERE",
+  /*  150 */ "RETURNING",
+  /*  151 */ "INTO",
+  /*  152 */ "NOTHING",
+  /*  153 */ "FLOAT",
+  /*  154 */ "BLOB",
+  /*  155 */ "INTEGER",
+  /*  156 */ "VARIABLE",
+  /*  157 */ "CASE",
+  /*  158 */ "WHEN",
+  /*  159 */ "THEN",
+  /*  160 */ "ELSE",
+  /*  161 */ "INDEX",
+  /*  162 */ "ALTER",
+  /*  163 */ "ADD",
+  /*  164 */ "WINDOW",
+  /*  165 */ "OVER",
+  /*  166 */ "FILTER",
+  /*  167 */ "COLUMN",
+  /*  168 */ "AGG_FUNCTION",
+  /*  169 */ "AGG_COLUMN",
+  /*  170 */ "TRUEFALSE",
+  /*  171 */ "ISNOT",
+  /*  172 */ "FUNCTION",
+  /*  173 */ "UMINUS",
+  /*  174 */ "UPLUS",
+  /*  175 */ "TRUTH",
+  /*  176 */ "REGISTER",
+  /*  177 */ "VECTOR",
+  /*  178 */ "SELECT_COLUMN",
+  /*  179 */ "IF_NULL_ROW",
+  /*  180 */ "ASTERISK",
+  /*  181 */ "SPAN",
+  /*  182 */ "ERROR",
+  /*  183 */ "SPACE",
+  /*  184 */ "ILLEGAL",
+  /*  185 */ "input",
+  /*  186 */ "cmdlist",
+  /*  187 */ "ecmd",
+  /*  188 */ "cmdx",
+  /*  189 */ "explain",
+  /*  190 */ "cmd",
+  /*  191 */ "transtype",
+  /*  192 */ "trans_opt",
+  /*  193 */ "nm",
+  /*  194 */ "savepoint_opt",
+  /*  195 */ "create_table",
+  /*  196 */ "create_table_args",
+  /*  197 */ "createkw",
+  /*  198 */ "temp",
+  /*  199 */ "ifnotexists",
+  /*  200 */ "dbnm",
+  /*  201 */ "columnlist",
+  /*  202 */ "conslist_opt",
+  /*  203 */ "table_option_set",
+  /*  204 */ "select",
+  /*  205 */ "table_option",
+  /*  206 */ "columnname",
+  /*  207 */ "carglist",
+  /*  208 */ "typetoken",
+  /*  209 */ "typename",
+  /*  210 */ "signed",
+  /*  211 */ "plus_num",
+  /*  212 */ "minus_num",
+  /*  213 */ "scanpt",
+  /*  214 */ "scantok",
+  /*  215 */ "ccons",
+  /*  216 */ "term",
+  /*  217 */ "expr",
+  /*  218 */ "onconf",
+  /*  219 */ "sortorder",
+  /*  220 */ "autoinc",
+  /*  221 */ "eidlist_opt",
+  /*  222 */ "refargs",
+  /*  223 */ "defer_subclause",
+  /*  224 */ "generated",
+  /*  225 */ "refarg",
+  /*  226 */ "refact",
+  /*  227 */ "init_deferred_pred_opt",
+  /*  228 */ "conslist",
+  /*  229 */ "tconscomma",
+  /*  230 */ "tcons",
+  /*  231 */ "sortlist",
+  /*  232 */ "eidlist",
+  /*  233 */ "defer_subclause_opt",
+  /*  234 */ "orconf",
+  /*  235 */ "resolvetype",
+  /*  236 */ "raisetype",
+  /*  237 */ "ifexists",
+  /*  238 */ "fullname",
+  /*  239 */ "selectnowith",
+  /*  240 */ "oneselect",
+  /*  241 */ "wqlist",
+  /*  242 */ "multiselect_op",
+  /*  243 */ "distinct",
+  /*  244 */ "selcollist",
+  /*  245 */ "from",
+  /*  246 */ "where_opt",
+  /*  247 */ "groupby_opt",
+  /*  248 */ "having_opt",
+  /*  249 */ "orderby_opt",
+  /*  250 */ "limit_opt",
+  /*  251 */ "window_clause",
+  /*  252 */ "values",
+  /*  253 */ "nexprlist",
+  /*  254 */ "sclp",
+  /*  255 */ "as",
+  /*  256 */ "seltablist",
+  /*  257 */ "stl_prefix",
+  /*  258 */ "joinop",
+  /*  259 */ "indexed_opt",
+  /*  260 */ "on_opt",
+  /*  261 */ "using_opt",
+  /*  262 */ "exprlist",
+  /*  263 */ "xfullname",
+  /*  264 */ "idlist",
+  /*  265 */ "nulls",
+  /*  266 */ "with",
+  /*  267 */ "where_opt_ret",
+  /*  268 */ "setlist",
+  /*  269 */ "insert_cmd",
+  /*  270 */ "idlist_opt",
+  /*  271 */ "upsert",
+  /*  272 */ "returning",
+  /*  273 */ "filter_over",
+  /*  274 */ "likeop",
+  /*  275 */ "between_op",
+  /*  276 */ "in_op",
+  /*  277 */ "paren_exprlist",
+  /*  278 */ "case_operand",
+  /*  279 */ "case_exprlist",
+  /*  280 */ "case_else",
+  /*  281 */ "uniqueflag",
+  /*  282 */ "collate",
+  /*  283 */ "vinto",
+  /*  284 */ "nmnum",
+  /*  285 */ "trigger_decl",
+  /*  286 */ "trigger_cmd_list",
+  /*  287 */ "trigger_time",
+  /*  288 */ "trigger_event",
+  /*  289 */ "foreach_clause",
+  /*  290 */ "when_clause",
+  /*  291 */ "trigger_cmd",
+  /*  292 */ "trnm",
+  /*  293 */ "tridxby",
+  /*  294 */ "database_kw_opt",
+  /*  295 */ "key_opt",
+  /*  296 */ "add_column_fullname",
+  /*  297 */ "kwcolumn_opt",
+  /*  298 */ "create_vtab",
+  /*  299 */ "vtabarglist",
+  /*  300 */ "vtabarg",
+  /*  301 */ "vtabargtoken",
+  /*  302 */ "lp",
+  /*  303 */ "anylist",
+  /*  304 */ "wqitem",
+  /*  305 */ "wqas",
+  /*  306 */ "windowdefn_list",
+  /*  307 */ "windowdefn",
+  /*  308 */ "window",
+  /*  309 */ "frame_opt",
+  /*  310 */ "part_opt",
+  /*  311 */ "filter_clause",
+  /*  312 */ "over_clause",
+  /*  313 */ "range_or_rows",
+  /*  314 */ "frame_bound",
+  /*  315 */ "frame_bound_s",
+  /*  316 */ "frame_bound_e",
+  /*  317 */ "frame_exclude_opt",
+  /*  318 */ "frame_exclude",
 };
 #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
 
@@ -158791,385 +163234,389 @@ static const char *const yyRuleName[] = {
  /*  16 */ "ifnotexists ::= IF NOT EXISTS",
  /*  17 */ "temp ::= TEMP",
  /*  18 */ "temp ::=",
- /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
+ /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP table_option_set",
  /*  20 */ "create_table_args ::= AS select",
- /*  21 */ "table_options ::=",
- /*  22 */ "table_options ::= WITHOUT nm",
- /*  23 */ "columnname ::= nm typetoken",
- /*  24 */ "typetoken ::=",
- /*  25 */ "typetoken ::= typename LP signed RP",
- /*  26 */ "typetoken ::= typename LP signed COMMA signed RP",
- /*  27 */ "typename ::= typename ID|STRING",
- /*  28 */ "scanpt ::=",
- /*  29 */ "scantok ::=",
- /*  30 */ "ccons ::= CONSTRAINT nm",
- /*  31 */ "ccons ::= DEFAULT scantok term",
- /*  32 */ "ccons ::= DEFAULT LP expr RP",
- /*  33 */ "ccons ::= DEFAULT PLUS scantok term",
- /*  34 */ "ccons ::= DEFAULT MINUS scantok term",
- /*  35 */ "ccons ::= DEFAULT scantok ID|INDEXED",
- /*  36 */ "ccons ::= NOT NULL onconf",
- /*  37 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
- /*  38 */ "ccons ::= UNIQUE onconf",
- /*  39 */ "ccons ::= CHECK LP expr RP",
- /*  40 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
- /*  41 */ "ccons ::= defer_subclause",
- /*  42 */ "ccons ::= COLLATE ID|STRING",
- /*  43 */ "generated ::= LP expr RP",
- /*  44 */ "generated ::= LP expr RP ID",
- /*  45 */ "autoinc ::=",
- /*  46 */ "autoinc ::= AUTOINCR",
- /*  47 */ "refargs ::=",
- /*  48 */ "refargs ::= refargs refarg",
- /*  49 */ "refarg ::= MATCH nm",
- /*  50 */ "refarg ::= ON INSERT refact",
- /*  51 */ "refarg ::= ON DELETE refact",
- /*  52 */ "refarg ::= ON UPDATE refact",
- /*  53 */ "refact ::= SET NULL",
- /*  54 */ "refact ::= SET DEFAULT",
- /*  55 */ "refact ::= CASCADE",
- /*  56 */ "refact ::= RESTRICT",
- /*  57 */ "refact ::= NO ACTION",
- /*  58 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
- /*  59 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
- /*  60 */ "init_deferred_pred_opt ::=",
- /*  61 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
- /*  62 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
- /*  63 */ "conslist_opt ::=",
- /*  64 */ "tconscomma ::= COMMA",
- /*  65 */ "tcons ::= CONSTRAINT nm",
- /*  66 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
- /*  67 */ "tcons ::= UNIQUE LP sortlist RP onconf",
- /*  68 */ "tcons ::= CHECK LP expr RP onconf",
- /*  69 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
- /*  70 */ "defer_subclause_opt ::=",
- /*  71 */ "onconf ::=",
- /*  72 */ "onconf ::= ON CONFLICT resolvetype",
- /*  73 */ "orconf ::=",
- /*  74 */ "orconf ::= OR resolvetype",
- /*  75 */ "resolvetype ::= IGNORE",
- /*  76 */ "resolvetype ::= REPLACE",
- /*  77 */ "cmd ::= DROP TABLE ifexists fullname",
- /*  78 */ "ifexists ::= IF EXISTS",
- /*  79 */ "ifexists ::=",
- /*  80 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
- /*  81 */ "cmd ::= DROP VIEW ifexists fullname",
- /*  82 */ "cmd ::= select",
- /*  83 */ "select ::= WITH wqlist selectnowith",
- /*  84 */ "select ::= WITH RECURSIVE wqlist selectnowith",
- /*  85 */ "select ::= selectnowith",
- /*  86 */ "selectnowith ::= selectnowith multiselect_op oneselect",
- /*  87 */ "multiselect_op ::= UNION",
- /*  88 */ "multiselect_op ::= UNION ALL",
- /*  89 */ "multiselect_op ::= EXCEPT|INTERSECT",
- /*  90 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
- /*  91 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
- /*  92 */ "values ::= VALUES LP nexprlist RP",
- /*  93 */ "values ::= values COMMA LP nexprlist RP",
- /*  94 */ "distinct ::= DISTINCT",
- /*  95 */ "distinct ::= ALL",
- /*  96 */ "distinct ::=",
- /*  97 */ "sclp ::=",
- /*  98 */ "selcollist ::= sclp scanpt expr scanpt as",
- /*  99 */ "selcollist ::= sclp scanpt STAR",
- /* 100 */ "selcollist ::= sclp scanpt nm DOT STAR",
- /* 101 */ "as ::= AS nm",
- /* 102 */ "as ::=",
- /* 103 */ "from ::=",
- /* 104 */ "from ::= FROM seltablist",
- /* 105 */ "stl_prefix ::= seltablist joinop",
- /* 106 */ "stl_prefix ::=",
- /* 107 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
- /* 108 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
- /* 109 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
- /* 110 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
- /* 111 */ "dbnm ::=",
- /* 112 */ "dbnm ::= DOT nm",
- /* 113 */ "fullname ::= nm",
- /* 114 */ "fullname ::= nm DOT nm",
- /* 115 */ "xfullname ::= nm",
- /* 116 */ "xfullname ::= nm DOT nm",
- /* 117 */ "xfullname ::= nm DOT nm AS nm",
- /* 118 */ "xfullname ::= nm AS nm",
- /* 119 */ "joinop ::= COMMA|JOIN",
- /* 120 */ "joinop ::= JOIN_KW JOIN",
- /* 121 */ "joinop ::= JOIN_KW nm JOIN",
- /* 122 */ "joinop ::= JOIN_KW nm nm JOIN",
- /* 123 */ "on_opt ::= ON expr",
- /* 124 */ "on_opt ::=",
- /* 125 */ "indexed_opt ::=",
- /* 126 */ "indexed_opt ::= INDEXED BY nm",
- /* 127 */ "indexed_opt ::= NOT INDEXED",
- /* 128 */ "using_opt ::= USING LP idlist RP",
- /* 129 */ "using_opt ::=",
- /* 130 */ "orderby_opt ::=",
- /* 131 */ "orderby_opt ::= ORDER BY sortlist",
- /* 132 */ "sortlist ::= sortlist COMMA expr sortorder nulls",
- /* 133 */ "sortlist ::= expr sortorder nulls",
- /* 134 */ "sortorder ::= ASC",
- /* 135 */ "sortorder ::= DESC",
- /* 136 */ "sortorder ::=",
- /* 137 */ "nulls ::= NULLS FIRST",
- /* 138 */ "nulls ::= NULLS LAST",
- /* 139 */ "nulls ::=",
- /* 140 */ "groupby_opt ::=",
- /* 141 */ "groupby_opt ::= GROUP BY nexprlist",
- /* 142 */ "having_opt ::=",
- /* 143 */ "having_opt ::= HAVING expr",
- /* 144 */ "limit_opt ::=",
- /* 145 */ "limit_opt ::= LIMIT expr",
- /* 146 */ "limit_opt ::= LIMIT expr OFFSET expr",
- /* 147 */ "limit_opt ::= LIMIT expr COMMA expr",
- /* 148 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret",
- /* 149 */ "where_opt ::=",
- /* 150 */ "where_opt ::= WHERE expr",
- /* 151 */ "where_opt_ret ::=",
- /* 152 */ "where_opt_ret ::= WHERE expr",
- /* 153 */ "where_opt_ret ::= RETURNING selcollist",
- /* 154 */ "where_opt_ret ::= WHERE expr RETURNING selcollist",
- /* 155 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret",
- /* 156 */ "setlist ::= setlist COMMA nm EQ expr",
- /* 157 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
- /* 158 */ "setlist ::= nm EQ expr",
- /* 159 */ "setlist ::= LP idlist RP EQ expr",
- /* 160 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
- /* 161 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning",
- /* 162 */ "upsert ::=",
- /* 163 */ "upsert ::= RETURNING selcollist",
- /* 164 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert",
- /* 165 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert",
- /* 166 */ "upsert ::= ON CONFLICT DO NOTHING returning",
- /* 167 */ "upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning",
- /* 168 */ "returning ::= RETURNING selcollist",
- /* 169 */ "insert_cmd ::= INSERT orconf",
- /* 170 */ "insert_cmd ::= REPLACE",
- /* 171 */ "idlist_opt ::=",
- /* 172 */ "idlist_opt ::= LP idlist RP",
- /* 173 */ "idlist ::= idlist COMMA nm",
- /* 174 */ "idlist ::= nm",
- /* 175 */ "expr ::= LP expr RP",
- /* 176 */ "expr ::= ID|INDEXED",
- /* 177 */ "expr ::= JOIN_KW",
- /* 178 */ "expr ::= nm DOT nm",
- /* 179 */ "expr ::= nm DOT nm DOT nm",
- /* 180 */ "term ::= NULL|FLOAT|BLOB",
- /* 181 */ "term ::= STRING",
- /* 182 */ "term ::= INTEGER",
- /* 183 */ "expr ::= VARIABLE",
- /* 184 */ "expr ::= expr COLLATE ID|STRING",
- /* 185 */ "expr ::= CAST LP expr AS typetoken RP",
- /* 186 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
- /* 187 */ "expr ::= ID|INDEXED LP STAR RP",
- /* 188 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over",
- /* 189 */ "expr ::= ID|INDEXED LP STAR RP filter_over",
- /* 190 */ "term ::= CTIME_KW",
- /* 191 */ "expr ::= LP nexprlist COMMA expr RP",
- /* 192 */ "expr ::= expr AND expr",
- /* 193 */ "expr ::= expr OR expr",
- /* 194 */ "expr ::= expr LT|GT|GE|LE expr",
- /* 195 */ "expr ::= expr EQ|NE expr",
- /* 196 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
- /* 197 */ "expr ::= expr PLUS|MINUS expr",
- /* 198 */ "expr ::= expr STAR|SLASH|REM expr",
- /* 199 */ "expr ::= expr CONCAT expr",
- /* 200 */ "likeop ::= NOT LIKE_KW|MATCH",
- /* 201 */ "expr ::= expr likeop expr",
- /* 202 */ "expr ::= expr likeop expr ESCAPE expr",
- /* 203 */ "expr ::= expr ISNULL|NOTNULL",
- /* 204 */ "expr ::= expr NOT NULL",
- /* 205 */ "expr ::= expr IS expr",
- /* 206 */ "expr ::= expr IS NOT expr",
- /* 207 */ "expr ::= NOT expr",
- /* 208 */ "expr ::= BITNOT expr",
- /* 209 */ "expr ::= PLUS|MINUS expr",
- /* 210 */ "between_op ::= BETWEEN",
- /* 211 */ "between_op ::= NOT BETWEEN",
- /* 212 */ "expr ::= expr between_op expr AND expr",
- /* 213 */ "in_op ::= IN",
- /* 214 */ "in_op ::= NOT IN",
- /* 215 */ "expr ::= expr in_op LP exprlist RP",
- /* 216 */ "expr ::= LP select RP",
- /* 217 */ "expr ::= expr in_op LP select RP",
- /* 218 */ "expr ::= expr in_op nm dbnm paren_exprlist",
- /* 219 */ "expr ::= EXISTS LP select RP",
- /* 220 */ "expr ::= CASE case_operand case_exprlist case_else END",
- /* 221 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
- /* 222 */ "case_exprlist ::= WHEN expr THEN expr",
- /* 223 */ "case_else ::= ELSE expr",
- /* 224 */ "case_else ::=",
- /* 225 */ "case_operand ::= expr",
- /* 226 */ "case_operand ::=",
- /* 227 */ "exprlist ::=",
- /* 228 */ "nexprlist ::= nexprlist COMMA expr",
- /* 229 */ "nexprlist ::= expr",
- /* 230 */ "paren_exprlist ::=",
- /* 231 */ "paren_exprlist ::= LP exprlist RP",
- /* 232 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
- /* 233 */ "uniqueflag ::= UNIQUE",
- /* 234 */ "uniqueflag ::=",
- /* 235 */ "eidlist_opt ::=",
- /* 236 */ "eidlist_opt ::= LP eidlist RP",
- /* 237 */ "eidlist ::= eidlist COMMA nm collate sortorder",
- /* 238 */ "eidlist ::= nm collate sortorder",
- /* 239 */ "collate ::=",
- /* 240 */ "collate ::= COLLATE ID|STRING",
- /* 241 */ "cmd ::= DROP INDEX ifexists fullname",
- /* 242 */ "cmd ::= VACUUM vinto",
- /* 243 */ "cmd ::= VACUUM nm vinto",
- /* 244 */ "vinto ::= INTO expr",
- /* 245 */ "vinto ::=",
- /* 246 */ "cmd ::= PRAGMA nm dbnm",
- /* 247 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
- /* 248 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
- /* 249 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
- /* 250 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
- /* 251 */ "plus_num ::= PLUS INTEGER|FLOAT",
- /* 252 */ "minus_num ::= MINUS INTEGER|FLOAT",
- /* 253 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
- /* 254 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
- /* 255 */ "trigger_time ::= BEFORE|AFTER",
- /* 256 */ "trigger_time ::= INSTEAD OF",
- /* 257 */ "trigger_time ::=",
- /* 258 */ "trigger_event ::= DELETE|INSERT",
- /* 259 */ "trigger_event ::= UPDATE",
- /* 260 */ "trigger_event ::= UPDATE OF idlist",
- /* 261 */ "when_clause ::=",
- /* 262 */ "when_clause ::= WHEN expr",
- /* 263 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
- /* 264 */ "trigger_cmd_list ::= trigger_cmd SEMI",
- /* 265 */ "trnm ::= nm DOT nm",
- /* 266 */ "tridxby ::= INDEXED BY nm",
- /* 267 */ "tridxby ::= NOT INDEXED",
- /* 268 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
- /* 269 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
- /* 270 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
- /* 271 */ "trigger_cmd ::= scanpt select scanpt",
- /* 272 */ "expr ::= RAISE LP IGNORE RP",
- /* 273 */ "expr ::= RAISE LP raisetype COMMA nm RP",
- /* 274 */ "raisetype ::= ROLLBACK",
- /* 275 */ "raisetype ::= ABORT",
- /* 276 */ "raisetype ::= FAIL",
- /* 277 */ "cmd ::= DROP TRIGGER ifexists fullname",
- /* 278 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
- /* 279 */ "cmd ::= DETACH database_kw_opt expr",
- /* 280 */ "key_opt ::=",
- /* 281 */ "key_opt ::= KEY expr",
- /* 282 */ "cmd ::= REINDEX",
- /* 283 */ "cmd ::= REINDEX nm dbnm",
- /* 284 */ "cmd ::= ANALYZE",
- /* 285 */ "cmd ::= ANALYZE nm dbnm",
- /* 286 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
- /* 287 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
- /* 288 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm",
- /* 289 */ "add_column_fullname ::= fullname",
- /* 290 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
- /* 291 */ "cmd ::= create_vtab",
- /* 292 */ "cmd ::= create_vtab LP vtabarglist RP",
- /* 293 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
- /* 294 */ "vtabarg ::=",
- /* 295 */ "vtabargtoken ::= ANY",
- /* 296 */ "vtabargtoken ::= lp anylist RP",
- /* 297 */ "lp ::= LP",
- /* 298 */ "with ::= WITH wqlist",
- /* 299 */ "with ::= WITH RECURSIVE wqlist",
- /* 300 */ "wqas ::= AS",
- /* 301 */ "wqas ::= AS MATERIALIZED",
- /* 302 */ "wqas ::= AS NOT MATERIALIZED",
- /* 303 */ "wqitem ::= nm eidlist_opt wqas LP select RP",
- /* 304 */ "wqlist ::= wqitem",
- /* 305 */ "wqlist ::= wqlist COMMA wqitem",
- /* 306 */ "windowdefn_list ::= windowdefn",
- /* 307 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
- /* 308 */ "windowdefn ::= nm AS LP window RP",
- /* 309 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
- /* 310 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
- /* 311 */ "window ::= ORDER BY sortlist frame_opt",
- /* 312 */ "window ::= nm ORDER BY sortlist frame_opt",
- /* 313 */ "window ::= frame_opt",
- /* 314 */ "window ::= nm frame_opt",
- /* 315 */ "frame_opt ::=",
- /* 316 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
- /* 317 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
- /* 318 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
- /* 319 */ "frame_bound_s ::= frame_bound",
- /* 320 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
- /* 321 */ "frame_bound_e ::= frame_bound",
- /* 322 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
- /* 323 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
- /* 324 */ "frame_bound ::= CURRENT ROW",
- /* 325 */ "frame_exclude_opt ::=",
- /* 326 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
- /* 327 */ "frame_exclude ::= NO OTHERS",
- /* 328 */ "frame_exclude ::= CURRENT ROW",
- /* 329 */ "frame_exclude ::= GROUP|TIES",
- /* 330 */ "window_clause ::= WINDOW windowdefn_list",
- /* 331 */ "filter_over ::= filter_clause over_clause",
- /* 332 */ "filter_over ::= over_clause",
- /* 333 */ "filter_over ::= filter_clause",
- /* 334 */ "over_clause ::= OVER LP window RP",
- /* 335 */ "over_clause ::= OVER nm",
- /* 336 */ "filter_clause ::= FILTER LP WHERE expr RP",
- /* 337 */ "input ::= cmdlist",
- /* 338 */ "cmdlist ::= cmdlist ecmd",
- /* 339 */ "cmdlist ::= ecmd",
- /* 340 */ "ecmd ::= SEMI",
- /* 341 */ "ecmd ::= cmdx SEMI",
- /* 342 */ "ecmd ::= explain cmdx SEMI",
- /* 343 */ "trans_opt ::=",
- /* 344 */ "trans_opt ::= TRANSACTION",
- /* 345 */ "trans_opt ::= TRANSACTION nm",
- /* 346 */ "savepoint_opt ::= SAVEPOINT",
- /* 347 */ "savepoint_opt ::=",
- /* 348 */ "cmd ::= create_table create_table_args",
- /* 349 */ "columnlist ::= columnlist COMMA columnname carglist",
- /* 350 */ "columnlist ::= columnname carglist",
- /* 351 */ "nm ::= ID|INDEXED",
- /* 352 */ "nm ::= STRING",
- /* 353 */ "nm ::= JOIN_KW",
- /* 354 */ "typetoken ::= typename",
- /* 355 */ "typename ::= ID|STRING",
- /* 356 */ "signed ::= plus_num",
- /* 357 */ "signed ::= minus_num",
- /* 358 */ "carglist ::= carglist ccons",
- /* 359 */ "carglist ::=",
- /* 360 */ "ccons ::= NULL onconf",
- /* 361 */ "ccons ::= GENERATED ALWAYS AS generated",
- /* 362 */ "ccons ::= AS generated",
- /* 363 */ "conslist_opt ::= COMMA conslist",
- /* 364 */ "conslist ::= conslist tconscomma tcons",
- /* 365 */ "conslist ::= tcons",
- /* 366 */ "tconscomma ::=",
- /* 367 */ "defer_subclause_opt ::= defer_subclause",
- /* 368 */ "resolvetype ::= raisetype",
- /* 369 */ "selectnowith ::= oneselect",
- /* 370 */ "oneselect ::= values",
- /* 371 */ "sclp ::= selcollist COMMA",
- /* 372 */ "as ::= ID|STRING",
- /* 373 */ "returning ::=",
- /* 374 */ "expr ::= term",
- /* 375 */ "likeop ::= LIKE_KW|MATCH",
- /* 376 */ "exprlist ::= nexprlist",
- /* 377 */ "nmnum ::= plus_num",
- /* 378 */ "nmnum ::= nm",
- /* 379 */ "nmnum ::= ON",
- /* 380 */ "nmnum ::= DELETE",
- /* 381 */ "nmnum ::= DEFAULT",
- /* 382 */ "plus_num ::= INTEGER|FLOAT",
- /* 383 */ "foreach_clause ::=",
- /* 384 */ "foreach_clause ::= FOR EACH ROW",
- /* 385 */ "trnm ::= nm",
- /* 386 */ "tridxby ::=",
- /* 387 */ "database_kw_opt ::= DATABASE",
- /* 388 */ "database_kw_opt ::=",
- /* 389 */ "kwcolumn_opt ::=",
- /* 390 */ "kwcolumn_opt ::= COLUMNKW",
- /* 391 */ "vtabarglist ::= vtabarg",
- /* 392 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
- /* 393 */ "vtabarg ::= vtabarg vtabargtoken",
- /* 394 */ "anylist ::=",
- /* 395 */ "anylist ::= anylist LP anylist RP",
- /* 396 */ "anylist ::= anylist ANY",
- /* 397 */ "with ::=",
+ /*  21 */ "table_option_set ::=",
+ /*  22 */ "table_option_set ::= table_option_set COMMA table_option",
+ /*  23 */ "table_option ::= WITHOUT nm",
+ /*  24 */ "table_option ::= nm",
+ /*  25 */ "columnname ::= nm typetoken",
+ /*  26 */ "typetoken ::=",
+ /*  27 */ "typetoken ::= typename LP signed RP",
+ /*  28 */ "typetoken ::= typename LP signed COMMA signed RP",
+ /*  29 */ "typename ::= typename ID|STRING",
+ /*  30 */ "scanpt ::=",
+ /*  31 */ "scantok ::=",
+ /*  32 */ "ccons ::= CONSTRAINT nm",
+ /*  33 */ "ccons ::= DEFAULT scantok term",
+ /*  34 */ "ccons ::= DEFAULT LP expr RP",
+ /*  35 */ "ccons ::= DEFAULT PLUS scantok term",
+ /*  36 */ "ccons ::= DEFAULT MINUS scantok term",
+ /*  37 */ "ccons ::= DEFAULT scantok ID|INDEXED",
+ /*  38 */ "ccons ::= NOT NULL onconf",
+ /*  39 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
+ /*  40 */ "ccons ::= UNIQUE onconf",
+ /*  41 */ "ccons ::= CHECK LP expr RP",
+ /*  42 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
+ /*  43 */ "ccons ::= defer_subclause",
+ /*  44 */ "ccons ::= COLLATE ID|STRING",
+ /*  45 */ "generated ::= LP expr RP",
+ /*  46 */ "generated ::= LP expr RP ID",
+ /*  47 */ "autoinc ::=",
+ /*  48 */ "autoinc ::= AUTOINCR",
+ /*  49 */ "refargs ::=",
+ /*  50 */ "refargs ::= refargs refarg",
+ /*  51 */ "refarg ::= MATCH nm",
+ /*  52 */ "refarg ::= ON INSERT refact",
+ /*  53 */ "refarg ::= ON DELETE refact",
+ /*  54 */ "refarg ::= ON UPDATE refact",
+ /*  55 */ "refact ::= SET NULL",
+ /*  56 */ "refact ::= SET DEFAULT",
+ /*  57 */ "refact ::= CASCADE",
+ /*  58 */ "refact ::= RESTRICT",
+ /*  59 */ "refact ::= NO ACTION",
+ /*  60 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
+ /*  61 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
+ /*  62 */ "init_deferred_pred_opt ::=",
+ /*  63 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
+ /*  64 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
+ /*  65 */ "conslist_opt ::=",
+ /*  66 */ "tconscomma ::= COMMA",
+ /*  67 */ "tcons ::= CONSTRAINT nm",
+ /*  68 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
+ /*  69 */ "tcons ::= UNIQUE LP sortlist RP onconf",
+ /*  70 */ "tcons ::= CHECK LP expr RP onconf",
+ /*  71 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
+ /*  72 */ "defer_subclause_opt ::=",
+ /*  73 */ "onconf ::=",
+ /*  74 */ "onconf ::= ON CONFLICT resolvetype",
+ /*  75 */ "orconf ::=",
+ /*  76 */ "orconf ::= OR resolvetype",
+ /*  77 */ "resolvetype ::= IGNORE",
+ /*  78 */ "resolvetype ::= REPLACE",
+ /*  79 */ "cmd ::= DROP TABLE ifexists fullname",
+ /*  80 */ "ifexists ::= IF EXISTS",
+ /*  81 */ "ifexists ::=",
+ /*  82 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
+ /*  83 */ "cmd ::= DROP VIEW ifexists fullname",
+ /*  84 */ "cmd ::= select",
+ /*  85 */ "select ::= WITH wqlist selectnowith",
+ /*  86 */ "select ::= WITH RECURSIVE wqlist selectnowith",
+ /*  87 */ "select ::= selectnowith",
+ /*  88 */ "selectnowith ::= selectnowith multiselect_op oneselect",
+ /*  89 */ "multiselect_op ::= UNION",
+ /*  90 */ "multiselect_op ::= UNION ALL",
+ /*  91 */ "multiselect_op ::= EXCEPT|INTERSECT",
+ /*  92 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
+ /*  93 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
+ /*  94 */ "values ::= VALUES LP nexprlist RP",
+ /*  95 */ "values ::= values COMMA LP nexprlist RP",
+ /*  96 */ "distinct ::= DISTINCT",
+ /*  97 */ "distinct ::= ALL",
+ /*  98 */ "distinct ::=",
+ /*  99 */ "sclp ::=",
+ /* 100 */ "selcollist ::= sclp scanpt expr scanpt as",
+ /* 101 */ "selcollist ::= sclp scanpt STAR",
+ /* 102 */ "selcollist ::= sclp scanpt nm DOT STAR",
+ /* 103 */ "as ::= AS nm",
+ /* 104 */ "as ::=",
+ /* 105 */ "from ::=",
+ /* 106 */ "from ::= FROM seltablist",
+ /* 107 */ "stl_prefix ::= seltablist joinop",
+ /* 108 */ "stl_prefix ::=",
+ /* 109 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
+ /* 110 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
+ /* 111 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
+ /* 112 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
+ /* 113 */ "dbnm ::=",
+ /* 114 */ "dbnm ::= DOT nm",
+ /* 115 */ "fullname ::= nm",
+ /* 116 */ "fullname ::= nm DOT nm",
+ /* 117 */ "xfullname ::= nm",
+ /* 118 */ "xfullname ::= nm DOT nm",
+ /* 119 */ "xfullname ::= nm DOT nm AS nm",
+ /* 120 */ "xfullname ::= nm AS nm",
+ /* 121 */ "joinop ::= COMMA|JOIN",
+ /* 122 */ "joinop ::= JOIN_KW JOIN",
+ /* 123 */ "joinop ::= JOIN_KW nm JOIN",
+ /* 124 */ "joinop ::= JOIN_KW nm nm JOIN",
+ /* 125 */ "on_opt ::= ON expr",
+ /* 126 */ "on_opt ::=",
+ /* 127 */ "indexed_opt ::=",
+ /* 128 */ "indexed_opt ::= INDEXED BY nm",
+ /* 129 */ "indexed_opt ::= NOT INDEXED",
+ /* 130 */ "using_opt ::= USING LP idlist RP",
+ /* 131 */ "using_opt ::=",
+ /* 132 */ "orderby_opt ::=",
+ /* 133 */ "orderby_opt ::= ORDER BY sortlist",
+ /* 134 */ "sortlist ::= sortlist COMMA expr sortorder nulls",
+ /* 135 */ "sortlist ::= expr sortorder nulls",
+ /* 136 */ "sortorder ::= ASC",
+ /* 137 */ "sortorder ::= DESC",
+ /* 138 */ "sortorder ::=",
+ /* 139 */ "nulls ::= NULLS FIRST",
+ /* 140 */ "nulls ::= NULLS LAST",
+ /* 141 */ "nulls ::=",
+ /* 142 */ "groupby_opt ::=",
+ /* 143 */ "groupby_opt ::= GROUP BY nexprlist",
+ /* 144 */ "having_opt ::=",
+ /* 145 */ "having_opt ::= HAVING expr",
+ /* 146 */ "limit_opt ::=",
+ /* 147 */ "limit_opt ::= LIMIT expr",
+ /* 148 */ "limit_opt ::= LIMIT expr OFFSET expr",
+ /* 149 */ "limit_opt ::= LIMIT expr COMMA expr",
+ /* 150 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret",
+ /* 151 */ "where_opt ::=",
+ /* 152 */ "where_opt ::= WHERE expr",
+ /* 153 */ "where_opt_ret ::=",
+ /* 154 */ "where_opt_ret ::= WHERE expr",
+ /* 155 */ "where_opt_ret ::= RETURNING selcollist",
+ /* 156 */ "where_opt_ret ::= WHERE expr RETURNING selcollist",
+ /* 157 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret",
+ /* 158 */ "setlist ::= setlist COMMA nm EQ expr",
+ /* 159 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
+ /* 160 */ "setlist ::= nm EQ expr",
+ /* 161 */ "setlist ::= LP idlist RP EQ expr",
+ /* 162 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
+ /* 163 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning",
+ /* 164 */ "upsert ::=",
+ /* 165 */ "upsert ::= RETURNING selcollist",
+ /* 166 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert",
+ /* 167 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert",
+ /* 168 */ "upsert ::= ON CONFLICT DO NOTHING returning",
+ /* 169 */ "upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning",
+ /* 170 */ "returning ::= RETURNING selcollist",
+ /* 171 */ "insert_cmd ::= INSERT orconf",
+ /* 172 */ "insert_cmd ::= REPLACE",
+ /* 173 */ "idlist_opt ::=",
+ /* 174 */ "idlist_opt ::= LP idlist RP",
+ /* 175 */ "idlist ::= idlist COMMA nm",
+ /* 176 */ "idlist ::= nm",
+ /* 177 */ "expr ::= LP expr RP",
+ /* 178 */ "expr ::= ID|INDEXED",
+ /* 179 */ "expr ::= JOIN_KW",
+ /* 180 */ "expr ::= nm DOT nm",
+ /* 181 */ "expr ::= nm DOT nm DOT nm",
+ /* 182 */ "term ::= NULL|FLOAT|BLOB",
+ /* 183 */ "term ::= STRING",
+ /* 184 */ "term ::= INTEGER",
+ /* 185 */ "expr ::= VARIABLE",
+ /* 186 */ "expr ::= expr COLLATE ID|STRING",
+ /* 187 */ "expr ::= CAST LP expr AS typetoken RP",
+ /* 188 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
+ /* 189 */ "expr ::= ID|INDEXED LP STAR RP",
+ /* 190 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over",
+ /* 191 */ "expr ::= ID|INDEXED LP STAR RP filter_over",
+ /* 192 */ "term ::= CTIME_KW",
+ /* 193 */ "expr ::= LP nexprlist COMMA expr RP",
+ /* 194 */ "expr ::= expr AND expr",
+ /* 195 */ "expr ::= expr OR expr",
+ /* 196 */ "expr ::= expr LT|GT|GE|LE expr",
+ /* 197 */ "expr ::= expr EQ|NE expr",
+ /* 198 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
+ /* 199 */ "expr ::= expr PLUS|MINUS expr",
+ /* 200 */ "expr ::= expr STAR|SLASH|REM expr",
+ /* 201 */ "expr ::= expr CONCAT expr",
+ /* 202 */ "likeop ::= NOT LIKE_KW|MATCH",
+ /* 203 */ "expr ::= expr likeop expr",
+ /* 204 */ "expr ::= expr likeop expr ESCAPE expr",
+ /* 205 */ "expr ::= expr ISNULL|NOTNULL",
+ /* 206 */ "expr ::= expr NOT NULL",
+ /* 207 */ "expr ::= expr IS expr",
+ /* 208 */ "expr ::= expr IS NOT expr",
+ /* 209 */ "expr ::= NOT expr",
+ /* 210 */ "expr ::= BITNOT expr",
+ /* 211 */ "expr ::= PLUS|MINUS expr",
+ /* 212 */ "expr ::= expr PTR expr",
+ /* 213 */ "between_op ::= BETWEEN",
+ /* 214 */ "between_op ::= NOT BETWEEN",
+ /* 215 */ "expr ::= expr between_op expr AND expr",
+ /* 216 */ "in_op ::= IN",
+ /* 217 */ "in_op ::= NOT IN",
+ /* 218 */ "expr ::= expr in_op LP exprlist RP",
+ /* 219 */ "expr ::= LP select RP",
+ /* 220 */ "expr ::= expr in_op LP select RP",
+ /* 221 */ "expr ::= expr in_op nm dbnm paren_exprlist",
+ /* 222 */ "expr ::= EXISTS LP select RP",
+ /* 223 */ "expr ::= CASE case_operand case_exprlist case_else END",
+ /* 224 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
+ /* 225 */ "case_exprlist ::= WHEN expr THEN expr",
+ /* 226 */ "case_else ::= ELSE expr",
+ /* 227 */ "case_else ::=",
+ /* 228 */ "case_operand ::= expr",
+ /* 229 */ "case_operand ::=",
+ /* 230 */ "exprlist ::=",
+ /* 231 */ "nexprlist ::= nexprlist COMMA expr",
+ /* 232 */ "nexprlist ::= expr",
+ /* 233 */ "paren_exprlist ::=",
+ /* 234 */ "paren_exprlist ::= LP exprlist RP",
+ /* 235 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
+ /* 236 */ "uniqueflag ::= UNIQUE",
+ /* 237 */ "uniqueflag ::=",
+ /* 238 */ "eidlist_opt ::=",
+ /* 239 */ "eidlist_opt ::= LP eidlist RP",
+ /* 240 */ "eidlist ::= eidlist COMMA nm collate sortorder",
+ /* 241 */ "eidlist ::= nm collate sortorder",
+ /* 242 */ "collate ::=",
+ /* 243 */ "collate ::= COLLATE ID|STRING",
+ /* 244 */ "cmd ::= DROP INDEX ifexists fullname",
+ /* 245 */ "cmd ::= VACUUM vinto",
+ /* 246 */ "cmd ::= VACUUM nm vinto",
+ /* 247 */ "vinto ::= INTO expr",
+ /* 248 */ "vinto ::=",
+ /* 249 */ "cmd ::= PRAGMA nm dbnm",
+ /* 250 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
+ /* 251 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
+ /* 252 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
+ /* 253 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
+ /* 254 */ "plus_num ::= PLUS INTEGER|FLOAT",
+ /* 255 */ "minus_num ::= MINUS INTEGER|FLOAT",
+ /* 256 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
+ /* 257 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
+ /* 258 */ "trigger_time ::= BEFORE|AFTER",
+ /* 259 */ "trigger_time ::= INSTEAD OF",
+ /* 260 */ "trigger_time ::=",
+ /* 261 */ "trigger_event ::= DELETE|INSERT",
+ /* 262 */ "trigger_event ::= UPDATE",
+ /* 263 */ "trigger_event ::= UPDATE OF idlist",
+ /* 264 */ "when_clause ::=",
+ /* 265 */ "when_clause ::= WHEN expr",
+ /* 266 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
+ /* 267 */ "trigger_cmd_list ::= trigger_cmd SEMI",
+ /* 268 */ "trnm ::= nm DOT nm",
+ /* 269 */ "tridxby ::= INDEXED BY nm",
+ /* 270 */ "tridxby ::= NOT INDEXED",
+ /* 271 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
+ /* 272 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
+ /* 273 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
+ /* 274 */ "trigger_cmd ::= scanpt select scanpt",
+ /* 275 */ "expr ::= RAISE LP IGNORE RP",
+ /* 276 */ "expr ::= RAISE LP raisetype COMMA nm RP",
+ /* 277 */ "raisetype ::= ROLLBACK",
+ /* 278 */ "raisetype ::= ABORT",
+ /* 279 */ "raisetype ::= FAIL",
+ /* 280 */ "cmd ::= DROP TRIGGER ifexists fullname",
+ /* 281 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
+ /* 282 */ "cmd ::= DETACH database_kw_opt expr",
+ /* 283 */ "key_opt ::=",
+ /* 284 */ "key_opt ::= KEY expr",
+ /* 285 */ "cmd ::= REINDEX",
+ /* 286 */ "cmd ::= REINDEX nm dbnm",
+ /* 287 */ "cmd ::= ANALYZE",
+ /* 288 */ "cmd ::= ANALYZE nm dbnm",
+ /* 289 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
+ /* 290 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
+ /* 291 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm",
+ /* 292 */ "add_column_fullname ::= fullname",
+ /* 293 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
+ /* 294 */ "cmd ::= create_vtab",
+ /* 295 */ "cmd ::= create_vtab LP vtabarglist RP",
+ /* 296 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
+ /* 297 */ "vtabarg ::=",
+ /* 298 */ "vtabargtoken ::= ANY",
+ /* 299 */ "vtabargtoken ::= lp anylist RP",
+ /* 300 */ "lp ::= LP",
+ /* 301 */ "with ::= WITH wqlist",
+ /* 302 */ "with ::= WITH RECURSIVE wqlist",
+ /* 303 */ "wqas ::= AS",
+ /* 304 */ "wqas ::= AS MATERIALIZED",
+ /* 305 */ "wqas ::= AS NOT MATERIALIZED",
+ /* 306 */ "wqitem ::= nm eidlist_opt wqas LP select RP",
+ /* 307 */ "wqlist ::= wqitem",
+ /* 308 */ "wqlist ::= wqlist COMMA wqitem",
+ /* 309 */ "windowdefn_list ::= windowdefn",
+ /* 310 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
+ /* 311 */ "windowdefn ::= nm AS LP window RP",
+ /* 312 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
+ /* 313 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
+ /* 314 */ "window ::= ORDER BY sortlist frame_opt",
+ /* 315 */ "window ::= nm ORDER BY sortlist frame_opt",
+ /* 316 */ "window ::= frame_opt",
+ /* 317 */ "window ::= nm frame_opt",
+ /* 318 */ "frame_opt ::=",
+ /* 319 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
+ /* 320 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
+ /* 321 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
+ /* 322 */ "frame_bound_s ::= frame_bound",
+ /* 323 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
+ /* 324 */ "frame_bound_e ::= frame_bound",
+ /* 325 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
+ /* 326 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
+ /* 327 */ "frame_bound ::= CURRENT ROW",
+ /* 328 */ "frame_exclude_opt ::=",
+ /* 329 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
+ /* 330 */ "frame_exclude ::= NO OTHERS",
+ /* 331 */ "frame_exclude ::= CURRENT ROW",
+ /* 332 */ "frame_exclude ::= GROUP|TIES",
+ /* 333 */ "window_clause ::= WINDOW windowdefn_list",
+ /* 334 */ "filter_over ::= filter_clause over_clause",
+ /* 335 */ "filter_over ::= over_clause",
+ /* 336 */ "filter_over ::= filter_clause",
+ /* 337 */ "over_clause ::= OVER LP window RP",
+ /* 338 */ "over_clause ::= OVER nm",
+ /* 339 */ "filter_clause ::= FILTER LP WHERE expr RP",
+ /* 340 */ "input ::= cmdlist",
+ /* 341 */ "cmdlist ::= cmdlist ecmd",
+ /* 342 */ "cmdlist ::= ecmd",
+ /* 343 */ "ecmd ::= SEMI",
+ /* 344 */ "ecmd ::= cmdx SEMI",
+ /* 345 */ "ecmd ::= explain cmdx SEMI",
+ /* 346 */ "trans_opt ::=",
+ /* 347 */ "trans_opt ::= TRANSACTION",
+ /* 348 */ "trans_opt ::= TRANSACTION nm",
+ /* 349 */ "savepoint_opt ::= SAVEPOINT",
+ /* 350 */ "savepoint_opt ::=",
+ /* 351 */ "cmd ::= create_table create_table_args",
+ /* 352 */ "table_option_set ::= table_option",
+ /* 353 */ "columnlist ::= columnlist COMMA columnname carglist",
+ /* 354 */ "columnlist ::= columnname carglist",
+ /* 355 */ "nm ::= ID|INDEXED",
+ /* 356 */ "nm ::= STRING",
+ /* 357 */ "nm ::= JOIN_KW",
+ /* 358 */ "typetoken ::= typename",
+ /* 359 */ "typename ::= ID|STRING",
+ /* 360 */ "signed ::= plus_num",
+ /* 361 */ "signed ::= minus_num",
+ /* 362 */ "carglist ::= carglist ccons",
+ /* 363 */ "carglist ::=",
+ /* 364 */ "ccons ::= NULL onconf",
+ /* 365 */ "ccons ::= GENERATED ALWAYS AS generated",
+ /* 366 */ "ccons ::= AS generated",
+ /* 367 */ "conslist_opt ::= COMMA conslist",
+ /* 368 */ "conslist ::= conslist tconscomma tcons",
+ /* 369 */ "conslist ::= tcons",
+ /* 370 */ "tconscomma ::=",
+ /* 371 */ "defer_subclause_opt ::= defer_subclause",
+ /* 372 */ "resolvetype ::= raisetype",
+ /* 373 */ "selectnowith ::= oneselect",
+ /* 374 */ "oneselect ::= values",
+ /* 375 */ "sclp ::= selcollist COMMA",
+ /* 376 */ "as ::= ID|STRING",
+ /* 377 */ "returning ::=",
+ /* 378 */ "expr ::= term",
+ /* 379 */ "likeop ::= LIKE_KW|MATCH",
+ /* 380 */ "exprlist ::= nexprlist",
+ /* 381 */ "nmnum ::= plus_num",
+ /* 382 */ "nmnum ::= nm",
+ /* 383 */ "nmnum ::= ON",
+ /* 384 */ "nmnum ::= DELETE",
+ /* 385 */ "nmnum ::= DEFAULT",
+ /* 386 */ "plus_num ::= INTEGER|FLOAT",
+ /* 387 */ "foreach_clause ::=",
+ /* 388 */ "foreach_clause ::= FOR EACH ROW",
+ /* 389 */ "trnm ::= nm",
+ /* 390 */ "tridxby ::=",
+ /* 391 */ "database_kw_opt ::= DATABASE",
+ /* 392 */ "database_kw_opt ::=",
+ /* 393 */ "kwcolumn_opt ::=",
+ /* 394 */ "kwcolumn_opt ::= COLUMNKW",
+ /* 395 */ "vtabarglist ::= vtabarg",
+ /* 396 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
+ /* 397 */ "vtabarg ::= vtabarg vtabargtoken",
+ /* 398 */ "anylist ::=",
+ /* 399 */ "anylist ::= anylist LP anylist RP",
+ /* 400 */ "anylist ::= anylist ANY",
+ /* 401 */ "with ::=",
 };
 #endif /* NDEBUG */
 
@@ -159295,99 +163742,99 @@ static void yy_destructor(
     ** inside the C code.
     */
 /********* Begin destructor definitions ***************************************/
-    case 202: /* select */
-    case 236: /* selectnowith */
-    case 237: /* oneselect */
-    case 249: /* values */
+    case 204: /* select */
+    case 239: /* selectnowith */
+    case 240: /* oneselect */
+    case 252: /* values */
 {
-sqlite3SelectDelete(pParse->db, (yypminor->yy307));
-}
-      break;
-    case 213: /* term */
-    case 214: /* expr */
-    case 243: /* where_opt */
-    case 245: /* having_opt */
-    case 257: /* on_opt */
-    case 264: /* where_opt_ret */
-    case 275: /* case_operand */
-    case 277: /* case_else */
-    case 280: /* vinto */
-    case 287: /* when_clause */
-    case 292: /* key_opt */
-    case 308: /* filter_clause */
+sqlite3SelectDelete(pParse->db, (yypminor->yy47));
+}
+      break;
+    case 216: /* term */
+    case 217: /* expr */
+    case 246: /* where_opt */
+    case 248: /* having_opt */
+    case 260: /* on_opt */
+    case 267: /* where_opt_ret */
+    case 278: /* case_operand */
+    case 280: /* case_else */
+    case 283: /* vinto */
+    case 290: /* when_clause */
+    case 295: /* key_opt */
+    case 311: /* filter_clause */
 {
-sqlite3ExprDelete(pParse->db, (yypminor->yy602));
-}
-      break;
-    case 218: /* eidlist_opt */
-    case 228: /* sortlist */
-    case 229: /* eidlist */
-    case 241: /* selcollist */
-    case 244: /* groupby_opt */
-    case 246: /* orderby_opt */
-    case 250: /* nexprlist */
-    case 251: /* sclp */
-    case 259: /* exprlist */
-    case 265: /* setlist */
-    case 274: /* paren_exprlist */
-    case 276: /* case_exprlist */
-    case 307: /* part_opt */
+sqlite3ExprDelete(pParse->db, (yypminor->yy528));
+}
+      break;
+    case 221: /* eidlist_opt */
+    case 231: /* sortlist */
+    case 232: /* eidlist */
+    case 244: /* selcollist */
+    case 247: /* groupby_opt */
+    case 249: /* orderby_opt */
+    case 253: /* nexprlist */
+    case 254: /* sclp */
+    case 262: /* exprlist */
+    case 268: /* setlist */
+    case 277: /* paren_exprlist */
+    case 279: /* case_exprlist */
+    case 310: /* part_opt */
 {
-sqlite3ExprListDelete(pParse->db, (yypminor->yy338));
+sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
 }
       break;
-    case 235: /* fullname */
-    case 242: /* from */
-    case 253: /* seltablist */
-    case 254: /* stl_prefix */
-    case 260: /* xfullname */
+    case 238: /* fullname */
+    case 245: /* from */
+    case 256: /* seltablist */
+    case 257: /* stl_prefix */
+    case 263: /* xfullname */
 {
-sqlite3SrcListDelete(pParse->db, (yypminor->yy291));
+sqlite3SrcListDelete(pParse->db, (yypminor->yy131));
 }
       break;
-    case 238: /* wqlist */
+    case 241: /* wqlist */
 {
-sqlite3WithDelete(pParse->db, (yypminor->yy195));
+sqlite3WithDelete(pParse->db, (yypminor->yy521));
 }
       break;
-    case 248: /* window_clause */
-    case 303: /* windowdefn_list */
+    case 251: /* window_clause */
+    case 306: /* windowdefn_list */
 {
-sqlite3WindowListDelete(pParse->db, (yypminor->yy19));
+sqlite3WindowListDelete(pParse->db, (yypminor->yy41));
 }
       break;
-    case 258: /* using_opt */
-    case 261: /* idlist */
-    case 267: /* idlist_opt */
+    case 261: /* using_opt */
+    case 264: /* idlist */
+    case 270: /* idlist_opt */
 {
-sqlite3IdListDelete(pParse->db, (yypminor->yy288));
+sqlite3IdListDelete(pParse->db, (yypminor->yy254));
 }
       break;
-    case 270: /* filter_over */
-    case 304: /* windowdefn */
-    case 305: /* window */
-    case 306: /* frame_opt */
-    case 309: /* over_clause */
+    case 273: /* filter_over */
+    case 307: /* windowdefn */
+    case 308: /* window */
+    case 309: /* frame_opt */
+    case 312: /* over_clause */
 {
-sqlite3WindowDelete(pParse->db, (yypminor->yy19));
+sqlite3WindowDelete(pParse->db, (yypminor->yy41));
 }
       break;
-    case 283: /* trigger_cmd_list */
-    case 288: /* trigger_cmd */
+    case 286: /* trigger_cmd_list */
+    case 291: /* trigger_cmd */
 {
-sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy483));
+sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy33));
 }
       break;
-    case 285: /* trigger_event */
+    case 288: /* trigger_event */
 {
-sqlite3IdListDelete(pParse->db, (yypminor->yy50).b);
+sqlite3IdListDelete(pParse->db, (yypminor->yy180).b);
 }
       break;
-    case 311: /* frame_bound */
-    case 312: /* frame_bound_s */
-    case 313: /* frame_bound_e */
+    case 314: /* frame_bound */
+    case 315: /* frame_bound_s */
+    case 316: /* frame_bound_e */
 {
-sqlite3ExprDelete(pParse->db, (yypminor->yy113).pExpr);
+sqlite3ExprDelete(pParse->db, (yypminor->yy595).pExpr);
 }
       break;
 /********* End destructor definitions *****************************************/
@@ -159678,404 +164125,408 @@ static void yy_shift(
 /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
 ** of that rule */
 static const YYCODETYPE yyRuleInfoLhs[] = {
-   187,  /* (0) explain ::= EXPLAIN */
-   187,  /* (1) explain ::= EXPLAIN QUERY PLAN */
-   186,  /* (2) cmdx ::= cmd */
-   188,  /* (3) cmd ::= BEGIN transtype trans_opt */
-   189,  /* (4) transtype ::= */
-   189,  /* (5) transtype ::= DEFERRED */
-   189,  /* (6) transtype ::= IMMEDIATE */
-   189,  /* (7) transtype ::= EXCLUSIVE */
-   188,  /* (8) cmd ::= COMMIT|END trans_opt */
-   188,  /* (9) cmd ::= ROLLBACK trans_opt */
-   188,  /* (10) cmd ::= SAVEPOINT nm */
-   188,  /* (11) cmd ::= RELEASE savepoint_opt nm */
-   188,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
-   193,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
-   195,  /* (14) createkw ::= CREATE */
-   197,  /* (15) ifnotexists ::= */
-   197,  /* (16) ifnotexists ::= IF NOT EXISTS */
-   196,  /* (17) temp ::= TEMP */
-   196,  /* (18) temp ::= */
-   194,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
-   194,  /* (20) create_table_args ::= AS select */
-   201,  /* (21) table_options ::= */
-   201,  /* (22) table_options ::= WITHOUT nm */
-   203,  /* (23) columnname ::= nm typetoken */
-   205,  /* (24) typetoken ::= */
-   205,  /* (25) typetoken ::= typename LP signed RP */
-   205,  /* (26) typetoken ::= typename LP signed COMMA signed RP */
-   206,  /* (27) typename ::= typename ID|STRING */
-   210,  /* (28) scanpt ::= */
-   211,  /* (29) scantok ::= */
-   212,  /* (30) ccons ::= CONSTRAINT nm */
-   212,  /* (31) ccons ::= DEFAULT scantok term */
-   212,  /* (32) ccons ::= DEFAULT LP expr RP */
-   212,  /* (33) ccons ::= DEFAULT PLUS scantok term */
-   212,  /* (34) ccons ::= DEFAULT MINUS scantok term */
-   212,  /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
-   212,  /* (36) ccons ::= NOT NULL onconf */
-   212,  /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
-   212,  /* (38) ccons ::= UNIQUE onconf */
-   212,  /* (39) ccons ::= CHECK LP expr RP */
-   212,  /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
-   212,  /* (41) ccons ::= defer_subclause */
-   212,  /* (42) ccons ::= COLLATE ID|STRING */
-   221,  /* (43) generated ::= LP expr RP */
-   221,  /* (44) generated ::= LP expr RP ID */
-   217,  /* (45) autoinc ::= */
-   217,  /* (46) autoinc ::= AUTOINCR */
-   219,  /* (47) refargs ::= */
-   219,  /* (48) refargs ::= refargs refarg */
-   222,  /* (49) refarg ::= MATCH nm */
-   222,  /* (50) refarg ::= ON INSERT refact */
-   222,  /* (51) refarg ::= ON DELETE refact */
-   222,  /* (52) refarg ::= ON UPDATE refact */
-   223,  /* (53) refact ::= SET NULL */
-   223,  /* (54) refact ::= SET DEFAULT */
-   223,  /* (55) refact ::= CASCADE */
-   223,  /* (56) refact ::= RESTRICT */
-   223,  /* (57) refact ::= NO ACTION */
-   220,  /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
-   220,  /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
-   224,  /* (60) init_deferred_pred_opt ::= */
-   224,  /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
-   224,  /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
-   200,  /* (63) conslist_opt ::= */
-   226,  /* (64) tconscomma ::= COMMA */
-   227,  /* (65) tcons ::= CONSTRAINT nm */
-   227,  /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
-   227,  /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
-   227,  /* (68) tcons ::= CHECK LP expr RP onconf */
-   227,  /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
-   230,  /* (70) defer_subclause_opt ::= */
-   215,  /* (71) onconf ::= */
-   215,  /* (72) onconf ::= ON CONFLICT resolvetype */
-   231,  /* (73) orconf ::= */
-   231,  /* (74) orconf ::= OR resolvetype */
-   232,  /* (75) resolvetype ::= IGNORE */
-   232,  /* (76) resolvetype ::= REPLACE */
-   188,  /* (77) cmd ::= DROP TABLE ifexists fullname */
-   234,  /* (78) ifexists ::= IF EXISTS */
-   234,  /* (79) ifexists ::= */
-   188,  /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
-   188,  /* (81) cmd ::= DROP VIEW ifexists fullname */
-   188,  /* (82) cmd ::= select */
-   202,  /* (83) select ::= WITH wqlist selectnowith */
-   202,  /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
-   202,  /* (85) select ::= selectnowith */
-   236,  /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
-   239,  /* (87) multiselect_op ::= UNION */
-   239,  /* (88) multiselect_op ::= UNION ALL */
-   239,  /* (89) multiselect_op ::= EXCEPT|INTERSECT */
-   237,  /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
-   237,  /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
-   249,  /* (92) values ::= VALUES LP nexprlist RP */
-   249,  /* (93) values ::= values COMMA LP nexprlist RP */
-   240,  /* (94) distinct ::= DISTINCT */
-   240,  /* (95) distinct ::= ALL */
-   240,  /* (96) distinct ::= */
-   251,  /* (97) sclp ::= */
-   241,  /* (98) selcollist ::= sclp scanpt expr scanpt as */
-   241,  /* (99) selcollist ::= sclp scanpt STAR */
-   241,  /* (100) selcollist ::= sclp scanpt nm DOT STAR */
-   252,  /* (101) as ::= AS nm */
-   252,  /* (102) as ::= */
-   242,  /* (103) from ::= */
-   242,  /* (104) from ::= FROM seltablist */
-   254,  /* (105) stl_prefix ::= seltablist joinop */
-   254,  /* (106) stl_prefix ::= */
-   253,  /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
-   253,  /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
-   253,  /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
-   253,  /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
-   198,  /* (111) dbnm ::= */
-   198,  /* (112) dbnm ::= DOT nm */
-   235,  /* (113) fullname ::= nm */
-   235,  /* (114) fullname ::= nm DOT nm */
-   260,  /* (115) xfullname ::= nm */
-   260,  /* (116) xfullname ::= nm DOT nm */
-   260,  /* (117) xfullname ::= nm DOT nm AS nm */
-   260,  /* (118) xfullname ::= nm AS nm */
-   255,  /* (119) joinop ::= COMMA|JOIN */
-   255,  /* (120) joinop ::= JOIN_KW JOIN */
-   255,  /* (121) joinop ::= JOIN_KW nm JOIN */
-   255,  /* (122) joinop ::= JOIN_KW nm nm JOIN */
-   257,  /* (123) on_opt ::= ON expr */
-   257,  /* (124) on_opt ::= */
-   256,  /* (125) indexed_opt ::= */
-   256,  /* (126) indexed_opt ::= INDEXED BY nm */
-   256,  /* (127) indexed_opt ::= NOT INDEXED */
-   258,  /* (128) using_opt ::= USING LP idlist RP */
-   258,  /* (129) using_opt ::= */
-   246,  /* (130) orderby_opt ::= */
-   246,  /* (131) orderby_opt ::= ORDER BY sortlist */
-   228,  /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
-   228,  /* (133) sortlist ::= expr sortorder nulls */
-   216,  /* (134) sortorder ::= ASC */
-   216,  /* (135) sortorder ::= DESC */
-   216,  /* (136) sortorder ::= */
-   262,  /* (137) nulls ::= NULLS FIRST */
-   262,  /* (138) nulls ::= NULLS LAST */
-   262,  /* (139) nulls ::= */
-   244,  /* (140) groupby_opt ::= */
-   244,  /* (141) groupby_opt ::= GROUP BY nexprlist */
-   245,  /* (142) having_opt ::= */
-   245,  /* (143) having_opt ::= HAVING expr */
-   247,  /* (144) limit_opt ::= */
-   247,  /* (145) limit_opt ::= LIMIT expr */
-   247,  /* (146) limit_opt ::= LIMIT expr OFFSET expr */
-   247,  /* (147) limit_opt ::= LIMIT expr COMMA expr */
-   188,  /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
-   243,  /* (149) where_opt ::= */
-   243,  /* (150) where_opt ::= WHERE expr */
-   264,  /* (151) where_opt_ret ::= */
-   264,  /* (152) where_opt_ret ::= WHERE expr */
-   264,  /* (153) where_opt_ret ::= RETURNING selcollist */
-   264,  /* (154) where_opt_ret ::= WHERE expr RETURNING selcollist */
-   188,  /* (155) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
-   265,  /* (156) setlist ::= setlist COMMA nm EQ expr */
-   265,  /* (157) setlist ::= setlist COMMA LP idlist RP EQ expr */
-   265,  /* (158) setlist ::= nm EQ expr */
-   265,  /* (159) setlist ::= LP idlist RP EQ expr */
-   188,  /* (160) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
-   188,  /* (161) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
-   268,  /* (162) upsert ::= */
-   268,  /* (163) upsert ::= RETURNING selcollist */
-   268,  /* (164) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
-   268,  /* (165) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
-   268,  /* (166) upsert ::= ON CONFLICT DO NOTHING returning */
-   268,  /* (167) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
-   269,  /* (168) returning ::= RETURNING selcollist */
-   266,  /* (169) insert_cmd ::= INSERT orconf */
-   266,  /* (170) insert_cmd ::= REPLACE */
-   267,  /* (171) idlist_opt ::= */
-   267,  /* (172) idlist_opt ::= LP idlist RP */
-   261,  /* (173) idlist ::= idlist COMMA nm */
-   261,  /* (174) idlist ::= nm */
-   214,  /* (175) expr ::= LP expr RP */
-   214,  /* (176) expr ::= ID|INDEXED */
-   214,  /* (177) expr ::= JOIN_KW */
-   214,  /* (178) expr ::= nm DOT nm */
-   214,  /* (179) expr ::= nm DOT nm DOT nm */
-   213,  /* (180) term ::= NULL|FLOAT|BLOB */
-   213,  /* (181) term ::= STRING */
-   213,  /* (182) term ::= INTEGER */
-   214,  /* (183) expr ::= VARIABLE */
-   214,  /* (184) expr ::= expr COLLATE ID|STRING */
-   214,  /* (185) expr ::= CAST LP expr AS typetoken RP */
-   214,  /* (186) expr ::= ID|INDEXED LP distinct exprlist RP */
-   214,  /* (187) expr ::= ID|INDEXED LP STAR RP */
-   214,  /* (188) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
-   214,  /* (189) expr ::= ID|INDEXED LP STAR RP filter_over */
-   213,  /* (190) term ::= CTIME_KW */
-   214,  /* (191) expr ::= LP nexprlist COMMA expr RP */
-   214,  /* (192) expr ::= expr AND expr */
-   214,  /* (193) expr ::= expr OR expr */
-   214,  /* (194) expr ::= expr LT|GT|GE|LE expr */
-   214,  /* (195) expr ::= expr EQ|NE expr */
-   214,  /* (196) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
-   214,  /* (197) expr ::= expr PLUS|MINUS expr */
-   214,  /* (198) expr ::= expr STAR|SLASH|REM expr */
-   214,  /* (199) expr ::= expr CONCAT expr */
-   271,  /* (200) likeop ::= NOT LIKE_KW|MATCH */
-   214,  /* (201) expr ::= expr likeop expr */
-   214,  /* (202) expr ::= expr likeop expr ESCAPE expr */
-   214,  /* (203) expr ::= expr ISNULL|NOTNULL */
-   214,  /* (204) expr ::= expr NOT NULL */
-   214,  /* (205) expr ::= expr IS expr */
-   214,  /* (206) expr ::= expr IS NOT expr */
-   214,  /* (207) expr ::= NOT expr */
-   214,  /* (208) expr ::= BITNOT expr */
-   214,  /* (209) expr ::= PLUS|MINUS expr */
-   272,  /* (210) between_op ::= BETWEEN */
-   272,  /* (211) between_op ::= NOT BETWEEN */
-   214,  /* (212) expr ::= expr between_op expr AND expr */
-   273,  /* (213) in_op ::= IN */
-   273,  /* (214) in_op ::= NOT IN */
-   214,  /* (215) expr ::= expr in_op LP exprlist RP */
-   214,  /* (216) expr ::= LP select RP */
-   214,  /* (217) expr ::= expr in_op LP select RP */
-   214,  /* (218) expr ::= expr in_op nm dbnm paren_exprlist */
-   214,  /* (219) expr ::= EXISTS LP select RP */
-   214,  /* (220) expr ::= CASE case_operand case_exprlist case_else END */
-   276,  /* (221) case_exprlist ::= case_exprlist WHEN expr THEN expr */
-   276,  /* (222) case_exprlist ::= WHEN expr THEN expr */
-   277,  /* (223) case_else ::= ELSE expr */
-   277,  /* (224) case_else ::= */
-   275,  /* (225) case_operand ::= expr */
-   275,  /* (226) case_operand ::= */
-   259,  /* (227) exprlist ::= */
-   250,  /* (228) nexprlist ::= nexprlist COMMA expr */
-   250,  /* (229) nexprlist ::= expr */
-   274,  /* (230) paren_exprlist ::= */
-   274,  /* (231) paren_exprlist ::= LP exprlist RP */
-   188,  /* (232) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
-   278,  /* (233) uniqueflag ::= UNIQUE */
-   278,  /* (234) uniqueflag ::= */
-   218,  /* (235) eidlist_opt ::= */
-   218,  /* (236) eidlist_opt ::= LP eidlist RP */
-   229,  /* (237) eidlist ::= eidlist COMMA nm collate sortorder */
-   229,  /* (238) eidlist ::= nm collate sortorder */
-   279,  /* (239) collate ::= */
-   279,  /* (240) collate ::= COLLATE ID|STRING */
-   188,  /* (241) cmd ::= DROP INDEX ifexists fullname */
-   188,  /* (242) cmd ::= VACUUM vinto */
-   188,  /* (243) cmd ::= VACUUM nm vinto */
-   280,  /* (244) vinto ::= INTO expr */
-   280,  /* (245) vinto ::= */
-   188,  /* (246) cmd ::= PRAGMA nm dbnm */
-   188,  /* (247) cmd ::= PRAGMA nm dbnm EQ nmnum */
-   188,  /* (248) cmd ::= PRAGMA nm dbnm LP nmnum RP */
-   188,  /* (249) cmd ::= PRAGMA nm dbnm EQ minus_num */
-   188,  /* (250) cmd ::= PRAGMA nm dbnm LP minus_num RP */
-   208,  /* (251) plus_num ::= PLUS INTEGER|FLOAT */
-   209,  /* (252) minus_num ::= MINUS INTEGER|FLOAT */
-   188,  /* (253) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
-   282,  /* (254) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
-   284,  /* (255) trigger_time ::= BEFORE|AFTER */
-   284,  /* (256) trigger_time ::= INSTEAD OF */
-   284,  /* (257) trigger_time ::= */
-   285,  /* (258) trigger_event ::= DELETE|INSERT */
-   285,  /* (259) trigger_event ::= UPDATE */
-   285,  /* (260) trigger_event ::= UPDATE OF idlist */
-   287,  /* (261) when_clause ::= */
-   287,  /* (262) when_clause ::= WHEN expr */
-   283,  /* (263) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
-   283,  /* (264) trigger_cmd_list ::= trigger_cmd SEMI */
-   289,  /* (265) trnm ::= nm DOT nm */
-   290,  /* (266) tridxby ::= INDEXED BY nm */
-   290,  /* (267) tridxby ::= NOT INDEXED */
-   288,  /* (268) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
-   288,  /* (269) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
-   288,  /* (270) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-   288,  /* (271) trigger_cmd ::= scanpt select scanpt */
-   214,  /* (272) expr ::= RAISE LP IGNORE RP */
-   214,  /* (273) expr ::= RAISE LP raisetype COMMA nm RP */
-   233,  /* (274) raisetype ::= ROLLBACK */
-   233,  /* (275) raisetype ::= ABORT */
-   233,  /* (276) raisetype ::= FAIL */
-   188,  /* (277) cmd ::= DROP TRIGGER ifexists fullname */
-   188,  /* (278) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
-   188,  /* (279) cmd ::= DETACH database_kw_opt expr */
-   292,  /* (280) key_opt ::= */
-   292,  /* (281) key_opt ::= KEY expr */
-   188,  /* (282) cmd ::= REINDEX */
-   188,  /* (283) cmd ::= REINDEX nm dbnm */
-   188,  /* (284) cmd ::= ANALYZE */
-   188,  /* (285) cmd ::= ANALYZE nm dbnm */
-   188,  /* (286) cmd ::= ALTER TABLE fullname RENAME TO nm */
-   188,  /* (287) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
-   188,  /* (288) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
-   293,  /* (289) add_column_fullname ::= fullname */
-   188,  /* (290) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
-   188,  /* (291) cmd ::= create_vtab */
-   188,  /* (292) cmd ::= create_vtab LP vtabarglist RP */
-   295,  /* (293) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
-   297,  /* (294) vtabarg ::= */
-   298,  /* (295) vtabargtoken ::= ANY */
-   298,  /* (296) vtabargtoken ::= lp anylist RP */
-   299,  /* (297) lp ::= LP */
-   263,  /* (298) with ::= WITH wqlist */
-   263,  /* (299) with ::= WITH RECURSIVE wqlist */
-   302,  /* (300) wqas ::= AS */
-   302,  /* (301) wqas ::= AS MATERIALIZED */
-   302,  /* (302) wqas ::= AS NOT MATERIALIZED */
-   301,  /* (303) wqitem ::= nm eidlist_opt wqas LP select RP */
-   238,  /* (304) wqlist ::= wqitem */
-   238,  /* (305) wqlist ::= wqlist COMMA wqitem */
-   303,  /* (306) windowdefn_list ::= windowdefn */
-   303,  /* (307) windowdefn_list ::= windowdefn_list COMMA windowdefn */
-   304,  /* (308) windowdefn ::= nm AS LP window RP */
-   305,  /* (309) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
-   305,  /* (310) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
-   305,  /* (311) window ::= ORDER BY sortlist frame_opt */
-   305,  /* (312) window ::= nm ORDER BY sortlist frame_opt */
-   305,  /* (313) window ::= frame_opt */
-   305,  /* (314) window ::= nm frame_opt */
-   306,  /* (315) frame_opt ::= */
-   306,  /* (316) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
-   306,  /* (317) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
-   310,  /* (318) range_or_rows ::= RANGE|ROWS|GROUPS */
-   312,  /* (319) frame_bound_s ::= frame_bound */
-   312,  /* (320) frame_bound_s ::= UNBOUNDED PRECEDING */
-   313,  /* (321) frame_bound_e ::= frame_bound */
-   313,  /* (322) frame_bound_e ::= UNBOUNDED FOLLOWING */
-   311,  /* (323) frame_bound ::= expr PRECEDING|FOLLOWING */
-   311,  /* (324) frame_bound ::= CURRENT ROW */
-   314,  /* (325) frame_exclude_opt ::= */
-   314,  /* (326) frame_exclude_opt ::= EXCLUDE frame_exclude */
-   315,  /* (327) frame_exclude ::= NO OTHERS */
-   315,  /* (328) frame_exclude ::= CURRENT ROW */
-   315,  /* (329) frame_exclude ::= GROUP|TIES */
-   248,  /* (330) window_clause ::= WINDOW windowdefn_list */
-   270,  /* (331) filter_over ::= filter_clause over_clause */
-   270,  /* (332) filter_over ::= over_clause */
-   270,  /* (333) filter_over ::= filter_clause */
-   309,  /* (334) over_clause ::= OVER LP window RP */
-   309,  /* (335) over_clause ::= OVER nm */
-   308,  /* (336) filter_clause ::= FILTER LP WHERE expr RP */
-   183,  /* (337) input ::= cmdlist */
-   184,  /* (338) cmdlist ::= cmdlist ecmd */
-   184,  /* (339) cmdlist ::= ecmd */
-   185,  /* (340) ecmd ::= SEMI */
-   185,  /* (341) ecmd ::= cmdx SEMI */
-   185,  /* (342) ecmd ::= explain cmdx SEMI */
-   190,  /* (343) trans_opt ::= */
-   190,  /* (344) trans_opt ::= TRANSACTION */
-   190,  /* (345) trans_opt ::= TRANSACTION nm */
-   192,  /* (346) savepoint_opt ::= SAVEPOINT */
-   192,  /* (347) savepoint_opt ::= */
-   188,  /* (348) cmd ::= create_table create_table_args */
-   199,  /* (349) columnlist ::= columnlist COMMA columnname carglist */
-   199,  /* (350) columnlist ::= columnname carglist */
-   191,  /* (351) nm ::= ID|INDEXED */
-   191,  /* (352) nm ::= STRING */
-   191,  /* (353) nm ::= JOIN_KW */
-   205,  /* (354) typetoken ::= typename */
-   206,  /* (355) typename ::= ID|STRING */
-   207,  /* (356) signed ::= plus_num */
-   207,  /* (357) signed ::= minus_num */
-   204,  /* (358) carglist ::= carglist ccons */
-   204,  /* (359) carglist ::= */
-   212,  /* (360) ccons ::= NULL onconf */
-   212,  /* (361) ccons ::= GENERATED ALWAYS AS generated */
-   212,  /* (362) ccons ::= AS generated */
-   200,  /* (363) conslist_opt ::= COMMA conslist */
-   225,  /* (364) conslist ::= conslist tconscomma tcons */
-   225,  /* (365) conslist ::= tcons */
-   226,  /* (366) tconscomma ::= */
-   230,  /* (367) defer_subclause_opt ::= defer_subclause */
-   232,  /* (368) resolvetype ::= raisetype */
-   236,  /* (369) selectnowith ::= oneselect */
-   237,  /* (370) oneselect ::= values */
-   251,  /* (371) sclp ::= selcollist COMMA */
-   252,  /* (372) as ::= ID|STRING */
-   269,  /* (373) returning ::= */
-   214,  /* (374) expr ::= term */
-   271,  /* (375) likeop ::= LIKE_KW|MATCH */
-   259,  /* (376) exprlist ::= nexprlist */
-   281,  /* (377) nmnum ::= plus_num */
-   281,  /* (378) nmnum ::= nm */
-   281,  /* (379) nmnum ::= ON */
-   281,  /* (380) nmnum ::= DELETE */
-   281,  /* (381) nmnum ::= DEFAULT */
-   208,  /* (382) plus_num ::= INTEGER|FLOAT */
-   286,  /* (383) foreach_clause ::= */
-   286,  /* (384) foreach_clause ::= FOR EACH ROW */
-   289,  /* (385) trnm ::= nm */
-   290,  /* (386) tridxby ::= */
-   291,  /* (387) database_kw_opt ::= DATABASE */
-   291,  /* (388) database_kw_opt ::= */
-   294,  /* (389) kwcolumn_opt ::= */
-   294,  /* (390) kwcolumn_opt ::= COLUMNKW */
-   296,  /* (391) vtabarglist ::= vtabarg */
-   296,  /* (392) vtabarglist ::= vtabarglist COMMA vtabarg */
-   297,  /* (393) vtabarg ::= vtabarg vtabargtoken */
-   300,  /* (394) anylist ::= */
-   300,  /* (395) anylist ::= anylist LP anylist RP */
-   300,  /* (396) anylist ::= anylist ANY */
-   263,  /* (397) with ::= */
+   189,  /* (0) explain ::= EXPLAIN */
+   189,  /* (1) explain ::= EXPLAIN QUERY PLAN */
+   188,  /* (2) cmdx ::= cmd */
+   190,  /* (3) cmd ::= BEGIN transtype trans_opt */
+   191,  /* (4) transtype ::= */
+   191,  /* (5) transtype ::= DEFERRED */
+   191,  /* (6) transtype ::= IMMEDIATE */
+   191,  /* (7) transtype ::= EXCLUSIVE */
+   190,  /* (8) cmd ::= COMMIT|END trans_opt */
+   190,  /* (9) cmd ::= ROLLBACK trans_opt */
+   190,  /* (10) cmd ::= SAVEPOINT nm */
+   190,  /* (11) cmd ::= RELEASE savepoint_opt nm */
+   190,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
+   195,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
+   197,  /* (14) createkw ::= CREATE */
+   199,  /* (15) ifnotexists ::= */
+   199,  /* (16) ifnotexists ::= IF NOT EXISTS */
+   198,  /* (17) temp ::= TEMP */
+   198,  /* (18) temp ::= */
+   196,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_option_set */
+   196,  /* (20) create_table_args ::= AS select */
+   203,  /* (21) table_option_set ::= */
+   203,  /* (22) table_option_set ::= table_option_set COMMA table_option */
+   205,  /* (23) table_option ::= WITHOUT nm */
+   205,  /* (24) table_option ::= nm */
+   206,  /* (25) columnname ::= nm typetoken */
+   208,  /* (26) typetoken ::= */
+   208,  /* (27) typetoken ::= typename LP signed RP */
+   208,  /* (28) typetoken ::= typename LP signed COMMA signed RP */
+   209,  /* (29) typename ::= typename ID|STRING */
+   213,  /* (30) scanpt ::= */
+   214,  /* (31) scantok ::= */
+   215,  /* (32) ccons ::= CONSTRAINT nm */
+   215,  /* (33) ccons ::= DEFAULT scantok term */
+   215,  /* (34) ccons ::= DEFAULT LP expr RP */
+   215,  /* (35) ccons ::= DEFAULT PLUS scantok term */
+   215,  /* (36) ccons ::= DEFAULT MINUS scantok term */
+   215,  /* (37) ccons ::= DEFAULT scantok ID|INDEXED */
+   215,  /* (38) ccons ::= NOT NULL onconf */
+   215,  /* (39) ccons ::= PRIMARY KEY sortorder onconf autoinc */
+   215,  /* (40) ccons ::= UNIQUE onconf */
+   215,  /* (41) ccons ::= CHECK LP expr RP */
+   215,  /* (42) ccons ::= REFERENCES nm eidlist_opt refargs */
+   215,  /* (43) ccons ::= defer_subclause */
+   215,  /* (44) ccons ::= COLLATE ID|STRING */
+   224,  /* (45) generated ::= LP expr RP */
+   224,  /* (46) generated ::= LP expr RP ID */
+   220,  /* (47) autoinc ::= */
+   220,  /* (48) autoinc ::= AUTOINCR */
+   222,  /* (49) refargs ::= */
+   222,  /* (50) refargs ::= refargs refarg */
+   225,  /* (51) refarg ::= MATCH nm */
+   225,  /* (52) refarg ::= ON INSERT refact */
+   225,  /* (53) refarg ::= ON DELETE refact */
+   225,  /* (54) refarg ::= ON UPDATE refact */
+   226,  /* (55) refact ::= SET NULL */
+   226,  /* (56) refact ::= SET DEFAULT */
+   226,  /* (57) refact ::= CASCADE */
+   226,  /* (58) refact ::= RESTRICT */
+   226,  /* (59) refact ::= NO ACTION */
+   223,  /* (60) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+   223,  /* (61) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+   227,  /* (62) init_deferred_pred_opt ::= */
+   227,  /* (63) init_deferred_pred_opt ::= INITIALLY DEFERRED */
+   227,  /* (64) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+   202,  /* (65) conslist_opt ::= */
+   229,  /* (66) tconscomma ::= COMMA */
+   230,  /* (67) tcons ::= CONSTRAINT nm */
+   230,  /* (68) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+   230,  /* (69) tcons ::= UNIQUE LP sortlist RP onconf */
+   230,  /* (70) tcons ::= CHECK LP expr RP onconf */
+   230,  /* (71) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+   233,  /* (72) defer_subclause_opt ::= */
+   218,  /* (73) onconf ::= */
+   218,  /* (74) onconf ::= ON CONFLICT resolvetype */
+   234,  /* (75) orconf ::= */
+   234,  /* (76) orconf ::= OR resolvetype */
+   235,  /* (77) resolvetype ::= IGNORE */
+   235,  /* (78) resolvetype ::= REPLACE */
+   190,  /* (79) cmd ::= DROP TABLE ifexists fullname */
+   237,  /* (80) ifexists ::= IF EXISTS */
+   237,  /* (81) ifexists ::= */
+   190,  /* (82) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+   190,  /* (83) cmd ::= DROP VIEW ifexists fullname */
+   190,  /* (84) cmd ::= select */
+   204,  /* (85) select ::= WITH wqlist selectnowith */
+   204,  /* (86) select ::= WITH RECURSIVE wqlist selectnowith */
+   204,  /* (87) select ::= selectnowith */
+   239,  /* (88) selectnowith ::= selectnowith multiselect_op oneselect */
+   242,  /* (89) multiselect_op ::= UNION */
+   242,  /* (90) multiselect_op ::= UNION ALL */
+   242,  /* (91) multiselect_op ::= EXCEPT|INTERSECT */
+   240,  /* (92) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+   240,  /* (93) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+   252,  /* (94) values ::= VALUES LP nexprlist RP */
+   252,  /* (95) values ::= values COMMA LP nexprlist RP */
+   243,  /* (96) distinct ::= DISTINCT */
+   243,  /* (97) distinct ::= ALL */
+   243,  /* (98) distinct ::= */
+   254,  /* (99) sclp ::= */
+   244,  /* (100) selcollist ::= sclp scanpt expr scanpt as */
+   244,  /* (101) selcollist ::= sclp scanpt STAR */
+   244,  /* (102) selcollist ::= sclp scanpt nm DOT STAR */
+   255,  /* (103) as ::= AS nm */
+   255,  /* (104) as ::= */
+   245,  /* (105) from ::= */
+   245,  /* (106) from ::= FROM seltablist */
+   257,  /* (107) stl_prefix ::= seltablist joinop */
+   257,  /* (108) stl_prefix ::= */
+   256,  /* (109) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+   256,  /* (110) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+   256,  /* (111) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+   256,  /* (112) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+   200,  /* (113) dbnm ::= */
+   200,  /* (114) dbnm ::= DOT nm */
+   238,  /* (115) fullname ::= nm */
+   238,  /* (116) fullname ::= nm DOT nm */
+   263,  /* (117) xfullname ::= nm */
+   263,  /* (118) xfullname ::= nm DOT nm */
+   263,  /* (119) xfullname ::= nm DOT nm AS nm */
+   263,  /* (120) xfullname ::= nm AS nm */
+   258,  /* (121) joinop ::= COMMA|JOIN */
+   258,  /* (122) joinop ::= JOIN_KW JOIN */
+   258,  /* (123) joinop ::= JOIN_KW nm JOIN */
+   258,  /* (124) joinop ::= JOIN_KW nm nm JOIN */
+   260,  /* (125) on_opt ::= ON expr */
+   260,  /* (126) on_opt ::= */
+   259,  /* (127) indexed_opt ::= */
+   259,  /* (128) indexed_opt ::= INDEXED BY nm */
+   259,  /* (129) indexed_opt ::= NOT INDEXED */
+   261,  /* (130) using_opt ::= USING LP idlist RP */
+   261,  /* (131) using_opt ::= */
+   249,  /* (132) orderby_opt ::= */
+   249,  /* (133) orderby_opt ::= ORDER BY sortlist */
+   231,  /* (134) sortlist ::= sortlist COMMA expr sortorder nulls */
+   231,  /* (135) sortlist ::= expr sortorder nulls */
+   219,  /* (136) sortorder ::= ASC */
+   219,  /* (137) sortorder ::= DESC */
+   219,  /* (138) sortorder ::= */
+   265,  /* (139) nulls ::= NULLS FIRST */
+   265,  /* (140) nulls ::= NULLS LAST */
+   265,  /* (141) nulls ::= */
+   247,  /* (142) groupby_opt ::= */
+   247,  /* (143) groupby_opt ::= GROUP BY nexprlist */
+   248,  /* (144) having_opt ::= */
+   248,  /* (145) having_opt ::= HAVING expr */
+   250,  /* (146) limit_opt ::= */
+   250,  /* (147) limit_opt ::= LIMIT expr */
+   250,  /* (148) limit_opt ::= LIMIT expr OFFSET expr */
+   250,  /* (149) limit_opt ::= LIMIT expr COMMA expr */
+   190,  /* (150) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
+   246,  /* (151) where_opt ::= */
+   246,  /* (152) where_opt ::= WHERE expr */
+   267,  /* (153) where_opt_ret ::= */
+   267,  /* (154) where_opt_ret ::= WHERE expr */
+   267,  /* (155) where_opt_ret ::= RETURNING selcollist */
+   267,  /* (156) where_opt_ret ::= WHERE expr RETURNING selcollist */
+   190,  /* (157) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
+   268,  /* (158) setlist ::= setlist COMMA nm EQ expr */
+   268,  /* (159) setlist ::= setlist COMMA LP idlist RP EQ expr */
+   268,  /* (160) setlist ::= nm EQ expr */
+   268,  /* (161) setlist ::= LP idlist RP EQ expr */
+   190,  /* (162) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+   190,  /* (163) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
+   271,  /* (164) upsert ::= */
+   271,  /* (165) upsert ::= RETURNING selcollist */
+   271,  /* (166) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
+   271,  /* (167) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
+   271,  /* (168) upsert ::= ON CONFLICT DO NOTHING returning */
+   271,  /* (169) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
+   272,  /* (170) returning ::= RETURNING selcollist */
+   269,  /* (171) insert_cmd ::= INSERT orconf */
+   269,  /* (172) insert_cmd ::= REPLACE */
+   270,  /* (173) idlist_opt ::= */
+   270,  /* (174) idlist_opt ::= LP idlist RP */
+   264,  /* (175) idlist ::= idlist COMMA nm */
+   264,  /* (176) idlist ::= nm */
+   217,  /* (177) expr ::= LP expr RP */
+   217,  /* (178) expr ::= ID|INDEXED */
+   217,  /* (179) expr ::= JOIN_KW */
+   217,  /* (180) expr ::= nm DOT nm */
+   217,  /* (181) expr ::= nm DOT nm DOT nm */
+   216,  /* (182) term ::= NULL|FLOAT|BLOB */
+   216,  /* (183) term ::= STRING */
+   216,  /* (184) term ::= INTEGER */
+   217,  /* (185) expr ::= VARIABLE */
+   217,  /* (186) expr ::= expr COLLATE ID|STRING */
+   217,  /* (187) expr ::= CAST LP expr AS typetoken RP */
+   217,  /* (188) expr ::= ID|INDEXED LP distinct exprlist RP */
+   217,  /* (189) expr ::= ID|INDEXED LP STAR RP */
+   217,  /* (190) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+   217,  /* (191) expr ::= ID|INDEXED LP STAR RP filter_over */
+   216,  /* (192) term ::= CTIME_KW */
+   217,  /* (193) expr ::= LP nexprlist COMMA expr RP */
+   217,  /* (194) expr ::= expr AND expr */
+   217,  /* (195) expr ::= expr OR expr */
+   217,  /* (196) expr ::= expr LT|GT|GE|LE expr */
+   217,  /* (197) expr ::= expr EQ|NE expr */
+   217,  /* (198) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+   217,  /* (199) expr ::= expr PLUS|MINUS expr */
+   217,  /* (200) expr ::= expr STAR|SLASH|REM expr */
+   217,  /* (201) expr ::= expr CONCAT expr */
+   274,  /* (202) likeop ::= NOT LIKE_KW|MATCH */
+   217,  /* (203) expr ::= expr likeop expr */
+   217,  /* (204) expr ::= expr likeop expr ESCAPE expr */
+   217,  /* (205) expr ::= expr ISNULL|NOTNULL */
+   217,  /* (206) expr ::= expr NOT NULL */
+   217,  /* (207) expr ::= expr IS expr */
+   217,  /* (208) expr ::= expr IS NOT expr */
+   217,  /* (209) expr ::= NOT expr */
+   217,  /* (210) expr ::= BITNOT expr */
+   217,  /* (211) expr ::= PLUS|MINUS expr */
+   217,  /* (212) expr ::= expr PTR expr */
+   275,  /* (213) between_op ::= BETWEEN */
+   275,  /* (214) between_op ::= NOT BETWEEN */
+   217,  /* (215) expr ::= expr between_op expr AND expr */
+   276,  /* (216) in_op ::= IN */
+   276,  /* (217) in_op ::= NOT IN */
+   217,  /* (218) expr ::= expr in_op LP exprlist RP */
+   217,  /* (219) expr ::= LP select RP */
+   217,  /* (220) expr ::= expr in_op LP select RP */
+   217,  /* (221) expr ::= expr in_op nm dbnm paren_exprlist */
+   217,  /* (222) expr ::= EXISTS LP select RP */
+   217,  /* (223) expr ::= CASE case_operand case_exprlist case_else END */
+   279,  /* (224) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+   279,  /* (225) case_exprlist ::= WHEN expr THEN expr */
+   280,  /* (226) case_else ::= ELSE expr */
+   280,  /* (227) case_else ::= */
+   278,  /* (228) case_operand ::= expr */
+   278,  /* (229) case_operand ::= */
+   262,  /* (230) exprlist ::= */
+   253,  /* (231) nexprlist ::= nexprlist COMMA expr */
+   253,  /* (232) nexprlist ::= expr */
+   277,  /* (233) paren_exprlist ::= */
+   277,  /* (234) paren_exprlist ::= LP exprlist RP */
+   190,  /* (235) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+   281,  /* (236) uniqueflag ::= UNIQUE */
+   281,  /* (237) uniqueflag ::= */
+   221,  /* (238) eidlist_opt ::= */
+   221,  /* (239) eidlist_opt ::= LP eidlist RP */
+   232,  /* (240) eidlist ::= eidlist COMMA nm collate sortorder */
+   232,  /* (241) eidlist ::= nm collate sortorder */
+   282,  /* (242) collate ::= */
+   282,  /* (243) collate ::= COLLATE ID|STRING */
+   190,  /* (244) cmd ::= DROP INDEX ifexists fullname */
+   190,  /* (245) cmd ::= VACUUM vinto */
+   190,  /* (246) cmd ::= VACUUM nm vinto */
+   283,  /* (247) vinto ::= INTO expr */
+   283,  /* (248) vinto ::= */
+   190,  /* (249) cmd ::= PRAGMA nm dbnm */
+   190,  /* (250) cmd ::= PRAGMA nm dbnm EQ nmnum */
+   190,  /* (251) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+   190,  /* (252) cmd ::= PRAGMA nm dbnm EQ minus_num */
+   190,  /* (253) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+   211,  /* (254) plus_num ::= PLUS INTEGER|FLOAT */
+   212,  /* (255) minus_num ::= MINUS INTEGER|FLOAT */
+   190,  /* (256) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+   285,  /* (257) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+   287,  /* (258) trigger_time ::= BEFORE|AFTER */
+   287,  /* (259) trigger_time ::= INSTEAD OF */
+   287,  /* (260) trigger_time ::= */
+   288,  /* (261) trigger_event ::= DELETE|INSERT */
+   288,  /* (262) trigger_event ::= UPDATE */
+   288,  /* (263) trigger_event ::= UPDATE OF idlist */
+   290,  /* (264) when_clause ::= */
+   290,  /* (265) when_clause ::= WHEN expr */
+   286,  /* (266) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+   286,  /* (267) trigger_cmd_list ::= trigger_cmd SEMI */
+   292,  /* (268) trnm ::= nm DOT nm */
+   293,  /* (269) tridxby ::= INDEXED BY nm */
+   293,  /* (270) tridxby ::= NOT INDEXED */
+   291,  /* (271) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+   291,  /* (272) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+   291,  /* (273) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+   291,  /* (274) trigger_cmd ::= scanpt select scanpt */
+   217,  /* (275) expr ::= RAISE LP IGNORE RP */
+   217,  /* (276) expr ::= RAISE LP raisetype COMMA nm RP */
+   236,  /* (277) raisetype ::= ROLLBACK */
+   236,  /* (278) raisetype ::= ABORT */
+   236,  /* (279) raisetype ::= FAIL */
+   190,  /* (280) cmd ::= DROP TRIGGER ifexists fullname */
+   190,  /* (281) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+   190,  /* (282) cmd ::= DETACH database_kw_opt expr */
+   295,  /* (283) key_opt ::= */
+   295,  /* (284) key_opt ::= KEY expr */
+   190,  /* (285) cmd ::= REINDEX */
+   190,  /* (286) cmd ::= REINDEX nm dbnm */
+   190,  /* (287) cmd ::= ANALYZE */
+   190,  /* (288) cmd ::= ANALYZE nm dbnm */
+   190,  /* (289) cmd ::= ALTER TABLE fullname RENAME TO nm */
+   190,  /* (290) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+   190,  /* (291) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
+   296,  /* (292) add_column_fullname ::= fullname */
+   190,  /* (293) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+   190,  /* (294) cmd ::= create_vtab */
+   190,  /* (295) cmd ::= create_vtab LP vtabarglist RP */
+   298,  /* (296) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+   300,  /* (297) vtabarg ::= */
+   301,  /* (298) vtabargtoken ::= ANY */
+   301,  /* (299) vtabargtoken ::= lp anylist RP */
+   302,  /* (300) lp ::= LP */
+   266,  /* (301) with ::= WITH wqlist */
+   266,  /* (302) with ::= WITH RECURSIVE wqlist */
+   305,  /* (303) wqas ::= AS */
+   305,  /* (304) wqas ::= AS MATERIALIZED */
+   305,  /* (305) wqas ::= AS NOT MATERIALIZED */
+   304,  /* (306) wqitem ::= nm eidlist_opt wqas LP select RP */
+   241,  /* (307) wqlist ::= wqitem */
+   241,  /* (308) wqlist ::= wqlist COMMA wqitem */
+   306,  /* (309) windowdefn_list ::= windowdefn */
+   306,  /* (310) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+   307,  /* (311) windowdefn ::= nm AS LP window RP */
+   308,  /* (312) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+   308,  /* (313) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+   308,  /* (314) window ::= ORDER BY sortlist frame_opt */
+   308,  /* (315) window ::= nm ORDER BY sortlist frame_opt */
+   308,  /* (316) window ::= frame_opt */
+   308,  /* (317) window ::= nm frame_opt */
+   309,  /* (318) frame_opt ::= */
+   309,  /* (319) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+   309,  /* (320) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+   313,  /* (321) range_or_rows ::= RANGE|ROWS|GROUPS */
+   315,  /* (322) frame_bound_s ::= frame_bound */
+   315,  /* (323) frame_bound_s ::= UNBOUNDED PRECEDING */
+   316,  /* (324) frame_bound_e ::= frame_bound */
+   316,  /* (325) frame_bound_e ::= UNBOUNDED FOLLOWING */
+   314,  /* (326) frame_bound ::= expr PRECEDING|FOLLOWING */
+   314,  /* (327) frame_bound ::= CURRENT ROW */
+   317,  /* (328) frame_exclude_opt ::= */
+   317,  /* (329) frame_exclude_opt ::= EXCLUDE frame_exclude */
+   318,  /* (330) frame_exclude ::= NO OTHERS */
+   318,  /* (331) frame_exclude ::= CURRENT ROW */
+   318,  /* (332) frame_exclude ::= GROUP|TIES */
+   251,  /* (333) window_clause ::= WINDOW windowdefn_list */
+   273,  /* (334) filter_over ::= filter_clause over_clause */
+   273,  /* (335) filter_over ::= over_clause */
+   273,  /* (336) filter_over ::= filter_clause */
+   312,  /* (337) over_clause ::= OVER LP window RP */
+   312,  /* (338) over_clause ::= OVER nm */
+   311,  /* (339) filter_clause ::= FILTER LP WHERE expr RP */
+   185,  /* (340) input ::= cmdlist */
+   186,  /* (341) cmdlist ::= cmdlist ecmd */
+   186,  /* (342) cmdlist ::= ecmd */
+   187,  /* (343) ecmd ::= SEMI */
+   187,  /* (344) ecmd ::= cmdx SEMI */
+   187,  /* (345) ecmd ::= explain cmdx SEMI */
+   192,  /* (346) trans_opt ::= */
+   192,  /* (347) trans_opt ::= TRANSACTION */
+   192,  /* (348) trans_opt ::= TRANSACTION nm */
+   194,  /* (349) savepoint_opt ::= SAVEPOINT */
+   194,  /* (350) savepoint_opt ::= */
+   190,  /* (351) cmd ::= create_table create_table_args */
+   203,  /* (352) table_option_set ::= table_option */
+   201,  /* (353) columnlist ::= columnlist COMMA columnname carglist */
+   201,  /* (354) columnlist ::= columnname carglist */
+   193,  /* (355) nm ::= ID|INDEXED */
+   193,  /* (356) nm ::= STRING */
+   193,  /* (357) nm ::= JOIN_KW */
+   208,  /* (358) typetoken ::= typename */
+   209,  /* (359) typename ::= ID|STRING */
+   210,  /* (360) signed ::= plus_num */
+   210,  /* (361) signed ::= minus_num */
+   207,  /* (362) carglist ::= carglist ccons */
+   207,  /* (363) carglist ::= */
+   215,  /* (364) ccons ::= NULL onconf */
+   215,  /* (365) ccons ::= GENERATED ALWAYS AS generated */
+   215,  /* (366) ccons ::= AS generated */
+   202,  /* (367) conslist_opt ::= COMMA conslist */
+   228,  /* (368) conslist ::= conslist tconscomma tcons */
+   228,  /* (369) conslist ::= tcons */
+   229,  /* (370) tconscomma ::= */
+   233,  /* (371) defer_subclause_opt ::= defer_subclause */
+   235,  /* (372) resolvetype ::= raisetype */
+   239,  /* (373) selectnowith ::= oneselect */
+   240,  /* (374) oneselect ::= values */
+   254,  /* (375) sclp ::= selcollist COMMA */
+   255,  /* (376) as ::= ID|STRING */
+   272,  /* (377) returning ::= */
+   217,  /* (378) expr ::= term */
+   274,  /* (379) likeop ::= LIKE_KW|MATCH */
+   262,  /* (380) exprlist ::= nexprlist */
+   284,  /* (381) nmnum ::= plus_num */
+   284,  /* (382) nmnum ::= nm */
+   284,  /* (383) nmnum ::= ON */
+   284,  /* (384) nmnum ::= DELETE */
+   284,  /* (385) nmnum ::= DEFAULT */
+   211,  /* (386) plus_num ::= INTEGER|FLOAT */
+   289,  /* (387) foreach_clause ::= */
+   289,  /* (388) foreach_clause ::= FOR EACH ROW */
+   292,  /* (389) trnm ::= nm */
+   293,  /* (390) tridxby ::= */
+   294,  /* (391) database_kw_opt ::= DATABASE */
+   294,  /* (392) database_kw_opt ::= */
+   297,  /* (393) kwcolumn_opt ::= */
+   297,  /* (394) kwcolumn_opt ::= COLUMNKW */
+   299,  /* (395) vtabarglist ::= vtabarg */
+   299,  /* (396) vtabarglist ::= vtabarglist COMMA vtabarg */
+   300,  /* (397) vtabarg ::= vtabarg vtabargtoken */
+   303,  /* (398) anylist ::= */
+   303,  /* (399) anylist ::= anylist LP anylist RP */
+   303,  /* (400) anylist ::= anylist ANY */
+   266,  /* (401) with ::= */
 };
 
 /* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
@@ -160100,385 +164551,389 @@ static const signed char yyRuleInfoNRhs[] = {
    -3,  /* (16) ifnotexists ::= IF NOT EXISTS */
    -1,  /* (17) temp ::= TEMP */
     0,  /* (18) temp ::= */
-   -5,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
+   -5,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_option_set */
    -2,  /* (20) create_table_args ::= AS select */
-    0,  /* (21) table_options ::= */
-   -2,  /* (22) table_options ::= WITHOUT nm */
-   -2,  /* (23) columnname ::= nm typetoken */
-    0,  /* (24) typetoken ::= */
-   -4,  /* (25) typetoken ::= typename LP signed RP */
-   -6,  /* (26) typetoken ::= typename LP signed COMMA signed RP */
-   -2,  /* (27) typename ::= typename ID|STRING */
-    0,  /* (28) scanpt ::= */
-    0,  /* (29) scantok ::= */
-   -2,  /* (30) ccons ::= CONSTRAINT nm */
-   -3,  /* (31) ccons ::= DEFAULT scantok term */
-   -4,  /* (32) ccons ::= DEFAULT LP expr RP */
-   -4,  /* (33) ccons ::= DEFAULT PLUS scantok term */
-   -4,  /* (34) ccons ::= DEFAULT MINUS scantok term */
-   -3,  /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
-   -3,  /* (36) ccons ::= NOT NULL onconf */
-   -5,  /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
-   -2,  /* (38) ccons ::= UNIQUE onconf */
-   -4,  /* (39) ccons ::= CHECK LP expr RP */
-   -4,  /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
-   -1,  /* (41) ccons ::= defer_subclause */
-   -2,  /* (42) ccons ::= COLLATE ID|STRING */
-   -3,  /* (43) generated ::= LP expr RP */
-   -4,  /* (44) generated ::= LP expr RP ID */
-    0,  /* (45) autoinc ::= */
-   -1,  /* (46) autoinc ::= AUTOINCR */
-    0,  /* (47) refargs ::= */
-   -2,  /* (48) refargs ::= refargs refarg */
-   -2,  /* (49) refarg ::= MATCH nm */
-   -3,  /* (50) refarg ::= ON INSERT refact */
-   -3,  /* (51) refarg ::= ON DELETE refact */
-   -3,  /* (52) refarg ::= ON UPDATE refact */
-   -2,  /* (53) refact ::= SET NULL */
-   -2,  /* (54) refact ::= SET DEFAULT */
-   -1,  /* (55) refact ::= CASCADE */
-   -1,  /* (56) refact ::= RESTRICT */
-   -2,  /* (57) refact ::= NO ACTION */
-   -3,  /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
-   -2,  /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
-    0,  /* (60) init_deferred_pred_opt ::= */
-   -2,  /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
-   -2,  /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
-    0,  /* (63) conslist_opt ::= */
-   -1,  /* (64) tconscomma ::= COMMA */
-   -2,  /* (65) tcons ::= CONSTRAINT nm */
-   -7,  /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
-   -5,  /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
-   -5,  /* (68) tcons ::= CHECK LP expr RP onconf */
-  -10,  /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
-    0,  /* (70) defer_subclause_opt ::= */
-    0,  /* (71) onconf ::= */
-   -3,  /* (72) onconf ::= ON CONFLICT resolvetype */
-    0,  /* (73) orconf ::= */
-   -2,  /* (74) orconf ::= OR resolvetype */
-   -1,  /* (75) resolvetype ::= IGNORE */
-   -1,  /* (76) resolvetype ::= REPLACE */
-   -4,  /* (77) cmd ::= DROP TABLE ifexists fullname */
-   -2,  /* (78) ifexists ::= IF EXISTS */
-    0,  /* (79) ifexists ::= */
-   -9,  /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
-   -4,  /* (81) cmd ::= DROP VIEW ifexists fullname */
-   -1,  /* (82) cmd ::= select */
-   -3,  /* (83) select ::= WITH wqlist selectnowith */
-   -4,  /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
-   -1,  /* (85) select ::= selectnowith */
-   -3,  /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
-   -1,  /* (87) multiselect_op ::= UNION */
-   -2,  /* (88) multiselect_op ::= UNION ALL */
-   -1,  /* (89) multiselect_op ::= EXCEPT|INTERSECT */
-   -9,  /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
-  -10,  /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
-   -4,  /* (92) values ::= VALUES LP nexprlist RP */
-   -5,  /* (93) values ::= values COMMA LP nexprlist RP */
-   -1,  /* (94) distinct ::= DISTINCT */
-   -1,  /* (95) distinct ::= ALL */
-    0,  /* (96) distinct ::= */
-    0,  /* (97) sclp ::= */
-   -5,  /* (98) selcollist ::= sclp scanpt expr scanpt as */
-   -3,  /* (99) selcollist ::= sclp scanpt STAR */
-   -5,  /* (100) selcollist ::= sclp scanpt nm DOT STAR */
-   -2,  /* (101) as ::= AS nm */
-    0,  /* (102) as ::= */
-    0,  /* (103) from ::= */
-   -2,  /* (104) from ::= FROM seltablist */
-   -2,  /* (105) stl_prefix ::= seltablist joinop */
-    0,  /* (106) stl_prefix ::= */
-   -7,  /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
-   -9,  /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
-   -7,  /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
-   -7,  /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
-    0,  /* (111) dbnm ::= */
-   -2,  /* (112) dbnm ::= DOT nm */
-   -1,  /* (113) fullname ::= nm */
-   -3,  /* (114) fullname ::= nm DOT nm */
-   -1,  /* (115) xfullname ::= nm */
-   -3,  /* (116) xfullname ::= nm DOT nm */
-   -5,  /* (117) xfullname ::= nm DOT nm AS nm */
-   -3,  /* (118) xfullname ::= nm AS nm */
-   -1,  /* (119) joinop ::= COMMA|JOIN */
-   -2,  /* (120) joinop ::= JOIN_KW JOIN */
-   -3,  /* (121) joinop ::= JOIN_KW nm JOIN */
-   -4,  /* (122) joinop ::= JOIN_KW nm nm JOIN */
-   -2,  /* (123) on_opt ::= ON expr */
-    0,  /* (124) on_opt ::= */
-    0,  /* (125) indexed_opt ::= */
-   -3,  /* (126) indexed_opt ::= INDEXED BY nm */
-   -2,  /* (127) indexed_opt ::= NOT INDEXED */
-   -4,  /* (128) using_opt ::= USING LP idlist RP */
-    0,  /* (129) using_opt ::= */
-    0,  /* (130) orderby_opt ::= */
-   -3,  /* (131) orderby_opt ::= ORDER BY sortlist */
-   -5,  /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
-   -3,  /* (133) sortlist ::= expr sortorder nulls */
-   -1,  /* (134) sortorder ::= ASC */
-   -1,  /* (135) sortorder ::= DESC */
-    0,  /* (136) sortorder ::= */
-   -2,  /* (137) nulls ::= NULLS FIRST */
-   -2,  /* (138) nulls ::= NULLS LAST */
-    0,  /* (139) nulls ::= */
-    0,  /* (140) groupby_opt ::= */
-   -3,  /* (141) groupby_opt ::= GROUP BY nexprlist */
-    0,  /* (142) having_opt ::= */
-   -2,  /* (143) having_opt ::= HAVING expr */
-    0,  /* (144) limit_opt ::= */
-   -2,  /* (145) limit_opt ::= LIMIT expr */
-   -4,  /* (146) limit_opt ::= LIMIT expr OFFSET expr */
-   -4,  /* (147) limit_opt ::= LIMIT expr COMMA expr */
-   -6,  /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
-    0,  /* (149) where_opt ::= */
-   -2,  /* (150) where_opt ::= WHERE expr */
-    0,  /* (151) where_opt_ret ::= */
-   -2,  /* (152) where_opt_ret ::= WHERE expr */
-   -2,  /* (153) where_opt_ret ::= RETURNING selcollist */
-   -4,  /* (154) where_opt_ret ::= WHERE expr RETURNING selcollist */
-   -9,  /* (155) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
-   -5,  /* (156) setlist ::= setlist COMMA nm EQ expr */
-   -7,  /* (157) setlist ::= setlist COMMA LP idlist RP EQ expr */
-   -3,  /* (158) setlist ::= nm EQ expr */
-   -5,  /* (159) setlist ::= LP idlist RP EQ expr */
-   -7,  /* (160) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
-   -8,  /* (161) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
-    0,  /* (162) upsert ::= */
-   -2,  /* (163) upsert ::= RETURNING selcollist */
-  -12,  /* (164) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
-   -9,  /* (165) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
-   -5,  /* (166) upsert ::= ON CONFLICT DO NOTHING returning */
-   -8,  /* (167) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
-   -2,  /* (168) returning ::= RETURNING selcollist */
-   -2,  /* (169) insert_cmd ::= INSERT orconf */
-   -1,  /* (170) insert_cmd ::= REPLACE */
-    0,  /* (171) idlist_opt ::= */
-   -3,  /* (172) idlist_opt ::= LP idlist RP */
-   -3,  /* (173) idlist ::= idlist COMMA nm */
-   -1,  /* (174) idlist ::= nm */
-   -3,  /* (175) expr ::= LP expr RP */
-   -1,  /* (176) expr ::= ID|INDEXED */
-   -1,  /* (177) expr ::= JOIN_KW */
-   -3,  /* (178) expr ::= nm DOT nm */
-   -5,  /* (179) expr ::= nm DOT nm DOT nm */
-   -1,  /* (180) term ::= NULL|FLOAT|BLOB */
-   -1,  /* (181) term ::= STRING */
-   -1,  /* (182) term ::= INTEGER */
-   -1,  /* (183) expr ::= VARIABLE */
-   -3,  /* (184) expr ::= expr COLLATE ID|STRING */
-   -6,  /* (185) expr ::= CAST LP expr AS typetoken RP */
-   -5,  /* (186) expr ::= ID|INDEXED LP distinct exprlist RP */
-   -4,  /* (187) expr ::= ID|INDEXED LP STAR RP */
-   -6,  /* (188) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
-   -5,  /* (189) expr ::= ID|INDEXED LP STAR RP filter_over */
-   -1,  /* (190) term ::= CTIME_KW */
-   -5,  /* (191) expr ::= LP nexprlist COMMA expr RP */
-   -3,  /* (192) expr ::= expr AND expr */
-   -3,  /* (193) expr ::= expr OR expr */
-   -3,  /* (194) expr ::= expr LT|GT|GE|LE expr */
-   -3,  /* (195) expr ::= expr EQ|NE expr */
-   -3,  /* (196) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
-   -3,  /* (197) expr ::= expr PLUS|MINUS expr */
-   -3,  /* (198) expr ::= expr STAR|SLASH|REM expr */
-   -3,  /* (199) expr ::= expr CONCAT expr */
-   -2,  /* (200) likeop ::= NOT LIKE_KW|MATCH */
-   -3,  /* (201) expr ::= expr likeop expr */
-   -5,  /* (202) expr ::= expr likeop expr ESCAPE expr */
-   -2,  /* (203) expr ::= expr ISNULL|NOTNULL */
-   -3,  /* (204) expr ::= expr NOT NULL */
-   -3,  /* (205) expr ::= expr IS expr */
-   -4,  /* (206) expr ::= expr IS NOT expr */
-   -2,  /* (207) expr ::= NOT expr */
-   -2,  /* (208) expr ::= BITNOT expr */
-   -2,  /* (209) expr ::= PLUS|MINUS expr */
-   -1,  /* (210) between_op ::= BETWEEN */
-   -2,  /* (211) between_op ::= NOT BETWEEN */
-   -5,  /* (212) expr ::= expr between_op expr AND expr */
-   -1,  /* (213) in_op ::= IN */
-   -2,  /* (214) in_op ::= NOT IN */
-   -5,  /* (215) expr ::= expr in_op LP exprlist RP */
-   -3,  /* (216) expr ::= LP select RP */
-   -5,  /* (217) expr ::= expr in_op LP select RP */
-   -5,  /* (218) expr ::= expr in_op nm dbnm paren_exprlist */
-   -4,  /* (219) expr ::= EXISTS LP select RP */
-   -5,  /* (220) expr ::= CASE case_operand case_exprlist case_else END */
-   -5,  /* (221) case_exprlist ::= case_exprlist WHEN expr THEN expr */
-   -4,  /* (222) case_exprlist ::= WHEN expr THEN expr */
-   -2,  /* (223) case_else ::= ELSE expr */
-    0,  /* (224) case_else ::= */
-   -1,  /* (225) case_operand ::= expr */
-    0,  /* (226) case_operand ::= */
-    0,  /* (227) exprlist ::= */
-   -3,  /* (228) nexprlist ::= nexprlist COMMA expr */
-   -1,  /* (229) nexprlist ::= expr */
-    0,  /* (230) paren_exprlist ::= */
-   -3,  /* (231) paren_exprlist ::= LP exprlist RP */
-  -12,  /* (232) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
-   -1,  /* (233) uniqueflag ::= UNIQUE */
-    0,  /* (234) uniqueflag ::= */
-    0,  /* (235) eidlist_opt ::= */
-   -3,  /* (236) eidlist_opt ::= LP eidlist RP */
-   -5,  /* (237) eidlist ::= eidlist COMMA nm collate sortorder */
-   -3,  /* (238) eidlist ::= nm collate sortorder */
-    0,  /* (239) collate ::= */
-   -2,  /* (240) collate ::= COLLATE ID|STRING */
-   -4,  /* (241) cmd ::= DROP INDEX ifexists fullname */
-   -2,  /* (242) cmd ::= VACUUM vinto */
-   -3,  /* (243) cmd ::= VACUUM nm vinto */
-   -2,  /* (244) vinto ::= INTO expr */
-    0,  /* (245) vinto ::= */
-   -3,  /* (246) cmd ::= PRAGMA nm dbnm */
-   -5,  /* (247) cmd ::= PRAGMA nm dbnm EQ nmnum */
-   -6,  /* (248) cmd ::= PRAGMA nm dbnm LP nmnum RP */
-   -5,  /* (249) cmd ::= PRAGMA nm dbnm EQ minus_num */
-   -6,  /* (250) cmd ::= PRAGMA nm dbnm LP minus_num RP */
-   -2,  /* (251) plus_num ::= PLUS INTEGER|FLOAT */
-   -2,  /* (252) minus_num ::= MINUS INTEGER|FLOAT */
-   -5,  /* (253) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
-  -11,  /* (254) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
-   -1,  /* (255) trigger_time ::= BEFORE|AFTER */
-   -2,  /* (256) trigger_time ::= INSTEAD OF */
-    0,  /* (257) trigger_time ::= */
-   -1,  /* (258) trigger_event ::= DELETE|INSERT */
-   -1,  /* (259) trigger_event ::= UPDATE */
-   -3,  /* (260) trigger_event ::= UPDATE OF idlist */
-    0,  /* (261) when_clause ::= */
-   -2,  /* (262) when_clause ::= WHEN expr */
-   -3,  /* (263) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
-   -2,  /* (264) trigger_cmd_list ::= trigger_cmd SEMI */
-   -3,  /* (265) trnm ::= nm DOT nm */
-   -3,  /* (266) tridxby ::= INDEXED BY nm */
-   -2,  /* (267) tridxby ::= NOT INDEXED */
-   -9,  /* (268) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
-   -8,  /* (269) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
-   -6,  /* (270) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-   -3,  /* (271) trigger_cmd ::= scanpt select scanpt */
-   -4,  /* (272) expr ::= RAISE LP IGNORE RP */
-   -6,  /* (273) expr ::= RAISE LP raisetype COMMA nm RP */
-   -1,  /* (274) raisetype ::= ROLLBACK */
-   -1,  /* (275) raisetype ::= ABORT */
-   -1,  /* (276) raisetype ::= FAIL */
-   -4,  /* (277) cmd ::= DROP TRIGGER ifexists fullname */
-   -6,  /* (278) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
-   -3,  /* (279) cmd ::= DETACH database_kw_opt expr */
-    0,  /* (280) key_opt ::= */
-   -2,  /* (281) key_opt ::= KEY expr */
-   -1,  /* (282) cmd ::= REINDEX */
-   -3,  /* (283) cmd ::= REINDEX nm dbnm */
-   -1,  /* (284) cmd ::= ANALYZE */
-   -3,  /* (285) cmd ::= ANALYZE nm dbnm */
-   -6,  /* (286) cmd ::= ALTER TABLE fullname RENAME TO nm */
-   -7,  /* (287) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
-   -6,  /* (288) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
-   -1,  /* (289) add_column_fullname ::= fullname */
-   -8,  /* (290) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
-   -1,  /* (291) cmd ::= create_vtab */
-   -4,  /* (292) cmd ::= create_vtab LP vtabarglist RP */
-   -8,  /* (293) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
-    0,  /* (294) vtabarg ::= */
-   -1,  /* (295) vtabargtoken ::= ANY */
-   -3,  /* (296) vtabargtoken ::= lp anylist RP */
-   -1,  /* (297) lp ::= LP */
-   -2,  /* (298) with ::= WITH wqlist */
-   -3,  /* (299) with ::= WITH RECURSIVE wqlist */
-   -1,  /* (300) wqas ::= AS */
-   -2,  /* (301) wqas ::= AS MATERIALIZED */
-   -3,  /* (302) wqas ::= AS NOT MATERIALIZED */
-   -6,  /* (303) wqitem ::= nm eidlist_opt wqas LP select RP */
-   -1,  /* (304) wqlist ::= wqitem */
-   -3,  /* (305) wqlist ::= wqlist COMMA wqitem */
-   -1,  /* (306) windowdefn_list ::= windowdefn */
-   -3,  /* (307) windowdefn_list ::= windowdefn_list COMMA windowdefn */
-   -5,  /* (308) windowdefn ::= nm AS LP window RP */
-   -5,  /* (309) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
-   -6,  /* (310) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
-   -4,  /* (311) window ::= ORDER BY sortlist frame_opt */
-   -5,  /* (312) window ::= nm ORDER BY sortlist frame_opt */
-   -1,  /* (313) window ::= frame_opt */
-   -2,  /* (314) window ::= nm frame_opt */
-    0,  /* (315) frame_opt ::= */
-   -3,  /* (316) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
-   -6,  /* (317) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
-   -1,  /* (318) range_or_rows ::= RANGE|ROWS|GROUPS */
-   -1,  /* (319) frame_bound_s ::= frame_bound */
-   -2,  /* (320) frame_bound_s ::= UNBOUNDED PRECEDING */
-   -1,  /* (321) frame_bound_e ::= frame_bound */
-   -2,  /* (322) frame_bound_e ::= UNBOUNDED FOLLOWING */
-   -2,  /* (323) frame_bound ::= expr PRECEDING|FOLLOWING */
-   -2,  /* (324) frame_bound ::= CURRENT ROW */
-    0,  /* (325) frame_exclude_opt ::= */
-   -2,  /* (326) frame_exclude_opt ::= EXCLUDE frame_exclude */
-   -2,  /* (327) frame_exclude ::= NO OTHERS */
-   -2,  /* (328) frame_exclude ::= CURRENT ROW */
-   -1,  /* (329) frame_exclude ::= GROUP|TIES */
-   -2,  /* (330) window_clause ::= WINDOW windowdefn_list */
-   -2,  /* (331) filter_over ::= filter_clause over_clause */
-   -1,  /* (332) filter_over ::= over_clause */
-   -1,  /* (333) filter_over ::= filter_clause */
-   -4,  /* (334) over_clause ::= OVER LP window RP */
-   -2,  /* (335) over_clause ::= OVER nm */
-   -5,  /* (336) filter_clause ::= FILTER LP WHERE expr RP */
-   -1,  /* (337) input ::= cmdlist */
-   -2,  /* (338) cmdlist ::= cmdlist ecmd */
-   -1,  /* (339) cmdlist ::= ecmd */
-   -1,  /* (340) ecmd ::= SEMI */
-   -2,  /* (341) ecmd ::= cmdx SEMI */
-   -3,  /* (342) ecmd ::= explain cmdx SEMI */
-    0,  /* (343) trans_opt ::= */
-   -1,  /* (344) trans_opt ::= TRANSACTION */
-   -2,  /* (345) trans_opt ::= TRANSACTION nm */
-   -1,  /* (346) savepoint_opt ::= SAVEPOINT */
-    0,  /* (347) savepoint_opt ::= */
-   -2,  /* (348) cmd ::= create_table create_table_args */
-   -4,  /* (349) columnlist ::= columnlist COMMA columnname carglist */
-   -2,  /* (350) columnlist ::= columnname carglist */
-   -1,  /* (351) nm ::= ID|INDEXED */
-   -1,  /* (352) nm ::= STRING */
-   -1,  /* (353) nm ::= JOIN_KW */
-   -1,  /* (354) typetoken ::= typename */
-   -1,  /* (355) typename ::= ID|STRING */
-   -1,  /* (356) signed ::= plus_num */
-   -1,  /* (357) signed ::= minus_num */
-   -2,  /* (358) carglist ::= carglist ccons */
-    0,  /* (359) carglist ::= */
-   -2,  /* (360) ccons ::= NULL onconf */
-   -4,  /* (361) ccons ::= GENERATED ALWAYS AS generated */
-   -2,  /* (362) ccons ::= AS generated */
-   -2,  /* (363) conslist_opt ::= COMMA conslist */
-   -3,  /* (364) conslist ::= conslist tconscomma tcons */
-   -1,  /* (365) conslist ::= tcons */
-    0,  /* (366) tconscomma ::= */
-   -1,  /* (367) defer_subclause_opt ::= defer_subclause */
-   -1,  /* (368) resolvetype ::= raisetype */
-   -1,  /* (369) selectnowith ::= oneselect */
-   -1,  /* (370) oneselect ::= values */
-   -2,  /* (371) sclp ::= selcollist COMMA */
-   -1,  /* (372) as ::= ID|STRING */
-    0,  /* (373) returning ::= */
-   -1,  /* (374) expr ::= term */
-   -1,  /* (375) likeop ::= LIKE_KW|MATCH */
-   -1,  /* (376) exprlist ::= nexprlist */
-   -1,  /* (377) nmnum ::= plus_num */
-   -1,  /* (378) nmnum ::= nm */
-   -1,  /* (379) nmnum ::= ON */
-   -1,  /* (380) nmnum ::= DELETE */
-   -1,  /* (381) nmnum ::= DEFAULT */
-   -1,  /* (382) plus_num ::= INTEGER|FLOAT */
-    0,  /* (383) foreach_clause ::= */
-   -3,  /* (384) foreach_clause ::= FOR EACH ROW */
-   -1,  /* (385) trnm ::= nm */
-    0,  /* (386) tridxby ::= */
-   -1,  /* (387) database_kw_opt ::= DATABASE */
-    0,  /* (388) database_kw_opt ::= */
-    0,  /* (389) kwcolumn_opt ::= */
-   -1,  /* (390) kwcolumn_opt ::= COLUMNKW */
-   -1,  /* (391) vtabarglist ::= vtabarg */
-   -3,  /* (392) vtabarglist ::= vtabarglist COMMA vtabarg */
-   -2,  /* (393) vtabarg ::= vtabarg vtabargtoken */
-    0,  /* (394) anylist ::= */
-   -4,  /* (395) anylist ::= anylist LP anylist RP */
-   -2,  /* (396) anylist ::= anylist ANY */
-    0,  /* (397) with ::= */
+    0,  /* (21) table_option_set ::= */
+   -3,  /* (22) table_option_set ::= table_option_set COMMA table_option */
+   -2,  /* (23) table_option ::= WITHOUT nm */
+   -1,  /* (24) table_option ::= nm */
+   -2,  /* (25) columnname ::= nm typetoken */
+    0,  /* (26) typetoken ::= */
+   -4,  /* (27) typetoken ::= typename LP signed RP */
+   -6,  /* (28) typetoken ::= typename LP signed COMMA signed RP */
+   -2,  /* (29) typename ::= typename ID|STRING */
+    0,  /* (30) scanpt ::= */
+    0,  /* (31) scantok ::= */
+   -2,  /* (32) ccons ::= CONSTRAINT nm */
+   -3,  /* (33) ccons ::= DEFAULT scantok term */
+   -4,  /* (34) ccons ::= DEFAULT LP expr RP */
+   -4,  /* (35) ccons ::= DEFAULT PLUS scantok term */
+   -4,  /* (36) ccons ::= DEFAULT MINUS scantok term */
+   -3,  /* (37) ccons ::= DEFAULT scantok ID|INDEXED */
+   -3,  /* (38) ccons ::= NOT NULL onconf */
+   -5,  /* (39) ccons ::= PRIMARY KEY sortorder onconf autoinc */
+   -2,  /* (40) ccons ::= UNIQUE onconf */
+   -4,  /* (41) ccons ::= CHECK LP expr RP */
+   -4,  /* (42) ccons ::= REFERENCES nm eidlist_opt refargs */
+   -1,  /* (43) ccons ::= defer_subclause */
+   -2,  /* (44) ccons ::= COLLATE ID|STRING */
+   -3,  /* (45) generated ::= LP expr RP */
+   -4,  /* (46) generated ::= LP expr RP ID */
+    0,  /* (47) autoinc ::= */
+   -1,  /* (48) autoinc ::= AUTOINCR */
+    0,  /* (49) refargs ::= */
+   -2,  /* (50) refargs ::= refargs refarg */
+   -2,  /* (51) refarg ::= MATCH nm */
+   -3,  /* (52) refarg ::= ON INSERT refact */
+   -3,  /* (53) refarg ::= ON DELETE refact */
+   -3,  /* (54) refarg ::= ON UPDATE refact */
+   -2,  /* (55) refact ::= SET NULL */
+   -2,  /* (56) refact ::= SET DEFAULT */
+   -1,  /* (57) refact ::= CASCADE */
+   -1,  /* (58) refact ::= RESTRICT */
+   -2,  /* (59) refact ::= NO ACTION */
+   -3,  /* (60) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+   -2,  /* (61) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+    0,  /* (62) init_deferred_pred_opt ::= */
+   -2,  /* (63) init_deferred_pred_opt ::= INITIALLY DEFERRED */
+   -2,  /* (64) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+    0,  /* (65) conslist_opt ::= */
+   -1,  /* (66) tconscomma ::= COMMA */
+   -2,  /* (67) tcons ::= CONSTRAINT nm */
+   -7,  /* (68) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+   -5,  /* (69) tcons ::= UNIQUE LP sortlist RP onconf */
+   -5,  /* (70) tcons ::= CHECK LP expr RP onconf */
+  -10,  /* (71) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+    0,  /* (72) defer_subclause_opt ::= */
+    0,  /* (73) onconf ::= */
+   -3,  /* (74) onconf ::= ON CONFLICT resolvetype */
+    0,  /* (75) orconf ::= */
+   -2,  /* (76) orconf ::= OR resolvetype */
+   -1,  /* (77) resolvetype ::= IGNORE */
+   -1,  /* (78) resolvetype ::= REPLACE */
+   -4,  /* (79) cmd ::= DROP TABLE ifexists fullname */
+   -2,  /* (80) ifexists ::= IF EXISTS */
+    0,  /* (81) ifexists ::= */
+   -9,  /* (82) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+   -4,  /* (83) cmd ::= DROP VIEW ifexists fullname */
+   -1,  /* (84) cmd ::= select */
+   -3,  /* (85) select ::= WITH wqlist selectnowith */
+   -4,  /* (86) select ::= WITH RECURSIVE wqlist selectnowith */
+   -1,  /* (87) select ::= selectnowith */
+   -3,  /* (88) selectnowith ::= selectnowith multiselect_op oneselect */
+   -1,  /* (89) multiselect_op ::= UNION */
+   -2,  /* (90) multiselect_op ::= UNION ALL */
+   -1,  /* (91) multiselect_op ::= EXCEPT|INTERSECT */
+   -9,  /* (92) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+  -10,  /* (93) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+   -4,  /* (94) values ::= VALUES LP nexprlist RP */
+   -5,  /* (95) values ::= values COMMA LP nexprlist RP */
+   -1,  /* (96) distinct ::= DISTINCT */
+   -1,  /* (97) distinct ::= ALL */
+    0,  /* (98) distinct ::= */
+    0,  /* (99) sclp ::= */
+   -5,  /* (100) selcollist ::= sclp scanpt expr scanpt as */
+   -3,  /* (101) selcollist ::= sclp scanpt STAR */
+   -5,  /* (102) selcollist ::= sclp scanpt nm DOT STAR */
+   -2,  /* (103) as ::= AS nm */
+    0,  /* (104) as ::= */
+    0,  /* (105) from ::= */
+   -2,  /* (106) from ::= FROM seltablist */
+   -2,  /* (107) stl_prefix ::= seltablist joinop */
+    0,  /* (108) stl_prefix ::= */
+   -7,  /* (109) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+   -9,  /* (110) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+   -7,  /* (111) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+   -7,  /* (112) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+    0,  /* (113) dbnm ::= */
+   -2,  /* (114) dbnm ::= DOT nm */
+   -1,  /* (115) fullname ::= nm */
+   -3,  /* (116) fullname ::= nm DOT nm */
+   -1,  /* (117) xfullname ::= nm */
+   -3,  /* (118) xfullname ::= nm DOT nm */
+   -5,  /* (119) xfullname ::= nm DOT nm AS nm */
+   -3,  /* (120) xfullname ::= nm AS nm */
+   -1,  /* (121) joinop ::= COMMA|JOIN */
+   -2,  /* (122) joinop ::= JOIN_KW JOIN */
+   -3,  /* (123) joinop ::= JOIN_KW nm JOIN */
+   -4,  /* (124) joinop ::= JOIN_KW nm nm JOIN */
+   -2,  /* (125) on_opt ::= ON expr */
+    0,  /* (126) on_opt ::= */
+    0,  /* (127) indexed_opt ::= */
+   -3,  /* (128) indexed_opt ::= INDEXED BY nm */
+   -2,  /* (129) indexed_opt ::= NOT INDEXED */
+   -4,  /* (130) using_opt ::= USING LP idlist RP */
+    0,  /* (131) using_opt ::= */
+    0,  /* (132) orderby_opt ::= */
+   -3,  /* (133) orderby_opt ::= ORDER BY sortlist */
+   -5,  /* (134) sortlist ::= sortlist COMMA expr sortorder nulls */
+   -3,  /* (135) sortlist ::= expr sortorder nulls */
+   -1,  /* (136) sortorder ::= ASC */
+   -1,  /* (137) sortorder ::= DESC */
+    0,  /* (138) sortorder ::= */
+   -2,  /* (139) nulls ::= NULLS FIRST */
+   -2,  /* (140) nulls ::= NULLS LAST */
+    0,  /* (141) nulls ::= */
+    0,  /* (142) groupby_opt ::= */
+   -3,  /* (143) groupby_opt ::= GROUP BY nexprlist */
+    0,  /* (144) having_opt ::= */
+   -2,  /* (145) having_opt ::= HAVING expr */
+    0,  /* (146) limit_opt ::= */
+   -2,  /* (147) limit_opt ::= LIMIT expr */
+   -4,  /* (148) limit_opt ::= LIMIT expr OFFSET expr */
+   -4,  /* (149) limit_opt ::= LIMIT expr COMMA expr */
+   -6,  /* (150) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
+    0,  /* (151) where_opt ::= */
+   -2,  /* (152) where_opt ::= WHERE expr */
+    0,  /* (153) where_opt_ret ::= */
+   -2,  /* (154) where_opt_ret ::= WHERE expr */
+   -2,  /* (155) where_opt_ret ::= RETURNING selcollist */
+   -4,  /* (156) where_opt_ret ::= WHERE expr RETURNING selcollist */
+   -9,  /* (157) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
+   -5,  /* (158) setlist ::= setlist COMMA nm EQ expr */
+   -7,  /* (159) setlist ::= setlist COMMA LP idlist RP EQ expr */
+   -3,  /* (160) setlist ::= nm EQ expr */
+   -5,  /* (161) setlist ::= LP idlist RP EQ expr */
+   -7,  /* (162) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+   -8,  /* (163) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
+    0,  /* (164) upsert ::= */
+   -2,  /* (165) upsert ::= RETURNING selcollist */
+  -12,  /* (166) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
+   -9,  /* (167) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
+   -5,  /* (168) upsert ::= ON CONFLICT DO NOTHING returning */
+   -8,  /* (169) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
+   -2,  /* (170) returning ::= RETURNING selcollist */
+   -2,  /* (171) insert_cmd ::= INSERT orconf */
+   -1,  /* (172) insert_cmd ::= REPLACE */
+    0,  /* (173) idlist_opt ::= */
+   -3,  /* (174) idlist_opt ::= LP idlist RP */
+   -3,  /* (175) idlist ::= idlist COMMA nm */
+   -1,  /* (176) idlist ::= nm */
+   -3,  /* (177) expr ::= LP expr RP */
+   -1,  /* (178) expr ::= ID|INDEXED */
+   -1,  /* (179) expr ::= JOIN_KW */
+   -3,  /* (180) expr ::= nm DOT nm */
+   -5,  /* (181) expr ::= nm DOT nm DOT nm */
+   -1,  /* (182) term ::= NULL|FLOAT|BLOB */
+   -1,  /* (183) term ::= STRING */
+   -1,  /* (184) term ::= INTEGER */
+   -1,  /* (185) expr ::= VARIABLE */
+   -3,  /* (186) expr ::= expr COLLATE ID|STRING */
+   -6,  /* (187) expr ::= CAST LP expr AS typetoken RP */
+   -5,  /* (188) expr ::= ID|INDEXED LP distinct exprlist RP */
+   -4,  /* (189) expr ::= ID|INDEXED LP STAR RP */
+   -6,  /* (190) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+   -5,  /* (191) expr ::= ID|INDEXED LP STAR RP filter_over */
+   -1,  /* (192) term ::= CTIME_KW */
+   -5,  /* (193) expr ::= LP nexprlist COMMA expr RP */
+   -3,  /* (194) expr ::= expr AND expr */
+   -3,  /* (195) expr ::= expr OR expr */
+   -3,  /* (196) expr ::= expr LT|GT|GE|LE expr */
+   -3,  /* (197) expr ::= expr EQ|NE expr */
+   -3,  /* (198) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+   -3,  /* (199) expr ::= expr PLUS|MINUS expr */
+   -3,  /* (200) expr ::= expr STAR|SLASH|REM expr */
+   -3,  /* (201) expr ::= expr CONCAT expr */
+   -2,  /* (202) likeop ::= NOT LIKE_KW|MATCH */
+   -3,  /* (203) expr ::= expr likeop expr */
+   -5,  /* (204) expr ::= expr likeop expr ESCAPE expr */
+   -2,  /* (205) expr ::= expr ISNULL|NOTNULL */
+   -3,  /* (206) expr ::= expr NOT NULL */
+   -3,  /* (207) expr ::= expr IS expr */
+   -4,  /* (208) expr ::= expr IS NOT expr */
+   -2,  /* (209) expr ::= NOT expr */
+   -2,  /* (210) expr ::= BITNOT expr */
+   -2,  /* (211) expr ::= PLUS|MINUS expr */
+   -3,  /* (212) expr ::= expr PTR expr */
+   -1,  /* (213) between_op ::= BETWEEN */
+   -2,  /* (214) between_op ::= NOT BETWEEN */
+   -5,  /* (215) expr ::= expr between_op expr AND expr */
+   -1,  /* (216) in_op ::= IN */
+   -2,  /* (217) in_op ::= NOT IN */
+   -5,  /* (218) expr ::= expr in_op LP exprlist RP */
+   -3,  /* (219) expr ::= LP select RP */
+   -5,  /* (220) expr ::= expr in_op LP select RP */
+   -5,  /* (221) expr ::= expr in_op nm dbnm paren_exprlist */
+   -4,  /* (222) expr ::= EXISTS LP select RP */
+   -5,  /* (223) expr ::= CASE case_operand case_exprlist case_else END */
+   -5,  /* (224) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+   -4,  /* (225) case_exprlist ::= WHEN expr THEN expr */
+   -2,  /* (226) case_else ::= ELSE expr */
+    0,  /* (227) case_else ::= */
+   -1,  /* (228) case_operand ::= expr */
+    0,  /* (229) case_operand ::= */
+    0,  /* (230) exprlist ::= */
+   -3,  /* (231) nexprlist ::= nexprlist COMMA expr */
+   -1,  /* (232) nexprlist ::= expr */
+    0,  /* (233) paren_exprlist ::= */
+   -3,  /* (234) paren_exprlist ::= LP exprlist RP */
+  -12,  /* (235) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+   -1,  /* (236) uniqueflag ::= UNIQUE */
+    0,  /* (237) uniqueflag ::= */
+    0,  /* (238) eidlist_opt ::= */
+   -3,  /* (239) eidlist_opt ::= LP eidlist RP */
+   -5,  /* (240) eidlist ::= eidlist COMMA nm collate sortorder */
+   -3,  /* (241) eidlist ::= nm collate sortorder */
+    0,  /* (242) collate ::= */
+   -2,  /* (243) collate ::= COLLATE ID|STRING */
+   -4,  /* (244) cmd ::= DROP INDEX ifexists fullname */
+   -2,  /* (245) cmd ::= VACUUM vinto */
+   -3,  /* (246) cmd ::= VACUUM nm vinto */
+   -2,  /* (247) vinto ::= INTO expr */
+    0,  /* (248) vinto ::= */
+   -3,  /* (249) cmd ::= PRAGMA nm dbnm */
+   -5,  /* (250) cmd ::= PRAGMA nm dbnm EQ nmnum */
+   -6,  /* (251) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+   -5,  /* (252) cmd ::= PRAGMA nm dbnm EQ minus_num */
+   -6,  /* (253) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+   -2,  /* (254) plus_num ::= PLUS INTEGER|FLOAT */
+   -2,  /* (255) minus_num ::= MINUS INTEGER|FLOAT */
+   -5,  /* (256) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+  -11,  /* (257) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+   -1,  /* (258) trigger_time ::= BEFORE|AFTER */
+   -2,  /* (259) trigger_time ::= INSTEAD OF */
+    0,  /* (260) trigger_time ::= */
+   -1,  /* (261) trigger_event ::= DELETE|INSERT */
+   -1,  /* (262) trigger_event ::= UPDATE */
+   -3,  /* (263) trigger_event ::= UPDATE OF idlist */
+    0,  /* (264) when_clause ::= */
+   -2,  /* (265) when_clause ::= WHEN expr */
+   -3,  /* (266) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+   -2,  /* (267) trigger_cmd_list ::= trigger_cmd SEMI */
+   -3,  /* (268) trnm ::= nm DOT nm */
+   -3,  /* (269) tridxby ::= INDEXED BY nm */
+   -2,  /* (270) tridxby ::= NOT INDEXED */
+   -9,  /* (271) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+   -8,  /* (272) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+   -6,  /* (273) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+   -3,  /* (274) trigger_cmd ::= scanpt select scanpt */
+   -4,  /* (275) expr ::= RAISE LP IGNORE RP */
+   -6,  /* (276) expr ::= RAISE LP raisetype COMMA nm RP */
+   -1,  /* (277) raisetype ::= ROLLBACK */
+   -1,  /* (278) raisetype ::= ABORT */
+   -1,  /* (279) raisetype ::= FAIL */
+   -4,  /* (280) cmd ::= DROP TRIGGER ifexists fullname */
+   -6,  /* (281) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+   -3,  /* (282) cmd ::= DETACH database_kw_opt expr */
+    0,  /* (283) key_opt ::= */
+   -2,  /* (284) key_opt ::= KEY expr */
+   -1,  /* (285) cmd ::= REINDEX */
+   -3,  /* (286) cmd ::= REINDEX nm dbnm */
+   -1,  /* (287) cmd ::= ANALYZE */
+   -3,  /* (288) cmd ::= ANALYZE nm dbnm */
+   -6,  /* (289) cmd ::= ALTER TABLE fullname RENAME TO nm */
+   -7,  /* (290) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+   -6,  /* (291) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
+   -1,  /* (292) add_column_fullname ::= fullname */
+   -8,  /* (293) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+   -1,  /* (294) cmd ::= create_vtab */
+   -4,  /* (295) cmd ::= create_vtab LP vtabarglist RP */
+   -8,  /* (296) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+    0,  /* (297) vtabarg ::= */
+   -1,  /* (298) vtabargtoken ::= ANY */
+   -3,  /* (299) vtabargtoken ::= lp anylist RP */
+   -1,  /* (300) lp ::= LP */
+   -2,  /* (301) with ::= WITH wqlist */
+   -3,  /* (302) with ::= WITH RECURSIVE wqlist */
+   -1,  /* (303) wqas ::= AS */
+   -2,  /* (304) wqas ::= AS MATERIALIZED */
+   -3,  /* (305) wqas ::= AS NOT MATERIALIZED */
+   -6,  /* (306) wqitem ::= nm eidlist_opt wqas LP select RP */
+   -1,  /* (307) wqlist ::= wqitem */
+   -3,  /* (308) wqlist ::= wqlist COMMA wqitem */
+   -1,  /* (309) windowdefn_list ::= windowdefn */
+   -3,  /* (310) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+   -5,  /* (311) windowdefn ::= nm AS LP window RP */
+   -5,  /* (312) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+   -6,  /* (313) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+   -4,  /* (314) window ::= ORDER BY sortlist frame_opt */
+   -5,  /* (315) window ::= nm ORDER BY sortlist frame_opt */
+   -1,  /* (316) window ::= frame_opt */
+   -2,  /* (317) window ::= nm frame_opt */
+    0,  /* (318) frame_opt ::= */
+   -3,  /* (319) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+   -6,  /* (320) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+   -1,  /* (321) range_or_rows ::= RANGE|ROWS|GROUPS */
+   -1,  /* (322) frame_bound_s ::= frame_bound */
+   -2,  /* (323) frame_bound_s ::= UNBOUNDED PRECEDING */
+   -1,  /* (324) frame_bound_e ::= frame_bound */
+   -2,  /* (325) frame_bound_e ::= UNBOUNDED FOLLOWING */
+   -2,  /* (326) frame_bound ::= expr PRECEDING|FOLLOWING */
+   -2,  /* (327) frame_bound ::= CURRENT ROW */
+    0,  /* (328) frame_exclude_opt ::= */
+   -2,  /* (329) frame_exclude_opt ::= EXCLUDE frame_exclude */
+   -2,  /* (330) frame_exclude ::= NO OTHERS */
+   -2,  /* (331) frame_exclude ::= CURRENT ROW */
+   -1,  /* (332) frame_exclude ::= GROUP|TIES */
+   -2,  /* (333) window_clause ::= WINDOW windowdefn_list */
+   -2,  /* (334) filter_over ::= filter_clause over_clause */
+   -1,  /* (335) filter_over ::= over_clause */
+   -1,  /* (336) filter_over ::= filter_clause */
+   -4,  /* (337) over_clause ::= OVER LP window RP */
+   -2,  /* (338) over_clause ::= OVER nm */
+   -5,  /* (339) filter_clause ::= FILTER LP WHERE expr RP */
+   -1,  /* (340) input ::= cmdlist */
+   -2,  /* (341) cmdlist ::= cmdlist ecmd */
+   -1,  /* (342) cmdlist ::= ecmd */
+   -1,  /* (343) ecmd ::= SEMI */
+   -2,  /* (344) ecmd ::= cmdx SEMI */
+   -3,  /* (345) ecmd ::= explain cmdx SEMI */
+    0,  /* (346) trans_opt ::= */
+   -1,  /* (347) trans_opt ::= TRANSACTION */
+   -2,  /* (348) trans_opt ::= TRANSACTION nm */
+   -1,  /* (349) savepoint_opt ::= SAVEPOINT */
+    0,  /* (350) savepoint_opt ::= */
+   -2,  /* (351) cmd ::= create_table create_table_args */
+   -1,  /* (352) table_option_set ::= table_option */
+   -4,  /* (353) columnlist ::= columnlist COMMA columnname carglist */
+   -2,  /* (354) columnlist ::= columnname carglist */
+   -1,  /* (355) nm ::= ID|INDEXED */
+   -1,  /* (356) nm ::= STRING */
+   -1,  /* (357) nm ::= JOIN_KW */
+   -1,  /* (358) typetoken ::= typename */
+   -1,  /* (359) typename ::= ID|STRING */
+   -1,  /* (360) signed ::= plus_num */
+   -1,  /* (361) signed ::= minus_num */
+   -2,  /* (362) carglist ::= carglist ccons */
+    0,  /* (363) carglist ::= */
+   -2,  /* (364) ccons ::= NULL onconf */
+   -4,  /* (365) ccons ::= GENERATED ALWAYS AS generated */
+   -2,  /* (366) ccons ::= AS generated */
+   -2,  /* (367) conslist_opt ::= COMMA conslist */
+   -3,  /* (368) conslist ::= conslist tconscomma tcons */
+   -1,  /* (369) conslist ::= tcons */
+    0,  /* (370) tconscomma ::= */
+   -1,  /* (371) defer_subclause_opt ::= defer_subclause */
+   -1,  /* (372) resolvetype ::= raisetype */
+   -1,  /* (373) selectnowith ::= oneselect */
+   -1,  /* (374) oneselect ::= values */
+   -2,  /* (375) sclp ::= selcollist COMMA */
+   -1,  /* (376) as ::= ID|STRING */
+    0,  /* (377) returning ::= */
+   -1,  /* (378) expr ::= term */
+   -1,  /* (379) likeop ::= LIKE_KW|MATCH */
+   -1,  /* (380) exprlist ::= nexprlist */
+   -1,  /* (381) nmnum ::= plus_num */
+   -1,  /* (382) nmnum ::= nm */
+   -1,  /* (383) nmnum ::= ON */
+   -1,  /* (384) nmnum ::= DELETE */
+   -1,  /* (385) nmnum ::= DEFAULT */
+   -1,  /* (386) plus_num ::= INTEGER|FLOAT */
+    0,  /* (387) foreach_clause ::= */
+   -3,  /* (388) foreach_clause ::= FOR EACH ROW */
+   -1,  /* (389) trnm ::= nm */
+    0,  /* (390) tridxby ::= */
+   -1,  /* (391) database_kw_opt ::= DATABASE */
+    0,  /* (392) database_kw_opt ::= */
+    0,  /* (393) kwcolumn_opt ::= */
+   -1,  /* (394) kwcolumn_opt ::= COLUMNKW */
+   -1,  /* (395) vtabarglist ::= vtabarg */
+   -3,  /* (396) vtabarglist ::= vtabarglist COMMA vtabarg */
+   -2,  /* (397) vtabarg ::= vtabarg vtabargtoken */
+    0,  /* (398) anylist ::= */
+   -4,  /* (399) anylist ::= anylist LP anylist RP */
+   -2,  /* (400) anylist ::= anylist ANY */
+    0,  /* (401) with ::= */
 };
 
 static void yy_accept(yyParser*);  /* Forward Declaration */
@@ -160530,16 +164985,16 @@ static YYACTIONTYPE yy_reduce(
 { sqlite3FinishCoding(pParse); }
         break;
       case 3: /* cmd ::= BEGIN transtype trans_opt */
-{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy60);}
+{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy394);}
         break;
       case 4: /* transtype ::= */
-{yymsp[1].minor.yy60 = TK_DEFERRED;}
+{yymsp[1].minor.yy394 = TK_DEFERRED;}
         break;
       case 5: /* transtype ::= DEFERRED */
       case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
       case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
-      case 318: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==318);
-{yymsp[0].minor.yy60 = yymsp[0].major; /*A-overwrites-X*/}
+      case 321: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==321);
+{yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/}
         break;
       case 8: /* cmd ::= COMMIT|END trans_opt */
       case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
@@ -160562,7 +165017,7 @@ static YYACTIONTYPE yy_reduce(
         break;
       case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
 {
-   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy60,0,0,yymsp[-2].minor.yy60);
+   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy394,0,0,yymsp[-2].minor.yy394);
 }
         break;
       case 14: /* createkw ::= CREATE */
@@ -160570,96 +165025,112 @@ static YYACTIONTYPE yy_reduce(
         break;
       case 15: /* ifnotexists ::= */
       case 18: /* temp ::= */ yytestcase(yyruleno==18);
-      case 21: /* table_options ::= */ yytestcase(yyruleno==21);
-      case 45: /* autoinc ::= */ yytestcase(yyruleno==45);
-      case 60: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==60);
-      case 70: /* defer_subclause_opt ::= */ yytestcase(yyruleno==70);
-      case 79: /* ifexists ::= */ yytestcase(yyruleno==79);
-      case 96: /* distinct ::= */ yytestcase(yyruleno==96);
-      case 239: /* collate ::= */ yytestcase(yyruleno==239);
-{yymsp[1].minor.yy60 = 0;}
+      case 47: /* autoinc ::= */ yytestcase(yyruleno==47);
+      case 62: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==62);
+      case 72: /* defer_subclause_opt ::= */ yytestcase(yyruleno==72);
+      case 81: /* ifexists ::= */ yytestcase(yyruleno==81);
+      case 98: /* distinct ::= */ yytestcase(yyruleno==98);
+      case 242: /* collate ::= */ yytestcase(yyruleno==242);
+{yymsp[1].minor.yy394 = 0;}
         break;
       case 16: /* ifnotexists ::= IF NOT EXISTS */
-{yymsp[-2].minor.yy60 = 1;}
+{yymsp[-2].minor.yy394 = 1;}
         break;
       case 17: /* temp ::= TEMP */
-      case 46: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==46);
-{yymsp[0].minor.yy60 = 1;}
+{yymsp[0].minor.yy394 = pParse->db->init.busy==0;}
         break;
-      case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
+      case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_option_set */
 {
-  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy60,0);
+  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy285,0);
 }
         break;
       case 20: /* create_table_args ::= AS select */
 {
-  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy307);
-  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy307);
+  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy47);
+  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy47);
 }
         break;
-      case 22: /* table_options ::= WITHOUT nm */
+      case 21: /* table_option_set ::= */
+{yymsp[1].minor.yy285 = 0;}
+        break;
+      case 22: /* table_option_set ::= table_option_set COMMA table_option */
+{yylhsminor.yy285 = yymsp[-2].minor.yy285|yymsp[0].minor.yy285;}
+  yymsp[-2].minor.yy285 = yylhsminor.yy285;
+        break;
+      case 23: /* table_option ::= WITHOUT nm */
 {
   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
-    yymsp[-1].minor.yy60 = TF_WithoutRowid | TF_NoVisibleRowid;
+    yymsp[-1].minor.yy285 = TF_WithoutRowid | TF_NoVisibleRowid;
   }else{
-    yymsp[-1].minor.yy60 = 0;
+    yymsp[-1].minor.yy285 = 0;
     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
   }
 }
         break;
-      case 23: /* columnname ::= nm typetoken */
-{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
+      case 24: /* table_option ::= nm */
+{
+  if( yymsp[0].minor.yy0.n==6 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"strict",6)==0 ){
+    yylhsminor.yy285 = TF_Strict;
+  }else{
+    yylhsminor.yy285 = 0;
+    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
+  }
+}
+  yymsp[0].minor.yy285 = yylhsminor.yy285;
+        break;
+      case 25: /* columnname ::= nm typetoken */
+{sqlite3AddColumn(pParse,yymsp[-1].minor.yy0,yymsp[0].minor.yy0);}
         break;
-      case 24: /* typetoken ::= */
-      case 63: /* conslist_opt ::= */ yytestcase(yyruleno==63);
-      case 102: /* as ::= */ yytestcase(yyruleno==102);
+      case 26: /* typetoken ::= */
+      case 65: /* conslist_opt ::= */ yytestcase(yyruleno==65);
+      case 104: /* as ::= */ yytestcase(yyruleno==104);
 {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
         break;
-      case 25: /* typetoken ::= typename LP signed RP */
+      case 27: /* typetoken ::= typename LP signed RP */
 {
   yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
 }
         break;
-      case 26: /* typetoken ::= typename LP signed COMMA signed RP */
+      case 28: /* typetoken ::= typename LP signed COMMA signed RP */
 {
   yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
 }
         break;
-      case 27: /* typename ::= typename ID|STRING */
+      case 29: /* typename ::= typename ID|STRING */
 {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
         break;
-      case 28: /* scanpt ::= */
+      case 30: /* scanpt ::= */
 {
   assert( yyLookahead!=YYNOCODE );
-  yymsp[1].minor.yy528 = yyLookaheadToken.z;
+  yymsp[1].minor.yy522 = yyLookaheadToken.z;
 }
         break;
-      case 29: /* scantok ::= */
+      case 31: /* scantok ::= */
 {
   assert( yyLookahead!=YYNOCODE );
   yymsp[1].minor.yy0 = yyLookaheadToken;
 }
         break;
-      case 30: /* ccons ::= CONSTRAINT nm */
-      case 65: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==65);
+      case 32: /* ccons ::= CONSTRAINT nm */
+      case 67: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==67);
 {pParse->constraintName = yymsp[0].minor.yy0;}
         break;
-      case 31: /* ccons ::= DEFAULT scantok term */
-{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy602,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
+      case 33: /* ccons ::= DEFAULT scantok term */
+{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy528,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
         break;
-      case 32: /* ccons ::= DEFAULT LP expr RP */
-{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy602,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
+      case 34: /* ccons ::= DEFAULT LP expr RP */
+{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy528,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
         break;
-      case 33: /* ccons ::= DEFAULT PLUS scantok term */
-{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy602,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
+      case 35: /* ccons ::= DEFAULT PLUS scantok term */
+{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy528,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
         break;
-      case 34: /* ccons ::= DEFAULT MINUS scantok term */
+      case 36: /* ccons ::= DEFAULT MINUS scantok term */
 {
-  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy602, 0);
+  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy528, 0);
   sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);
 }
         break;
-      case 35: /* ccons ::= DEFAULT scantok ID|INDEXED */
+      case 37: /* ccons ::= DEFAULT scantok ID|INDEXED */
 {
   Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
   if( p ){
@@ -160669,159 +165140,162 @@ static YYACTIONTYPE yy_reduce(
     sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
 }
         break;
-      case 36: /* ccons ::= NOT NULL onconf */
-{sqlite3AddNotNull(pParse, yymsp[0].minor.yy60);}
+      case 38: /* ccons ::= NOT NULL onconf */
+{sqlite3AddNotNull(pParse, yymsp[0].minor.yy394);}
         break;
-      case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
-{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy60,yymsp[0].minor.yy60,yymsp[-2].minor.yy60);}
+      case 39: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
+{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy394,yymsp[0].minor.yy394,yymsp[-2].minor.yy394);}
         break;
-      case 38: /* ccons ::= UNIQUE onconf */
-{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy60,0,0,0,0,
+      case 40: /* ccons ::= UNIQUE onconf */
+{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy394,0,0,0,0,
                                    SQLITE_IDXTYPE_UNIQUE);}
         break;
-      case 39: /* ccons ::= CHECK LP expr RP */
-{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy602,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy0.z);}
+      case 41: /* ccons ::= CHECK LP expr RP */
+{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy528,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy0.z);}
         break;
-      case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */
-{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy338,yymsp[0].minor.yy60);}
+      case 42: /* ccons ::= REFERENCES nm eidlist_opt refargs */
+{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy394);}
         break;
-      case 41: /* ccons ::= defer_subclause */
-{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy60);}
+      case 43: /* ccons ::= defer_subclause */
+{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy394);}
         break;
-      case 42: /* ccons ::= COLLATE ID|STRING */
+      case 44: /* ccons ::= COLLATE ID|STRING */
 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
         break;
-      case 43: /* generated ::= LP expr RP */
-{sqlite3AddGenerated(pParse,yymsp[-1].minor.yy602,0);}
+      case 45: /* generated ::= LP expr RP */
+{sqlite3AddGenerated(pParse,yymsp[-1].minor.yy528,0);}
         break;
-      case 44: /* generated ::= LP expr RP ID */
-{sqlite3AddGenerated(pParse,yymsp[-2].minor.yy602,&yymsp[0].minor.yy0);}
+      case 46: /* generated ::= LP expr RP ID */
+{sqlite3AddGenerated(pParse,yymsp[-2].minor.yy528,&yymsp[0].minor.yy0);}
         break;
-      case 47: /* refargs ::= */
-{ yymsp[1].minor.yy60 = OE_None*0x0101; /* EV: R-19803-45884 */}
+      case 48: /* autoinc ::= AUTOINCR */
+{yymsp[0].minor.yy394 = 1;}
         break;
-      case 48: /* refargs ::= refargs refarg */
-{ yymsp[-1].minor.yy60 = (yymsp[-1].minor.yy60 & ~yymsp[0].minor.yy615.mask) | yymsp[0].minor.yy615.value; }
+      case 49: /* refargs ::= */
+{ yymsp[1].minor.yy394 = OE_None*0x0101; /* EV: R-19803-45884 */}
         break;
-      case 49: /* refarg ::= MATCH nm */
-{ yymsp[-1].minor.yy615.value = 0;     yymsp[-1].minor.yy615.mask = 0x000000; }
+      case 50: /* refargs ::= refargs refarg */
+{ yymsp[-1].minor.yy394 = (yymsp[-1].minor.yy394 & ~yymsp[0].minor.yy231.mask) | yymsp[0].minor.yy231.value; }
         break;
-      case 50: /* refarg ::= ON INSERT refact */
-{ yymsp[-2].minor.yy615.value = 0;     yymsp[-2].minor.yy615.mask = 0x000000; }
+      case 51: /* refarg ::= MATCH nm */
+{ yymsp[-1].minor.yy231.value = 0;     yymsp[-1].minor.yy231.mask = 0x000000; }
         break;
-      case 51: /* refarg ::= ON DELETE refact */
-{ yymsp[-2].minor.yy615.value = yymsp[0].minor.yy60;     yymsp[-2].minor.yy615.mask = 0x0000ff; }
+      case 52: /* refarg ::= ON INSERT refact */
+{ yymsp[-2].minor.yy231.value = 0;     yymsp[-2].minor.yy231.mask = 0x000000; }
         break;
-      case 52: /* refarg ::= ON UPDATE refact */
-{ yymsp[-2].minor.yy615.value = yymsp[0].minor.yy60<<8;  yymsp[-2].minor.yy615.mask = 0x00ff00; }
+      case 53: /* refarg ::= ON DELETE refact */
+{ yymsp[-2].minor.yy231.value = yymsp[0].minor.yy394;     yymsp[-2].minor.yy231.mask = 0x0000ff; }
         break;
-      case 53: /* refact ::= SET NULL */
-{ yymsp[-1].minor.yy60 = OE_SetNull;  /* EV: R-33326-45252 */}
+      case 54: /* refarg ::= ON UPDATE refact */
+{ yymsp[-2].minor.yy231.value = yymsp[0].minor.yy394<<8;  yymsp[-2].minor.yy231.mask = 0x00ff00; }
         break;
-      case 54: /* refact ::= SET DEFAULT */
-{ yymsp[-1].minor.yy60 = OE_SetDflt;  /* EV: R-33326-45252 */}
+      case 55: /* refact ::= SET NULL */
+{ yymsp[-1].minor.yy394 = OE_SetNull;  /* EV: R-33326-45252 */}
         break;
-      case 55: /* refact ::= CASCADE */
-{ yymsp[0].minor.yy60 = OE_Cascade;  /* EV: R-33326-45252 */}
+      case 56: /* refact ::= SET DEFAULT */
+{ yymsp[-1].minor.yy394 = OE_SetDflt;  /* EV: R-33326-45252 */}
         break;
-      case 56: /* refact ::= RESTRICT */
-{ yymsp[0].minor.yy60 = OE_Restrict; /* EV: R-33326-45252 */}
+      case 57: /* refact ::= CASCADE */
+{ yymsp[0].minor.yy394 = OE_Cascade;  /* EV: R-33326-45252 */}
         break;
-      case 57: /* refact ::= NO ACTION */
-{ yymsp[-1].minor.yy60 = OE_None;     /* EV: R-33326-45252 */}
+      case 58: /* refact ::= RESTRICT */
+{ yymsp[0].minor.yy394 = OE_Restrict; /* EV: R-33326-45252 */}
         break;
-      case 58: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
-{yymsp[-2].minor.yy60 = 0;}
+      case 59: /* refact ::= NO ACTION */
+{ yymsp[-1].minor.yy394 = OE_None;     /* EV: R-33326-45252 */}
         break;
-      case 59: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
-      case 74: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==74);
-      case 169: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==169);
-{yymsp[-1].minor.yy60 = yymsp[0].minor.yy60;}
+      case 60: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+{yymsp[-2].minor.yy394 = 0;}
         break;
-      case 61: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
-      case 78: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==78);
-      case 211: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==211);
-      case 214: /* in_op ::= NOT IN */ yytestcase(yyruleno==214);
-      case 240: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==240);
-{yymsp[-1].minor.yy60 = 1;}
+      case 61: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+      case 76: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==76);
+      case 171: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==171);
+{yymsp[-1].minor.yy394 = yymsp[0].minor.yy394;}
         break;
-      case 62: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
-{yymsp[-1].minor.yy60 = 0;}
+      case 63: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
+      case 80: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==80);
+      case 214: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==214);
+      case 217: /* in_op ::= NOT IN */ yytestcase(yyruleno==217);
+      case 243: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==243);
+{yymsp[-1].minor.yy394 = 1;}
         break;
-      case 64: /* tconscomma ::= COMMA */
+      case 64: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+{yymsp[-1].minor.yy394 = 0;}
+        break;
+      case 66: /* tconscomma ::= COMMA */
 {pParse->constraintName.n = 0;}
         break;
-      case 66: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
-{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy338,yymsp[0].minor.yy60,yymsp[-2].minor.yy60,0);}
+      case 68: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy394,yymsp[-2].minor.yy394,0);}
         break;
-      case 67: /* tcons ::= UNIQUE LP sortlist RP onconf */
-{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy338,yymsp[0].minor.yy60,0,0,0,0,
+      case 69: /* tcons ::= UNIQUE LP sortlist RP onconf */
+{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy394,0,0,0,0,
                                        SQLITE_IDXTYPE_UNIQUE);}
         break;
-      case 68: /* tcons ::= CHECK LP expr RP onconf */
-{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy602,yymsp[-3].minor.yy0.z,yymsp[-1].minor.yy0.z);}
+      case 70: /* tcons ::= CHECK LP expr RP onconf */
+{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy528,yymsp[-3].minor.yy0.z,yymsp[-1].minor.yy0.z);}
         break;
-      case 69: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+      case 71: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
 {
-    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy338, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy338, yymsp[-1].minor.yy60);
-    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy60);
+    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy394);
+    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy394);
 }
         break;
-      case 71: /* onconf ::= */
-      case 73: /* orconf ::= */ yytestcase(yyruleno==73);
-{yymsp[1].minor.yy60 = OE_Default;}
+      case 73: /* onconf ::= */
+      case 75: /* orconf ::= */ yytestcase(yyruleno==75);
+{yymsp[1].minor.yy394 = OE_Default;}
         break;
-      case 72: /* onconf ::= ON CONFLICT resolvetype */
-{yymsp[-2].minor.yy60 = yymsp[0].minor.yy60;}
+      case 74: /* onconf ::= ON CONFLICT resolvetype */
+{yymsp[-2].minor.yy394 = yymsp[0].minor.yy394;}
         break;
-      case 75: /* resolvetype ::= IGNORE */
-{yymsp[0].minor.yy60 = OE_Ignore;}
+      case 77: /* resolvetype ::= IGNORE */
+{yymsp[0].minor.yy394 = OE_Ignore;}
         break;
-      case 76: /* resolvetype ::= REPLACE */
-      case 170: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==170);
-{yymsp[0].minor.yy60 = OE_Replace;}
+      case 78: /* resolvetype ::= REPLACE */
+      case 172: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==172);
+{yymsp[0].minor.yy394 = OE_Replace;}
         break;
-      case 77: /* cmd ::= DROP TABLE ifexists fullname */
+      case 79: /* cmd ::= DROP TABLE ifexists fullname */
 {
-  sqlite3DropTable(pParse, yymsp[0].minor.yy291, 0, yymsp[-1].minor.yy60);
+  sqlite3DropTable(pParse, yymsp[0].minor.yy131, 0, yymsp[-1].minor.yy394);
 }
         break;
-      case 80: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+      case 82: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
 {
-  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy338, yymsp[0].minor.yy307, yymsp[-7].minor.yy60, yymsp[-5].minor.yy60);
+  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[0].minor.yy47, yymsp[-7].minor.yy394, yymsp[-5].minor.yy394);
 }
         break;
-      case 81: /* cmd ::= DROP VIEW ifexists fullname */
+      case 83: /* cmd ::= DROP VIEW ifexists fullname */
 {
-  sqlite3DropTable(pParse, yymsp[0].minor.yy291, 1, yymsp[-1].minor.yy60);
+  sqlite3DropTable(pParse, yymsp[0].minor.yy131, 1, yymsp[-1].minor.yy394);
 }
         break;
-      case 82: /* cmd ::= select */
+      case 84: /* cmd ::= select */
 {
   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0, 0};
-  sqlite3Select(pParse, yymsp[0].minor.yy307, &dest);
-  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy307);
+  sqlite3Select(pParse, yymsp[0].minor.yy47, &dest);
+  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy47);
 }
         break;
-      case 83: /* select ::= WITH wqlist selectnowith */
-{yymsp[-2].minor.yy307 = attachWithToSelect(pParse,yymsp[0].minor.yy307,yymsp[-1].minor.yy195);}
+      case 85: /* select ::= WITH wqlist selectnowith */
+{yymsp[-2].minor.yy47 = attachWithToSelect(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy521);}
         break;
-      case 84: /* select ::= WITH RECURSIVE wqlist selectnowith */
-{yymsp[-3].minor.yy307 = attachWithToSelect(pParse,yymsp[0].minor.yy307,yymsp[-1].minor.yy195);}
+      case 86: /* select ::= WITH RECURSIVE wqlist selectnowith */
+{yymsp[-3].minor.yy47 = attachWithToSelect(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy521);}
         break;
-      case 85: /* select ::= selectnowith */
+      case 87: /* select ::= selectnowith */
 {
-  Select *p = yymsp[0].minor.yy307;
+  Select *p = yymsp[0].minor.yy47;
   if( p ){
     parserDoubleLinkSelect(pParse, p);
   }
-  yymsp[0].minor.yy307 = p; /*A-overwrites-X*/
+  yymsp[0].minor.yy47 = p; /*A-overwrites-X*/
 }
         break;
-      case 86: /* selectnowith ::= selectnowith multiselect_op oneselect */
+      case 88: /* selectnowith ::= selectnowith multiselect_op oneselect */
 {
-  Select *pRhs = yymsp[0].minor.yy307;
-  Select *pLhs = yymsp[-2].minor.yy307;
+  Select *pRhs = yymsp[0].minor.yy47;
+  Select *pLhs = yymsp[-2].minor.yy47;
   if( pRhs && pRhs->pPrior ){
     SrcList *pFrom;
     Token x;
@@ -160831,140 +165305,140 @@ static YYACTIONTYPE yy_reduce(
     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
   }
   if( pRhs ){
-    pRhs->op = (u8)yymsp[-1].minor.yy60;
+    pRhs->op = (u8)yymsp[-1].minor.yy394;
     pRhs->pPrior = pLhs;
     if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
     pRhs->selFlags &= ~SF_MultiValue;
-    if( yymsp[-1].minor.yy60!=TK_ALL ) pParse->hasCompound = 1;
+    if( yymsp[-1].minor.yy394!=TK_ALL ) pParse->hasCompound = 1;
   }else{
     sqlite3SelectDelete(pParse->db, pLhs);
   }
-  yymsp[-2].minor.yy307 = pRhs;
+  yymsp[-2].minor.yy47 = pRhs;
 }
         break;
-      case 87: /* multiselect_op ::= UNION */
-      case 89: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==89);
-{yymsp[0].minor.yy60 = yymsp[0].major; /*A-overwrites-OP*/}
+      case 89: /* multiselect_op ::= UNION */
+      case 91: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==91);
+{yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-OP*/}
         break;
-      case 88: /* multiselect_op ::= UNION ALL */
-{yymsp[-1].minor.yy60 = TK_ALL;}
+      case 90: /* multiselect_op ::= UNION ALL */
+{yymsp[-1].minor.yy394 = TK_ALL;}
         break;
-      case 90: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+      case 92: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
 {
-  yymsp[-8].minor.yy307 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy338,yymsp[-5].minor.yy291,yymsp[-4].minor.yy602,yymsp[-3].minor.yy338,yymsp[-2].minor.yy602,yymsp[-1].minor.yy338,yymsp[-7].minor.yy60,yymsp[0].minor.yy602);
+  yymsp[-8].minor.yy47 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy131,yymsp[-4].minor.yy528,yymsp[-3].minor.yy322,yymsp[-2].minor.yy528,yymsp[-1].minor.yy322,yymsp[-7].minor.yy394,yymsp[0].minor.yy528);
 }
         break;
-      case 91: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+      case 93: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
 {
-  yymsp[-9].minor.yy307 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy338,yymsp[-6].minor.yy291,yymsp[-5].minor.yy602,yymsp[-4].minor.yy338,yymsp[-3].minor.yy602,yymsp[-1].minor.yy338,yymsp[-8].minor.yy60,yymsp[0].minor.yy602);
-  if( yymsp[-9].minor.yy307 ){
-    yymsp[-9].minor.yy307->pWinDefn = yymsp[-2].minor.yy19;
+  yymsp[-9].minor.yy47 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy322,yymsp[-6].minor.yy131,yymsp[-5].minor.yy528,yymsp[-4].minor.yy322,yymsp[-3].minor.yy528,yymsp[-1].minor.yy322,yymsp[-8].minor.yy394,yymsp[0].minor.yy528);
+  if( yymsp[-9].minor.yy47 ){
+    yymsp[-9].minor.yy47->pWinDefn = yymsp[-2].minor.yy41;
   }else{
-    sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy19);
+    sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy41);
   }
 }
         break;
-      case 92: /* values ::= VALUES LP nexprlist RP */
+      case 94: /* values ::= VALUES LP nexprlist RP */
 {
-  yymsp[-3].minor.yy307 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy338,0,0,0,0,0,SF_Values,0);
+  yymsp[-3].minor.yy47 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values,0);
 }
         break;
-      case 93: /* values ::= values COMMA LP nexprlist RP */
+      case 95: /* values ::= values COMMA LP nexprlist RP */
 {
-  Select *pRight, *pLeft = yymsp[-4].minor.yy307;
-  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy338,0,0,0,0,0,SF_Values|SF_MultiValue,0);
+  Select *pRight, *pLeft = yymsp[-4].minor.yy47;
+  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values|SF_MultiValue,0);
   if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
   if( pRight ){
     pRight->op = TK_ALL;
     pRight->pPrior = pLeft;
-    yymsp[-4].minor.yy307 = pRight;
+    yymsp[-4].minor.yy47 = pRight;
   }else{
-    yymsp[-4].minor.yy307 = pLeft;
+    yymsp[-4].minor.yy47 = pLeft;
   }
 }
         break;
-      case 94: /* distinct ::= DISTINCT */
-{yymsp[0].minor.yy60 = SF_Distinct;}
+      case 96: /* distinct ::= DISTINCT */
+{yymsp[0].minor.yy394 = SF_Distinct;}
         break;
-      case 95: /* distinct ::= ALL */
-{yymsp[0].minor.yy60 = SF_All;}
+      case 97: /* distinct ::= ALL */
+{yymsp[0].minor.yy394 = SF_All;}
         break;
-      case 97: /* sclp ::= */
-      case 130: /* orderby_opt ::= */ yytestcase(yyruleno==130);
-      case 140: /* groupby_opt ::= */ yytestcase(yyruleno==140);
-      case 227: /* exprlist ::= */ yytestcase(yyruleno==227);
-      case 230: /* paren_exprlist ::= */ yytestcase(yyruleno==230);
-      case 235: /* eidlist_opt ::= */ yytestcase(yyruleno==235);
-{yymsp[1].minor.yy338 = 0;}
+      case 99: /* sclp ::= */
+      case 132: /* orderby_opt ::= */ yytestcase(yyruleno==132);
+      case 142: /* groupby_opt ::= */ yytestcase(yyruleno==142);
+      case 230: /* exprlist ::= */ yytestcase(yyruleno==230);
+      case 233: /* paren_exprlist ::= */ yytestcase(yyruleno==233);
+      case 238: /* eidlist_opt ::= */ yytestcase(yyruleno==238);
+{yymsp[1].minor.yy322 = 0;}
         break;
-      case 98: /* selcollist ::= sclp scanpt expr scanpt as */
+      case 100: /* selcollist ::= sclp scanpt expr scanpt as */
 {
-   yymsp[-4].minor.yy338 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy338, yymsp[-2].minor.yy602);
-   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy338, &yymsp[0].minor.yy0, 1);
-   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy338,yymsp[-3].minor.yy528,yymsp[-1].minor.yy528);
+   yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
+   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[0].minor.yy0, 1);
+   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy322,yymsp[-3].minor.yy522,yymsp[-1].minor.yy522);
 }
         break;
-      case 99: /* selcollist ::= sclp scanpt STAR */
+      case 101: /* selcollist ::= sclp scanpt STAR */
 {
   Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
-  yymsp[-2].minor.yy338 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy338, p);
+  yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, p);
 }
         break;
-      case 100: /* selcollist ::= sclp scanpt nm DOT STAR */
+      case 102: /* selcollist ::= sclp scanpt nm DOT STAR */
 {
   Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
-  Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
+  Expr *pLeft = tokenExpr(pParse, TK_ID, yymsp[-2].minor.yy0);
   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
-  yymsp[-4].minor.yy338 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy338, pDot);
+  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, pDot);
 }
         break;
-      case 101: /* as ::= AS nm */
-      case 112: /* dbnm ::= DOT nm */ yytestcase(yyruleno==112);
-      case 251: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==251);
-      case 252: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==252);
+      case 103: /* as ::= AS nm */
+      case 114: /* dbnm ::= DOT nm */ yytestcase(yyruleno==114);
+      case 254: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==254);
+      case 255: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==255);
 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
         break;
-      case 103: /* from ::= */
-      case 106: /* stl_prefix ::= */ yytestcase(yyruleno==106);
-{yymsp[1].minor.yy291 = 0;}
+      case 105: /* from ::= */
+      case 108: /* stl_prefix ::= */ yytestcase(yyruleno==108);
+{yymsp[1].minor.yy131 = 0;}
         break;
-      case 104: /* from ::= FROM seltablist */
+      case 106: /* from ::= FROM seltablist */
 {
-  yymsp[-1].minor.yy291 = yymsp[0].minor.yy291;
-  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy291);
+  yymsp[-1].minor.yy131 = yymsp[0].minor.yy131;
+  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy131);
 }
         break;
-      case 105: /* stl_prefix ::= seltablist joinop */
+      case 107: /* stl_prefix ::= seltablist joinop */
 {
-   if( ALWAYS(yymsp[-1].minor.yy291 && yymsp[-1].minor.yy291->nSrc>0) ) yymsp[-1].minor.yy291->a[yymsp[-1].minor.yy291->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy60;
+   if( ALWAYS(yymsp[-1].minor.yy131 && yymsp[-1].minor.yy131->nSrc>0) ) yymsp[-1].minor.yy131->a[yymsp[-1].minor.yy131->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy394;
 }
         break;
-      case 107: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+      case 109: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
 {
-  yymsp[-6].minor.yy291 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy291,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy602,yymsp[0].minor.yy288);
-  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy291, &yymsp[-2].minor.yy0);
+  yymsp[-6].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy131,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy528,yymsp[0].minor.yy254);
+  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy131, &yymsp[-2].minor.yy0);
 }
         break;
-      case 108: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+      case 110: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
 {
-  yymsp[-8].minor.yy291 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy291,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy602,yymsp[0].minor.yy288);
-  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy291, yymsp[-4].minor.yy338);
+  yymsp[-8].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy131,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy528,yymsp[0].minor.yy254);
+  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy131, yymsp[-4].minor.yy322);
 }
         break;
-      case 109: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+      case 111: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
 {
-    yymsp[-6].minor.yy291 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy291,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy307,yymsp[-1].minor.yy602,yymsp[0].minor.yy288);
+    yymsp[-6].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy131,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy47,yymsp[-1].minor.yy528,yymsp[0].minor.yy254);
   }
         break;
-      case 110: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+      case 112: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
 {
-    if( yymsp[-6].minor.yy291==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy602==0 && yymsp[0].minor.yy288==0 ){
-      yymsp[-6].minor.yy291 = yymsp[-4].minor.yy291;
-    }else if( yymsp[-4].minor.yy291->nSrc==1 ){
-      yymsp[-6].minor.yy291 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy291,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy602,yymsp[0].minor.yy288);
-      if( yymsp[-6].minor.yy291 ){
-        SrcItem *pNew = &yymsp[-6].minor.yy291->a[yymsp[-6].minor.yy291->nSrc-1];
-        SrcItem *pOld = yymsp[-4].minor.yy291->a;
+    if( yymsp[-6].minor.yy131==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy528==0 && yymsp[0].minor.yy254==0 ){
+      yymsp[-6].minor.yy131 = yymsp[-4].minor.yy131;
+    }else if( yymsp[-4].minor.yy131->nSrc==1 ){
+      yymsp[-6].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy131,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy528,yymsp[0].minor.yy254);
+      if( yymsp[-6].minor.yy131 ){
+        SrcItem *pNew = &yymsp[-6].minor.yy131->a[yymsp[-6].minor.yy131->nSrc-1];
+        SrcItem *pOld = yymsp[-4].minor.yy131->a;
         pNew->zName = pOld->zName;
         pNew->zDatabase = pOld->zDatabase;
         pNew->pSelect = pOld->pSelect;
@@ -160977,267 +165451,263 @@ static YYACTIONTYPE yy_reduce(
         pOld->zName = pOld->zDatabase = 0;
         pOld->pSelect = 0;
       }
-      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy291);
+      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy131);
     }else{
       Select *pSubquery;
-      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy291);
-      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy291,0,0,0,0,SF_NestedFrom,0);
-      yymsp[-6].minor.yy291 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy291,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy602,yymsp[0].minor.yy288);
+      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy131);
+      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy131,0,0,0,0,SF_NestedFrom,0);
+      yymsp[-6].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy131,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy528,yymsp[0].minor.yy254);
     }
   }
         break;
-      case 111: /* dbnm ::= */
-      case 125: /* indexed_opt ::= */ yytestcase(yyruleno==125);
+      case 113: /* dbnm ::= */
+      case 127: /* indexed_opt ::= */ yytestcase(yyruleno==127);
 {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
         break;
-      case 113: /* fullname ::= nm */
+      case 115: /* fullname ::= nm */
 {
-  yylhsminor.yy291 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
-  if( IN_RENAME_OBJECT && yylhsminor.yy291 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy291->a[0].zName, &yymsp[0].minor.yy0);
+  yylhsminor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
+  if( IN_RENAME_OBJECT && yylhsminor.yy131 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy131->a[0].zName, &yymsp[0].minor.yy0);
 }
-  yymsp[0].minor.yy291 = yylhsminor.yy291;
+  yymsp[0].minor.yy131 = yylhsminor.yy131;
         break;
-      case 114: /* fullname ::= nm DOT nm */
+      case 116: /* fullname ::= nm DOT nm */
 {
-  yylhsminor.yy291 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
-  if( IN_RENAME_OBJECT && yylhsminor.yy291 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy291->a[0].zName, &yymsp[0].minor.yy0);
+  yylhsminor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
+  if( IN_RENAME_OBJECT && yylhsminor.yy131 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy131->a[0].zName, &yymsp[0].minor.yy0);
 }
-  yymsp[-2].minor.yy291 = yylhsminor.yy291;
+  yymsp[-2].minor.yy131 = yylhsminor.yy131;
         break;
-      case 115: /* xfullname ::= nm */
-{yymsp[0].minor.yy291 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
+      case 117: /* xfullname ::= nm */
+{yymsp[0].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
         break;
-      case 116: /* xfullname ::= nm DOT nm */
-{yymsp[-2].minor.yy291 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
+      case 118: /* xfullname ::= nm DOT nm */
+{yymsp[-2].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
         break;
-      case 117: /* xfullname ::= nm DOT nm AS nm */
+      case 119: /* xfullname ::= nm DOT nm AS nm */
 {
-   yymsp[-4].minor.yy291 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
-   if( yymsp[-4].minor.yy291 ) yymsp[-4].minor.yy291->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
+   yymsp[-4].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
+   if( yymsp[-4].minor.yy131 ) yymsp[-4].minor.yy131->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
 }
         break;
-      case 118: /* xfullname ::= nm AS nm */
+      case 120: /* xfullname ::= nm AS nm */
 {
-   yymsp[-2].minor.yy291 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
-   if( yymsp[-2].minor.yy291 ) yymsp[-2].minor.yy291->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
+   yymsp[-2].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
+   if( yymsp[-2].minor.yy131 ) yymsp[-2].minor.yy131->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
 }
         break;
-      case 119: /* joinop ::= COMMA|JOIN */
-{ yymsp[0].minor.yy60 = JT_INNER; }
+      case 121: /* joinop ::= COMMA|JOIN */
+{ yymsp[0].minor.yy394 = JT_INNER; }
         break;
-      case 120: /* joinop ::= JOIN_KW JOIN */
-{yymsp[-1].minor.yy60 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
+      case 122: /* joinop ::= JOIN_KW JOIN */
+{yymsp[-1].minor.yy394 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
         break;
-      case 121: /* joinop ::= JOIN_KW nm JOIN */
-{yymsp[-2].minor.yy60 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
+      case 123: /* joinop ::= JOIN_KW nm JOIN */
+{yymsp[-2].minor.yy394 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
         break;
-      case 122: /* joinop ::= JOIN_KW nm nm JOIN */
-{yymsp[-3].minor.yy60 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
+      case 124: /* joinop ::= JOIN_KW nm nm JOIN */
+{yymsp[-3].minor.yy394 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
         break;
-      case 123: /* on_opt ::= ON expr */
-      case 143: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==143);
-      case 150: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==150);
-      case 152: /* where_opt_ret ::= WHERE expr */ yytestcase(yyruleno==152);
-      case 223: /* case_else ::= ELSE expr */ yytestcase(yyruleno==223);
-      case 244: /* vinto ::= INTO expr */ yytestcase(yyruleno==244);
-{yymsp[-1].minor.yy602 = yymsp[0].minor.yy602;}
+      case 125: /* on_opt ::= ON expr */
+      case 145: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==145);
+      case 152: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==152);
+      case 154: /* where_opt_ret ::= WHERE expr */ yytestcase(yyruleno==154);
+      case 226: /* case_else ::= ELSE expr */ yytestcase(yyruleno==226);
+      case 247: /* vinto ::= INTO expr */ yytestcase(yyruleno==247);
+{yymsp[-1].minor.yy528 = yymsp[0].minor.yy528;}
         break;
-      case 124: /* on_opt ::= */
-      case 142: /* having_opt ::= */ yytestcase(yyruleno==142);
-      case 144: /* limit_opt ::= */ yytestcase(yyruleno==144);
-      case 149: /* where_opt ::= */ yytestcase(yyruleno==149);
-      case 151: /* where_opt_ret ::= */ yytestcase(yyruleno==151);
-      case 224: /* case_else ::= */ yytestcase(yyruleno==224);
-      case 226: /* case_operand ::= */ yytestcase(yyruleno==226);
-      case 245: /* vinto ::= */ yytestcase(yyruleno==245);
-{yymsp[1].minor.yy602 = 0;}
+      case 126: /* on_opt ::= */
+      case 144: /* having_opt ::= */ yytestcase(yyruleno==144);
+      case 146: /* limit_opt ::= */ yytestcase(yyruleno==146);
+      case 151: /* where_opt ::= */ yytestcase(yyruleno==151);
+      case 153: /* where_opt_ret ::= */ yytestcase(yyruleno==153);
+      case 227: /* case_else ::= */ yytestcase(yyruleno==227);
+      case 229: /* case_operand ::= */ yytestcase(yyruleno==229);
+      case 248: /* vinto ::= */ yytestcase(yyruleno==248);
+{yymsp[1].minor.yy528 = 0;}
         break;
-      case 126: /* indexed_opt ::= INDEXED BY nm */
+      case 128: /* indexed_opt ::= INDEXED BY nm */
 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
         break;
-      case 127: /* indexed_opt ::= NOT INDEXED */
+      case 129: /* indexed_opt ::= NOT INDEXED */
 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
         break;
-      case 128: /* using_opt ::= USING LP idlist RP */
-{yymsp[-3].minor.yy288 = yymsp[-1].minor.yy288;}
+      case 130: /* using_opt ::= USING LP idlist RP */
+{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
         break;
-      case 129: /* using_opt ::= */
-      case 171: /* idlist_opt ::= */ yytestcase(yyruleno==171);
-{yymsp[1].minor.yy288 = 0;}
+      case 131: /* using_opt ::= */
+      case 173: /* idlist_opt ::= */ yytestcase(yyruleno==173);
+{yymsp[1].minor.yy254 = 0;}
         break;
-      case 131: /* orderby_opt ::= ORDER BY sortlist */
-      case 141: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==141);
-{yymsp[-2].minor.yy338 = yymsp[0].minor.yy338;}
+      case 133: /* orderby_opt ::= ORDER BY sortlist */
+      case 143: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==143);
+{yymsp[-2].minor.yy322 = yymsp[0].minor.yy322;}
         break;
-      case 132: /* sortlist ::= sortlist COMMA expr sortorder nulls */
+      case 134: /* sortlist ::= sortlist COMMA expr sortorder nulls */
 {
-  yymsp[-4].minor.yy338 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy338,yymsp[-2].minor.yy602);
-  sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy338,yymsp[-1].minor.yy60,yymsp[0].minor.yy60);
+  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322,yymsp[-2].minor.yy528);
+  sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy322,yymsp[-1].minor.yy394,yymsp[0].minor.yy394);
 }
         break;
-      case 133: /* sortlist ::= expr sortorder nulls */
+      case 135: /* sortlist ::= expr sortorder nulls */
 {
-  yymsp[-2].minor.yy338 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy602); /*A-overwrites-Y*/
-  sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy338,yymsp[-1].minor.yy60,yymsp[0].minor.yy60);
+  yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy528); /*A-overwrites-Y*/
+  sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy322,yymsp[-1].minor.yy394,yymsp[0].minor.yy394);
 }
         break;
-      case 134: /* sortorder ::= ASC */
-{yymsp[0].minor.yy60 = SQLITE_SO_ASC;}
+      case 136: /* sortorder ::= ASC */
+{yymsp[0].minor.yy394 = SQLITE_SO_ASC;}
         break;
-      case 135: /* sortorder ::= DESC */
-{yymsp[0].minor.yy60 = SQLITE_SO_DESC;}
+      case 137: /* sortorder ::= DESC */
+{yymsp[0].minor.yy394 = SQLITE_SO_DESC;}
         break;
-      case 136: /* sortorder ::= */
-      case 139: /* nulls ::= */ yytestcase(yyruleno==139);
-{yymsp[1].minor.yy60 = SQLITE_SO_UNDEFINED;}
+      case 138: /* sortorder ::= */
+      case 141: /* nulls ::= */ yytestcase(yyruleno==141);
+{yymsp[1].minor.yy394 = SQLITE_SO_UNDEFINED;}
         break;
-      case 137: /* nulls ::= NULLS FIRST */
-{yymsp[-1].minor.yy60 = SQLITE_SO_ASC;}
+      case 139: /* nulls ::= NULLS FIRST */
+{yymsp[-1].minor.yy394 = SQLITE_SO_ASC;}
         break;
-      case 138: /* nulls ::= NULLS LAST */
-{yymsp[-1].minor.yy60 = SQLITE_SO_DESC;}
+      case 140: /* nulls ::= NULLS LAST */
+{yymsp[-1].minor.yy394 = SQLITE_SO_DESC;}
         break;
-      case 145: /* limit_opt ::= LIMIT expr */
-{yymsp[-1].minor.yy602 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy602,0);}
+      case 147: /* limit_opt ::= LIMIT expr */
+{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy528,0);}
         break;
-      case 146: /* limit_opt ::= LIMIT expr OFFSET expr */
-{yymsp[-3].minor.yy602 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy602,yymsp[0].minor.yy602);}
+      case 148: /* limit_opt ::= LIMIT expr OFFSET expr */
+{yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
         break;
-      case 147: /* limit_opt ::= LIMIT expr COMMA expr */
-{yymsp[-3].minor.yy602 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy602,yymsp[-2].minor.yy602);}
+      case 149: /* limit_opt ::= LIMIT expr COMMA expr */
+{yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy528,yymsp[-2].minor.yy528);}
         break;
-      case 148: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
+      case 150: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
 {
-  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy291, &yymsp[-1].minor.yy0);
-  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy291,yymsp[0].minor.yy602,0,0);
+  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy131, &yymsp[-1].minor.yy0);
+  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy131,yymsp[0].minor.yy528,0,0);
 }
         break;
-      case 153: /* where_opt_ret ::= RETURNING selcollist */
-{sqlite3AddReturning(pParse,yymsp[0].minor.yy338); yymsp[-1].minor.yy602 = 0;}
+      case 155: /* where_opt_ret ::= RETURNING selcollist */
+{sqlite3AddReturning(pParse,yymsp[0].minor.yy322); yymsp[-1].minor.yy528 = 0;}
         break;
-      case 154: /* where_opt_ret ::= WHERE expr RETURNING selcollist */
-{sqlite3AddReturning(pParse,yymsp[0].minor.yy338); yymsp[-3].minor.yy602 = yymsp[-2].minor.yy602;}
+      case 156: /* where_opt_ret ::= WHERE expr RETURNING selcollist */
+{sqlite3AddReturning(pParse,yymsp[0].minor.yy322); yymsp[-3].minor.yy528 = yymsp[-2].minor.yy528;}
         break;
-      case 155: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
+      case 157: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
 {
-  sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy291, &yymsp[-4].minor.yy0);
-  sqlite3ExprListCheckLength(pParse,yymsp[-2].minor.yy338,"set list");
-  yymsp[-5].minor.yy291 = sqlite3SrcListAppendList(pParse, yymsp[-5].minor.yy291, yymsp[-1].minor.yy291);
-  sqlite3Update(pParse,yymsp[-5].minor.yy291,yymsp[-2].minor.yy338,yymsp[0].minor.yy602,yymsp[-6].minor.yy60,0,0,0);
+  sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy131, &yymsp[-4].minor.yy0);
+  sqlite3ExprListCheckLength(pParse,yymsp[-2].minor.yy322,"set list");
+  yymsp[-5].minor.yy131 = sqlite3SrcListAppendList(pParse, yymsp[-5].minor.yy131, yymsp[-1].minor.yy131);
+  sqlite3Update(pParse,yymsp[-5].minor.yy131,yymsp[-2].minor.yy322,yymsp[0].minor.yy528,yymsp[-6].minor.yy394,0,0,0);
 }
         break;
-      case 156: /* setlist ::= setlist COMMA nm EQ expr */
+      case 158: /* setlist ::= setlist COMMA nm EQ expr */
 {
-  yymsp[-4].minor.yy338 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy338, yymsp[0].minor.yy602);
-  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy338, &yymsp[-2].minor.yy0, 1);
+  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy528);
+  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, 1);
 }
         break;
-      case 157: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
+      case 159: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
 {
-  yymsp[-6].minor.yy338 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy338, yymsp[-3].minor.yy288, yymsp[0].minor.yy602);
+  yymsp[-6].minor.yy322 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy322, yymsp[-3].minor.yy254, yymsp[0].minor.yy528);
 }
         break;
-      case 158: /* setlist ::= nm EQ expr */
+      case 160: /* setlist ::= nm EQ expr */
 {
-  yylhsminor.yy338 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy602);
-  sqlite3ExprListSetName(pParse, yylhsminor.yy338, &yymsp[-2].minor.yy0, 1);
+  yylhsminor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy528);
+  sqlite3ExprListSetName(pParse, yylhsminor.yy322, &yymsp[-2].minor.yy0, 1);
 }
-  yymsp[-2].minor.yy338 = yylhsminor.yy338;
+  yymsp[-2].minor.yy322 = yylhsminor.yy322;
         break;
-      case 159: /* setlist ::= LP idlist RP EQ expr */
+      case 161: /* setlist ::= LP idlist RP EQ expr */
 {
-  yymsp[-4].minor.yy338 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy288, yymsp[0].minor.yy602);
+  yymsp[-4].minor.yy322 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy528);
 }
         break;
-      case 160: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+      case 162: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
 {
-  sqlite3Insert(pParse, yymsp[-3].minor.yy291, yymsp[-1].minor.yy307, yymsp[-2].minor.yy288, yymsp[-5].minor.yy60, yymsp[0].minor.yy178);
+  sqlite3Insert(pParse, yymsp[-3].minor.yy131, yymsp[-1].minor.yy47, yymsp[-2].minor.yy254, yymsp[-5].minor.yy394, yymsp[0].minor.yy444);
 }
         break;
-      case 161: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
+      case 163: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
 {
-  sqlite3Insert(pParse, yymsp[-4].minor.yy291, 0, yymsp[-3].minor.yy288, yymsp[-6].minor.yy60, 0);
+  sqlite3Insert(pParse, yymsp[-4].minor.yy131, 0, yymsp[-3].minor.yy254, yymsp[-6].minor.yy394, 0);
 }
         break;
-      case 162: /* upsert ::= */
-{ yymsp[1].minor.yy178 = 0; }
+      case 164: /* upsert ::= */
+{ yymsp[1].minor.yy444 = 0; }
         break;
-      case 163: /* upsert ::= RETURNING selcollist */
-{ yymsp[-1].minor.yy178 = 0; sqlite3AddReturning(pParse,yymsp[0].minor.yy338); }
+      case 165: /* upsert ::= RETURNING selcollist */
+{ yymsp[-1].minor.yy444 = 0; sqlite3AddReturning(pParse,yymsp[0].minor.yy322); }
         break;
-      case 164: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
-{ yymsp[-11].minor.yy178 = sqlite3UpsertNew(pParse->db,yymsp[-8].minor.yy338,yymsp[-6].minor.yy602,yymsp[-2].minor.yy338,yymsp[-1].minor.yy602,yymsp[0].minor.yy178);}
+      case 166: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */
+{ yymsp[-11].minor.yy444 = sqlite3UpsertNew(pParse->db,yymsp[-8].minor.yy322,yymsp[-6].minor.yy528,yymsp[-2].minor.yy322,yymsp[-1].minor.yy528,yymsp[0].minor.yy444);}
         break;
-      case 165: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
-{ yymsp[-8].minor.yy178 = sqlite3UpsertNew(pParse->db,yymsp[-5].minor.yy338,yymsp[-3].minor.yy602,0,0,yymsp[0].minor.yy178); }
+      case 167: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
+{ yymsp[-8].minor.yy444 = sqlite3UpsertNew(pParse->db,yymsp[-5].minor.yy322,yymsp[-3].minor.yy528,0,0,yymsp[0].minor.yy444); }
         break;
-      case 166: /* upsert ::= ON CONFLICT DO NOTHING returning */
-{ yymsp[-4].minor.yy178 = sqlite3UpsertNew(pParse->db,0,0,0,0,0); }
+      case 168: /* upsert ::= ON CONFLICT DO NOTHING returning */
+{ yymsp[-4].minor.yy444 = sqlite3UpsertNew(pParse->db,0,0,0,0,0); }
         break;
-      case 167: /* upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
-{ yymsp[-7].minor.yy178 = sqlite3UpsertNew(pParse->db,0,0,yymsp[-2].minor.yy338,yymsp[-1].minor.yy602,0);}
+      case 169: /* upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
+{ yymsp[-7].minor.yy444 = sqlite3UpsertNew(pParse->db,0,0,yymsp[-2].minor.yy322,yymsp[-1].minor.yy528,0);}
         break;
-      case 168: /* returning ::= RETURNING selcollist */
-{sqlite3AddReturning(pParse,yymsp[0].minor.yy338);}
+      case 170: /* returning ::= RETURNING selcollist */
+{sqlite3AddReturning(pParse,yymsp[0].minor.yy322);}
         break;
-      case 172: /* idlist_opt ::= LP idlist RP */
-{yymsp[-2].minor.yy288 = yymsp[-1].minor.yy288;}
+      case 174: /* idlist_opt ::= LP idlist RP */
+{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
         break;
-      case 173: /* idlist ::= idlist COMMA nm */
-{yymsp[-2].minor.yy288 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy288,&yymsp[0].minor.yy0);}
+      case 175: /* idlist ::= idlist COMMA nm */
+{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
         break;
-      case 174: /* idlist ::= nm */
-{yymsp[0].minor.yy288 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
+      case 176: /* idlist ::= nm */
+{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
         break;
-      case 175: /* expr ::= LP expr RP */
-{yymsp[-2].minor.yy602 = yymsp[-1].minor.yy602;}
+      case 177: /* expr ::= LP expr RP */
+{yymsp[-2].minor.yy528 = yymsp[-1].minor.yy528;}
         break;
-      case 176: /* expr ::= ID|INDEXED */
-      case 177: /* expr ::= JOIN_KW */ yytestcase(yyruleno==177);
-{yymsp[0].minor.yy602=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
+      case 178: /* expr ::= ID|INDEXED */
+      case 179: /* expr ::= JOIN_KW */ yytestcase(yyruleno==179);
+{yymsp[0].minor.yy528=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
         break;
-      case 178: /* expr ::= nm DOT nm */
+      case 180: /* expr ::= nm DOT nm */
 {
-  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
-  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
-  if( IN_RENAME_OBJECT ){
-    sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
-    sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
-  }
-  yylhsminor.yy602 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
+  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
+  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
+  yylhsminor.yy528 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
 }
-  yymsp[-2].minor.yy602 = yylhsminor.yy602;
+  yymsp[-2].minor.yy528 = yylhsminor.yy528;
         break;
-      case 179: /* expr ::= nm DOT nm DOT nm */
+      case 181: /* expr ::= nm DOT nm DOT nm */
 {
-  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
-  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
-  Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
+  Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-4].minor.yy0);
+  Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
+  Expr *temp3 = tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0);
   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
   if( IN_RENAME_OBJECT ){
-    sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
-    sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
+    sqlite3RenameTokenRemap(pParse, 0, temp1);
   }
-  yylhsminor.yy602 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
+  yylhsminor.yy528 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
 }
-  yymsp[-4].minor.yy602 = yylhsminor.yy602;
+  yymsp[-4].minor.yy528 = yylhsminor.yy528;
         break;
-      case 180: /* term ::= NULL|FLOAT|BLOB */
-      case 181: /* term ::= STRING */ yytestcase(yyruleno==181);
-{yymsp[0].minor.yy602=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
+      case 182: /* term ::= NULL|FLOAT|BLOB */
+      case 183: /* term ::= STRING */ yytestcase(yyruleno==183);
+{yymsp[0].minor.yy528=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
         break;
-      case 182: /* term ::= INTEGER */
+      case 184: /* term ::= INTEGER */
 {
-  yylhsminor.yy602 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
+  yylhsminor.yy528 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
+  if( yylhsminor.yy528 ) yylhsminor.yy528->w.iOfst = (int)(yymsp[0].minor.yy0.z - pParse->zTail);
 }
-  yymsp[0].minor.yy602 = yylhsminor.yy602;
+  yymsp[0].minor.yy528 = yylhsminor.yy528;
         break;
-      case 183: /* expr ::= VARIABLE */
+      case 185: /* expr ::= VARIABLE */
 {
   if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
     u32 n = yymsp[0].minor.yy0.n;
-    yymsp[0].minor.yy602 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
-    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy602, n);
+    yymsp[0].minor.yy528 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
+    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy528, n);
   }else{
     /* When doing a nested parse, one can include terms in an expression
     ** that look like this:   #1 #2 ...  These terms refer to registers
@@ -161246,159 +165716,167 @@ static YYACTIONTYPE yy_reduce(
     assert( t.n>=2 );
     if( pParse->nested==0 ){
       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
-      yymsp[0].minor.yy602 = 0;
+      yymsp[0].minor.yy528 = 0;
     }else{
-      yymsp[0].minor.yy602 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
-      if( yymsp[0].minor.yy602 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy602->iTable);
+      yymsp[0].minor.yy528 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
+      if( yymsp[0].minor.yy528 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy528->iTable);
     }
   }
 }
         break;
-      case 184: /* expr ::= expr COLLATE ID|STRING */
+      case 186: /* expr ::= expr COLLATE ID|STRING */
 {
-  yymsp[-2].minor.yy602 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy602, &yymsp[0].minor.yy0, 1);
+  yymsp[-2].minor.yy528 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy528, &yymsp[0].minor.yy0, 1);
 }
         break;
-      case 185: /* expr ::= CAST LP expr AS typetoken RP */
+      case 187: /* expr ::= CAST LP expr AS typetoken RP */
 {
-  yymsp[-5].minor.yy602 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
-  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy602, yymsp[-3].minor.yy602, 0);
+  yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
+  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy528, yymsp[-3].minor.yy528, 0);
 }
         break;
-      case 186: /* expr ::= ID|INDEXED LP distinct exprlist RP */
+      case 188: /* expr ::= ID|INDEXED LP distinct exprlist RP */
 {
-  yylhsminor.yy602 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy338, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy60);
+  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy394);
 }
-  yymsp[-4].minor.yy602 = yylhsminor.yy602;
+  yymsp[-4].minor.yy528 = yylhsminor.yy528;
         break;
-      case 187: /* expr ::= ID|INDEXED LP STAR RP */
+      case 189: /* expr ::= ID|INDEXED LP STAR RP */
 {
-  yylhsminor.yy602 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
+  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
 }
-  yymsp[-3].minor.yy602 = yylhsminor.yy602;
+  yymsp[-3].minor.yy528 = yylhsminor.yy528;
         break;
-      case 188: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+      case 190: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
 {
-  yylhsminor.yy602 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy338, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy60);
-  sqlite3WindowAttach(pParse, yylhsminor.yy602, yymsp[0].minor.yy19);
+  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy322, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy394);
+  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
 }
-  yymsp[-5].minor.yy602 = yylhsminor.yy602;
+  yymsp[-5].minor.yy528 = yylhsminor.yy528;
         break;
-      case 189: /* expr ::= ID|INDEXED LP STAR RP filter_over */
+      case 191: /* expr ::= ID|INDEXED LP STAR RP filter_over */
 {
-  yylhsminor.yy602 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
-  sqlite3WindowAttach(pParse, yylhsminor.yy602, yymsp[0].minor.yy19);
+  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
+  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
 }
-  yymsp[-4].minor.yy602 = yylhsminor.yy602;
+  yymsp[-4].minor.yy528 = yylhsminor.yy528;
         break;
-      case 190: /* term ::= CTIME_KW */
+      case 192: /* term ::= CTIME_KW */
 {
-  yylhsminor.yy602 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
+  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
 }
-  yymsp[0].minor.yy602 = yylhsminor.yy602;
+  yymsp[0].minor.yy528 = yylhsminor.yy528;
         break;
-      case 191: /* expr ::= LP nexprlist COMMA expr RP */
+      case 193: /* expr ::= LP nexprlist COMMA expr RP */
 {
-  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy338, yymsp[-1].minor.yy602);
-  yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
-  if( yymsp[-4].minor.yy602 ){
-    yymsp[-4].minor.yy602->x.pList = pList;
+  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528);
+  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
+  if( yymsp[-4].minor.yy528 ){
+    yymsp[-4].minor.yy528->x.pList = pList;
     if( ALWAYS(pList->nExpr) ){
-      yymsp[-4].minor.yy602->flags |= pList->a[0].pExpr->flags & EP_Propagate;
+      yymsp[-4].minor.yy528->flags |= pList->a[0].pExpr->flags & EP_Propagate;
     }
   }else{
     sqlite3ExprListDelete(pParse->db, pList);
   }
 }
         break;
-      case 192: /* expr ::= expr AND expr */
-{yymsp[-2].minor.yy602=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy602,yymsp[0].minor.yy602);}
+      case 194: /* expr ::= expr AND expr */
+{yymsp[-2].minor.yy528=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
         break;
-      case 193: /* expr ::= expr OR expr */
-      case 194: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==194);
-      case 195: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==195);
-      case 196: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==196);
-      case 197: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==197);
-      case 198: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==198);
-      case 199: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==199);
-{yymsp[-2].minor.yy602=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy602,yymsp[0].minor.yy602);}
+      case 195: /* expr ::= expr OR expr */
+      case 196: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==196);
+      case 197: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==197);
+      case 198: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==198);
+      case 199: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==199);
+      case 200: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==200);
+      case 201: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==201);
+{yymsp[-2].minor.yy528=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
         break;
-      case 200: /* likeop ::= NOT LIKE_KW|MATCH */
+      case 202: /* likeop ::= NOT LIKE_KW|MATCH */
 {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
         break;
-      case 201: /* expr ::= expr likeop expr */
+      case 203: /* expr ::= expr likeop expr */
 {
   ExprList *pList;
   int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
   yymsp[-1].minor.yy0.n &= 0x7fffffff;
-  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy602);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy602);
-  yymsp[-2].minor.yy602 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
-  if( bNot ) yymsp[-2].minor.yy602 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy602, 0);
-  if( yymsp[-2].minor.yy602 ) yymsp[-2].minor.yy602->flags |= EP_InfixFunc;
+  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy528);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy528);
+  yymsp[-2].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
+  if( bNot ) yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy528, 0);
+  if( yymsp[-2].minor.yy528 ) yymsp[-2].minor.yy528->flags |= EP_InfixFunc;
 }
         break;
-      case 202: /* expr ::= expr likeop expr ESCAPE expr */
+      case 204: /* expr ::= expr likeop expr ESCAPE expr */
 {
   ExprList *pList;
   int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
   yymsp[-3].minor.yy0.n &= 0x7fffffff;
-  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy602);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy602);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy602);
-  yymsp[-4].minor.yy602 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
-  if( bNot ) yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy602, 0);
-  if( yymsp[-4].minor.yy602 ) yymsp[-4].minor.yy602->flags |= EP_InfixFunc;
+  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy528);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy528);
+  yymsp[-4].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
+  if( bNot ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
+  if( yymsp[-4].minor.yy528 ) yymsp[-4].minor.yy528->flags |= EP_InfixFunc;
 }
         break;
-      case 203: /* expr ::= expr ISNULL|NOTNULL */
-{yymsp[-1].minor.yy602 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy602,0);}
+      case 205: /* expr ::= expr ISNULL|NOTNULL */
+{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy528,0);}
         break;
-      case 204: /* expr ::= expr NOT NULL */
-{yymsp[-2].minor.yy602 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy602,0);}
+      case 206: /* expr ::= expr NOT NULL */
+{yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy528,0);}
         break;
-      case 205: /* expr ::= expr IS expr */
+      case 207: /* expr ::= expr IS expr */
 {
-  yymsp[-2].minor.yy602 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy602,yymsp[0].minor.yy602);
-  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy602, yymsp[-2].minor.yy602, TK_ISNULL);
+  yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);
+  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-2].minor.yy528, TK_ISNULL);
 }
         break;
-      case 206: /* expr ::= expr IS NOT expr */
+      case 208: /* expr ::= expr IS NOT expr */
 {
-  yymsp[-3].minor.yy602 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy602,yymsp[0].minor.yy602);
-  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy602, yymsp[-3].minor.yy602, TK_NOTNULL);
+  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy528,yymsp[0].minor.yy528);
+  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-3].minor.yy528, TK_NOTNULL);
 }
         break;
-      case 207: /* expr ::= NOT expr */
-      case 208: /* expr ::= BITNOT expr */ yytestcase(yyruleno==208);
-{yymsp[-1].minor.yy602 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy602, 0);/*A-overwrites-B*/}
+      case 209: /* expr ::= NOT expr */
+      case 210: /* expr ::= BITNOT expr */ yytestcase(yyruleno==210);
+{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy528, 0);/*A-overwrites-B*/}
         break;
-      case 209: /* expr ::= PLUS|MINUS expr */
+      case 211: /* expr ::= PLUS|MINUS expr */
 {
-  yymsp[-1].minor.yy602 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy602, 0);
+  yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy528, 0);
   /*A-overwrites-B*/
 }
         break;
-      case 210: /* between_op ::= BETWEEN */
-      case 213: /* in_op ::= IN */ yytestcase(yyruleno==213);
-{yymsp[0].minor.yy60 = 0;}
+      case 212: /* expr ::= expr PTR expr */
+{
+  ExprList *pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy528);
+  pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy528);
+  yylhsminor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
+}
+  yymsp[-2].minor.yy528 = yylhsminor.yy528;
+        break;
+      case 213: /* between_op ::= BETWEEN */
+      case 216: /* in_op ::= IN */ yytestcase(yyruleno==216);
+{yymsp[0].minor.yy394 = 0;}
         break;
-      case 212: /* expr ::= expr between_op expr AND expr */
+      case 215: /* expr ::= expr between_op expr AND expr */
 {
-  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy602);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy602);
-  yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy602, 0);
-  if( yymsp[-4].minor.yy602 ){
-    yymsp[-4].minor.yy602->x.pList = pList;
+  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy528);
+  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy528, 0);
+  if( yymsp[-4].minor.yy528 ){
+    yymsp[-4].minor.yy528->x.pList = pList;
   }else{
     sqlite3ExprListDelete(pParse->db, pList);
   }
-  if( yymsp[-3].minor.yy60 ) yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy602, 0);
+  if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
 }
         break;
-      case 215: /* expr ::= expr in_op LP exprlist RP */
+      case 218: /* expr ::= expr in_op LP exprlist RP */
 {
-    if( yymsp[-1].minor.yy338==0 ){
+    if( yymsp[-1].minor.yy322==0 ){
       /* Expressions of the form
       **
       **      expr1 IN ()
@@ -161407,197 +165885,205 @@ static YYACTIONTYPE yy_reduce(
       ** simplify to constants 0 (false) and 1 (true), respectively,
       ** regardless of the value of expr1.
       */
-      sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy602);
-      yymsp[-4].minor.yy602 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy60 ? "1" : "0");
-    }else if( yymsp[-1].minor.yy338->nExpr==1 && sqlite3ExprIsConstant(yymsp[-1].minor.yy338->a[0].pExpr) ){
-      Expr *pRHS = yymsp[-1].minor.yy338->a[0].pExpr;
-      yymsp[-1].minor.yy338->a[0].pExpr = 0;
-      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy338);
-      pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
-      yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy602, pRHS);
-      if( yymsp[-3].minor.yy60 ) yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy602, 0);
-    }else{
-      yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy602, 0);
-      if( yymsp[-4].minor.yy602 ){
-        yymsp[-4].minor.yy602->x.pList = yymsp[-1].minor.yy338;
-        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy602);
+      sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy528);
+      yymsp[-4].minor.yy528 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy394 ? "1" : "0");
+    }else{
+      Expr *pRHS = yymsp[-1].minor.yy322->a[0].pExpr;
+      if( yymsp[-1].minor.yy322->nExpr==1 && sqlite3ExprIsConstant(pRHS) && yymsp[-4].minor.yy528->op!=TK_VECTOR ){
+        yymsp[-1].minor.yy322->a[0].pExpr = 0;
+        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
+        pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
+        yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy528, pRHS);
       }else{
-        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy338);
+        yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
+        if( yymsp[-4].minor.yy528==0 ){
+          sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
+        }else if( yymsp[-4].minor.yy528->pLeft->op==TK_VECTOR ){
+          int nExpr = yymsp[-4].minor.yy528->pLeft->x.pList->nExpr;
+          Select *pSelectRHS = sqlite3ExprListToValues(pParse, nExpr, yymsp[-1].minor.yy322);
+          if( pSelectRHS ){
+            parserDoubleLinkSelect(pParse, pSelectRHS);
+            sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, pSelectRHS);
+          }
+        }else{
+          yymsp[-4].minor.yy528->x.pList = yymsp[-1].minor.yy322;
+          sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
+        }
       }
-      if( yymsp[-3].minor.yy60 ) yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy602, 0);
+      if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
     }
   }
         break;
-      case 216: /* expr ::= LP select RP */
+      case 219: /* expr ::= LP select RP */
 {
-    yymsp[-2].minor.yy602 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
-    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy602, yymsp[-1].minor.yy307);
+    yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
+    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy528, yymsp[-1].minor.yy47);
   }
         break;
-      case 217: /* expr ::= expr in_op LP select RP */
+      case 220: /* expr ::= expr in_op LP select RP */
 {
-    yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy602, 0);
-    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy602, yymsp[-1].minor.yy307);
-    if( yymsp[-3].minor.yy60 ) yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy602, 0);
+    yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
+    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, yymsp[-1].minor.yy47);
+    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
   }
         break;
-      case 218: /* expr ::= expr in_op nm dbnm paren_exprlist */
+      case 221: /* expr ::= expr in_op nm dbnm paren_exprlist */
 {
     SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
     Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
-    if( yymsp[0].minor.yy338 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy338);
-    yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy602, 0);
-    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy602, pSelect);
-    if( yymsp[-3].minor.yy60 ) yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy602, 0);
+    if( yymsp[0].minor.yy322 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy322);
+    yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
+    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, pSelect);
+    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
   }
         break;
-      case 219: /* expr ::= EXISTS LP select RP */
+      case 222: /* expr ::= EXISTS LP select RP */
 {
     Expr *p;
-    p = yymsp[-3].minor.yy602 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
-    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy307);
+    p = yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
+    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy47);
   }
         break;
-      case 220: /* expr ::= CASE case_operand case_exprlist case_else END */
+      case 223: /* expr ::= CASE case_operand case_exprlist case_else END */
 {
-  yymsp[-4].minor.yy602 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy602, 0);
-  if( yymsp[-4].minor.yy602 ){
-    yymsp[-4].minor.yy602->x.pList = yymsp[-1].minor.yy602 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy338,yymsp[-1].minor.yy602) : yymsp[-2].minor.yy338;
-    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy602);
+  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy528, 0);
+  if( yymsp[-4].minor.yy528 ){
+    yymsp[-4].minor.yy528->x.pList = yymsp[-1].minor.yy528 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[-1].minor.yy528) : yymsp[-2].minor.yy322;
+    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
   }else{
-    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy338);
-    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy602);
+    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
+    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
   }
 }
         break;
-      case 221: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
+      case 224: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
 {
-  yymsp[-4].minor.yy338 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy338, yymsp[-2].minor.yy602);
-  yymsp[-4].minor.yy338 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy338, yymsp[0].minor.yy602);
+  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
+  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[0].minor.yy528);
 }
         break;
-      case 222: /* case_exprlist ::= WHEN expr THEN expr */
+      case 225: /* case_exprlist ::= WHEN expr THEN expr */
 {
-  yymsp[-3].minor.yy338 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy602);
-  yymsp[-3].minor.yy338 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy338, yymsp[0].minor.yy602);
+  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
+  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, yymsp[0].minor.yy528);
 }
         break;
-      case 225: /* case_operand ::= expr */
-{yymsp[0].minor.yy602 = yymsp[0].minor.yy602; /*A-overwrites-X*/}
+      case 228: /* case_operand ::= expr */
+{yymsp[0].minor.yy528 = yymsp[0].minor.yy528; /*A-overwrites-X*/}
         break;
-      case 228: /* nexprlist ::= nexprlist COMMA expr */
-{yymsp[-2].minor.yy338 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy338,yymsp[0].minor.yy602);}
+      case 231: /* nexprlist ::= nexprlist COMMA expr */
+{yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy528);}
         break;
-      case 229: /* nexprlist ::= expr */
-{yymsp[0].minor.yy338 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy602); /*A-overwrites-Y*/}
+      case 232: /* nexprlist ::= expr */
+{yymsp[0].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy528); /*A-overwrites-Y*/}
         break;
-      case 231: /* paren_exprlist ::= LP exprlist RP */
-      case 236: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==236);
-{yymsp[-2].minor.yy338 = yymsp[-1].minor.yy338;}
+      case 234: /* paren_exprlist ::= LP exprlist RP */
+      case 239: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==239);
+{yymsp[-2].minor.yy322 = yymsp[-1].minor.yy322;}
         break;
-      case 232: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+      case 235: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
 {
   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
-                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy338, yymsp[-10].minor.yy60,
-                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy602, SQLITE_SO_ASC, yymsp[-8].minor.yy60, SQLITE_IDXTYPE_APPDEF);
+                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy394,
+                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy528, SQLITE_SO_ASC, yymsp[-8].minor.yy394, SQLITE_IDXTYPE_APPDEF);
   if( IN_RENAME_OBJECT && pParse->pNewIndex ){
     sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
   }
 }
         break;
-      case 233: /* uniqueflag ::= UNIQUE */
-      case 275: /* raisetype ::= ABORT */ yytestcase(yyruleno==275);
-{yymsp[0].minor.yy60 = OE_Abort;}
+      case 236: /* uniqueflag ::= UNIQUE */
+      case 278: /* raisetype ::= ABORT */ yytestcase(yyruleno==278);
+{yymsp[0].minor.yy394 = OE_Abort;}
         break;
-      case 234: /* uniqueflag ::= */
-{yymsp[1].minor.yy60 = OE_None;}
+      case 237: /* uniqueflag ::= */
+{yymsp[1].minor.yy394 = OE_None;}
         break;
-      case 237: /* eidlist ::= eidlist COMMA nm collate sortorder */
+      case 240: /* eidlist ::= eidlist COMMA nm collate sortorder */
 {
-  yymsp[-4].minor.yy338 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy338, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy60, yymsp[0].minor.yy60);
+  yymsp[-4].minor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394);
 }
         break;
-      case 238: /* eidlist ::= nm collate sortorder */
+      case 241: /* eidlist ::= nm collate sortorder */
 {
-  yymsp[-2].minor.yy338 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy60, yymsp[0].minor.yy60); /*A-overwrites-Y*/
+  yymsp[-2].minor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394); /*A-overwrites-Y*/
 }
         break;
-      case 241: /* cmd ::= DROP INDEX ifexists fullname */
-{sqlite3DropIndex(pParse, yymsp[0].minor.yy291, yymsp[-1].minor.yy60);}
+      case 244: /* cmd ::= DROP INDEX ifexists fullname */
+{sqlite3DropIndex(pParse, yymsp[0].minor.yy131, yymsp[-1].minor.yy394);}
         break;
-      case 242: /* cmd ::= VACUUM vinto */
-{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy602);}
+      case 245: /* cmd ::= VACUUM vinto */
+{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy528);}
         break;
-      case 243: /* cmd ::= VACUUM nm vinto */
-{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy602);}
+      case 246: /* cmd ::= VACUUM nm vinto */
+{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy528);}
         break;
-      case 246: /* cmd ::= PRAGMA nm dbnm */
+      case 249: /* cmd ::= PRAGMA nm dbnm */
 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
         break;
-      case 247: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
+      case 250: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
         break;
-      case 248: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
+      case 251: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
         break;
-      case 249: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
+      case 252: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
         break;
-      case 250: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
+      case 253: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
         break;
-      case 253: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+      case 256: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
 {
   Token all;
   all.z = yymsp[-3].minor.yy0.z;
   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
-  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy483, &all);
+  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy33, &all);
 }
         break;
-      case 254: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+      case 257: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
 {
-  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy60, yymsp[-4].minor.yy50.a, yymsp[-4].minor.yy50.b, yymsp[-2].minor.yy291, yymsp[0].minor.yy602, yymsp[-10].minor.yy60, yymsp[-8].minor.yy60);
+  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy394, yymsp[-4].minor.yy180.a, yymsp[-4].minor.yy180.b, yymsp[-2].minor.yy131, yymsp[0].minor.yy528, yymsp[-10].minor.yy394, yymsp[-8].minor.yy394);
   yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
 }
         break;
-      case 255: /* trigger_time ::= BEFORE|AFTER */
-{ yymsp[0].minor.yy60 = yymsp[0].major; /*A-overwrites-X*/ }
+      case 258: /* trigger_time ::= BEFORE|AFTER */
+{ yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/ }
         break;
-      case 256: /* trigger_time ::= INSTEAD OF */
-{ yymsp[-1].minor.yy60 = TK_INSTEAD;}
+      case 259: /* trigger_time ::= INSTEAD OF */
+{ yymsp[-1].minor.yy394 = TK_INSTEAD;}
         break;
-      case 257: /* trigger_time ::= */
-{ yymsp[1].minor.yy60 = TK_BEFORE; }
+      case 260: /* trigger_time ::= */
+{ yymsp[1].minor.yy394 = TK_BEFORE; }
         break;
-      case 258: /* trigger_event ::= DELETE|INSERT */
-      case 259: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==259);
-{yymsp[0].minor.yy50.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy50.b = 0;}
+      case 261: /* trigger_event ::= DELETE|INSERT */
+      case 262: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==262);
+{yymsp[0].minor.yy180.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy180.b = 0;}
         break;
-      case 260: /* trigger_event ::= UPDATE OF idlist */
-{yymsp[-2].minor.yy50.a = TK_UPDATE; yymsp[-2].minor.yy50.b = yymsp[0].minor.yy288;}
+      case 263: /* trigger_event ::= UPDATE OF idlist */
+{yymsp[-2].minor.yy180.a = TK_UPDATE; yymsp[-2].minor.yy180.b = yymsp[0].minor.yy254;}
         break;
-      case 261: /* when_clause ::= */
-      case 280: /* key_opt ::= */ yytestcase(yyruleno==280);
-{ yymsp[1].minor.yy602 = 0; }
+      case 264: /* when_clause ::= */
+      case 283: /* key_opt ::= */ yytestcase(yyruleno==283);
+{ yymsp[1].minor.yy528 = 0; }
         break;
-      case 262: /* when_clause ::= WHEN expr */
-      case 281: /* key_opt ::= KEY expr */ yytestcase(yyruleno==281);
-{ yymsp[-1].minor.yy602 = yymsp[0].minor.yy602; }
+      case 265: /* when_clause ::= WHEN expr */
+      case 284: /* key_opt ::= KEY expr */ yytestcase(yyruleno==284);
+{ yymsp[-1].minor.yy528 = yymsp[0].minor.yy528; }
         break;
-      case 263: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+      case 266: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
 {
-  assert( yymsp[-2].minor.yy483!=0 );
-  yymsp[-2].minor.yy483->pLast->pNext = yymsp[-1].minor.yy483;
-  yymsp[-2].minor.yy483->pLast = yymsp[-1].minor.yy483;
+  assert( yymsp[-2].minor.yy33!=0 );
+  yymsp[-2].minor.yy33->pLast->pNext = yymsp[-1].minor.yy33;
+  yymsp[-2].minor.yy33->pLast = yymsp[-1].minor.yy33;
 }
         break;
-      case 264: /* trigger_cmd_list ::= trigger_cmd SEMI */
+      case 267: /* trigger_cmd_list ::= trigger_cmd SEMI */
 {
-  assert( yymsp[-1].minor.yy483!=0 );
-  yymsp[-1].minor.yy483->pLast = yymsp[-1].minor.yy483;
+  assert( yymsp[-1].minor.yy33!=0 );
+  yymsp[-1].minor.yy33->pLast = yymsp[-1].minor.yy33;
 }
         break;
-      case 265: /* trnm ::= nm DOT nm */
+      case 268: /* trnm ::= nm DOT nm */
 {
   yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
   sqlite3ErrorMsg(pParse,
@@ -161605,364 +166091,369 @@ static YYACTIONTYPE yy_reduce(
         "statements within triggers");
 }
         break;
-      case 266: /* tridxby ::= INDEXED BY nm */
+      case 269: /* tridxby ::= INDEXED BY nm */
 {
   sqlite3ErrorMsg(pParse,
         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
         "within triggers");
 }
         break;
-      case 267: /* tridxby ::= NOT INDEXED */
+      case 270: /* tridxby ::= NOT INDEXED */
 {
   sqlite3ErrorMsg(pParse,
         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
         "within triggers");
 }
         break;
-      case 268: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
-{yylhsminor.yy483 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy291, yymsp[-3].minor.yy338, yymsp[-1].minor.yy602, yymsp[-7].minor.yy60, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy528);}
-  yymsp[-8].minor.yy483 = yylhsminor.yy483;
+      case 271: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+{yylhsminor.yy33 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy131, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528, yymsp[-7].minor.yy394, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy522);}
+  yymsp[-8].minor.yy33 = yylhsminor.yy33;
         break;
-      case 269: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+      case 272: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
 {
-   yylhsminor.yy483 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy288,yymsp[-2].minor.yy307,yymsp[-6].minor.yy60,yymsp[-1].minor.yy178,yymsp[-7].minor.yy528,yymsp[0].minor.yy528);/*yylhsminor.yy483-overwrites-yymsp[-6].minor.yy60*/
+   yylhsminor.yy33 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy254,yymsp[-2].minor.yy47,yymsp[-6].minor.yy394,yymsp[-1].minor.yy444,yymsp[-7].minor.yy522,yymsp[0].minor.yy522);/*yylhsminor.yy33-overwrites-yymsp[-6].minor.yy394*/
 }
-  yymsp[-7].minor.yy483 = yylhsminor.yy483;
+  yymsp[-7].minor.yy33 = yylhsminor.yy33;
         break;
-      case 270: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-{yylhsminor.yy483 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy602, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy528);}
-  yymsp[-5].minor.yy483 = yylhsminor.yy483;
+      case 273: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+{yylhsminor.yy33 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy528, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy522);}
+  yymsp[-5].minor.yy33 = yylhsminor.yy33;
         break;
-      case 271: /* trigger_cmd ::= scanpt select scanpt */
-{yylhsminor.yy483 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy307, yymsp[-2].minor.yy528, yymsp[0].minor.yy528); /*yylhsminor.yy483-overwrites-yymsp[-1].minor.yy307*/}
-  yymsp[-2].minor.yy483 = yylhsminor.yy483;
+      case 274: /* trigger_cmd ::= scanpt select scanpt */
+{yylhsminor.yy33 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy47, yymsp[-2].minor.yy522, yymsp[0].minor.yy522); /*yylhsminor.yy33-overwrites-yymsp[-1].minor.yy47*/}
+  yymsp[-2].minor.yy33 = yylhsminor.yy33;
         break;
-      case 272: /* expr ::= RAISE LP IGNORE RP */
+      case 275: /* expr ::= RAISE LP IGNORE RP */
 {
-  yymsp[-3].minor.yy602 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
-  if( yymsp[-3].minor.yy602 ){
-    yymsp[-3].minor.yy602->affExpr = OE_Ignore;
+  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
+  if( yymsp[-3].minor.yy528 ){
+    yymsp[-3].minor.yy528->affExpr = OE_Ignore;
   }
 }
         break;
-      case 273: /* expr ::= RAISE LP raisetype COMMA nm RP */
+      case 276: /* expr ::= RAISE LP raisetype COMMA nm RP */
 {
-  yymsp[-5].minor.yy602 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
-  if( yymsp[-5].minor.yy602 ) {
-    yymsp[-5].minor.yy602->affExpr = (char)yymsp[-3].minor.yy60;
+  yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
+  if( yymsp[-5].minor.yy528 ) {
+    yymsp[-5].minor.yy528->affExpr = (char)yymsp[-3].minor.yy394;
   }
 }
         break;
-      case 274: /* raisetype ::= ROLLBACK */
-{yymsp[0].minor.yy60 = OE_Rollback;}
+      case 277: /* raisetype ::= ROLLBACK */
+{yymsp[0].minor.yy394 = OE_Rollback;}
         break;
-      case 276: /* raisetype ::= FAIL */
-{yymsp[0].minor.yy60 = OE_Fail;}
+      case 279: /* raisetype ::= FAIL */
+{yymsp[0].minor.yy394 = OE_Fail;}
         break;
-      case 277: /* cmd ::= DROP TRIGGER ifexists fullname */
+      case 280: /* cmd ::= DROP TRIGGER ifexists fullname */
 {
-  sqlite3DropTrigger(pParse,yymsp[0].minor.yy291,yymsp[-1].minor.yy60);
+  sqlite3DropTrigger(pParse,yymsp[0].minor.yy131,yymsp[-1].minor.yy394);
 }
         break;
-      case 278: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+      case 281: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
 {
-  sqlite3Attach(pParse, yymsp[-3].minor.yy602, yymsp[-1].minor.yy602, yymsp[0].minor.yy602);
+  sqlite3Attach(pParse, yymsp[-3].minor.yy528, yymsp[-1].minor.yy528, yymsp[0].minor.yy528);
 }
         break;
-      case 279: /* cmd ::= DETACH database_kw_opt expr */
+      case 282: /* cmd ::= DETACH database_kw_opt expr */
 {
-  sqlite3Detach(pParse, yymsp[0].minor.yy602);
+  sqlite3Detach(pParse, yymsp[0].minor.yy528);
 }
         break;
-      case 282: /* cmd ::= REINDEX */
+      case 285: /* cmd ::= REINDEX */
 {sqlite3Reindex(pParse, 0, 0);}
         break;
-      case 283: /* cmd ::= REINDEX nm dbnm */
+      case 286: /* cmd ::= REINDEX nm dbnm */
 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
         break;
-      case 284: /* cmd ::= ANALYZE */
+      case 287: /* cmd ::= ANALYZE */
 {sqlite3Analyze(pParse, 0, 0);}
         break;
-      case 285: /* cmd ::= ANALYZE nm dbnm */
+      case 288: /* cmd ::= ANALYZE nm dbnm */
 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
         break;
-      case 286: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
+      case 289: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
 {
-  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy291,&yymsp[0].minor.yy0);
+  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy131,&yymsp[0].minor.yy0);
 }
         break;
-      case 287: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+      case 290: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
 {
   yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
   sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
 }
         break;
-      case 288: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
+      case 291: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
 {
-  sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy291, &yymsp[0].minor.yy0);
+  sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy131, &yymsp[0].minor.yy0);
 }
         break;
-      case 289: /* add_column_fullname ::= fullname */
+      case 292: /* add_column_fullname ::= fullname */
 {
   disableLookaside(pParse);
-  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy291);
+  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy131);
 }
         break;
-      case 290: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+      case 293: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
 {
-  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy291, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
+  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy131, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
 }
         break;
-      case 291: /* cmd ::= create_vtab */
+      case 294: /* cmd ::= create_vtab */
 {sqlite3VtabFinishParse(pParse,0);}
         break;
-      case 292: /* cmd ::= create_vtab LP vtabarglist RP */
+      case 295: /* cmd ::= create_vtab LP vtabarglist RP */
 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
         break;
-      case 293: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+      case 296: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
 {
-    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy60);
+    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy394);
 }
         break;
-      case 294: /* vtabarg ::= */
+      case 297: /* vtabarg ::= */
 {sqlite3VtabArgInit(pParse);}
         break;
-      case 295: /* vtabargtoken ::= ANY */
-      case 296: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==296);
-      case 297: /* lp ::= LP */ yytestcase(yyruleno==297);
+      case 298: /* vtabargtoken ::= ANY */
+      case 299: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==299);
+      case 300: /* lp ::= LP */ yytestcase(yyruleno==300);
 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
         break;
-      case 298: /* with ::= WITH wqlist */
-      case 299: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==299);
-{ sqlite3WithPush(pParse, yymsp[0].minor.yy195, 1); }
+      case 301: /* with ::= WITH wqlist */
+      case 302: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==302);
+{ sqlite3WithPush(pParse, yymsp[0].minor.yy521, 1); }
         break;
-      case 300: /* wqas ::= AS */
-{yymsp[0].minor.yy570 = M10d_Any;}
+      case 303: /* wqas ::= AS */
+{yymsp[0].minor.yy516 = M10d_Any;}
         break;
-      case 301: /* wqas ::= AS MATERIALIZED */
-{yymsp[-1].minor.yy570 = M10d_Yes;}
+      case 304: /* wqas ::= AS MATERIALIZED */
+{yymsp[-1].minor.yy516 = M10d_Yes;}
         break;
-      case 302: /* wqas ::= AS NOT MATERIALIZED */
-{yymsp[-2].minor.yy570 = M10d_No;}
+      case 305: /* wqas ::= AS NOT MATERIALIZED */
+{yymsp[-2].minor.yy516 = M10d_No;}
         break;
-      case 303: /* wqitem ::= nm eidlist_opt wqas LP select RP */
+      case 306: /* wqitem ::= nm eidlist_opt wqas LP select RP */
 {
-  yymsp[-5].minor.yy607 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy338, yymsp[-1].minor.yy307, yymsp[-3].minor.yy570); /*A-overwrites-X*/
+  yymsp[-5].minor.yy385 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy47, yymsp[-3].minor.yy516); /*A-overwrites-X*/
 }
         break;
-      case 304: /* wqlist ::= wqitem */
+      case 307: /* wqlist ::= wqitem */
 {
-  yymsp[0].minor.yy195 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy607); /*A-overwrites-X*/
+  yymsp[0].minor.yy521 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy385); /*A-overwrites-X*/
 }
         break;
-      case 305: /* wqlist ::= wqlist COMMA wqitem */
+      case 308: /* wqlist ::= wqlist COMMA wqitem */
 {
-  yymsp[-2].minor.yy195 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy195, yymsp[0].minor.yy607);
+  yymsp[-2].minor.yy521 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy521, yymsp[0].minor.yy385);
 }
         break;
-      case 306: /* windowdefn_list ::= windowdefn */
-{ yylhsminor.yy19 = yymsp[0].minor.yy19; }
-  yymsp[0].minor.yy19 = yylhsminor.yy19;
+      case 309: /* windowdefn_list ::= windowdefn */
+{ yylhsminor.yy41 = yymsp[0].minor.yy41; }
+  yymsp[0].minor.yy41 = yylhsminor.yy41;
         break;
-      case 307: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
+      case 310: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
 {
-  assert( yymsp[0].minor.yy19!=0 );
-  sqlite3WindowChain(pParse, yymsp[0].minor.yy19, yymsp[-2].minor.yy19);
-  yymsp[0].minor.yy19->pNextWin = yymsp[-2].minor.yy19;
-  yylhsminor.yy19 = yymsp[0].minor.yy19;
+  assert( yymsp[0].minor.yy41!=0 );
+  sqlite3WindowChain(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy41);
+  yymsp[0].minor.yy41->pNextWin = yymsp[-2].minor.yy41;
+  yylhsminor.yy41 = yymsp[0].minor.yy41;
 }
-  yymsp[-2].minor.yy19 = yylhsminor.yy19;
+  yymsp[-2].minor.yy41 = yylhsminor.yy41;
         break;
-      case 308: /* windowdefn ::= nm AS LP window RP */
+      case 311: /* windowdefn ::= nm AS LP window RP */
 {
-  if( ALWAYS(yymsp[-1].minor.yy19) ){
-    yymsp[-1].minor.yy19->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
+  if( ALWAYS(yymsp[-1].minor.yy41) ){
+    yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
   }
-  yylhsminor.yy19 = yymsp[-1].minor.yy19;
+  yylhsminor.yy41 = yymsp[-1].minor.yy41;
 }
-  yymsp[-4].minor.yy19 = yylhsminor.yy19;
+  yymsp[-4].minor.yy41 = yylhsminor.yy41;
         break;
-      case 309: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+      case 312: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
 {
-  yymsp[-4].minor.yy19 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy19, yymsp[-2].minor.yy338, yymsp[-1].minor.yy338, 0);
+  yymsp[-4].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, 0);
 }
         break;
-      case 310: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+      case 313: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
 {
-  yylhsminor.yy19 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy19, yymsp[-2].minor.yy338, yymsp[-1].minor.yy338, &yymsp[-5].minor.yy0);
+  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, &yymsp[-5].minor.yy0);
 }
-  yymsp[-5].minor.yy19 = yylhsminor.yy19;
+  yymsp[-5].minor.yy41 = yylhsminor.yy41;
         break;
-      case 311: /* window ::= ORDER BY sortlist frame_opt */
+      case 314: /* window ::= ORDER BY sortlist frame_opt */
 {
-  yymsp[-3].minor.yy19 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy19, 0, yymsp[-1].minor.yy338, 0);
+  yymsp[-3].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, 0);
 }
         break;
-      case 312: /* window ::= nm ORDER BY sortlist frame_opt */
+      case 315: /* window ::= nm ORDER BY sortlist frame_opt */
 {
-  yylhsminor.yy19 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy19, 0, yymsp[-1].minor.yy338, &yymsp[-4].minor.yy0);
+  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
 }
-  yymsp[-4].minor.yy19 = yylhsminor.yy19;
+  yymsp[-4].minor.yy41 = yylhsminor.yy41;
         break;
-      case 313: /* window ::= frame_opt */
-      case 332: /* filter_over ::= over_clause */ yytestcase(yyruleno==332);
+      case 316: /* window ::= frame_opt */
+      case 335: /* filter_over ::= over_clause */ yytestcase(yyruleno==335);
 {
-  yylhsminor.yy19 = yymsp[0].minor.yy19;
+  yylhsminor.yy41 = yymsp[0].minor.yy41;
 }
-  yymsp[0].minor.yy19 = yylhsminor.yy19;
+  yymsp[0].minor.yy41 = yylhsminor.yy41;
         break;
-      case 314: /* window ::= nm frame_opt */
+      case 317: /* window ::= nm frame_opt */
 {
-  yylhsminor.yy19 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy19, 0, 0, &yymsp[-1].minor.yy0);
+  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, 0, &yymsp[-1].minor.yy0);
 }
-  yymsp[-1].minor.yy19 = yylhsminor.yy19;
+  yymsp[-1].minor.yy41 = yylhsminor.yy41;
         break;
-      case 315: /* frame_opt ::= */
+      case 318: /* frame_opt ::= */
 {
-  yymsp[1].minor.yy19 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
+  yymsp[1].minor.yy41 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
 }
         break;
-      case 316: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+      case 319: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
 {
-  yylhsminor.yy19 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy60, yymsp[-1].minor.yy113.eType, yymsp[-1].minor.yy113.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy570);
+  yylhsminor.yy41 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy394, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy516);
 }
-  yymsp[-2].minor.yy19 = yylhsminor.yy19;
+  yymsp[-2].minor.yy41 = yylhsminor.yy41;
         break;
-      case 317: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+      case 320: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
 {
-  yylhsminor.yy19 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy60, yymsp[-3].minor.yy113.eType, yymsp[-3].minor.yy113.pExpr, yymsp[-1].minor.yy113.eType, yymsp[-1].minor.yy113.pExpr, yymsp[0].minor.yy570);
+  yylhsminor.yy41 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy394, yymsp[-3].minor.yy595.eType, yymsp[-3].minor.yy595.pExpr, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, yymsp[0].minor.yy516);
 }
-  yymsp[-5].minor.yy19 = yylhsminor.yy19;
+  yymsp[-5].minor.yy41 = yylhsminor.yy41;
         break;
-      case 319: /* frame_bound_s ::= frame_bound */
-      case 321: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==321);
-{yylhsminor.yy113 = yymsp[0].minor.yy113;}
-  yymsp[0].minor.yy113 = yylhsminor.yy113;
+      case 322: /* frame_bound_s ::= frame_bound */
+      case 324: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==324);
+{yylhsminor.yy595 = yymsp[0].minor.yy595;}
+  yymsp[0].minor.yy595 = yylhsminor.yy595;
         break;
-      case 320: /* frame_bound_s ::= UNBOUNDED PRECEDING */
-      case 322: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==322);
-      case 324: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==324);
-{yylhsminor.yy113.eType = yymsp[-1].major; yylhsminor.yy113.pExpr = 0;}
-  yymsp[-1].minor.yy113 = yylhsminor.yy113;
+      case 323: /* frame_bound_s ::= UNBOUNDED PRECEDING */
+      case 325: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==325);
+      case 327: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==327);
+{yylhsminor.yy595.eType = yymsp[-1].major; yylhsminor.yy595.pExpr = 0;}
+  yymsp[-1].minor.yy595 = yylhsminor.yy595;
         break;
-      case 323: /* frame_bound ::= expr PRECEDING|FOLLOWING */
-{yylhsminor.yy113.eType = yymsp[0].major; yylhsminor.yy113.pExpr = yymsp[-1].minor.yy602;}
-  yymsp[-1].minor.yy113 = yylhsminor.yy113;
+      case 326: /* frame_bound ::= expr PRECEDING|FOLLOWING */
+{yylhsminor.yy595.eType = yymsp[0].major; yylhsminor.yy595.pExpr = yymsp[-1].minor.yy528;}
+  yymsp[-1].minor.yy595 = yylhsminor.yy595;
         break;
-      case 325: /* frame_exclude_opt ::= */
-{yymsp[1].minor.yy570 = 0;}
+      case 328: /* frame_exclude_opt ::= */
+{yymsp[1].minor.yy516 = 0;}
         break;
-      case 326: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
-{yymsp[-1].minor.yy570 = yymsp[0].minor.yy570;}
+      case 329: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
+{yymsp[-1].minor.yy516 = yymsp[0].minor.yy516;}
         break;
-      case 327: /* frame_exclude ::= NO OTHERS */
-      case 328: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==328);
-{yymsp[-1].minor.yy570 = yymsp[-1].major; /*A-overwrites-X*/}
+      case 330: /* frame_exclude ::= NO OTHERS */
+      case 331: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==331);
+{yymsp[-1].minor.yy516 = yymsp[-1].major; /*A-overwrites-X*/}
         break;
-      case 329: /* frame_exclude ::= GROUP|TIES */
-{yymsp[0].minor.yy570 = yymsp[0].major; /*A-overwrites-X*/}
+      case 332: /* frame_exclude ::= GROUP|TIES */
+{yymsp[0].minor.yy516 = yymsp[0].major; /*A-overwrites-X*/}
         break;
-      case 330: /* window_clause ::= WINDOW windowdefn_list */
-{ yymsp[-1].minor.yy19 = yymsp[0].minor.yy19; }
+      case 333: /* window_clause ::= WINDOW windowdefn_list */
+{ yymsp[-1].minor.yy41 = yymsp[0].minor.yy41; }
         break;
-      case 331: /* filter_over ::= filter_clause over_clause */
+      case 334: /* filter_over ::= filter_clause over_clause */
 {
-  yymsp[0].minor.yy19->pFilter = yymsp[-1].minor.yy602;
-  yylhsminor.yy19 = yymsp[0].minor.yy19;
+  if( yymsp[0].minor.yy41 ){
+    yymsp[0].minor.yy41->pFilter = yymsp[-1].minor.yy528;
+  }else{
+    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
+  }
+  yylhsminor.yy41 = yymsp[0].minor.yy41;
 }
-  yymsp[-1].minor.yy19 = yylhsminor.yy19;
+  yymsp[-1].minor.yy41 = yylhsminor.yy41;
         break;
-      case 333: /* filter_over ::= filter_clause */
+      case 336: /* filter_over ::= filter_clause */
 {
-  yylhsminor.yy19 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
-  if( yylhsminor.yy19 ){
-    yylhsminor.yy19->eFrmType = TK_FILTER;
-    yylhsminor.yy19->pFilter = yymsp[0].minor.yy602;
+  yylhsminor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
+  if( yylhsminor.yy41 ){
+    yylhsminor.yy41->eFrmType = TK_FILTER;
+    yylhsminor.yy41->pFilter = yymsp[0].minor.yy528;
   }else{
-    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy602);
+    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy528);
   }
 }
-  yymsp[0].minor.yy19 = yylhsminor.yy19;
+  yymsp[0].minor.yy41 = yylhsminor.yy41;
         break;
-      case 334: /* over_clause ::= OVER LP window RP */
+      case 337: /* over_clause ::= OVER LP window RP */
 {
-  yymsp[-3].minor.yy19 = yymsp[-1].minor.yy19;
-  assert( yymsp[-3].minor.yy19!=0 );
+  yymsp[-3].minor.yy41 = yymsp[-1].minor.yy41;
+  assert( yymsp[-3].minor.yy41!=0 );
 }
         break;
-      case 335: /* over_clause ::= OVER nm */
+      case 338: /* over_clause ::= OVER nm */
 {
-  yymsp[-1].minor.yy19 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
-  if( yymsp[-1].minor.yy19 ){
-    yymsp[-1].minor.yy19->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
+  yymsp[-1].minor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
+  if( yymsp[-1].minor.yy41 ){
+    yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
   }
 }
         break;
-      case 336: /* filter_clause ::= FILTER LP WHERE expr RP */
-{ yymsp[-4].minor.yy602 = yymsp[-1].minor.yy602; }
+      case 339: /* filter_clause ::= FILTER LP WHERE expr RP */
+{ yymsp[-4].minor.yy528 = yymsp[-1].minor.yy528; }
         break;
       default:
-      /* (337) input ::= cmdlist */ yytestcase(yyruleno==337);
-      /* (338) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==338);
-      /* (339) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=339);
-      /* (340) ecmd ::= SEMI */ yytestcase(yyruleno==340);
-      /* (341) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==341);
-      /* (342) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=342);
-      /* (343) trans_opt ::= */ yytestcase(yyruleno==343);
-      /* (344) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==344);
-      /* (345) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==345);
-      /* (346) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==346);
-      /* (347) savepoint_opt ::= */ yytestcase(yyruleno==347);
-      /* (348) cmd ::= create_table create_table_args */ yytestcase(yyruleno==348);
-      /* (349) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==349);
-      /* (350) columnlist ::= columnname carglist */ yytestcase(yyruleno==350);
-      /* (351) nm ::= ID|INDEXED */ yytestcase(yyruleno==351);
-      /* (352) nm ::= STRING */ yytestcase(yyruleno==352);
-      /* (353) nm ::= JOIN_KW */ yytestcase(yyruleno==353);
-      /* (354) typetoken ::= typename */ yytestcase(yyruleno==354);
-      /* (355) typename ::= ID|STRING */ yytestcase(yyruleno==355);
-      /* (356) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=356);
-      /* (357) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=357);
-      /* (358) carglist ::= carglist ccons */ yytestcase(yyruleno==358);
-      /* (359) carglist ::= */ yytestcase(yyruleno==359);
-      /* (360) ccons ::= NULL onconf */ yytestcase(yyruleno==360);
-      /* (361) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==361);
-      /* (362) ccons ::= AS generated */ yytestcase(yyruleno==362);
-      /* (363) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==363);
-      /* (364) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==364);
-      /* (365) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=365);
-      /* (366) tconscomma ::= */ yytestcase(yyruleno==366);
-      /* (367) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=367);
-      /* (368) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=368);
-      /* (369) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=369);
-      /* (370) oneselect ::= values */ yytestcase(yyruleno==370);
-      /* (371) sclp ::= selcollist COMMA */ yytestcase(yyruleno==371);
-      /* (372) as ::= ID|STRING */ yytestcase(yyruleno==372);
-      /* (373) returning ::= */ yytestcase(yyruleno==373);
-      /* (374) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=374);
-      /* (375) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==375);
-      /* (376) exprlist ::= nexprlist */ yytestcase(yyruleno==376);
-      /* (377) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=377);
-      /* (378) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=378);
-      /* (379) nmnum ::= ON */ yytestcase(yyruleno==379);
-      /* (380) nmnum ::= DELETE */ yytestcase(yyruleno==380);
-      /* (381) nmnum ::= DEFAULT */ yytestcase(yyruleno==381);
-      /* (382) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==382);
-      /* (383) foreach_clause ::= */ yytestcase(yyruleno==383);
-      /* (384) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==384);
-      /* (385) trnm ::= nm */ yytestcase(yyruleno==385);
-      /* (386) tridxby ::= */ yytestcase(yyruleno==386);
-      /* (387) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==387);
-      /* (388) database_kw_opt ::= */ yytestcase(yyruleno==388);
-      /* (389) kwcolumn_opt ::= */ yytestcase(yyruleno==389);
-      /* (390) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==390);
-      /* (391) vtabarglist ::= vtabarg */ yytestcase(yyruleno==391);
-      /* (392) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==392);
-      /* (393) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==393);
-      /* (394) anylist ::= */ yytestcase(yyruleno==394);
-      /* (395) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==395);
-      /* (396) anylist ::= anylist ANY */ yytestcase(yyruleno==396);
-      /* (397) with ::= */ yytestcase(yyruleno==397);
+      /* (340) input ::= cmdlist */ yytestcase(yyruleno==340);
+      /* (341) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==341);
+      /* (342) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=342);
+      /* (343) ecmd ::= SEMI */ yytestcase(yyruleno==343);
+      /* (344) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==344);
+      /* (345) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=345);
+      /* (346) trans_opt ::= */ yytestcase(yyruleno==346);
+      /* (347) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==347);
+      /* (348) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==348);
+      /* (349) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==349);
+      /* (350) savepoint_opt ::= */ yytestcase(yyruleno==350);
+      /* (351) cmd ::= create_table create_table_args */ yytestcase(yyruleno==351);
+      /* (352) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=352);
+      /* (353) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==353);
+      /* (354) columnlist ::= columnname carglist */ yytestcase(yyruleno==354);
+      /* (355) nm ::= ID|INDEXED */ yytestcase(yyruleno==355);
+      /* (356) nm ::= STRING */ yytestcase(yyruleno==356);
+      /* (357) nm ::= JOIN_KW */ yytestcase(yyruleno==357);
+      /* (358) typetoken ::= typename */ yytestcase(yyruleno==358);
+      /* (359) typename ::= ID|STRING */ yytestcase(yyruleno==359);
+      /* (360) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=360);
+      /* (361) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=361);
+      /* (362) carglist ::= carglist ccons */ yytestcase(yyruleno==362);
+      /* (363) carglist ::= */ yytestcase(yyruleno==363);
+      /* (364) ccons ::= NULL onconf */ yytestcase(yyruleno==364);
+      /* (365) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==365);
+      /* (366) ccons ::= AS generated */ yytestcase(yyruleno==366);
+      /* (367) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==367);
+      /* (368) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==368);
+      /* (369) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=369);
+      /* (370) tconscomma ::= */ yytestcase(yyruleno==370);
+      /* (371) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=371);
+      /* (372) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=372);
+      /* (373) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=373);
+      /* (374) oneselect ::= values */ yytestcase(yyruleno==374);
+      /* (375) sclp ::= selcollist COMMA */ yytestcase(yyruleno==375);
+      /* (376) as ::= ID|STRING */ yytestcase(yyruleno==376);
+      /* (377) returning ::= */ yytestcase(yyruleno==377);
+      /* (378) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=378);
+      /* (379) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==379);
+      /* (380) exprlist ::= nexprlist */ yytestcase(yyruleno==380);
+      /* (381) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=381);
+      /* (382) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=382);
+      /* (383) nmnum ::= ON */ yytestcase(yyruleno==383);
+      /* (384) nmnum ::= DELETE */ yytestcase(yyruleno==384);
+      /* (385) nmnum ::= DEFAULT */ yytestcase(yyruleno==385);
+      /* (386) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==386);
+      /* (387) foreach_clause ::= */ yytestcase(yyruleno==387);
+      /* (388) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==388);
+      /* (389) trnm ::= nm */ yytestcase(yyruleno==389);
+      /* (390) tridxby ::= */ yytestcase(yyruleno==390);
+      /* (391) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==391);
+      /* (392) database_kw_opt ::= */ yytestcase(yyruleno==392);
+      /* (393) kwcolumn_opt ::= */ yytestcase(yyruleno==393);
+      /* (394) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==394);
+      /* (395) vtabarglist ::= vtabarg */ yytestcase(yyruleno==395);
+      /* (396) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==396);
+      /* (397) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==397);
+      /* (398) anylist ::= */ yytestcase(yyruleno==398);
+      /* (399) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==399);
+      /* (400) anylist ::= anylist ANY */ yytestcase(yyruleno==400);
+      /* (401) with ::= */ yytestcase(yyruleno==401);
         break;
 /********** End reduce actions ************************************************/
   };
@@ -162120,8 +166611,8 @@ SQLITE_PRIVATE void sqlite3Parser(
     yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
     if( yyact >= YY_MIN_REDUCE ){
       unsigned int yyruleno = yyact - YY_MIN_REDUCE; /* Reduce by this rule */
-      assert( yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) );
 #ifndef NDEBUG
+      assert( yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) );
       if( yyTraceFILE ){
         int yysize = yyRuleInfoNRhs[yyruleno];
         if( yysize ){
@@ -162219,14 +166710,13 @@ SQLITE_PRIVATE void sqlite3Parser(
         yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
         yymajor = YYNOCODE;
       }else{
-        while( yypParser->yytos >= yypParser->yystack
-            && (yyact = yy_find_reduce_action(
-                        yypParser->yytos->stateno,
-                        YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
-        ){
+        while( yypParser->yytos > yypParser->yystack ){
+          yyact = yy_find_reduce_action(yypParser->yytos->stateno,
+                                        YYERRORSYMBOL);
+          if( yyact<=YY_MAX_SHIFTREDUCE ) break;
           yy_pop_parser_stack(yypParser);
         }
-        if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
+        if( yypParser->yytos <= yypParser->yystack || yymajor==0 ){
           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
           yy_parse_failed(yypParser);
 #ifndef YYNOERRORRECOVERY
@@ -162366,6 +166856,7 @@ SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
 #define CC_ID        27    /* unicode characters usable in IDs */
 #define CC_ILLEGAL   28    /* Illegal character */
 #define CC_NUL       29    /* 0x00 */
+#define CC_BOM       30    /* First byte of UTF8 BOM:  0xEF 0xBB 0xBF */
 
 static const unsigned char aiClass[] = {
 #ifdef SQLITE_ASCII
@@ -162378,14 +166869,14 @@ static const unsigned char aiClass[] = {
 /* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  2,  2,  9, 28, 28, 28,  2,
 /* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
 /* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  2,  2, 28, 10, 28, 25, 28,
-/* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
-/* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
-/* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
-/* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
-/* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
-/* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
-/* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
-/* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
+/* 8x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* 9x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* Ax */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* Cx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* Dx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+/* Ex */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 30,
+/* Fx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27
 #endif
 #ifdef SQLITE_EBCDIC
 /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
@@ -163085,6 +167576,9 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
         return i;
+      }else if( z[1]=='>' ){
+        *tokenType = TK_PTR;
+        return 2 + (z[2]=='>');
       }
       *tokenType = TK_MINUS;
       return 1;
@@ -163331,6 +167825,14 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
       i = 1;
       break;
     }
+    case CC_BOM: {
+      if( z[1]==0xbb && z[2]==0xbf ){
+        *tokenType = TK_SPACE;
+        return 3;
+      }
+      i = 1;
+      break;
+    }
     case CC_NUL: {
       *tokenType = TK_ILLEGAL;
       return 0;
@@ -163346,13 +167848,9 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
 }
 
 /*
-** Run the parser on the given SQL string.  The parser structure is
-** passed in.  An SQLITE_ status code is returned.  If an error occurs
-** then an and attempt is made to write an error message into
-** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
-** error message.
+** Run the parser on the given SQL string.
 */
-SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
+SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){
   int nErr = 0;                   /* Number of errors encountered */
   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   int n = 0;                      /* Length of the next token token */
@@ -163360,6 +167858,7 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
   int lastTokenParsed = -1;       /* type of the previous token */
   sqlite3 *db = pParse->db;       /* The database connection */
   int mxSqlLen;                   /* Max length of an SQL string */
+  Parse *pParentParse = 0;        /* Outer parse context, if any */
 #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
   yyParser sEngine;    /* Space to hold the Lemon-generated Parser object */
 #endif
@@ -163372,7 +167871,6 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
   }
   pParse->rc = SQLITE_OK;
   pParse->zTail = zSql;
-  assert( pzErrMsg!=0 );
 #ifdef SQLITE_DEBUG
   if( db->flags & SQLITE_ParserTrace ){
     printf("parser: [[[%s]]]\n", zSql);
@@ -163395,7 +167893,7 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
   assert( pParse->pNewTrigger==0 );
   assert( pParse->nVar==0 );
   assert( pParse->pVList==0 );
-  pParse->pParentParse = db->pParse;
+  pParentParse = db->pParse;
   db->pParse = pParse;
   while( 1 ){
     n = sqlite3GetToken((u8*)zSql, &tokenType);
@@ -163415,6 +167913,7 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
 #endif /* SQLITE_OMIT_WINDOWFUNC */
       if( AtomicLoad(&db->u1.isInterrupted) ){
         pParse->rc = SQLITE_INTERRUPT;
+        pParse->nErr++;
         break;
       }
       if( tokenType==TK_SPACE ){
@@ -163444,7 +167943,10 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
         tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
 #endif /* SQLITE_OMIT_WINDOWFUNC */
       }else{
-        sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
+        Token x;
+        x.z = zSql;
+        x.n = n;
+        sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", &x);
         break;
       }
     }
@@ -163472,46 +167974,30 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
   if( db->mallocFailed ){
     pParse->rc = SQLITE_NOMEM_BKPT;
   }
-  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
-    pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
-  }
-  assert( pzErrMsg!=0 );
-  if( pParse->zErrMsg ){
-    *pzErrMsg = pParse->zErrMsg;
-    sqlite3_log(pParse->rc, "%s in \"%s\"",
-                *pzErrMsg, pParse->zTail);
-    pParse->zErrMsg = 0;
+  if( pParse->zErrMsg || (pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE) ){
+    if( pParse->zErrMsg==0 ){
+      pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
+    }
+    sqlite3_log(pParse->rc, "%s in \"%s\"", pParse->zErrMsg, pParse->zTail);
     nErr++;
   }
   pParse->zTail = zSql;
-  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
-    sqlite3VdbeDelete(pParse->pVdbe);
-    pParse->pVdbe = 0;
-  }
-#ifndef SQLITE_OMIT_SHARED_CACHE
-  if( pParse->nested==0 ){
-    sqlite3DbFree(db, pParse->aTableLock);
-    pParse->aTableLock = 0;
-    pParse->nTableLock = 0;
-  }
-#endif
 #ifndef SQLITE_OMIT_VIRTUALTABLE
   sqlite3_free(pParse->apVtabLock);
 #endif
 
-  if( !IN_SPECIAL_PARSE ){
+  if( pParse->pNewTable && !IN_SPECIAL_PARSE ){
     /* If the pParse->declareVtab flag is set, do not delete any table
     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
     ** will take responsibility for freeing the Table structure.
     */
     sqlite3DeleteTable(db, pParse->pNewTable);
   }
-  if( !IN_RENAME_OBJECT ){
+  if( pParse->pNewTrigger && !IN_RENAME_OBJECT ){
     sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   }
   sqlite3DbFree(db, pParse->pVList);
-  db->pParse = pParse->pParentParse;
-  pParse->pParentParse = 0;
+  db->pParse = pParentParse;
   assert( nErr==0 || pParse->rc!=SQLITE_OK );
   return nErr;
 }
@@ -164092,9 +168578,6 @@ SQLITE_PRIVATE int sqlite3Fts2Init(sqlite3*);
 #ifdef SQLITE_ENABLE_FTS5
 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
 #endif
-#ifdef SQLITE_ENABLE_JSON1
-SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
-#endif
 #ifdef SQLITE_ENABLE_STMTVTAB
 SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
 #endif
@@ -164129,8 +168612,8 @@ static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
   sqlite3DbstatRegister,
 #endif
   sqlite3TestExtInit,
-#ifdef SQLITE_ENABLE_JSON1
-  sqlite3Json1Init,
+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
+  sqlite3JsonTableFunctions,
 #endif
 #ifdef SQLITE_ENABLE_STMTVTAB
   sqlite3StmtVtabInit,
@@ -164347,7 +168830,7 @@ SQLITE_API int sqlite3_initialize(void){
       sqlite3GlobalConfig.isPCacheInit = 1;
       rc = sqlite3OsInit();
     }
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
     if( rc==SQLITE_OK ){
       rc = sqlite3MemdbInit();
     }
@@ -164762,12 +169245,12 @@ SQLITE_API int sqlite3_config(int op, ...){
     }
 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
 
-#ifdef SQLITE_ENABLE_DESERIALIZE
+#ifndef SQLITE_OMIT_DESERIALIZE
     case SQLITE_CONFIG_MEMDB_MAXSIZE: {
       sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
       break;
     }
-#endif /* SQLITE_ENABLE_DESERIALIZE */
+#endif /* SQLITE_OMIT_DESERIALIZE */
 
     default: {
       rc = SQLITE_ERROR;
@@ -165128,7 +169611,7 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid)
 /*
 ** Return the number of changes in the most recent call to sqlite3_exec().
 */
-SQLITE_API int sqlite3_changes(sqlite3 *db){
+SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3 *db){
 #ifdef SQLITE_ENABLE_API_ARMOR
   if( !sqlite3SafetyCheckOk(db) ){
     (void)SQLITE_MISUSE_BKPT;
@@ -165137,11 +169620,14 @@ SQLITE_API int sqlite3_changes(sqlite3 *db){
 #endif
   return db->nChange;
 }
+SQLITE_API int sqlite3_changes(sqlite3 *db){
+  return (int)sqlite3_changes64(db);
+}
 
 /*
 ** Return the number of changes since the database handle was opened.
 */
-SQLITE_API int sqlite3_total_changes(sqlite3 *db){
+SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
 #ifdef SQLITE_ENABLE_API_ARMOR
   if( !sqlite3SafetyCheckOk(db) ){
     (void)SQLITE_MISUSE_BKPT;
@@ -165150,6 +169636,9 @@ SQLITE_API int sqlite3_total_changes(sqlite3 *db){
 #endif
   return db->nTotalChange;
 }
+SQLITE_API int sqlite3_total_changes(sqlite3 *db){
+  return (int)sqlite3_total_changes64(db);
+}
 
 /*
 ** Close all open savepoints. This function only manipulates fields of the
@@ -165174,7 +169663,9 @@ SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
 ** with SQLITE_ANY as the encoding.
 */
 static void functionDestroy(sqlite3 *db, FuncDef *p){
-  FuncDestructor *pDestructor = p->u.pDestructor;
+  FuncDestructor *pDestructor;
+  assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
+  pDestructor = p->u.pDestructor;
   if( pDestructor ){
     pDestructor->nRef--;
     if( pDestructor->nRef==0 ){
@@ -165278,7 +169769,7 @@ static int sqlite3Close(sqlite3 *db, int forceZombie){
 
   /* Convert the connection into a zombie and then close it.
   */
-  db->magic = SQLITE_MAGIC_ZOMBIE;
+  db->eOpenState = SQLITE_STATE_ZOMBIE;
   sqlite3LeaveMutexAndCloseZombie(db);
   return SQLITE_OK;
 }
@@ -165316,7 +169807,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
 /*
 ** Two variations on the public interface for closing a database
 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
-** leaves the connection option if there are unfinalized prepared
+** leaves the connection open if there are unfinalized prepared
 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
 ** version forces the connection to become a zombie if there are
 ** unclosed resources, and arranges for deallocation when the last
@@ -165342,7 +169833,7 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
   ** or if the connection has not yet been closed by sqlite3_close_v2(),
   ** then just leave the mutex and return.
   */
-  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
+  if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
     sqlite3_mutex_leave(db->mutex);
     return;
   }
@@ -165428,7 +169919,7 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
   sqlite3_free(db->auth.zAuthPW);
 #endif
 
-  db->magic = SQLITE_MAGIC_ERROR;
+  db->eOpenState = SQLITE_STATE_ERROR;
 
   /* The temp-database schema is allocated differently from the other schema
   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
@@ -165437,8 +169928,11 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
   ** structure?
   */
   sqlite3DbFree(db, db->aDb[1].pSchema);
+  if( db->xAutovacDestr ){
+    db->xAutovacDestr(db->pAutovacPagesArg);
+  }
   sqlite3_mutex_leave(db->mutex);
-  db->magic = SQLITE_MAGIC_CLOSED;
+  db->eOpenState = SQLITE_STATE_CLOSED;
   sqlite3_mutex_free(db->mutex);
   assert( sqlite3LookasideUsed(db,0)==0 );
   if( db->lookaside.bMalloced ){
@@ -165491,7 +169985,7 @@ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   /* Any deferred constraint violations have now been resolved. */
   db->nDeferredCons = 0;
   db->nDeferredImmCons = 0;
-  db->flags &= ~(u64)SQLITE_DeferFKs;
+  db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
 
   /* If one has been configured, invoke the rollback-hook callback */
   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
@@ -165826,7 +170320,7 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
 */
 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
 #ifdef SQLITE_ENABLE_API_ARMOR
-  if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
+  if( !sqlite3SafetyCheckOk(db) && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE) ){
     (void)SQLITE_MISUSE_BKPT;
     return;
   }
@@ -165855,7 +170349,6 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
   FuncDestructor *pDestructor
 ){
   FuncDef *p;
-  int nName;
   int extraFlags;
 
   assert( sqlite3_mutex_held(db->mutex) );
@@ -165865,7 +170358,7 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
    || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */
    || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */
    || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
-   || (255<(nName = sqlite3Strlen30( zFunctionName)))
+   || (255<sqlite3Strlen30(zFunctionName))
   ){
     return SQLITE_MISUSE_BKPT;
   }
@@ -165890,22 +170383,33 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
   ** If SQLITE_ANY is specified, add three versions of the function
   ** to the hash table.
   */
-  if( enc==SQLITE_UTF16 ){
-    enc = SQLITE_UTF16NATIVE;
-  }else if( enc==SQLITE_ANY ){
-    int rc;
-    rc = sqlite3CreateFunc(db, zFunctionName, nArg,
-         (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,
-         pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
-    if( rc==SQLITE_OK ){
+  switch( enc ){
+    case SQLITE_UTF16:
+      enc = SQLITE_UTF16NATIVE;
+      break;
+    case SQLITE_ANY: {
+      int rc;
       rc = sqlite3CreateFunc(db, zFunctionName, nArg,
-           (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,
+           (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,
            pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
+      if( rc==SQLITE_OK ){
+        rc = sqlite3CreateFunc(db, zFunctionName, nArg,
+             (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,
+             pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
+      }
+      if( rc!=SQLITE_OK ){
+        return rc;
+      }
+      enc = SQLITE_UTF16BE;
+      break;
     }
-    if( rc!=SQLITE_OK ){
-      return rc;
-    }
-    enc = SQLITE_UTF16BE;
+    case SQLITE_UTF8:
+    case SQLITE_UTF16LE:
+    case SQLITE_UTF16BE:
+      break;
+    default:
+      enc = SQLITE_UTF8;
+      break;
   }
 #else
   enc = SQLITE_UTF8;
@@ -165926,6 +170430,10 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
     }else{
       sqlite3ExpirePreparedStatements(db, 0);
     }
+  }else if( xSFunc==0 && xFinal==0 ){
+    /* Trying to delete a function that does not exist.  This is a no-op.
+    ** https://sqlite.org/forum/forumpost/726219164b */
+    return SQLITE_OK;
   }
 
   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
@@ -165998,7 +170506,7 @@ static int createFunctionApi(
       xSFunc, xStep, xFinal, xValue, xInverse, pArg
   );
   if( pArg && pArg->nRef==0 ){
-    assert( rc!=SQLITE_OK );
+    assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
     xDestroy(p);
     sqlite3_free(pArg);
   }
@@ -166324,6 +170832,34 @@ SQLITE_API void *sqlite3_preupdate_hook(
 }
 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 
+/*
+** Register a function to be invoked prior to each autovacuum that
+** determines the number of pages to vacuum.
+*/
+SQLITE_API int sqlite3_autovacuum_pages(
+  sqlite3 *db,                 /* Attach the hook to this database */
+  unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
+  void *pArg,                  /* Argument to the function */
+  void (*xDestructor)(void*)   /* Destructor for pArg */
+){
+#ifdef SQLITE_ENABLE_API_ARMOR
+  if( !sqlite3SafetyCheckOk(db) ){
+    if( xDestructor ) xDestructor(pArg);
+    return SQLITE_MISUSE_BKPT;
+  }
+#endif
+  sqlite3_mutex_enter(db->mutex);
+  if( db->xAutovacDestr ){
+    db->xAutovacDestr(db->pAutovacPagesArg);
+  }
+  db->xAutovacPages = xCallback;
+  db->pAutovacPagesArg = pArg;
+  db->xAutovacDestr = xDestructor;
+  sqlite3_mutex_leave(db->mutex);
+  return SQLITE_OK;
+}
+
+
 #ifndef SQLITE_OMIT_WAL
 /*
 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
@@ -166586,6 +171122,19 @@ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   return z;
 }
 
+/*
+** Return the byte offset of the most recent error
+*/
+SQLITE_API int sqlite3_error_offset(sqlite3 *db){
+  int iOffset = -1;
+  if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
+    sqlite3_mutex_enter(db->mutex);
+    iOffset = db->errByteOffset;
+    sqlite3_mutex_leave(db->mutex);
+  }
+  return iOffset;
+}
+
 #ifndef SQLITE_OMIT_UTF16
 /*
 ** Return UTF-16 encoded English language explanation of the most recent
@@ -166846,6 +171395,8 @@ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
     if( newLimit>aHardLimit[limitId] ){
       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
+    }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){
+      newLimit = 1;
     }
     db->aLimit[limitId] = newLimit;
   }
@@ -167117,7 +171668,7 @@ SQLITE_PRIVATE int sqlite3ParseUri(
 */
 static const char *uriParameter(const char *zFilename, const char *zParam){
   zFilename += sqlite3Strlen30(zFilename) + 1;
-  while( zFilename[0] ){
+  while( ALWAYS(zFilename!=0) && zFilename[0] ){
     int x = strcmp(zFilename, zParam);
     zFilename += sqlite3Strlen30(zFilename) + 1;
     if( x==0 ) return zFilename;
@@ -167177,8 +171728,8 @@ static int openDatabase(
   ** dealt with in the previous code block.  Besides these, the only
   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
-  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
-  ** off all other flags.
+  ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
+  ** bits.  Silently mask off all other flags.
   */
   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
                SQLITE_OPEN_EXCLUSIVE |
@@ -167213,9 +171764,9 @@ static int openDatabase(
     }
   }
   sqlite3_mutex_enter(db->mutex);
-  db->errMask = 0xff;
+  db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
   db->nDb = 2;
-  db->magic = SQLITE_MAGIC_BUSY;
+  db->eOpenState = SQLITE_STATE_BUSY;
   db->aDb = db->aDbStatic;
   db->lookaside.bDisable = 1;
   db->lookaside.sz = 0;
@@ -167227,7 +171778,15 @@ static int openDatabase(
   db->nextAutovac = -1;
   db->szMmap = sqlite3GlobalConfig.szMmap;
   db->nextPagesize = 0;
+  db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
+#ifdef SQLITE_ENABLE_SORTER_MMAP
+  /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
+  ** the temporary files used to do external sorts (see code in vdbesort.c)
+  ** is disabled. It can still be used either by defining
+  ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
+  ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
   db->nMaxSorterMmap = 0x7FFFFFFF;
+#endif
   db->flags |= SQLITE_ShortColNames
                  | SQLITE_EnableTrigger
                  | SQLITE_EnableView
@@ -167375,7 +171934,7 @@ static int openDatabase(
   db->aDb[1].zDbSName = "temp";
   db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
 
-  db->magic = SQLITE_MAGIC_OPEN;
+  db->eOpenState = SQLITE_STATE_OPEN;
   if( db->mallocFailed ){
     goto opendb_out;
   }
@@ -167437,12 +171996,12 @@ opendb_out:
     sqlite3_mutex_leave(db->mutex);
   }
   rc = sqlite3_errcode(db);
-  assert( db!=0 || rc==SQLITE_NOMEM );
-  if( rc==SQLITE_NOMEM ){
+  assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
+  if( (rc&0xff)==SQLITE_NOMEM ){
     sqlite3_close(db);
     db = 0;
   }else if( rc!=SQLITE_OK ){
-    db->magic = SQLITE_MAGIC_SICK;
+    db->eOpenState = SQLITE_STATE_SICK;
   }
   *ppDb = db;
 #ifdef SQLITE_ENABLE_SQLLOG
@@ -167453,7 +172012,7 @@ opendb_out:
   }
 #endif
   sqlite3_free_filename(zOpen);
-  return rc & 0xff;
+  return rc;
 }
 
 
@@ -167753,7 +172312,7 @@ SQLITE_API int sqlite3_table_column_metadata(
 
   /* Locate the table in question */
   pTab = sqlite3FindTable(db, zTableName, zDbName);
-  if( !pTab || pTab->pSelect ){
+  if( !pTab || IsView(pTab) ){
     pTab = 0;
     goto error_out;
   }
@@ -167764,7 +172323,7 @@ SQLITE_API int sqlite3_table_column_metadata(
   }else{
     for(iCol=0; iCol<pTab->nCol; iCol++){
       pCol = &pTab->aCol[iCol];
-      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
+      if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
         break;
       }
     }
@@ -167791,7 +172350,7 @@ SQLITE_API int sqlite3_table_column_metadata(
   */
   if( pCol ){
     zDataType = sqlite3ColumnType(pCol,0);
-    zCollSeq = pCol->zColl;
+    zCollSeq = sqlite3ColumnColl(pCol);
     notnull = pCol->notNull!=0;
     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
@@ -167998,12 +172557,16 @@ SQLITE_API int sqlite3_test_control(int op, ...){
     ** sqlite3_test_control().
     */
     case SQLITE_TESTCTRL_FAULT_INSTALL: {
-      /* MSVC is picky about pulling func ptrs from va lists.
-      ** http://support.microsoft.com/kb/47961
+      /* A bug in MSVC prevents it from understanding pointers to functions
+      ** types in the second argument to va_arg().  Work around the problem
+      ** using a typedef.
+      ** http://support.microsoft.com/kb/47961  <-- dead hyperlink
+      ** Search at http://web.archive.org/ to find the 2015-03-16 archive
+      ** of the link above to see the original text.
       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
       */
-      typedef int(*TESTCALLBACKFUNC_t)(int);
-      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
+      typedef int(*sqlite3FaultFuncType)(int);
+      sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
       rc = sqlite3FaultSim(0);
       break;
     }
@@ -168130,13 +172693,27 @@ SQLITE_API int sqlite3_test_control(int op, ...){
       break;
     }
 
-    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
+    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
     **
-    ** If parameter onoff is non-zero, subsequent calls to localtime()
-    ** and its variants fail. If onoff is zero, undo this setting.
+    ** If parameter onoff is 1, subsequent calls to localtime() fail.
+    ** If 2, then invoke xAlt() instead of localtime().  If 0, normal
+    ** processing.
+    **
+    ** xAlt arguments are void pointers, but they really want to be:
+    **
+    **    int xAlt(const time_t*, struct tm*);
+    **
+    ** xAlt should write results in to struct tm object of its 2nd argument
+    ** and return zero on success, or return non-zero on failure.
     */
     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
+      if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
+        typedef int(*sqlite3LocaltimeType)(const void*,void*);
+        sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
+      }else{
+        sqlite3GlobalConfig.xAltLocaltime = 0;
+      }
       break;
     }
 
@@ -168241,12 +172818,16 @@ SQLITE_API int sqlite3_test_control(int op, ...){
     */
     case SQLITE_TESTCTRL_IMPOSTER: {
       sqlite3 *db = va_arg(ap, sqlite3*);
+      int iDb;
       sqlite3_mutex_enter(db->mutex);
-      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
-      db->init.busy = db->init.imposterTable = va_arg(ap,int);
-      db->init.newTnum = va_arg(ap,int);
-      if( db->init.busy==0 && db->init.newTnum>0 ){
-        sqlite3ResetAllSchemasOfConnection(db);
+      iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
+      if( iDb>=0 ){
+        db->init.iDb = iDb;
+        db->init.busy = db->init.imposterTable = va_arg(ap,int);
+        db->init.newTnum = va_arg(ap,int);
+        if( db->init.busy==0 && db->init.newTnum>0 ){
+          sqlite3ResetAllSchemasOfConnection(db);
+        }
       }
       sqlite3_mutex_leave(db->mutex);
       break;
@@ -168321,6 +172902,56 @@ SQLITE_API int sqlite3_test_control(int op, ...){
        }
        break;
     }
+
+    /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
+    **      double fIn,     // Input value
+    **      int *pLogEst,   // sqlite3LogEstFromDouble(fIn)
+    **      u64 *pInt,      // sqlite3LogEstToInt(*pLogEst)
+    **      int *pLogEst2   // sqlite3LogEst(*pInt)
+    ** );
+    **
+    ** Test access for the LogEst conversion routines.
+    */
+    case SQLITE_TESTCTRL_LOGEST: {
+      double rIn = va_arg(ap, double);
+      LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
+      u64 iInt = sqlite3LogEstToInt(rLogEst);
+      va_arg(ap, int*)[0] = rLogEst;
+      va_arg(ap, u64*)[0] = iInt;
+      va_arg(ap, int*)[0] = sqlite3LogEst(iInt);
+      break;
+    }
+
+
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
+    /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
+    **
+    ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
+    ** of the id-th tuning parameter to *piValue.  If "id" is between -1
+    ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
+    ** tuning parameter into *piValue.
+    **
+    ** Tuning parameters are for use during transient development builds,
+    ** to help find the best values for constants in the query planner.
+    ** Access tuning parameters using the Tuning(ID) macro.  Set the
+    ** parameters in the CLI using ".testctrl tune ID VALUE".
+    **
+    ** Transient use only.  Tuning parameters should not be used in
+    ** checked-in code.
+    */
+    case SQLITE_TESTCTRL_TUNE: {
+      int id = va_arg(ap, int);
+      int *piValue = va_arg(ap, int*);
+      if( id>0 && id<=SQLITE_NTUNE ){
+        Tuning(id) = *piValue;
+      }else if( id<0 && id>=-SQLITE_NTUNE ){
+        *piValue = Tuning(-id);
+      }else{
+        rc = SQLITE_NOTFOUND;
+      }
+      break;
+    }
+#endif
   }
   va_end(ap);
 #endif /* SQLITE_UNTESTABLE */
@@ -168428,7 +173059,7 @@ SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N){
   if( zFilename==0 || N<0 ) return 0;
   zFilename = databaseName(zFilename);
   zFilename += sqlite3Strlen30(zFilename) + 1;
-  while( zFilename[0] && (N--)>0 ){
+  while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
     zFilename += sqlite3Strlen30(zFilename) + 1;
     zFilename += sqlite3Strlen30(zFilename) + 1;
   }
@@ -168471,12 +173102,14 @@ SQLITE_API sqlite3_int64 sqlite3_uri_int64(
 ** corruption.
 */
 SQLITE_API const char *sqlite3_filename_database(const char *zFilename){
+  if( zFilename==0 ) return 0;
   return databaseName(zFilename);
 }
 SQLITE_API const char *sqlite3_filename_journal(const char *zFilename){
+  if( zFilename==0 ) return 0;
   zFilename = databaseName(zFilename);
   zFilename += sqlite3Strlen30(zFilename) + 1;
-  while( zFilename[0] ){
+  while( ALWAYS(zFilename) && zFilename[0] ){
     zFilename += sqlite3Strlen30(zFilename) + 1;
     zFilename += sqlite3Strlen30(zFilename) + 1;
   }
@@ -168487,7 +173120,7 @@ SQLITE_API const char *sqlite3_filename_wal(const char *zFilename){
   return 0;
 #else
   zFilename = sqlite3_filename_journal(zFilename);
-  zFilename += sqlite3Strlen30(zFilename) + 1;
+  if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
   return zFilename;
 #endif
 }
@@ -169763,7 +174396,7 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi
 ** is used for assert() conditions that are true only if it can be
 ** guranteed that the database is not corrupt.
 */
-#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+#ifdef SQLITE_DEBUG
 SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
 # define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))
 #else
@@ -169780,17 +174413,18 @@ SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
 ** Macros indicating that conditional expressions are always true or
 ** false.
 */
-#ifdef SQLITE_COVERAGE_TEST
-# define ALWAYS(x) (1)
-# define NEVER(X)  (0)
-#elif defined(SQLITE_DEBUG)
-# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
-# define NEVER(x) sqlite3Fts3Never((x)!=0)
-SQLITE_PRIVATE int sqlite3Fts3Always(int b);
-SQLITE_PRIVATE int sqlite3Fts3Never(int b);
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
+# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
+#endif
+#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
+# define ALWAYS(X)      (1)
+# define NEVER(X)       (0)
+#elif !defined(NDEBUG)
+# define ALWAYS(X)      ((X)?1:(assert(0),0))
+# define NEVER(X)       ((X)?(assert(0),1):0)
 #else
-# define ALWAYS(x) (x)
-# define NEVER(x)  (x)
+# define ALWAYS(X)      (X)
+# define NEVER(X)       (X)
 #endif
 
 /*
@@ -170249,6 +174883,7 @@ SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
 #endif
+SQLITE_PRIVATE void *sqlite3Fts3MallocZero(i64 nByte);
 
 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
   sqlite3_tokenizer_cursor **
@@ -170268,7 +174903,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *)
 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
 
 /* fts3_tokenize_vtab.c */
-SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
+SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *, void(*xDestroy)(void*));
 
 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
 #ifndef SQLITE_DISABLE_FTS3_UNICODE
@@ -170301,25 +174936,26 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
   SQLITE_EXTENSION_INIT1
 #endif
 
+typedef struct Fts3HashWrapper Fts3HashWrapper;
+struct Fts3HashWrapper {
+  Fts3Hash hash;                  /* Hash table */
+  int nRef;                       /* Number of pointers to this object */
+};
+
 static int fts3EvalNext(Fts3Cursor *pCsr);
 static int fts3EvalStart(Fts3Cursor *pCsr);
 static int fts3TermSegReaderCursor(
     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
 
-#ifndef SQLITE_AMALGAMATION
-# if defined(SQLITE_DEBUG)
-SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
-SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
-# endif
-#endif
-
 /*
 ** This variable is set to false when running tests for which the on disk
 ** structures should not be corrupt. Otherwise, true. If it is false, extra
 ** assert() conditions in the fts3 code are activated - conditions that are
 ** only true if it is guaranteed that the fts3 database is not corrupt.
 */
+#ifdef SQLITE_DEBUG
 SQLITE_API int sqlite3_fts3_may_be_corrupt = 1;
+#endif
 
 /*
 ** Write a 64-bit variable-length integer to memory starting at p[0].
@@ -171170,7 +175806,7 @@ static int fts3InitVtab(
   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   char **pzErr                    /* Write any error message here */
 ){
-  Fts3Hash *pHash = (Fts3Hash *)pAux;
+  Fts3Hash *pHash = &((Fts3HashWrapper*)pAux)->hash;
   Fts3Table *p = 0;               /* Pointer to allocated vtab */
   int rc = SQLITE_OK;             /* Return code */
   int i;                          /* Iterator variable */
@@ -171890,7 +176526,7 @@ static int fts3ScanInteriorNode(
   char *zBuffer = 0;              /* Buffer to load terms into */
   i64 nAlloc = 0;                 /* Size of allocated buffer */
   int isFirstTerm = 1;            /* True when processing first term on page */
-  sqlite3_int64 iChild;           /* Block id of child node to descend to */
+  u64 iChild;                     /* Block id of child node to descend to */
   int nBuffer = 0;                /* Total term size */
 
   /* Skip over the 'height' varint that occurs at the start of every
@@ -171906,8 +176542,8 @@ static int fts3ScanInteriorNode(
   ** table, then there are always 20 bytes of zeroed padding following the
   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
   */
-  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
-  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
+  zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
+  zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
   if( zCsr>zEnd ){
     return FTS_CORRUPT_VTAB;
   }
@@ -171960,20 +176596,20 @@ static int fts3ScanInteriorNode(
     */
     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
-      *piFirst = iChild;
+      *piFirst = (i64)iChild;
       piFirst = 0;
     }
 
     if( piLast && cmp<0 ){
-      *piLast = iChild;
+      *piLast = (i64)iChild;
       piLast = 0;
     }
 
     iChild++;
   };
 
-  if( piFirst ) *piFirst = iChild;
-  if( piLast ) *piLast = iChild;
+  if( piFirst ) *piFirst = (i64)iChild;
+  if( piLast ) *piLast = (i64)iChild;
 
  finish_scan:
   sqlite3_free(zBuffer);
@@ -173579,14 +178215,20 @@ static int fts3SetHasStat(Fts3Table *p){
 */
 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   Fts3Table *p = (Fts3Table*)pVtab;
+  int rc;
   UNUSED_PARAMETER(pVtab);
   assert( p->pSegments==0 );
   assert( p->nPendingData==0 );
   assert( p->inTransaction!=1 );
-  TESTONLY( p->inTransaction = 1 );
-  TESTONLY( p->mxSavepoint = -1; );
   p->nLeafAdd = 0;
-  return fts3SetHasStat(p);
+  rc = fts3SetHasStat(p);
+#ifdef SQLITE_DEBUG
+  if( rc==SQLITE_OK ){
+    p->inTransaction = 1;
+    p->mxSavepoint = -1;
+  }
+#endif
+  return rc;
 }
 
 /*
@@ -173999,9 +178641,12 @@ static const sqlite3_module fts3Module = {
 ** allocated for the tokenizer hash table.
 */
 static void hashDestroy(void *p){
-  Fts3Hash *pHash = (Fts3Hash *)p;
-  sqlite3Fts3HashClear(pHash);
-  sqlite3_free(pHash);
+  Fts3HashWrapper *pHash = (Fts3HashWrapper *)p;
+  pHash->nRef--;
+  if( pHash->nRef<=0 ){
+    sqlite3Fts3HashClear(&pHash->hash);
+    sqlite3_free(pHash);
+  }
 }
 
 /*
@@ -174031,7 +178676,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const
 */
 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   int rc = SQLITE_OK;
-  Fts3Hash *pHash = 0;
+  Fts3HashWrapper *pHash = 0;
   const sqlite3_tokenizer_module *pSimple = 0;
   const sqlite3_tokenizer_module *pPorter = 0;
 #ifndef SQLITE_DISABLE_FTS3_UNICODE
@@ -174059,23 +178704,24 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   sqlite3Fts3PorterTokenizerModule(&pPorter);
 
   /* Allocate and initialize the hash-table used to store tokenizers. */
-  pHash = sqlite3_malloc(sizeof(Fts3Hash));
+  pHash = sqlite3_malloc(sizeof(Fts3HashWrapper));
   if( !pHash ){
     rc = SQLITE_NOMEM;
   }else{
-    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
+    sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1);
+    pHash->nRef = 0;
   }
 
   /* Load the built-in tokenizers into the hash table */
   if( rc==SQLITE_OK ){
-    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
-     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
+    if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple)
+     || sqlite3Fts3HashInsert(&pHash->hash, "porter", 7, (void *)pPorter)
 
 #ifndef SQLITE_DISABLE_FTS3_UNICODE
-     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
+     || sqlite3Fts3HashInsert(&pHash->hash, "unicode61", 10, (void *)pUnicode)
 #endif
 #ifdef SQLITE_ENABLE_ICU
-     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
+     || (pIcu && sqlite3Fts3HashInsert(&pHash->hash, "icu", 4, (void *)pIcu))
 #endif
     ){
       rc = SQLITE_NOMEM;
@@ -174084,7 +178730,7 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
 
 #ifdef SQLITE_TEST
   if( rc==SQLITE_OK ){
-    rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
+    rc = sqlite3Fts3ExprInitTestInterface(db, &pHash->hash);
   }
 #endif
 
@@ -174093,23 +178739,26 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   ** module with sqlite.
   */
   if( SQLITE_OK==rc
-   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
+   && SQLITE_OK==(rc=sqlite3Fts3InitHashTable(db,&pHash->hash,"fts3_tokenizer"))
    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   ){
+    pHash->nRef++;
     rc = sqlite3_create_module_v2(
         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
     );
     if( rc==SQLITE_OK ){
+      pHash->nRef++;
       rc = sqlite3_create_module_v2(
-          db, "fts4", &fts3Module, (void *)pHash, 0
+          db, "fts4", &fts3Module, (void *)pHash, hashDestroy
       );
     }
     if( rc==SQLITE_OK ){
-      rc = sqlite3Fts3InitTok(db, (void *)pHash);
+      pHash->nRef++;
+      rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy);
     }
     return rc;
   }
@@ -174118,7 +178767,7 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   /* An error has occurred. Delete the hash table and return the error code. */
   assert( rc!=SQLITE_OK );
   if( pHash ){
-    sqlite3Fts3HashClear(pHash);
+    sqlite3Fts3HashClear(&pHash->hash);
     sqlite3_free(pHash);
   }
   return rc;
@@ -174465,7 +179114,7 @@ SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
 
   assert( nDoclist>0 );
   assert( *pbEof==0 );
-  assert( p || *piDocid==0 );
+  assert_fts3_nc( p || *piDocid==0 );
   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
 
   if( p==0 ){
@@ -175115,16 +179764,15 @@ static int fts3EvalStart(Fts3Cursor *pCsr){
 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
     Fts3TokenAndCost *aTC;
-    Fts3Expr **apOr;
     aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
         sizeof(Fts3TokenAndCost) * nToken
       + sizeof(Fts3Expr *) * nOr * 2
     );
-    apOr = (Fts3Expr **)&aTC[nToken];
 
     if( !aTC ){
       rc = SQLITE_NOMEM;
     }else{
+      Fts3Expr **apOr = (Fts3Expr **)&aTC[nToken];
       int ii;
       Fts3TokenAndCost *pTC = aTC;
       Fts3Expr **ppOr = apOr;
@@ -175330,8 +179978,8 @@ static void fts3EvalNextRow(
         Fts3Expr *pRight = pExpr->pRight;
         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
 
-        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
-        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
+        assert_fts3_nc( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
+        assert_fts3_nc( pRight->bStart || pLeft->iDocid==pRight->iDocid );
 
         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
           fts3EvalNextRow(pCsr, pLeft, pRc);
@@ -175969,6 +180617,9 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
         if( bEofSave==0 && pNear->iDocid==iDocid ) break;
       }
       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
+      if( rc==SQLITE_OK && pNear->bEof!=bEofSave ){
+        rc = FTS_CORRUPT_VTAB;
+      }
     }
     if( bTreeEof ){
       while( rc==SQLITE_OK && !pNear->bEof ){
@@ -176391,6 +181042,7 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
     iCol = 0;
+    rc = SQLITE_OK;
 
     while( i<nDoclist ){
       sqlite3_int64 v = 0;
@@ -176434,6 +181086,10 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
         /* State 3. The integer just read is a column number. */
         default: assert( eState==3 );
           iCol = (int)v;
+          if( iCol<1 ){
+            rc = SQLITE_CORRUPT_VTAB;
+            break;
+          }
           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
           pCsr->aStat[iCol+1].nDoc++;
           eState = 2;
@@ -176442,7 +181098,6 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
     }
 
     pCsr->iCol = 0;
-    rc = SQLITE_OK;
   }else{
     pCsr->isEof = 1;
   }
@@ -176500,6 +181155,7 @@ static int fts3auxFilterMethod(
   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   sqlite3_free((void *)pCsr->filter.zTerm);
   sqlite3_free(pCsr->aStat);
+  sqlite3_free(pCsr->zStop);
   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
 
   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
@@ -176770,7 +181426,7 @@ static int fts3isspace(char c){
 ** zero the memory before returning a pointer to it. If unsuccessful,
 ** return NULL.
 */
-static void *fts3MallocZero(sqlite3_int64 nByte){
+SQLITE_PRIVATE void *sqlite3Fts3MallocZero(sqlite3_int64 nByte){
   void *pRet = sqlite3_malloc64(nByte);
   if( pRet ) memset(pRet, 0, nByte);
   return pRet;
@@ -176851,7 +181507,7 @@ static int getNextToken(
     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
     if( rc==SQLITE_OK ){
       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
-      pRet = (Fts3Expr *)fts3MallocZero(nByte);
+      pRet = (Fts3Expr *)sqlite3Fts3MallocZero(nByte);
       if( !pRet ){
         rc = SQLITE_NOMEM;
       }else{
@@ -177106,7 +181762,7 @@ static int getNextNode(
       if( fts3isspace(cNext)
        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
       ){
-        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
+        pRet = (Fts3Expr *)sqlite3Fts3MallocZero(sizeof(Fts3Expr));
         if( !pRet ){
           return SQLITE_NOMEM;
         }
@@ -177285,7 +181941,7 @@ static int fts3ExprParse(
             && p->eType==FTSQUERY_PHRASE && pParse->isNot
         ){
           /* Create an implicit NOT operator. */
-          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
+          Fts3Expr *pNot = sqlite3Fts3MallocZero(sizeof(Fts3Expr));
           if( !pNot ){
             sqlite3Fts3ExprFree(p);
             rc = SQLITE_NOMEM;
@@ -177319,7 +181975,7 @@ static int fts3ExprParse(
             /* Insert an implicit AND operator. */
             Fts3Expr *pAnd;
             assert( pRet && pPrev );
-            pAnd = fts3MallocZero(sizeof(Fts3Expr));
+            pAnd = sqlite3Fts3MallocZero(sizeof(Fts3Expr));
             if( !pAnd ){
               sqlite3Fts3ExprFree(p);
               rc = SQLITE_NOMEM;
@@ -180175,7 +184831,7 @@ static int fts3tokRowidMethod(
 ** Register the fts3tok module with database connection db. Return SQLITE_OK
 ** if successful or an error code if sqlite3_create_module() fails.
 */
-SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
+SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash, void(*xDestroy)(void*)){
   static const sqlite3_module fts3tok_module = {
      0,                           /* iVersion      */
      fts3tokConnectMethod,        /* xCreate       */
@@ -180204,7 +184860,9 @@ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
   };
   int rc;                         /* Return code */
 
-  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
+  rc = sqlite3_create_module_v2(
+      db, "fts3tokenize", &fts3tok_module, (void*)pHash, xDestroy
+  );
   return rc;
 }
 
@@ -181549,8 +186207,18 @@ static int fts3SegReaderNext(
         char *aCopy;
         PendingList *pList = (PendingList *)fts3HashData(pElem);
         int nCopy = pList->nData+1;
-        pReader->zTerm = (char *)fts3HashKey(pElem);
-        pReader->nTerm = fts3HashKeysize(pElem);
+
+        int nTerm = fts3HashKeysize(pElem);
+        if( (nTerm+1)>pReader->nTermAlloc ){
+          sqlite3_free(pReader->zTerm);
+          pReader->zTerm = (char*)sqlite3_malloc((nTerm+1)*2);
+          if( !pReader->zTerm ) return SQLITE_NOMEM;
+          pReader->nTermAlloc = (nTerm+1)*2;
+        }
+        memcpy(pReader->zTerm, fts3HashKey(pElem), nTerm);
+        pReader->zTerm[nTerm] = '\0';
+        pReader->nTerm = nTerm;
+
         aCopy = (char*)sqlite3_malloc(nCopy);
         if( !aCopy ) return SQLITE_NOMEM;
         memcpy(aCopy, pList->aData, nCopy);
@@ -181803,9 +186471,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
 */
 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
   if( pReader ){
-    if( !fts3SegReaderIsPending(pReader) ){
-      sqlite3_free(pReader->zTerm);
-    }
+    sqlite3_free(pReader->zTerm);
     if( !fts3SegReaderIsRootOnly(pReader) ){
       sqlite3_free(pReader->aNode);
     }
@@ -182021,7 +186687,7 @@ static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   if( rc==0 ){
     rc = pRhs->iIdx - pLhs->iIdx;
   }
-  assert( rc!=0 );
+  assert_fts3_nc( rc!=0 );
   return rc;
 }
 
@@ -182217,8 +186883,8 @@ static int fts3PrefixCompress(
   int nNext                       /* Size of buffer zNext in bytes */
 ){
   int n;
-  UNUSED_PARAMETER(nNext);
-  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
+  for(n=0; n<nPrev && n<nNext && zPrev[n]==zNext[n]; n++);
+  assert_fts3_nc( n<nNext );
   return n;
 }
 
@@ -183217,7 +187883,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
 
           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
 
-          rc = fts3GrowSegReaderBuffer(pCsr, nByte+nDoclist);
+          rc = fts3GrowSegReaderBuffer(pCsr, nByte+nDoclist+FTS3_NODE_PADDING);
           if( rc ) return rc;
 
           if( isFirst ){
@@ -183997,7 +188663,7 @@ static int nodeReaderNext(NodeReader *p){
       return FTS_CORRUPT_VTAB;
     }
     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
-    if( rc==SQLITE_OK ){
+    if( rc==SQLITE_OK && ALWAYS(p->term.a!=0) ){
       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
       p->term.n = nPrefix+nSuffix;
       p->iOff += nSuffix;
@@ -184391,7 +189057,11 @@ static int fts3TermCmp(
   int nCmp = MIN(nLhs, nRhs);
   int res;
 
-  res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0);
+  if( nCmp && ALWAYS(zLhs) && ALWAYS(zRhs) ){
+    res = memcmp(zLhs, zRhs, nCmp);
+  }else{
+    res = 0;
+  }
   if( res==0 ) res = nLhs - nRhs;
 
   return res;
@@ -185035,7 +189705,7 @@ static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
       if( aHint ){
         blobGrowBuffer(pHint, nHint, &rc);
         if( rc==SQLITE_OK ){
-          memcpy(pHint->a, aHint, nHint);
+          if( ALWAYS(pHint->a!=0) ) memcpy(pHint->a, aHint, nHint);
           pHint->n = nHint;
         }
       }
@@ -186031,6 +190701,10 @@ SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
 /* #include <string.h> */
 /* #include <assert.h> */
 
+#ifndef SQLITE_AMALGAMATION
+typedef sqlite3_int64 i64;
+#endif
+
 /*
 ** Characters that may appear in the second argument to matchinfo().
 */
@@ -186081,9 +190755,9 @@ struct SnippetIter {
 struct SnippetPhrase {
   int nToken;                     /* Number of tokens in phrase */
   char *pList;                    /* Pointer to start of phrase position list */
-  int iHead;                      /* Next value in position list */
+  i64 iHead;                      /* Next value in position list */
   char *pHead;                    /* Position list data following iHead */
-  int iTail;                      /* Next value in trailing position list */
+  i64 iTail;                      /* Next value in trailing position list */
   char *pTail;                    /* Position list data following iTail */
 };
 
@@ -186148,9 +190822,8 @@ static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
                            + sizeof(MatchinfoBuffer);
   sqlite3_int64 nStr = strlen(zMatchinfo);
 
-  pRet = sqlite3_malloc64(nByte + nStr+1);
+  pRet = sqlite3Fts3MallocZero(nByte + nStr+1);
   if( pRet ){
-    memset(pRet, 0, nByte);
     pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
     pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]
                                       + sizeof(u32)*((int)nElem+1);
@@ -186248,7 +190921,7 @@ SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
 ** After it returns, *piPos contains the value of the next element of the
 ** list and *pp is advanced to the following varint.
 */
-static void fts3GetDeltaPosition(char **pp, int *piPos){
+static void fts3GetDeltaPosition(char **pp, i64 *piPos){
   int iVal;
   *pp += fts3GetVarint32(*pp, &iVal);
   *piPos += (iVal-2);
@@ -186357,10 +191030,10 @@ static int fts3ExprPhraseCount(Fts3Expr *pExpr){
 ** arguments so that it points to the first element with a value greater
 ** than or equal to parameter iNext.
 */
-static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
+static void fts3SnippetAdvance(char **ppIter, i64 *piIter, int iNext){
   char *pIter = *ppIter;
   if( pIter ){
-    int iIter = *piIter;
+    i64 iIter = *piIter;
 
     while( iIter<iNext ){
       if( 0==(*pIter & 0xFE) ){
@@ -186443,7 +191116,7 @@ static void fts3SnippetDetails(
     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
     if( pPhrase->pTail ){
       char *pCsr = pPhrase->pTail;
-      int iCsr = pPhrase->iTail;
+      i64 iCsr = pPhrase->iTail;
 
       while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){
         int j;
@@ -186489,7 +191162,7 @@ static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
   assert( rc==SQLITE_OK || pCsr==0 );
   if( pCsr ){
-    int iFirst = 0;
+    i64 iFirst = 0;
     pPhrase->pList = pCsr;
     fts3GetDeltaPosition(&pCsr, &iFirst);
     if( iFirst<0 ){
@@ -186554,11 +191227,10 @@ static int fts3BestSnippet(
   ** the required space using malloc().
   */
   nByte = sizeof(SnippetPhrase) * nList;
-  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte);
+  sIter.aPhrase = (SnippetPhrase *)sqlite3Fts3MallocZero(nByte);
   if( !sIter.aPhrase ){
     return SQLITE_NOMEM;
   }
-  memset(sIter.aPhrase, 0, nByte);
 
   /* Initialize the contents of the SnippetIter object. Then iterate through
   ** the set of phrases in the expression to populate the aPhrase[] array.
@@ -187122,10 +191794,12 @@ static int fts3MatchinfoLcsCb(
 ** position list for the next column.
 */
 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
-  char *pRead = pIter->pRead;
+  char *pRead;
   sqlite3_int64 iRead;
   int rc = 0;
 
+  if( NEVER(pIter==0) ) return 1;
+  pRead = pIter->pRead;
   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   if( iRead==0 || iRead==1 ){
     pRead = 0;
@@ -187159,9 +191833,8 @@ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
   /* Allocate and populate the array of LcsIterator objects. The array
   ** contains one element for each matchable phrase in the query.
   **/
-  aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase);
+  aIter = sqlite3Fts3MallocZero(sizeof(LcsIterator) * pCsr->nPhrase);
   if( !aIter ) return SQLITE_NOMEM;
-  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
 
   for(i=0; i<pInfo->nPhrase; i++){
@@ -187553,8 +192226,8 @@ typedef struct TermOffsetCtx TermOffsetCtx;
 
 struct TermOffset {
   char *pList;                    /* Position-list */
-  int iPos;                       /* Position just read from pList */
-  int iOff;                       /* Offset of this term from read positions */
+  i64 iPos;                       /* Position just read from pList */
+  i64 iOff;                       /* Offset of this term from read positions */
 };
 
 struct TermOffsetCtx {
@@ -187573,7 +192246,7 @@ static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
   int nTerm;                      /* Number of tokens in phrase */
   int iTerm;                      /* For looping through nTerm phrase terms */
   char *pList;                    /* Pointer to position list for phrase */
-  int iPos = 0;                   /* First position in position-list */
+  i64 iPos = 0;                   /* First position in position-list */
   int rc;
 
   UNUSED_PARAMETER(iPhrase);
@@ -187622,7 +192295,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets(
   if( rc!=SQLITE_OK ) goto offsets_out;
 
   /* Allocate the array of TermOffset iterators. */
-  sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken);
+  sCtx.aTerm = (TermOffset *)sqlite3Fts3MallocZero(sizeof(TermOffset)*nToken);
   if( 0==sCtx.aTerm ){
     rc = SQLITE_NOMEM;
     goto offsets_out;
@@ -187643,13 +192316,13 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets(
     const char *zDoc;
     int nDoc;
 
-    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
-    ** no way that this operation can fail, so the return code from
-    ** fts3ExprIterate() can be discarded.
+    /* Initialize the contents of sCtx.aTerm[] for column iCol. This
+    ** operation may fail if the database contains corrupt records.
     */
     sCtx.iCol = iCol;
     sCtx.iTerm = 0;
-    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
+    rc = fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
+    if( rc!=SQLITE_OK ) goto offsets_out;
 
     /* Retreive the text stored in column iCol. If an SQL NULL is stored
     ** in column iCol, jump immediately to the next iteration of the loop.
@@ -188548,7 +193221,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
 
 /************** End of fts3_unicode2.c ***************************************/
-/************** Begin file json1.c *******************************************/
+/************** Begin file json.c ********************************************/
 /*
 ** 2015-08-12
 **
@@ -188561,10 +193234,10 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
 **
 ******************************************************************************
 **
-** This SQLite extension implements JSON functions.  The interface is
-** modeled after MySQL JSON functions:
+** This SQLite JSON functions.
 **
-**     https://dev.mysql.com/doc/refman/5.7/en/json.html
+** This file began as an extension in ext/misc/json1.c in 2015.  That
+** extension proved so useful that it has now been moved into the core.
 **
 ** For the time being, all JSON is stored as pure text.  (We might add
 ** a JSONB type in the future which stores a binary encoding of JSON in
@@ -188572,48 +193245,8 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
 ** This implementation parses JSON text at 250 MB/s, so it is hard to see
 ** how JSONB might improve on that.)
 */
-#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
-#if !defined(SQLITEINT_H)
-/* #include "sqlite3ext.h" */
-#endif
-SQLITE_EXTENSION_INIT1
-/* #include <assert.h> */
-/* #include <string.h> */
-/* #include <stdlib.h> */
-/* #include <stdarg.h> */
-
-/* Mark a function parameter as unused, to suppress nuisance compiler
-** warnings. */
-#ifndef UNUSED_PARAM
-# define UNUSED_PARAM(X)  (void)(X)
-#endif
-
-#ifndef LARGEST_INT64
-# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
-# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
-#endif
-
-#ifndef deliberate_fall_through
-# define deliberate_fall_through
-#endif
-
-/*
-** Versions of isspace(), isalnum() and isdigit() to which it is safe
-** to pass signed char values.
-*/
-#ifdef sqlite3Isdigit
-   /* Use the SQLite core versions if this routine is part of the
-   ** SQLite amalgamation */
-#  define safe_isdigit(x)  sqlite3Isdigit(x)
-#  define safe_isalnum(x)  sqlite3Isalnum(x)
-#  define safe_isxdigit(x) sqlite3Isxdigit(x)
-#else
-   /* Use the standard library for separate compilation */
-#include <ctype.h>  /* amalgamator: keep */
-#  define safe_isdigit(x)  isdigit((unsigned char)(x))
-#  define safe_isalnum(x)  isalnum((unsigned char)(x))
-#  define safe_isxdigit(x) isxdigit((unsigned char)(x))
-#endif
+#ifndef SQLITE_OMIT_JSON
+/* #include "sqliteInt.h" */
 
 /*
 ** Growing our own isspace() routine this way is twice as fast as
@@ -188638,15 +193271,12 @@ static const char jsonIsSpace[] = {
   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
 };
-#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
+#define fast_isspace(x) (jsonIsSpace[(unsigned char)x])
 
-#ifndef SQLITE_AMALGAMATION
-  /* Unsigned integer types.  These are already defined in the sqliteInt.h,
-  ** but the definitions need to be repeated for separate compilation. */
-  typedef sqlite3_uint64 u64;
-  typedef unsigned int u32;
-  typedef unsigned short int u16;
-  typedef unsigned char u8;
+#if !defined(SQLITE_DEBUG) && !defined(SQLITE_COVERAGE_TEST)
+#  define VVA(X)
+#else
+#  define VVA(X) X
 #endif
 
 /* Objects */
@@ -188705,13 +193335,14 @@ static const char * const jsonType[] = {
 struct JsonNode {
   u8 eType;              /* One of the JSON_ type values */
   u8 jnFlags;            /* JNODE flags */
+  u8 eU;                 /* Which union element to use */
   u32 n;                 /* Bytes of content, or number of sub-nodes */
   union {
-    const char *zJContent; /* Content for INT, REAL, and STRING */
-    u32 iAppend;           /* More terms for ARRAY and OBJECT */
-    u32 iKey;              /* Key for ARRAY objects in json_tree() */
-    u32 iReplace;          /* Replacement content for JNODE_REPLACE */
-    JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */
+    const char *zJContent; /* 1: Content for INT, REAL, and STRING */
+    u32 iAppend;           /* 2: More terms for ARRAY and OBJECT */
+    u32 iKey;              /* 3: Key for ARRAY objects in json_tree() */
+    u32 iReplace;          /* 4: Replacement content for JNODE_REPLACE */
+    JsonNode *pPatch;      /* 5: Node chain of patch for JNODE_PATCH */
   } u;
 };
 
@@ -188850,7 +193481,7 @@ static void jsonAppendSeparator(JsonString *p){
 */
 static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
   u32 i;
-  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
+  if( zIn==0 || ((N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0) ) return;
   p->zBuf[p->nUsed++] = '"';
   for(i=0; i<N; i++){
     unsigned char c = ((unsigned const char*)zIn)[i];
@@ -188989,11 +193620,14 @@ static void jsonRenderNode(
   JsonString *pOut,              /* Write JSON here */
   sqlite3_value **aReplace       /* Replacement values */
 ){
+  assert( pNode!=0 );
   if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
-    if( pNode->jnFlags & JNODE_REPLACE ){
+    if( (pNode->jnFlags & JNODE_REPLACE)!=0 && ALWAYS(aReplace!=0) ){
+      assert( pNode->eU==4 );
       jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
       return;
     }
+    assert( pNode->eU==5 );
     pNode = pNode->u.pPatch;
   }
   switch( pNode->eType ){
@@ -189012,6 +193646,7 @@ static void jsonRenderNode(
     }
     case JSON_STRING: {
       if( pNode->jnFlags & JNODE_RAW ){
+        assert( pNode->eU==1 );
         jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
         break;
       }
@@ -189019,6 +193654,7 @@ static void jsonRenderNode(
     }
     case JSON_REAL:
     case JSON_INT: {
+      assert( pNode->eU==1 );
       jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
       break;
     }
@@ -189034,6 +193670,7 @@ static void jsonRenderNode(
           j += jsonNodeSize(&pNode[j]);
         }
         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
+        assert( pNode->eU==2 );
         pNode = &pNode[pNode->u.iAppend];
         j = 1;
       }
@@ -189054,6 +193691,7 @@ static void jsonRenderNode(
           j += 1 + jsonNodeSize(&pNode[j+1]);
         }
         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
+        assert( pNode->eU==2 );
         pNode = &pNode[pNode->u.iAppend];
         j = 1;
       }
@@ -189098,10 +193736,10 @@ static u8 jsonHexToInt(int h){
 */
 static u32 jsonHexToInt4(const char *z){
   u32 v;
-  assert( safe_isxdigit(z[0]) );
-  assert( safe_isxdigit(z[1]) );
-  assert( safe_isxdigit(z[2]) );
-  assert( safe_isxdigit(z[3]) );
+  assert( sqlite3Isxdigit(z[0]) );
+  assert( sqlite3Isxdigit(z[1]) );
+  assert( sqlite3Isxdigit(z[2]) );
+  assert( sqlite3Isxdigit(z[3]) );
   v = (jsonHexToInt(z[0])<<12)
     + (jsonHexToInt(z[1])<<8)
     + (jsonHexToInt(z[2])<<4)
@@ -189133,7 +193771,9 @@ static void jsonReturn(
     }
     case JSON_INT: {
       sqlite3_int64 i = 0;
-      const char *z = pNode->u.zJContent;
+      const char *z;
+      assert( pNode->eU==1 );
+      z = pNode->u.zJContent;
       if( z[0]=='-' ){ z++; }
       while( z[0]>='0' && z[0]<='9' ){
         unsigned v = *(z++) - '0';
@@ -189156,14 +193796,17 @@ static void jsonReturn(
       sqlite3_result_int64(pCtx, i);
       int_done:
       break;
-      int_as_real: i=0; /* no break */ deliberate_fall_through
+      int_as_real: ; /* no break */ deliberate_fall_through
     }
     case JSON_REAL: {
       double r;
 #ifdef SQLITE_AMALGAMATION
-      const char *z = pNode->u.zJContent;
+      const char *z;
+      assert( pNode->eU==1 );
+      z = pNode->u.zJContent;
       sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
 #else
+      assert( pNode->eU==1 );
       r = strtod(pNode->u.zJContent, 0);
 #endif
       sqlite3_result_double(pCtx, r);
@@ -189174,6 +193817,7 @@ static void jsonReturn(
       ** json_insert() and json_replace() and those routines do not
       ** call jsonReturn() */
       if( pNode->jnFlags & JNODE_RAW ){
+        assert( pNode->eU==1 );
         sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
                             SQLITE_TRANSIENT);
       }else
@@ -189181,15 +193825,18 @@ static void jsonReturn(
       assert( (pNode->jnFlags & JNODE_RAW)==0 );
       if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
         /* JSON formatted without any backslash-escapes */
+        assert( pNode->eU==1 );
         sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
                             SQLITE_TRANSIENT);
       }else{
         /* Translate JSON formatted string into raw text */
         u32 i;
         u32 n = pNode->n;
-        const char *z = pNode->u.zJContent;
+        const char *z;
         char *zOut;
         u32 j;
+        assert( pNode->eU==1 );
+        z = pNode->u.zJContent;
         zOut = sqlite3_malloc( n+1 );
         if( zOut==0 ){
           sqlite3_result_error_nomem(pCtx);
@@ -189310,12 +193957,13 @@ static int jsonParseAddNode(
   const char *zContent      /* Content */
 ){
   JsonNode *p;
-  if( pParse->nNode>=pParse->nAlloc ){
+  if( pParse->aNode==0 || pParse->nNode>=pParse->nAlloc ){
     return jsonParseAddNodeExpand(pParse, eType, n, zContent);
   }
   p = &pParse->aNode[pParse->nNode];
   p->eType = (u8)eType;
   p->jnFlags = 0;
+  VVA( p->eU = zContent ? 1 : 0 );
   p->n = n;
   p->u.zJContent = zContent;
   return pParse->nNode++;
@@ -189326,7 +193974,7 @@ static int jsonParseAddNode(
 */
 static int jsonIs4Hex(const char *z){
   int i;
-  for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
+  for(i=0; i<4; i++) if( !sqlite3Isxdigit(z[i]) ) return 0;
   return 1;
 }
 
@@ -189345,13 +193993,13 @@ static int jsonParseValue(JsonParse *pParse, u32 i){
   int x;
   JsonNode *pNode;
   const char *z = pParse->zJson;
-  while( safe_isspace(z[i]) ){ i++; }
+  while( fast_isspace(z[i]) ){ i++; }
   if( (c = z[i])=='{' ){
     /* Parse object */
     iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
     if( iThis<0 ) return -1;
     for(j=i+1;;j++){
-      while( safe_isspace(z[j]) ){ j++; }
+      while( fast_isspace(z[j]) ){ j++; }
       if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
       x = jsonParseValue(pParse, j);
       if( x<0 ){
@@ -189364,14 +194012,14 @@ static int jsonParseValue(JsonParse *pParse, u32 i){
       if( pNode->eType!=JSON_STRING ) return -1;
       pNode->jnFlags |= JNODE_LABEL;
       j = x;
-      while( safe_isspace(z[j]) ){ j++; }
+      while( fast_isspace(z[j]) ){ j++; }
       if( z[j]!=':' ) return -1;
       j++;
       x = jsonParseValue(pParse, j);
       pParse->iDepth--;
       if( x<0 ) return -1;
       j = x;
-      while( safe_isspace(z[j]) ){ j++; }
+      while( fast_isspace(z[j]) ){ j++; }
       c = z[j];
       if( c==',' ) continue;
       if( c!='}' ) return -1;
@@ -189383,8 +194031,9 @@ static int jsonParseValue(JsonParse *pParse, u32 i){
     /* Parse array */
     iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
     if( iThis<0 ) return -1;
+    memset(&pParse->aNode[iThis].u, 0, sizeof(pParse->aNode[iThis].u));
     for(j=i+1;;j++){
-      while( safe_isspace(z[j]) ){ j++; }
+      while( fast_isspace(z[j]) ){ j++; }
       if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
       x = jsonParseValue(pParse, j);
       pParse->iDepth--;
@@ -189393,7 +194042,7 @@ static int jsonParseValue(JsonParse *pParse, u32 i){
         return -1;
       }
       j = x;
-      while( safe_isspace(z[j]) ){ j++; }
+      while( fast_isspace(z[j]) ){ j++; }
       c = z[j];
       if( c==',' ) continue;
       if( c!=']' ) return -1;
@@ -189430,17 +194079,17 @@ static int jsonParseValue(JsonParse *pParse, u32 i){
     return j+1;
   }else if( c=='n'
          && strncmp(z+i,"null",4)==0
-         && !safe_isalnum(z[i+4]) ){
+         && !sqlite3Isalnum(z[i+4]) ){
     jsonParseAddNode(pParse, JSON_NULL, 0, 0);
     return i+4;
   }else if( c=='t'
          && strncmp(z+i,"true",4)==0
-         && !safe_isalnum(z[i+4]) ){
+         && !sqlite3Isalnum(z[i+4]) ){
     jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
     return i+4;
   }else if( c=='f'
          && strncmp(z+i,"false",5)==0
-         && !safe_isalnum(z[i+5]) ){
+         && !sqlite3Isalnum(z[i+5]) ){
     jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
     return i+5;
   }else if( c=='-' || (c>='0' && c<='9') ){
@@ -189511,7 +194160,7 @@ static int jsonParse(
   if( pParse->oom ) i = -1;
   if( i>0 ){
     assert( pParse->iDepth==0 );
-    while( safe_isspace(zJson[i]) ) i++;
+    while( fast_isspace(zJson[i]) ) i++;
     if( zJson[i] ) i = -1;
   }
   if( i<=0 ){
@@ -189647,6 +194296,7 @@ static JsonParse *jsonParseCached(
 ** a match.
 */
 static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
+  assert( pNode->eU==1 );
   if( pNode->jnFlags & JNODE_RAW ){
     if( pNode->n!=nKey ) return 0;
     return strncmp(pNode->u.zJContent, zKey, nKey)==0;
@@ -189693,14 +194343,15 @@ static JsonNode *jsonLookupStep(
         *pzErr = zPath;
         return 0;
       }
+      testcase( nKey==0 );
     }else{
       zKey = zPath;
       for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
       nKey = i;
-    }
-    if( nKey==0 ){
-      *pzErr = zPath;
-      return 0;
+      if( nKey==0 ){
+        *pzErr = zPath;
+        return 0;
+      }
     }
     j = 1;
     for(;;){
@@ -189712,6 +194363,7 @@ static JsonNode *jsonLookupStep(
         j += jsonNodeSize(&pRoot[j]);
       }
       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
+      assert( pRoot->eU==2 );
       iRoot += pRoot->u.iAppend;
       pRoot = &pParse->aNode[iRoot];
       j = 1;
@@ -189726,8 +194378,10 @@ static JsonNode *jsonLookupStep(
       if( pParse->oom ) return 0;
       if( pNode ){
         pRoot = &pParse->aNode[iRoot];
+        assert( pRoot->eU==0 );
         pRoot->u.iAppend = iStart - iRoot;
         pRoot->jnFlags |= JNODE_APPEND;
+        VVA( pRoot->eU = 2 );
         pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
       }
       return pNode;
@@ -189735,7 +194389,7 @@ static JsonNode *jsonLookupStep(
   }else if( zPath[0]=='[' ){
     i = 0;
     j = 1;
-    while( safe_isdigit(zPath[j]) ){
+    while( sqlite3Isdigit(zPath[j]) ){
       i = i*10 + zPath[j] - '0';
       j++;
     }
@@ -189750,18 +194404,19 @@ static JsonNode *jsonLookupStep(
             j += jsonNodeSize(&pBase[j]);
           }
           if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
+          assert( pBase->eU==2 );
           iBase += pBase->u.iAppend;
           pBase = &pParse->aNode[iBase];
           j = 1;
         }
         j = 2;
-        if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){
+        if( zPath[2]=='-' && sqlite3Isdigit(zPath[3]) ){
           unsigned int x = 0;
           j = 3;
           do{
             x = x*10 + zPath[j] - '0';
             j++;
-          }while( safe_isdigit(zPath[j]) );
+          }while( sqlite3Isdigit(zPath[j]) );
           if( x>i ) return 0;
           i -= x;
         }
@@ -189783,6 +194438,7 @@ static JsonNode *jsonLookupStep(
         j += jsonNodeSize(&pRoot[j]);
       }
       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
+      assert( pRoot->eU==2 );
       iRoot += pRoot->u.iAppend;
       pRoot = &pParse->aNode[iRoot];
       j = 1;
@@ -189798,8 +194454,10 @@ static JsonNode *jsonLookupStep(
       if( pParse->oom ) return 0;
       if( pNode ){
         pRoot = &pParse->aNode[iRoot];
+        assert( pRoot->eU==0 );
         pRoot->u.iAppend = iStart - iRoot;
         pRoot->jnFlags |= JNODE_APPEND;
+        VVA( pRoot->eU = 2 );
       }
       return pNode;
     }
@@ -189953,9 +194611,13 @@ static void jsonParseFunc(
     }
     jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
                i, zType, x.aNode[i].n, x.aUp[i]);
+    assert( x.aNode[i].eU==0 || x.aNode[i].eU==1 );
     if( x.aNode[i].u.zJContent!=0 ){
+      assert( x.aNode[i].eU==1 );
       jsonAppendRaw(&s, " ", 1);
       jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
+    }else{
+      assert( x.aNode[i].eU==0 );
     }
     jsonAppendRaw(&s, "\n", 1);
   }
@@ -189973,7 +194635,7 @@ static void jsonTest1Func(
   int argc,
   sqlite3_value **argv
 ){
-  UNUSED_PARAM(argc);
+  UNUSED_PARAMETER(argc);
   sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
 }
 #endif /* SQLITE_DEBUG */
@@ -189994,7 +194656,7 @@ static void jsonQuoteFunc(
   sqlite3_value **argv
 ){
   JsonString jx;
-  UNUSED_PARAM(argc);
+  UNUSED_PARAMETER(argc);
 
   jsonInit(&jx, ctx);
   jsonAppendValue(&jx, argv[0]);
@@ -190065,13 +194727,34 @@ static void jsonArrayLengthFunc(
   sqlite3_result_int64(ctx, n);
 }
 
+/*
+** Bit values for the flags passed into jsonExtractFunc() or
+** jsonSetFunc() via the user-data value.
+*/
+#define JSON_JSON      0x01        /* Result is always JSON */
+#define JSON_SQL       0x02        /* Result is always SQL */
+#define JSON_ABPATH    0x03        /* Allow abbreviated JSON path specs */
+#define JSON_ISSET     0x04        /* json_set(), not json_insert() */
+
 /*
 ** json_extract(JSON, PATH, ...)
+** "->"(JSON,PATH)
+** "->>"(JSON,PATH)
+**
+** Return the element described by PATH.  Return NULL if that PATH element
+** is not found.
+**
+** If JSON_JSON is set or if more that one PATH argument is supplied then
+** always return a JSON representation of the result.  If JSON_SQL is set,
+** then always return an SQL representation of the result.  If neither flag
+** is present and argc==2, then return JSON for objects and arrays and SQL
+** for all other values.
 **
-** Return the element described by PATH.  Return NULL if there is no
-** PATH element.  If there are multiple PATHs, then return a JSON array
-** with the result from each path.  Throw an error if the JSON or any PATH
-** is malformed.
+** When multiple PATH arguments are supplied, the result is a JSON array
+** containing the result of each PATH.
+**
+** Abbreviated JSON path expressions are allows if JSON_ABPATH, for
+** compatibility with PG.
 */
 static void jsonExtractFunc(
   sqlite3_context *ctx,
@@ -190081,35 +194764,77 @@ static void jsonExtractFunc(
   JsonParse *p;          /* The parse */
   JsonNode *pNode;
   const char *zPath;
+  int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx));
   JsonString jx;
-  int i;
 
   if( argc<2 ) return;
   p = jsonParseCached(ctx, argv, ctx);
   if( p==0 ) return;
-  jsonInit(&jx, ctx);
-  jsonAppendChar(&jx, '[');
-  for(i=1; i<argc; i++){
-    zPath = (const char*)sqlite3_value_text(argv[i]);
-    pNode = jsonLookup(p, zPath, 0, ctx);
-    if( p->nErr ) break;
-    if( argc>2 ){
+  if( argc==2 ){
+    /* With a single PATH argument */
+    zPath = (const char*)sqlite3_value_text(argv[1]);
+    if( zPath==0 ) return;
+    if( flags & JSON_ABPATH ){
+      if( zPath[0]!='$' ){
+        /* The -> and ->> operators accept abbreviated PATH arguments.  This
+        ** is mostly for compatibility with PostgreSQL, but also for
+        ** convenience.
+        **
+        **     NUMBER   ==>  $[NUMBER]     // PG compatible
+        **     LABEL    ==>  $.LABEL       // PG compatible
+        **     [NUMBER] ==>  $[NUMBER]     // Not PG.  Purely for convenience
+        */
+        jsonInit(&jx, ctx);
+        if( sqlite3Isdigit(zPath[0]) ){
+          jsonAppendRaw(&jx, "$[", 2);
+          jsonAppendRaw(&jx, zPath, (int)strlen(zPath));
+          jsonAppendRaw(&jx, "]", 2);
+        }else{
+          jsonAppendRaw(&jx, "$.", 1 + (zPath[0]!='['));
+          jsonAppendRaw(&jx, zPath, (int)strlen(zPath));
+          jsonAppendChar(&jx, 0);
+        }
+        pNode = jx.bErr ? 0 : jsonLookup(p, jx.zBuf, 0, ctx);
+        jsonReset(&jx);
+      }else{
+        pNode = jsonLookup(p, zPath, 0, ctx);
+      }
+      if( pNode ){
+        if( flags & JSON_JSON ){
+          jsonReturnJson(pNode, ctx, 0);
+        }else{
+          jsonReturn(pNode, ctx, 0);
+          sqlite3_result_subtype(ctx, 0);
+        }
+      }
+    }else{
+      pNode = jsonLookup(p, zPath, 0, ctx);
+      if( p->nErr==0 && pNode ) jsonReturn(pNode, ctx, 0);
+    }
+  }else{
+    /* Two or more PATH arguments results in a JSON array with each
+    ** element of the array being the value selected by one of the PATHs */
+    int i;
+    jsonInit(&jx, ctx);
+    jsonAppendChar(&jx, '[');
+    for(i=1; i<argc; i++){
+      zPath = (const char*)sqlite3_value_text(argv[i]);
+      pNode = jsonLookup(p, zPath, 0, ctx);
+      if( p->nErr ) break;
       jsonAppendSeparator(&jx);
       if( pNode ){
         jsonRenderNode(pNode, &jx, 0);
       }else{
         jsonAppendRaw(&jx, "null", 4);
       }
-    }else if( pNode ){
-      jsonReturn(pNode, ctx, 0);
     }
+    if( i==argc ){
+      jsonAppendChar(&jx, ']');
+      jsonResult(&jx);
+      sqlite3_result_subtype(ctx, JSON_SUBTYPE);
+    }
+    jsonReset(&jx);
   }
-  if( argc>2 && i==argc ){
-    jsonAppendChar(&jx, ']');
-    jsonResult(&jx);
-    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
-  }
-  jsonReset(&jx);
 }
 
 /* This is the RFC 7396 MergePatch algorithm.
@@ -190138,6 +194863,7 @@ static JsonNode *jsonMergePatch(
     const char *zKey;
     assert( pPatch[i].eType==JSON_STRING );
     assert( pPatch[i].jnFlags & JNODE_LABEL );
+    assert( pPatch[i].eU==1 );
     nKey = pPatch[i].n;
     zKey = pPatch[i].u.zJContent;
     assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
@@ -190154,6 +194880,12 @@ static JsonNode *jsonMergePatch(
           if( pNew==0 ) return 0;
           pTarget = &pParse->aNode[iTarget];
           if( pNew!=&pTarget[j+1] ){
+            assert( pTarget[j+1].eU==0
+                 || pTarget[j+1].eU==1
+                 || pTarget[j+1].eU==2 );
+            testcase( pTarget[j+1].eU==1 );
+            testcase( pTarget[j+1].eU==2 );
+            VVA( pTarget[j+1].eU = 5 );
             pTarget[j+1].u.pPatch = pNew;
             pTarget[j+1].jnFlags |= JNODE_PATCH;
           }
@@ -190169,9 +194901,14 @@ static JsonNode *jsonMergePatch(
       if( pParse->oom ) return 0;
       jsonRemoveAllNulls(pPatch);
       pTarget = &pParse->aNode[iTarget];
+      assert( pParse->aNode[iRoot].eU==0 || pParse->aNode[iRoot].eU==2 );
+      testcase( pParse->aNode[iRoot].eU==2 );
       pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
+      VVA( pParse->aNode[iRoot].eU = 2 );
       pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
       iRoot = iStart;
+      assert( pParse->aNode[iPatch].eU==0 );
+      VVA( pParse->aNode[iPatch].eU = 5 );
       pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
       pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
     }
@@ -190193,7 +194930,7 @@ static void jsonPatchFunc(
   JsonParse y;     /* The patch */
   JsonNode *pResult;   /* The result of the merge */
 
-  UNUSED_PARAM(argc);
+  UNUSED_PARAMETER(argc);
   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
   if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
     jsonParseReset(&x);
@@ -190313,11 +195050,15 @@ static void jsonReplaceFunc(
     pNode = jsonLookup(&x, zPath, 0, ctx);
     if( x.nErr ) goto replace_err;
     if( pNode ){
+      assert( pNode->eU==0 || pNode->eU==1 || pNode->eU==4 );
+      testcase( pNode->eU!=0 && pNode->eU!=1 );
       pNode->jnFlags |= (u8)JNODE_REPLACE;
+      VVA( pNode->eU =  4 );
       pNode->u.iReplace = i + 1;
     }
   }
   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
+    assert( x.aNode[0].eU==4 );
     sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
   }else{
     jsonReturnJson(x.aNode, ctx, argv);
@@ -190326,6 +195067,7 @@ replace_err:
   jsonParseReset(&x);
 }
 
+
 /*
 ** json_set(JSON, PATH, VALUE, ...)
 **
@@ -190348,7 +195090,7 @@ static void jsonSetFunc(
   const char *zPath;
   u32 i;
   int bApnd;
-  int bIsSet = *(int*)sqlite3_user_data(ctx);
+  int bIsSet = sqlite3_user_data(ctx)!=0;
 
   if( argc<1 ) return;
   if( (argc&1)==0 ) {
@@ -190367,11 +195109,15 @@ static void jsonSetFunc(
     }else if( x.nErr ){
       goto jsonSetDone;
     }else if( pNode && (bApnd || bIsSet) ){
+      testcase( pNode->eU!=0 && pNode->eU!=1 );
+      assert( pNode->eU!=3 && pNode->eU!=5 );
+      VVA( pNode->eU = 4 );
       pNode->jnFlags |= (u8)JNODE_REPLACE;
       pNode->u.iReplace = i + 1;
     }
   }
   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
+    assert( x.aNode[0].eU==4 );
     sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
   }else{
     jsonReturnJson(x.aNode, ctx, argv);
@@ -190384,8 +195130,8 @@ jsonSetDone:
 ** json_type(JSON)
 ** json_type(JSON, PATH)
 **
-** Return the top-level "type" of a JSON string.  Throw an error if
-** either the JSON or PATH inputs are not well-formed.
+** Return the top-level "type" of a JSON string.  json_type() raises an
+** error if either the JSON or PATH inputs are not well-formed.
 */
 static void jsonTypeFunc(
   sqlite3_context *ctx,
@@ -190421,7 +195167,7 @@ static void jsonValidFunc(
   sqlite3_value **argv
 ){
   JsonParse *p;          /* The parse */
-  UNUSED_PARAM(argc);
+  UNUSED_PARAMETER(argc);
   p = jsonParseCached(ctx, argv, 0);
   sqlite3_result_int(ctx, p!=0);
 }
@@ -190441,7 +195187,7 @@ static void jsonArrayStep(
   sqlite3_value **argv
 ){
   JsonString *pStr;
-  UNUSED_PARAM(argc);
+  UNUSED_PARAMETER(argc);
   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
   if( pStr ){
     if( pStr->zBuf==0 ){
@@ -190449,8 +195195,8 @@ static void jsonArrayStep(
       jsonAppendChar(pStr, '[');
     }else if( pStr->nUsed>1 ){
       jsonAppendChar(pStr, ',');
-      pStr->pCtx = ctx;
     }
+    pStr->pCtx = ctx;
     jsonAppendValue(pStr, argv[0]);
   }
 }
@@ -190501,8 +195247,8 @@ static void jsonGroupInverse(
   char *z;
   char c;
   JsonString *pStr;
-  UNUSED_PARAM(argc);
-  UNUSED_PARAM(argv);
+  UNUSED_PARAMETER(argc);
+  UNUSED_PARAMETER(argv);
   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
 #ifdef NEVER
   /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
@@ -190510,11 +195256,7 @@ static void jsonGroupInverse(
   if( NEVER(!pStr) ) return;
 #endif
   z = pStr->zBuf;
-  for(i=1; (c = z[i])!=',' || inStr || nNest; i++){
-    if( i>=pStr->nUsed ){
-      pStr->nUsed = 1;
-      return;
-    }
+  for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){
     if( c=='"' ){
       inStr = !inStr;
     }else if( c=='\\' ){
@@ -190524,8 +195266,13 @@ static void jsonGroupInverse(
       if( c=='}' || c==']' ) nNest--;
     }
   }
-  pStr->nUsed -= i;
-  memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
+  if( i<pStr->nUsed ){
+    pStr->nUsed -= i;
+    memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
+    z[pStr->nUsed] = 0;
+  }else{
+    pStr->nUsed = 1;
+  }
 }
 #else
 # define jsonGroupInverse 0
@@ -190545,7 +195292,7 @@ static void jsonObjectStep(
   JsonString *pStr;
   const char *z;
   u32 n;
-  UNUSED_PARAM(argc);
+  UNUSED_PARAMETER(argc);
   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
   if( pStr ){
     if( pStr->zBuf==0 ){
@@ -190553,8 +195300,8 @@ static void jsonObjectStep(
       jsonAppendChar(pStr, '{');
     }else if( pStr->nUsed>1 ){
       jsonAppendChar(pStr, ',');
-      pStr->pCtx = ctx;
     }
+    pStr->pCtx = ctx;
     z = (const char*)sqlite3_value_text(argv[0]);
     n = (u32)sqlite3_value_bytes(argv[0]);
     jsonAppendString(pStr, z, n);
@@ -190636,10 +195383,10 @@ static int jsonEachConnect(
 #define JEACH_JSON    8
 #define JEACH_ROOT    9
 
-  UNUSED_PARAM(pzErr);
-  UNUSED_PARAM(argv);
-  UNUSED_PARAM(argc);
-  UNUSED_PARAM(pAux);
+  UNUSED_PARAMETER(pzErr);
+  UNUSED_PARAMETER(argv);
+  UNUSED_PARAMETER(argc);
+  UNUSED_PARAMETER(pAux);
   rc = sqlite3_declare_vtab(db,
      "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
                     "json HIDDEN,root HIDDEN)");
@@ -190662,7 +195409,7 @@ static int jsonEachDisconnect(sqlite3_vtab *pVtab){
 static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   JsonEachCursor *pCur;
 
-  UNUSED_PARAM(p);
+  UNUSED_PARAMETER(p);
   pCur = sqlite3_malloc( sizeof(*pCur) );
   if( pCur==0 ) return SQLITE_NOMEM;
   memset(pCur, 0, sizeof(*pCur));
@@ -190721,6 +195468,9 @@ static int jsonEachNext(sqlite3_vtab_cursor *cur){
       JsonNode *pUp = &p->sParse.aNode[iUp];
       p->eType = pUp->eType;
       if( pUp->eType==JSON_ARRAY ){
+        assert( pUp->eU==0 || pUp->eU==3 );
+        testcase( pUp->eU==3 );
+        VVA( pUp->eU = 3 );
         if( iUp==p->i-1 ){
           pUp->u.iKey = 0;
         }else{
@@ -190749,6 +195499,33 @@ static int jsonEachNext(sqlite3_vtab_cursor *cur){
   return SQLITE_OK;
 }
 
+/* Append an object label to the JSON Path being constructed
+** in pStr.
+*/
+static void jsonAppendObjectPathElement(
+  JsonString *pStr,
+  JsonNode *pNode
+){
+  int jj, nn;
+  const char *z;
+  assert( pNode->eType==JSON_STRING );
+  assert( pNode->jnFlags & JNODE_LABEL );
+  assert( pNode->eU==1 );
+  z = pNode->u.zJContent;
+  nn = pNode->n;
+  assert( nn>=2 );
+  assert( z[0]=='"' );
+  assert( z[nn-1]=='"' );
+  if( nn>2 && sqlite3Isalpha(z[1]) ){
+    for(jj=2; jj<nn-1 && sqlite3Isalnum(z[jj]); jj++){}
+    if( jj==nn-1 ){
+      z++;
+      nn -= 2;
+    }
+  }
+  jsonPrintf(nn+2, pStr, ".%.*s", nn, z);
+}
+
 /* Append the name of the path for element i to pStr
 */
 static void jsonEachComputePath(
@@ -190767,13 +195544,13 @@ static void jsonEachComputePath(
   pNode = &p->sParse.aNode[i];
   pUp = &p->sParse.aNode[iUp];
   if( pUp->eType==JSON_ARRAY ){
+    assert( pUp->eU==3 || (pUp->eU==0 && pUp->u.iKey==0) );
+    testcase( pUp->eU==0 );
     jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
   }else{
     assert( pUp->eType==JSON_OBJECT );
     if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
-    assert( pNode->eType==JSON_STRING );
-    assert( pNode->jnFlags & JNODE_LABEL );
-    jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
+    jsonAppendObjectPathElement(pStr, pNode);
   }
 }
 
@@ -190794,6 +195571,7 @@ static int jsonEachColumn(
         u32 iKey;
         if( p->bRecursive ){
           if( p->iRowid==0 ) break;
+          assert( p->sParse.aNode[p->sParse.aUp[p->i]].eU==3 );
           iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
         }else{
           iKey = p->iRowid;
@@ -190843,7 +195621,7 @@ static int jsonEachColumn(
         if( p->eType==JSON_ARRAY ){
           jsonPrintf(30, &x, "[%d]", p->iRowid);
         }else if( p->eType==JSON_OBJECT ){
-          jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
+          jsonAppendObjectPathElement(&x, pThis);
         }
       }
       jsonResult(&x);
@@ -190901,7 +195679,7 @@ static int jsonEachBestIndex(
   /* This implementation assumes that JSON and ROOT are the last two
   ** columns in the table */
   assert( JEACH_ROOT == JEACH_JSON+1 );
-  UNUSED_PARAM(tab);
+  UNUSED_PARAMETER(tab);
   aIdx[0] = aIdx[1] = -1;
   pConstraint = pIdxInfo->aConstraint;
   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
@@ -190910,6 +195688,7 @@ static int jsonEachBestIndex(
     if( pConstraint->iColumn < JEACH_JSON ) continue;
     iCol = pConstraint->iColumn - JEACH_JSON;
     assert( iCol==0 || iCol==1 );
+    testcase( iCol==0 );
     iMask = 1 << iCol;
     if( pConstraint->usable==0 ){
       unusableMask |= iMask;
@@ -190956,8 +195735,8 @@ static int jsonEachFilter(
   const char *zRoot = 0;
   sqlite3_int64 n;
 
-  UNUSED_PARAM(idxStr);
-  UNUSED_PARAM(argc);
+  UNUSED_PARAMETER(idxStr);
+  UNUSED_PARAMETER(argc);
   jsonEachCursorReset(p);
   if( idxNum==0 ) return SQLITE_OK;
   z = (const char*)sqlite3_value_text(argv[0]);
@@ -191007,6 +195786,8 @@ static int jsonEachFilter(
     p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
     p->eType = pNode->eType;
     if( p->eType>=JSON_ARRAY ){
+      assert( pNode->eU==0 );
+      VVA( pNode->eU = 3 );
       pNode->u.iKey = 0;
       p->iEnd = p->i + pNode->n + 1;
       if( p->bRecursive ){
@@ -191080,108 +195861,68 @@ static sqlite3_module jsonTreeModule = {
   0                          /* xShadowName */
 };
 #endif /* SQLITE_OMIT_VIRTUALTABLE */
-
-/****************************************************************************
-** The following routines are the only publically visible identifiers in this
-** file.  Call the following routines in order to register the various SQL
-** functions and the virtual table implemented by this file.
-****************************************************************************/
-
-SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
-  int rc = SQLITE_OK;
-  unsigned int i;
-  static const struct {
-     const char *zName;
-     int nArg;
-     int flag;
-     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
-  } aFunc[] = {
-    { "json",                 1, 0,   jsonRemoveFunc        },
-    { "json_array",          -1, 0,   jsonArrayFunc         },
-    { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
-    { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
-    { "json_extract",        -1, 0,   jsonExtractFunc       },
-    { "json_insert",         -1, 0,   jsonSetFunc           },
-    { "json_object",         -1, 0,   jsonObjectFunc        },
-    { "json_patch",           2, 0,   jsonPatchFunc         },
-    { "json_quote",           1, 0,   jsonQuoteFunc         },
-    { "json_remove",         -1, 0,   jsonRemoveFunc        },
-    { "json_replace",        -1, 0,   jsonReplaceFunc       },
-    { "json_set",            -1, 1,   jsonSetFunc           },
-    { "json_type",            1, 0,   jsonTypeFunc          },
-    { "json_type",            2, 0,   jsonTypeFunc          },
-    { "json_valid",           1, 0,   jsonValidFunc         },
-
+#endif /* !defined(SQLITE_OMIT_JSON) */
+
+/*
+** Register JSON functions.
+*/
+SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){
+#ifndef SQLITE_OMIT_JSON
+  static FuncDef aJsonFunc[] = {
+    JFUNCTION(json,               1, 0,  jsonRemoveFunc),
+    JFUNCTION(json_array,        -1, 0,  jsonArrayFunc),
+    JFUNCTION(json_array_length,  1, 0,  jsonArrayLengthFunc),
+    JFUNCTION(json_array_length,  2, 0,  jsonArrayLengthFunc),
+    JFUNCTION(json_extract,      -1, 0,  jsonExtractFunc),
+    JFUNCTION(->,                 2, JSON_JSON, jsonExtractFunc),
+    JFUNCTION(->>,                2, JSON_SQL, jsonExtractFunc),
+    JFUNCTION(json_insert,       -1, 0,  jsonSetFunc),
+    JFUNCTION(json_object,       -1, 0,  jsonObjectFunc),
+    JFUNCTION(json_patch,         2, 0,  jsonPatchFunc),
+    JFUNCTION(json_quote,         1, 0,  jsonQuoteFunc),
+    JFUNCTION(json_remove,       -1, 0,  jsonRemoveFunc),
+    JFUNCTION(json_replace,      -1, 0,  jsonReplaceFunc),
+    JFUNCTION(json_set,          -1, JSON_ISSET,  jsonSetFunc),
+    JFUNCTION(json_type,          1, 0,  jsonTypeFunc),
+    JFUNCTION(json_type,          2, 0,  jsonTypeFunc),
+    JFUNCTION(json_valid,         1, 0,  jsonValidFunc),
 #if SQLITE_DEBUG
-    /* DEBUG and TESTING functions */
-    { "json_parse",           1, 0,   jsonParseFunc         },
-    { "json_test1",           1, 0,   jsonTest1Func         },
-#endif
-  };
-  static const struct {
-     const char *zName;
-     int nArg;
-     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
-     void (*xFinal)(sqlite3_context*);
-     void (*xValue)(sqlite3_context*);
-  } aAgg[] = {
-    { "json_group_array",     1,
-      jsonArrayStep,   jsonArrayFinal,  jsonArrayValue  },
-    { "json_group_object",    2,
-      jsonObjectStep,  jsonObjectFinal, jsonObjectValue },
+    JFUNCTION(json_parse,         1, 0,  jsonParseFunc),
+    JFUNCTION(json_test1,         1, 0,  jsonTest1Func),
+#endif
+    WAGGREGATE(json_group_array,  1, 0, 0,
+       jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse,
+       SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS),
+    WAGGREGATE(json_group_object, 2, 0, 0,
+       jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse,
+       SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
   };
-#ifndef SQLITE_OMIT_VIRTUALTABLE
+  sqlite3InsertBuiltinFuncs(aJsonFunc, ArraySize(aJsonFunc));
+#endif
+}
+
+#if  !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
+/*
+** Register the JSON table-valued functions
+*/
+SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3 *db){
+  int rc = SQLITE_OK;
   static const struct {
-     const char *zName;
-     sqlite3_module *pModule;
+    const char *zName;
+    sqlite3_module *pModule;
   } aMod[] = {
     { "json_each",            &jsonEachModule               },
     { "json_tree",            &jsonTreeModule               },
   };
-#endif
-  static const int enc =
-       SQLITE_UTF8 |
-       SQLITE_DETERMINISTIC |
-       SQLITE_INNOCUOUS;
-  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
-    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,
-                                 (void*)&aFunc[i].flag,
-                                 aFunc[i].xFunc, 0, 0);
-  }
-#ifndef SQLITE_OMIT_WINDOWFUNC
-  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
-    rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
-                                 SQLITE_SUBTYPE | enc, 0,
-                                 aAgg[i].xStep, aAgg[i].xFinal,
-                                 aAgg[i].xValue, jsonGroupInverse, 0);
-  }
-#endif
-#ifndef SQLITE_OMIT_VIRTUALTABLE
+  unsigned int i;
   for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
     rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
   }
-#endif
   return rc;
 }
+#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */
 
-
-#ifndef SQLITE_CORE
-#ifdef _WIN32
-__declspec(dllexport)
-#endif
-SQLITE_API int sqlite3_json_init(
-  sqlite3 *db,
-  char **pzErrMsg,
-  const sqlite3_api_routines *pApi
-){
-  SQLITE_EXTENSION_INIT2(pApi);
-  (void)pzErrMsg;  /* Unused parameter */
-  return sqlite3Json1Init(db);
-}
-#endif
-#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
-
-/************** End of json1.c ***********************************************/
+/************** End of json.c ************************************************/
 /************** Begin file rtree.c *******************************************/
 /*
 ** 2001 September 15
@@ -191249,7 +195990,11 @@ SQLITE_API int sqlite3_json_init(
 #endif
 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */
 
-#ifndef SQLITE_AMALGAMATION
+/*
+** If building separately, we will need some setup that is normally
+** found in sqliteInt.h
+*/
+#if !defined(SQLITE_AMALGAMATION)
 #include "sqlite3rtree.h"
 typedef sqlite3_int64 i64;
 typedef sqlite3_uint64 u64;
@@ -191262,7 +196007,20 @@ typedef unsigned int u32;
 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
 # undef NDEBUG
 #endif
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
+# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
 #endif
+#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
+# define ALWAYS(X)      (1)
+# define NEVER(X)       (0)
+#elif !defined(NDEBUG)
+# define ALWAYS(X)      ((X)?1:(assert(0),0))
+# define NEVER(X)       ((X)?(assert(0),1):0)
+#else
+# define ALWAYS(X)      (X)
+# define NEVER(X)       (X)
+#endif
+#endif /* !defined(SQLITE_AMALGAMATION) */
 
 /* #include <string.h> */
 /* #include <stdio.h> */
@@ -191320,7 +196078,9 @@ struct Rtree {
   u8 nBytesPerCell;           /* Bytes consumed per cell */
   u8 inWrTrans;               /* True if inside write transaction */
   u8 nAux;                    /* # of auxiliary columns in %_rowid */
+#ifdef SQLITE_ENABLE_GEOPOLY
   u8 nAuxNotNull;             /* Number of initial not-null aux columns */
+#endif
 #ifdef SQLITE_DEBUG
   u8 bCorrupt;                /* Shadow table corruption detected */
 #endif
@@ -191602,7 +196362,12 @@ struct RtreeMatchArg {
 ** it is not, make it a no-op.
 */
 #ifndef SQLITE_AMALGAMATION
-# define testcase(X)
+# if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
+    unsigned int sqlite3RtreeTestcase = 0;
+#   define testcase(X)  if( X ){ sqlite3RtreeTestcase += __LINE__; }
+# else
+#   define testcase(X)
+# endif
 #endif
 
 /*
@@ -191851,18 +196616,6 @@ static void nodeBlobReset(Rtree *pRtree){
   }
 }
 
-/*
-** Check to see if pNode is the same as pParent or any of the parents
-** of pParent.
-*/
-static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){
-  do{
-    if( pNode==pParent ) return 1;
-    pParent = pParent->pParent;
-  }while( pParent );
-  return 0;
-}
-
 /*
 ** Obtain a reference to an r-tree node.
 */
@@ -191879,14 +196632,7 @@ static int nodeAcquire(
   ** increase its reference count and return it.
   */
   if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
-    if( pParent && !pNode->pParent ){
-      if( nodeInParentChain(pNode, pParent) ){
-        RTREE_IS_CORRUPT(pRtree);
-        return SQLITE_CORRUPT_VTAB;
-      }
-      pParent->nRef++;
-      pNode->pParent = pParent;
-    }else if( pParent && pNode->pParent && pParent!=pNode->pParent ){
+    if( pParent && pParent!=pNode->pParent ){
       RTREE_IS_CORRUPT(pRtree);
       return SQLITE_CORRUPT_VTAB;
     }
@@ -191944,7 +196690,7 @@ static int nodeAcquire(
   ** are the leaves, and so on. If the depth as specified on the root node
   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   */
-  if( pNode && rc==SQLITE_OK && iNode==1 ){
+  if( rc==SQLITE_OK && pNode && iNode==1 ){
     pRtree->iDepth = readInt16(pNode->zData);
     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
       rc = SQLITE_CORRUPT_VTAB;
@@ -192467,20 +197213,29 @@ static void rtreeNonleafConstraint(
   switch( p->op ){
     case RTREE_TRUE:  return;   /* Always satisfied */
     case RTREE_FALSE: break;    /* Never satisfied */
+    case RTREE_EQ:
+      RTREE_DECODE_COORD(eInt, pCellData, val);
+      /* val now holds the lower bound of the coordinate pair */
+      if( p->u.rValue>=val ){
+        pCellData += 4;
+        RTREE_DECODE_COORD(eInt, pCellData, val);
+        /* val now holds the upper bound of the coordinate pair */
+        if( p->u.rValue<=val ) return;
+      }
+      break;
     case RTREE_LE:
     case RTREE_LT:
-    case RTREE_EQ:
       RTREE_DECODE_COORD(eInt, pCellData, val);
       /* val now holds the lower bound of the coordinate pair */
       if( p->u.rValue>=val ) return;
-      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
-      /* Fall through for the RTREE_EQ case */
+      break;
 
-    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
+    default:
       pCellData += 4;
       RTREE_DECODE_COORD(eInt, pCellData, val);
       /* val now holds the upper bound of the coordinate pair */
       if( p->u.rValue<=val ) return;
+      break;
   }
   *peWithin = NOT_WITHIN;
 }
@@ -192550,11 +197305,12 @@ static int nodeRowidIndex(
 */
 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
   RtreeNode *pParent = pNode->pParent;
-  if( pParent ){
+  if( ALWAYS(pParent) ){
     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
+  }else{
+    *piIndex = -1;
+    return SQLITE_OK;
   }
-  *piIndex = -1;
-  return SQLITE_OK;
 }
 
 /*
@@ -192677,7 +197433,8 @@ static RtreeSearchPoint *rtreeSearchPointNew(
       pNew = rtreeEnqueue(pCur, rScore, iLevel);
       if( pNew==0 ) return 0;
       ii = (int)(pNew - pCur->aPoint) + 1;
-      if( ii<RTREE_CACHE_SZ ){
+      assert( ii==1 );
+      if( ALWAYS(ii<RTREE_CACHE_SZ) ){
         assert( pCur->aNode[ii]==0 );
         pCur->aNode[ii] = pCur->aNode[0];
       }else{
@@ -192738,7 +197495,7 @@ static void rtreeSearchPointPop(RtreeCursor *p){
   if( p->bPoint ){
     p->anQueue[p->sPoint.iLevel]--;
     p->bPoint = 0;
-  }else if( p->nPoint ){
+  }else if( ALWAYS(p->nPoint) ){
     p->anQueue[p->aPoint[0].iLevel]--;
     n = --p->nPoint;
     p->aPoint[0] = p->aPoint[n];
@@ -192879,7 +197636,7 @@ static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
   int rc = SQLITE_OK;
   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
-  if( rc==SQLITE_OK && p ){
+  if( rc==SQLITE_OK && ALWAYS(p) ){
     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
   }
   return rc;
@@ -192897,7 +197654,7 @@ static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
 
   if( rc ) return rc;
-  if( p==0 ) return SQLITE_OK;
+  if( NEVER(p==0) ) return SQLITE_OK;
   if( i==0 ){
     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
   }else if( i<=pRtree->nDim2 ){
@@ -193096,8 +197853,11 @@ static int rtreeFilter(
     }
     if( rc==SQLITE_OK ){
       RtreeSearchPoint *pNew;
+      assert( pCsr->bPoint==0 );  /* Due to the resetCursor() call above */
       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
-      if( pNew==0 ) return SQLITE_NOMEM;
+      if( NEVER(pNew==0) ){       /* Because pCsr->bPoint was FALSE */
+        return SQLITE_NOMEM;
+      }
       pNew->id = 1;
       pNew->iCell = 0;
       pNew->eWithin = PARTLY_WITHIN;
@@ -193174,7 +197934,7 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
 
     if( bMatch==0 && p->usable
-     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
+     && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
     ){
       /* We have an equality constraint on the rowid. Use strategy 1. */
       int jj;
@@ -193380,7 +198140,7 @@ static int ChooseLeaf(
 
     int nCell = NCELL(pNode);
     RtreeCell cell;
-    RtreeNode *pChild;
+    RtreeNode *pChild = 0;
 
     RtreeCell *aCell = 0;
 
@@ -193427,12 +198187,19 @@ static int AdjustTree(
 ){
   RtreeNode *p = pNode;
   int cnt = 0;
+  int rc;
   while( p->pParent ){
     RtreeNode *pParent = p->pParent;
     RtreeCell cell;
     int iCell;
 
-    if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell)  ){
+    cnt++;
+    if( NEVER(cnt>100) ){
+      RTREE_IS_CORRUPT(pRtree);
+      return SQLITE_CORRUPT_VTAB;
+    }
+    rc = nodeParentIndex(pRtree, p, &iCell);
+    if( NEVER(rc!=SQLITE_OK) ){
       RTREE_IS_CORRUPT(pRtree);
       return SQLITE_CORRUPT_VTAB;
     }
@@ -193721,12 +198488,17 @@ static int updateMapping(
   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   if( iHeight>0 ){
     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
+    RtreeNode *p;
+    for(p=pNode; p; p=p->pParent){
+      if( p==pChild ) return SQLITE_CORRUPT_VTAB;
+    }
     if( pChild ){
       nodeRelease(pRtree, pChild->pParent);
       nodeReference(pNode);
       pChild->pParent = pNode;
     }
   }
+  if( NEVER(pNode==0) ) return SQLITE_ERROR;
   return xSetMapping(pRtree, iRowid, pNode->iNode);
 }
 
@@ -193816,11 +198588,12 @@ static int SplitNode(
     RtreeNode *pParent = pLeft->pParent;
     int iCell;
     rc = nodeParentIndex(pRtree, pLeft, &iCell);
-    if( rc==SQLITE_OK ){
+    if( ALWAYS(rc==SQLITE_OK) ){
       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
       rc = AdjustTree(pRtree, pParent, &leftbbox);
+      assert( rc==SQLITE_OK );
     }
-    if( rc!=SQLITE_OK ){
+    if( NEVER(rc!=SQLITE_OK) ){
       goto splitnode_out;
     }
   }
@@ -193895,7 +198668,7 @@ static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
       */
       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
-      if( !pTest ){
+      if( pTest==0 ){
         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
       }
     }
@@ -193926,6 +198699,7 @@ static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
     pParent = pNode->pParent;
     pNode->pParent = 0;
     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
+    testcase( rc!=SQLITE_OK );
   }
   rc2 = nodeRelease(pRtree, pParent);
   if( rc==SQLITE_OK ){
@@ -194148,7 +198922,7 @@ static int rtreeInsertCell(
     }
   }else{
     rc = AdjustTree(pRtree, pNode, pCell);
-    if( rc==SQLITE_OK ){
+    if( ALWAYS(rc==SQLITE_OK) ){
       if( iHeight==0 ){
         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
       }else{
@@ -194254,7 +199028,7 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
     int rc2;
     RtreeNode *pChild = 0;
     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
-    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
+    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);  /* tag-20210916a */
     if( rc==SQLITE_OK ){
       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
     }
@@ -194589,7 +199363,7 @@ static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
   char *zSql;
   sqlite3_stmt *p;
   int rc;
-  i64 nRow = 0;
+  i64 nRow = RTREE_MIN_ROWEST;
 
   rc = sqlite3_table_column_metadata(
       db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
@@ -194606,20 +199380,10 @@ static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
     if( rc==SQLITE_OK ){
       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
       rc = sqlite3_finalize(p);
-    }else if( rc!=SQLITE_NOMEM ){
-      rc = SQLITE_OK;
-    }
-
-    if( rc==SQLITE_OK ){
-      if( nRow==0 ){
-        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
-      }else{
-        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
-      }
     }
     sqlite3_free(zSql);
   }
-
+  pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
   return rc;
 }
 
@@ -194769,9 +199533,12 @@ static int rtreeSqlInit(
       sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
       for(ii=0; ii<pRtree->nAux; ii++){
         if( ii ) sqlite3_str_append(p, ",", 1);
+#ifdef SQLITE_ENABLE_GEOPOLY
         if( ii<pRtree->nAuxNotNull ){
           sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
-        }else{
+        }else
+#endif
+        {
           sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
         }
       }
@@ -195036,6 +199803,7 @@ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   tree.nDim2 = tree.nDim*2;
   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
+  if( node.zData==0 ) return;
   nData = sqlite3_value_bytes(apArg[1]);
   if( nData<4 ) return;
   if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
@@ -195075,11 +199843,16 @@ static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   UNUSED_PARAMETER(nArg);
   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
    || sqlite3_value_bytes(apArg[0])<2
+
   ){
     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   }else{
     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
-    sqlite3_result_int(ctx, readInt16(zBlob));
+    if( zBlob ){
+      sqlite3_result_int(ctx, readInt16(zBlob));
+    }else{
+      sqlite3_result_error_nomem(ctx);
+    }
   }
 }
 
@@ -195445,8 +200218,10 @@ static int rtreeCheckTable(
     if( pStmt ){
       nAux = sqlite3_column_count(pStmt) - 2;
       sqlite3_finalize(pStmt);
+    }else
+    if( check.rc!=SQLITE_NOMEM ){
+      check.rc = SQLITE_OK;
     }
-    check.rc = SQLITE_OK;
   }
 
   /* Find number of dimensions in the rtree table. */
@@ -195581,11 +200356,7 @@ static void rtreecheck(
 # define GEODEBUG(X)
 #endif
 
-#ifndef JSON_NULL   /* The following stuff repeats things found in json1 */
-/*
-** Versions of isspace(), isalnum() and isdigit() to which it is safe
-** to pass signed char values.
-*/
+/* Character class routines */
 #ifdef sqlite3Isdigit
    /* Use the SQLite core versions if this routine is part of the
    ** SQLite amalgamation */
@@ -195600,6 +200371,7 @@ static void rtreecheck(
 #  define safe_isxdigit(x) isxdigit((unsigned char)(x))
 #endif
 
+#ifndef JSON_NULL   /* The following stuff repeats things found in json1 */
 /*
 ** Growing our own isspace() routine this way is twice as fast as
 ** the library isspace() function.
@@ -195622,7 +200394,7 @@ static const char geopolyIsSpace[] = {
   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
 };
-#define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])
+#define fast_isspace(x) (geopolyIsSpace[(unsigned char)x])
 #endif /* JSON NULL - back to original code */
 
 /* Compiler and version */
@@ -195711,7 +200483,7 @@ static void geopolySwab32(unsigned char *a){
 
 /* Skip whitespace.  Return the next non-whitespace character. */
 static char geopolySkipSpace(GeoParse *p){
-  while( safe_isspace(p->z[0]) ) p->z++;
+  while( fast_isspace(p->z[0]) ) p->z++;
   return p->z[0];
 }
 
@@ -195860,11 +200632,16 @@ static GeoPoly *geopolyFuncParam(
 ){
   GeoPoly *p = 0;
   int nByte;
+  testcase( pCtx==0 );
   if( sqlite3_value_type(pVal)==SQLITE_BLOB
    && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))
   ){
     const unsigned char *a = sqlite3_value_blob(pVal);
     int nVertex;
+    if( a==0 ){
+      if( pCtx ) sqlite3_result_error_nomem(pCtx);
+      return 0;
+    }
     nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
     if( (a[0]==0 || a[0]==1)
      && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
@@ -196238,7 +201015,7 @@ static GeoPoly *geopolyBBox(
       aCoord[2].f = mnY;
       aCoord[3].f = mxY;
     }
-  }else{
+  }else if( aCoord ){
     memset(aCoord, 0, sizeof(RtreeCoord)*4);
   }
   return pOut;
@@ -196689,11 +201466,11 @@ static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
     }else{
       /* Remove a segment */
       if( pActive==pThisEvent->pSeg ){
-        pActive = pActive->pNext;
+        pActive = ALWAYS(pActive) ? pActive->pNext : 0;
       }else{
         for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
           if( pSeg->pNext==pThisEvent->pSeg ){
-            pSeg->pNext = pSeg->pNext->pNext;
+            pSeg->pNext = ALWAYS(pSeg->pNext) ? pSeg->pNext->pNext : 0;
             break;
           }
         }
@@ -196937,6 +201714,7 @@ static int geopolyFilter(
       RtreeCoord bbox[4];
       RtreeConstraint *p;
       assert( argc==1 );
+      assert( argv[0]!=0 );
       geopolyBBox(0, argv[0], bbox, &rc);
       if( rc ){
         goto geopoly_filter_end;
@@ -197164,6 +201942,7 @@ static int geopolyUpdate(
         || !sqlite3_value_nochange(aData[2])  /* UPDATE _shape */
         || oldRowid!=newRowid)                /* Rowid change */
   ){
+    assert( aData[2]!=0 );
     geopolyBBox(0, aData[2], cell.aCoord, &rc);
     if( rc ){
       if( rc==SQLITE_ERROR ){
@@ -197517,7 +202296,10 @@ SQLITE_API int sqlite3_rtree_query_callback(
 
   /* Allocate and populate the context object. */
   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
-  if( !pGeomCtx ) return SQLITE_NOMEM;
+  if( !pGeomCtx ){
+    if( xDestructor ) xDestructor(pContext);
+    return SQLITE_NOMEM;
+  }
   pGeomCtx->xGeom = 0;
   pGeomCtx->xQueryFunc = xQueryFunc;
   pGeomCtx->xDestructor = xDestructor;
@@ -199088,6 +203870,13 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
 #endif
 
+/*
+** Name of the URI option that causes RBU to take an exclusive lock as
+** part of the incremental checkpoint operation.
+*/
+#define RBU_EXCLUSIVE_CHECKPOINT "rbu_exclusive_checkpoint"
+
+
 /*
 ** The rbu_state table is used to save the state of a partially applied
 ** update so that it can be resumed later. The table consists of integer
@@ -200172,7 +204961,9 @@ static void rbuTableType(
   assert( p->rc==SQLITE_OK );
   p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
     sqlite3_mprintf(
-          "SELECT (sql LIKE 'create virtual%%'), rootpage"
+          "SELECT "
+          " (sql COLLATE nocase BETWEEN 'CREATE VIRTUAL' AND 'CREATE VIRTUAM'),"
+          " rootpage"
           "  FROM sqlite_schema"
           " WHERE name=%Q", zTab
   ));
@@ -200532,7 +205323,7 @@ static char *rbuVacuumTableStart(
 ** the caller has to use an OFFSET clause to extract only the required
 ** rows from the sourct table, just as it does for an RBU update operation.
 */
-char *rbuVacuumIndexStart(
+static char *rbuVacuumIndexStart(
   sqlite3rbu *p,                  /* RBU handle */
   RbuObjIter *pIter               /* RBU iterator object */
 ){
@@ -200598,7 +205389,9 @@ char *rbuVacuumIndexStart(
       zSep = "";
       for(iCol=0; iCol<pIter->nCol; iCol++){
         const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);
-        if( zQuoted[0]=='N' ){
+        if( zQuoted==0 ){
+          p->rc = SQLITE_NOMEM;
+        }else if( zQuoted[0]=='N' ){
           bFailed = 1;
           break;
         }
@@ -201703,7 +206496,7 @@ static RbuState *rbuLoadState(sqlite3rbu *p){
         break;
 
       case RBU_STATE_OALSZ:
-        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
+        pRet->iOalSz = sqlite3_column_int64(pStmt, 1);
         break;
 
       case RBU_STATE_PHASEONESTEP:
@@ -201730,13 +206523,19 @@ static RbuState *rbuLoadState(sqlite3rbu *p){
 /*
 ** Open the database handle and attach the RBU database as "rbu". If an
 ** error occurs, leave an error code and message in the RBU handle.
+**
+** If argument dbMain is not NULL, then it is a database handle already
+** open on the target database. Use this handle instead of opening a new
+** one.
 */
-static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
+static void rbuOpenDatabase(sqlite3rbu *p, sqlite3 *dbMain, int *pbRetry){
   assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
   assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
+  assert( dbMain==0 || rbuIsVacuum(p)==0 );
 
   /* Open the RBU database */
   p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
+  p->dbMain = dbMain;
 
   if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
     sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
@@ -202102,15 +206901,31 @@ static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
 
 
 /*
-** Take an EXCLUSIVE lock on the database file.
+** Take an EXCLUSIVE lock on the database file. Return SQLITE_OK if
+** successful, or an SQLite error code otherwise.
 */
-static void rbuLockDatabase(sqlite3rbu *p){
-  sqlite3_file *pReal = p->pTargetFd->pReal;
-  assert( p->rc==SQLITE_OK );
-  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
-  if( p->rc==SQLITE_OK ){
-    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
+static int rbuLockDatabase(sqlite3 *db){
+  int rc = SQLITE_OK;
+  sqlite3_file *fd = 0;
+  sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
+
+  if( fd->pMethods ){
+    rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
+    if( rc==SQLITE_OK ){
+      rc = fd->pMethods->xLock(fd, SQLITE_LOCK_EXCLUSIVE);
+    }
   }
+  return rc;
+}
+
+/*
+** Return true if the database handle passed as the only argument
+** was opened with the rbu_exclusive_checkpoint=1 URI parameter
+** specified. Or false otherwise.
+*/
+static int rbuExclusiveCheckpoint(sqlite3 *db){
+  const char *zUri = sqlite3_db_filename(db, 0);
+  return sqlite3_uri_boolean(zUri, RBU_EXCLUSIVE_CHECKPOINT, 0);
 }
 
 #if defined(_WIN32_WCE)
@@ -202168,18 +206983,24 @@ static void rbuMoveOalFile(sqlite3rbu *p){
     ** In order to ensure that there are no database readers, an EXCLUSIVE
     ** lock is obtained here before the *-oal is moved to *-wal.
     */
-    rbuLockDatabase(p);
-    if( p->rc==SQLITE_OK ){
-      rbuFileSuffix3(zBase, zWal);
-      rbuFileSuffix3(zBase, zOal);
+    sqlite3 *dbMain = 0;
+    rbuFileSuffix3(zBase, zWal);
+    rbuFileSuffix3(zBase, zOal);
+
+    /* Re-open the databases. */
+    rbuObjIterFinalize(&p->objiter);
+    sqlite3_close(p->dbRbu);
+    sqlite3_close(p->dbMain);
+    p->dbMain = 0;
+    p->dbRbu = 0;
 
-      /* Re-open the databases. */
-      rbuObjIterFinalize(&p->objiter);
-      sqlite3_close(p->dbRbu);
-      sqlite3_close(p->dbMain);
-      p->dbMain = 0;
-      p->dbRbu = 0;
+    dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
+    if( dbMain ){
+      assert( p->rc==SQLITE_OK );
+      p->rc = rbuLockDatabase(dbMain);
+    }
 
+    if( p->rc==SQLITE_OK ){
 #if defined(_WIN32_WCE)
       {
         LPWSTR zWideOal;
@@ -202206,11 +207027,19 @@ static void rbuMoveOalFile(sqlite3rbu *p){
 #else
       p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
 #endif
+    }
 
-      if( p->rc==SQLITE_OK ){
-        rbuOpenDatabase(p, 0);
-        rbuSetupCheckpoint(p, 0);
-      }
+    if( p->rc!=SQLITE_OK
+     || rbuIsVacuum(p)
+     || rbuExclusiveCheckpoint(dbMain)==0
+    ){
+      sqlite3_close(dbMain);
+      dbMain = 0;
+    }
+
+    if( p->rc==SQLITE_OK ){
+      rbuOpenDatabase(p, dbMain, 0);
+      rbuSetupCheckpoint(p, 0);
     }
   }
 
@@ -202961,9 +207790,9 @@ static sqlite3rbu *openRbuHandle(
       ** If this is the case, it will have been checkpointed and deleted
       ** when the handle was closed and a second attempt to open the
       ** database may succeed.  */
-      rbuOpenDatabase(p, &bRetry);
+      rbuOpenDatabase(p, 0, &bRetry);
       if( bRetry ){
-        rbuOpenDatabase(p, 0);
+        rbuOpenDatabase(p, 0, 0);
       }
     }
 
@@ -203058,6 +207887,14 @@ static sqlite3rbu *openRbuHandle(
       }else if( p->eStage==RBU_STAGE_MOVE ){
         /* no-op */
       }else if( p->eStage==RBU_STAGE_CKPT ){
+        if( !rbuIsVacuum(p) && rbuExclusiveCheckpoint(p->dbMain) ){
+          /* If the rbu_exclusive_checkpoint=1 URI parameter was specified
+          ** and an incremental checkpoint is being resumed, attempt an
+          ** exclusive lock on the db file. If this fails, so be it.  */
+          p->eStage = RBU_STAGE_DONE;
+          rbuLockDatabase(p->dbMain);
+          p->eStage = RBU_STAGE_CKPT;
+        }
         rbuSetupCheckpoint(p, pState);
       }else if( p->eStage==RBU_STAGE_DONE ){
         p->rc = SQLITE_DONE;
@@ -203095,7 +207932,6 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open(
   const char *zState
 ){
   if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
-  /* TODO: Check that zTarget and zRbu are non-NULL */
   return openRbuHandle(zTarget, zRbu, zState);
 }
 
@@ -203970,28 +208806,14 @@ static int rbuVfsOpen(
       rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
       if( pDb ){
         if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
-          /* This call is to open a *-wal file. Intead, open the *-oal. This
-          ** code ensures that the string passed to xOpen() is terminated by a
-          ** pair of '\0' bytes in case the VFS attempts to extract a URI
-          ** parameter from it.  */
-          const char *zBase = zName;
-          size_t nCopy;
-          char *zCopy;
+          /* This call is to open a *-wal file. Intead, open the *-oal. */
+          size_t nOpen;
           if( rbuIsVacuum(pDb->pRbu) ){
-            zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
-            zBase = sqlite3_filename_wal(zBase);
-          }
-          nCopy = strlen(zBase);
-          zCopy = sqlite3_malloc64(nCopy+2);
-          if( zCopy ){
-            memcpy(zCopy, zBase, nCopy);
-            zCopy[nCopy-3] = 'o';
-            zCopy[nCopy] = '\0';
-            zCopy[nCopy+1] = '\0';
-            zOpen = (const char*)(pFd->zDel = zCopy);
-          }else{
-            rc = SQLITE_NOMEM;
+            zOpen = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
+            zOpen = sqlite3_filename_wal(zOpen);
           }
+          nOpen = strlen(zOpen);
+          ((char*)zOpen)[nOpen-3] = 'o';
           pFd->pRbu = pDb->pRbu;
         }
         pDb->pWalFd = pFd;
@@ -204312,6 +209134,15 @@ SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
     && !defined(SQLITE_OMIT_VIRTUALTABLE)
 
+/*
+** The pager and btree modules arrange objects in memory so that there are
+** always approximately 200 bytes of addressable memory following each page
+** buffer. This way small buffer overreads caused by corrupt database pages
+** do not cause undefined behaviour. This module pads each page buffer
+** by the following number of bytes for the same purpose.
+*/
+#define DBSTAT_PAGE_PADDING_BYTES 256
+
 /*
 ** Page paths:
 **
@@ -204379,9 +209210,8 @@ struct StatCell {
 /* Size information for a single btree page */
 struct StatPage {
   u32 iPgno;                      /* Page number */
-  DbPage *pPg;                    /* Page content */
+  u8 *aPg;                        /* Page buffer from sqlite3_malloc() */
   int iCell;                      /* Current cell */
-
   char *zPath;                    /* Path to this page */
 
   /* Variables populated by statDecodePage(): */
@@ -204593,18 +209423,25 @@ static void statClearCells(StatPage *p){
 }
 
 static void statClearPage(StatPage *p){
+  u8 *aPg = p->aPg;
   statClearCells(p);
-  sqlite3PagerUnref(p->pPg);
   sqlite3_free(p->zPath);
   memset(p, 0, sizeof(StatPage));
+  p->aPg = aPg;
 }
 
 static void statResetCsr(StatCursor *pCsr){
   int i;
-  sqlite3_reset(pCsr->pStmt);
+  /* In some circumstances, specifically if an OOM has occurred, the call
+  ** to sqlite3_reset() may cause the pager to be reset (emptied). It is
+  ** important that statClearPage() is called to free any page refs before
+  ** this happens. dbsqlfuzz 9ed3e4e3816219d3509d711636c38542bf3f40b1. */
   for(i=0; i<ArraySize(pCsr->aPage); i++){
     statClearPage(&pCsr->aPage[i]);
+    sqlite3_free(pCsr->aPage[i].aPg);
+    pCsr->aPage[i].aPg = 0;
   }
+  sqlite3_reset(pCsr->pStmt);
   pCsr->iPage = 0;
   sqlite3_free(pCsr->zPath);
   pCsr->zPath = 0;
@@ -204669,7 +209506,7 @@ static int statDecodePage(Btree *pBt, StatPage *p){
   int isLeaf;
   int szPage;
 
-  u8 *aData = sqlite3PagerGetData(p->pPg);
+  u8 *aData = p->aPg;
   u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
 
   p->flags = aHdr[0];
@@ -204740,7 +209577,7 @@ static int statDecodePage(Btree *pBt, StatPage *p){
         if( nPayload>(u32)nLocal ){
           int j;
           int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
-          if( iOff+nLocal>nUsable || nPayload>0x7fffffff ){
+          if( iOff+nLocal+4>nUsable || nPayload>0x7fffffff ){
             goto statPageIsCorrupt;
           }
           pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
@@ -204799,6 +209636,38 @@ static void statSizeAndOffset(StatCursor *pCsr){
   }
 }
 
+/*
+** Load a copy of the page data for page iPg into the buffer belonging
+** to page object pPg. Allocate the buffer if necessary. Return SQLITE_OK
+** if successful, or an SQLite error code otherwise.
+*/
+static int statGetPage(
+  Btree *pBt,                     /* Load page from this b-tree */
+  u32 iPg,                        /* Page number to load */
+  StatPage *pPg                   /* Load page into this object */
+){
+  int pgsz = sqlite3BtreeGetPageSize(pBt);
+  DbPage *pDbPage = 0;
+  int rc;
+
+  if( pPg->aPg==0 ){
+    pPg->aPg = (u8*)sqlite3_malloc(pgsz + DBSTAT_PAGE_PADDING_BYTES);
+    if( pPg->aPg==0 ){
+      return SQLITE_NOMEM_BKPT;
+    }
+    memset(&pPg->aPg[pgsz], 0, DBSTAT_PAGE_PADDING_BYTES);
+  }
+
+  rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPg, &pDbPage, 0);
+  if( rc==SQLITE_OK ){
+    const u8 *a = sqlite3PagerGetData(pDbPage);
+    memcpy(pPg->aPg, a, pgsz);
+    sqlite3PagerUnref(pDbPage);
+  }
+
+  return rc;
+}
+
 /*
 ** Move a DBSTAT cursor to the next entry.  Normally, the next
 ** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),
@@ -204817,7 +209686,7 @@ static int statNext(sqlite3_vtab_cursor *pCursor){
   pCsr->zPath = 0;
 
 statNextRestart:
-  if( pCsr->aPage[0].pPg==0 ){
+  if( pCsr->iPage<0 ){
     /* Start measuring space on the next btree */
     statResetCounts(pCsr);
     rc = sqlite3_step(pCsr->pStmt);
@@ -204829,7 +209698,7 @@ statNextRestart:
         pCsr->isEof = 1;
         return sqlite3_reset(pCsr->pStmt);
       }
-      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
+      rc = statGetPage(pBt, iRoot, &pCsr->aPage[0]);
       pCsr->aPage[0].iPgno = iRoot;
       pCsr->aPage[0].iCell = 0;
       if( !pCsr->isAgg ){
@@ -204880,9 +209749,8 @@ statNextRestart:
 
     if( !p->iRightChildPg || p->iCell>p->nCell ){
       statClearPage(p);
-      if( pCsr->iPage>0 ){
-        pCsr->iPage--;
-      }else if( pCsr->isAgg ){
+      pCsr->iPage--;
+      if( pCsr->isAgg && pCsr->iPage<0 ){
         /* label-statNext-done:  When computing aggregate space usage over
         ** an entire btree, this is the exit point from this function */
         return SQLITE_OK;
@@ -204901,7 +209769,7 @@ statNextRestart:
     }else{
       p[1].iPgno = p->aCell[p->iCell].iChildPg;
     }
-    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
+    rc = statGetPage(pBt, p[1].iPgno, &p[1]);
     pCsr->nPage++;
     p[1].iCell = 0;
     if( !pCsr->isAgg ){
@@ -205031,6 +209899,7 @@ static int statFilter(
   }
 
   if( rc==SQLITE_OK ){
+    pCsr->iPage = -1;
     rc = statNext(pCursor);
   }
   return rc;
@@ -205299,6 +210168,7 @@ static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   ){
     pIdxInfo->orderByConsumed = 1;
   }
+  sqlite3VtabWriteAll(pIdxInfo);
   return SQLITE_OK;
 }
 
@@ -205604,6 +210474,7 @@ struct SessionHook {
 struct sqlite3_session {
   sqlite3 *db;                    /* Database handle session is attached to */
   char *zDb;                      /* Name of database session is attached to */
+  int bEnableSize;                /* True if changeset_size() enabled */
   int bEnable;                    /* True if currently recording */
   int bIndirect;                  /* True if all changes are indirect */
   int bAutoAttach;                /* True to auto-attach tables */
@@ -205611,6 +210482,7 @@ struct sqlite3_session {
   void *pFilterCtx;               /* First argument to pass to xTableFilter */
   int (*xTableFilter)(void *pCtx, const char *zTab);
   i64 nMalloc;                    /* Number of bytes of data allocated */
+  i64 nMaxChangesetSize;
   sqlite3_value *pZeroBlob;       /* Value containing X'' */
   sqlite3_session *pNext;         /* Next session object on same db. */
   SessionTable *pTable;           /* List of attached tables */
@@ -205853,8 +210725,9 @@ struct SessionTable {
 ** this structure stored in a SessionTable.aChange[] hash table.
 */
 struct SessionChange {
-  int op;                         /* One of UPDATE, DELETE, INSERT */
-  int bIndirect;                  /* True if this change is "indirect" */
+  u8 op;                          /* One of UPDATE, DELETE, INSERT */
+  u8 bIndirect;                   /* True if this change is "indirect" */
+  int nMaxSize;                   /* Max size of eventual changeset record */
   int nRecord;                    /* Number of bytes in buffer aRecord[] */
   u8 *aRecord;                    /* Buffer containing old.* record */
   SessionChange *pNext;           /* For hash-table collisions */
@@ -205979,7 +210852,7 @@ static int sessionSerializeValue(
 
         if( aBuf ){
           sessionVarintPut(&aBuf[1], n);
-          if( n ) memcpy(&aBuf[nVarint + 1], z, n);
+          if( n>0 ) memcpy(&aBuf[nVarint + 1], z, n);
         }
 
         nByte = 1 + nVarint + n;
@@ -206584,16 +211457,32 @@ static int sessionTableInfo(
     }else if( rc==SQLITE_ERROR ){
       zPragma = sqlite3_mprintf("");
     }else{
+      *pazCol = 0;
+      *pabPK = 0;
+      *pnCol = 0;
+      if( pzTab ) *pzTab = 0;
       return rc;
     }
   }else{
     zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
   }
-  if( !zPragma ) return SQLITE_NOMEM;
+  if( !zPragma ){
+    *pazCol = 0;
+    *pabPK = 0;
+    *pnCol = 0;
+    if( pzTab ) *pzTab = 0;
+    return SQLITE_NOMEM;
+  }
 
   rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
   sqlite3_free(zPragma);
-  if( rc!=SQLITE_OK ) return rc;
+  if( rc!=SQLITE_OK ){
+    *pazCol = 0;
+    *pabPK = 0;
+    *pnCol = 0;
+    if( pzTab ) *pzTab = 0;
+    return rc;
+  }
 
   nByte = nThis + 1;
   while( SQLITE_ROW==sqlite3_step(pStmt) ){
@@ -206683,6 +211572,12 @@ static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
       if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
         pTab->bStat1 = 1;
       }
+
+      if( pSession->bEnableSize ){
+        pSession->nMaxChangesetSize += (
+          1 + sessionVarintLen(pTab->nCol) + pTab->nCol + strlen(pTab->zName)+1
+        );
+      }
     }
   }
   return (pSession->rc || pTab->abPK==0);
@@ -206728,6 +211623,103 @@ static int sessionStat1Depth(void *pCtx){
   return p->hook.xDepth(p->hook.pCtx);
 }
 
+static int sessionUpdateMaxSize(
+  int op,
+  sqlite3_session *pSession,      /* Session object pTab is attached to */
+  SessionTable *pTab,             /* Table that change applies to */
+  SessionChange *pC               /* Update pC->nMaxSize */
+){
+  i64 nNew = 2;
+  if( pC->op==SQLITE_INSERT ){
+    if( op!=SQLITE_DELETE ){
+      int ii;
+      for(ii=0; ii<pTab->nCol; ii++){
+        sqlite3_value *p = 0;
+        pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
+        sessionSerializeValue(0, p, &nNew);
+      }
+    }
+  }else if( op==SQLITE_DELETE ){
+    nNew += pC->nRecord;
+    if( sqlite3_preupdate_blobwrite(pSession->db)>=0 ){
+      nNew += pC->nRecord;
+    }
+  }else{
+    int ii;
+    u8 *pCsr = pC->aRecord;
+    for(ii=0; ii<pTab->nCol; ii++){
+      int bChanged = 1;
+      int nOld = 0;
+      int eType;
+      sqlite3_value *p = 0;
+      pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
+      if( p==0 ){
+        return SQLITE_NOMEM;
+      }
+
+      eType = *pCsr++;
+      switch( eType ){
+        case SQLITE_NULL:
+          bChanged = sqlite3_value_type(p)!=SQLITE_NULL;
+          break;
+
+        case SQLITE_FLOAT:
+        case SQLITE_INTEGER: {
+          if( eType==sqlite3_value_type(p) ){
+            sqlite3_int64 iVal = sessionGetI64(pCsr);
+            if( eType==SQLITE_INTEGER ){
+              bChanged = (iVal!=sqlite3_value_int64(p));
+            }else{
+              double dVal;
+              memcpy(&dVal, &iVal, 8);
+              bChanged = (dVal!=sqlite3_value_double(p));
+            }
+          }
+          nOld = 8;
+          pCsr += 8;
+          break;
+        }
+
+        default: {
+          int nByte;
+          nOld = sessionVarintGet(pCsr, &nByte);
+          pCsr += nOld;
+          nOld += nByte;
+          assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
+          if( eType==sqlite3_value_type(p)
+           && nByte==sqlite3_value_bytes(p)
+           && (nByte==0 || 0==memcmp(pCsr, sqlite3_value_blob(p), nByte))
+          ){
+            bChanged = 0;
+          }
+          pCsr += nByte;
+          break;
+        }
+      }
+
+      if( bChanged && pTab->abPK[ii] ){
+        nNew = pC->nRecord + 2;
+        break;
+      }
+
+      if( bChanged ){
+        nNew += 1 + nOld;
+        sessionSerializeValue(0, p, &nNew);
+      }else if( pTab->abPK[ii] ){
+        nNew += 2 + nOld;
+      }else{
+        nNew += 2;
+      }
+    }
+  }
+
+  if( nNew>pC->nMaxSize ){
+    int nIncr = nNew - pC->nMaxSize;
+    pC->nMaxSize = nNew;
+    pSession->nMaxChangesetSize += nIncr;
+  }
+  return SQLITE_OK;
+}
 
 /*
 ** This function is only called from with a pre-update-hook reporting a
@@ -206801,7 +211793,6 @@ static void sessionPreupdateOneChange(
       /* Create a new change object containing all the old values (if
       ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
       ** values (if this is an INSERT). */
-      SessionChange *pChange; /* New change object */
       sqlite3_int64 nByte;    /* Number of bytes to allocate */
       int i;                  /* Used to iterate through columns */
 
@@ -206827,13 +211818,13 @@ static void sessionPreupdateOneChange(
       }
 
       /* Allocate the change object */
-      pChange = (SessionChange *)sessionMalloc64(pSession, nByte);
-      if( !pChange ){
+      pC = (SessionChange *)sessionMalloc64(pSession, nByte);
+      if( !pC ){
         rc = SQLITE_NOMEM;
         goto error_out;
       }else{
-        memset(pChange, 0, sizeof(SessionChange));
-        pChange->aRecord = (u8 *)&pChange[1];
+        memset(pC, 0, sizeof(SessionChange));
+        pC->aRecord = (u8 *)&pC[1];
       }
 
       /* Populate the change object. None of the preupdate_old(),
@@ -206848,17 +211839,17 @@ static void sessionPreupdateOneChange(
         }else if( pTab->abPK[i] ){
           pSession->hook.xNew(pSession->hook.pCtx, i, &p);
         }
-        sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
+        sessionSerializeValue(&pC->aRecord[nByte], p, &nByte);
       }
 
       /* Add the change to the hash-table */
       if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
-        pChange->bIndirect = 1;
+        pC->bIndirect = 1;
       }
-      pChange->nRecord = nByte;
-      pChange->op = op;
-      pChange->pNext = pTab->apChange[iHash];
-      pTab->apChange[iHash] = pChange;
+      pC->nRecord = nByte;
+      pC->op = op;
+      pC->pNext = pTab->apChange[iHash];
+      pTab->apChange[iHash] = pC;
 
     }else if( pC->bIndirect ){
       /* If the existing change is considered "indirect", but this current
@@ -206869,8 +211860,14 @@ static void sessionPreupdateOneChange(
         pC->bIndirect = 0;
       }
     }
+
+    assert( rc==SQLITE_OK );
+    if( pSession->bEnableSize ){
+      rc = sessionUpdateMaxSize(op, pSession, pTab, pC);
+    }
   }
 
+
   /* If an error has occurred, mark the session object as failed. */
  error_out:
   if( pTab->bStat1 ){
@@ -206903,7 +211900,11 @@ static int sessionFindTable(
     ){
       rc = sqlite3session_attach(pSession, zName);
       if( rc==SQLITE_OK ){
-        for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
+        pRet = pSession->pTable;
+        while( ALWAYS(pRet) && pRet->pNext ){
+          pRet = pRet->pNext;
+        }
+        assert( pRet!=0 );
         assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
       }
     }
@@ -207425,13 +212426,29 @@ SQLITE_API int sqlite3session_attach(
 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
 ** set *pRc to SQLITE_NOMEM and return non-zero.
 */
-static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){
-  if( *pRc==SQLITE_OK && (size_t)(p->nAlloc-p->nBuf)<nByte ){
+static int sessionBufferGrow(SessionBuffer *p, i64 nByte, int *pRc){
+#define SESSION_MAX_BUFFER_SZ (0x7FFFFF00 - 1)
+  i64 nReq = p->nBuf + nByte;
+  if( *pRc==SQLITE_OK && nReq>p->nAlloc ){
     u8 *aNew;
     i64 nNew = p->nAlloc ? p->nAlloc : 128;
+
     do {
       nNew = nNew*2;
-    }while( (size_t)(nNew-p->nBuf)<nByte );
+    }while( nNew<nReq );
+
+    /* The value of SESSION_MAX_BUFFER_SZ is copied from the implementation
+    ** of sqlite3_realloc64(). Allocations greater than this size in bytes
+    ** always fail. It is used here to ensure that this routine can always
+    ** allocate up to this limit - instead of up to the largest power of
+    ** two smaller than the limit.  */
+    if( nNew>SESSION_MAX_BUFFER_SZ ){
+      nNew = SESSION_MAX_BUFFER_SZ;
+      if( nNew<nReq ){
+        *pRc = SQLITE_NOMEM;
+        return 1;
+      }
+    }
 
     aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
     if( 0==aNew ){
@@ -207660,6 +212677,7 @@ static int sessionAppendUpdate(
   int i;                        /* Used to iterate through columns */
   u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
 
+  assert( abPK!=0 );
   sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
   sessionAppendByte(pBuf, p->bIndirect, &rc);
   for(i=0; i<sqlite3_column_count(pStmt); i++){
@@ -207964,12 +212982,14 @@ static int sessionGenerateChangeset(
   SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
   int rc;                         /* Return code */
 
-  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
+  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0) );
+  assert( xOutput!=0 || (pnChangeset!=0 && ppChangeset!=0) );
 
   /* Zero the output variables in case an error occurs. If this session
   ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
   ** this call will be a no-op.  */
   if( xOutput==0 ){
+    assert( pnChangeset!=0  && ppChangeset!=0 );
     *pnChangeset = 0;
     *ppChangeset = 0;
   }
@@ -207983,8 +213003,8 @@ static int sessionGenerateChangeset(
   for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
     if( pTab->nEntry ){
       const char *zName = pTab->zName;
-      int nCol;                   /* Number of columns in table */
-      u8 *abPK;                   /* Primary key array */
+      int nCol = 0;               /* Number of columns in table */
+      u8 *abPK = 0;               /* Primary key array */
       const char **azCol = 0;     /* Table columns */
       int i;                      /* Used to iterate through hash buckets */
       sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
@@ -208022,6 +213042,7 @@ static int sessionGenerateChangeset(
                 sessionAppendCol(&buf, pSel, iCol, &rc);
               }
             }else{
+              assert( abPK!=0 );  /* Because sessionSelectStmt() returned ok */
               rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
             }
           }else if( p->op!=SQLITE_INSERT ){
@@ -208082,7 +213103,14 @@ SQLITE_API int sqlite3session_changeset(
   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
   void **ppChangeset              /* OUT: Buffer containing changeset */
 ){
-  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
+  int rc;
+
+  if( pnChangeset==0 || ppChangeset==0 ) return SQLITE_MISUSE;
+  rc = sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset,ppChangeset);
+  assert( rc || pnChangeset==0
+       || pSession->bEnableSize==0 || *pnChangeset<=pSession->nMaxChangesetSize
+  );
+  return rc;
 }
 
 /*
@@ -208093,6 +213121,7 @@ SQLITE_API int sqlite3session_changeset_strm(
   int (*xOutput)(void *pOut, const void *pData, int nData),
   void *pOut
 ){
+  if( xOutput==0 ) return SQLITE_MISUSE;
   return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
 }
 
@@ -208104,6 +213133,7 @@ SQLITE_API int sqlite3session_patchset_strm(
   int (*xOutput)(void *pOut, const void *pData, int nData),
   void *pOut
 ){
+  if( xOutput==0 ) return SQLITE_MISUSE;
   return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
 }
 
@@ -208119,6 +213149,7 @@ SQLITE_API int sqlite3session_patchset(
   int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
   void **ppPatchset               /* OUT: Buffer containing changeset */
 ){
+  if( pnPatchset==0 || ppPatchset==0 ) return SQLITE_MISUSE;
   return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
 }
 
@@ -208174,6 +213205,39 @@ SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession){
   return pSession->nMalloc;
 }
 
+/*
+** Configure the session object passed as the first argument.
+*/
+SQLITE_API int sqlite3session_object_config(sqlite3_session *pSession, int op, void *pArg){
+  int rc = SQLITE_OK;
+  switch( op ){
+    case SQLITE_SESSION_OBJCONFIG_SIZE: {
+      int iArg = *(int*)pArg;
+      if( iArg>=0 ){
+        if( pSession->pTable ){
+          rc = SQLITE_MISUSE;
+        }else{
+          pSession->bEnableSize = (iArg!=0);
+        }
+      }
+      *(int*)pArg = pSession->bEnableSize;
+      break;
+    }
+
+    default:
+      rc = SQLITE_MISUSE;
+  }
+
+  return rc;
+}
+
+/*
+** Return the maximum size of sqlite3session_changeset() output.
+*/
+SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession){
+  return pSession->nMaxChangesetSize;
+}
+
 /*
 ** Do the work for either sqlite3changeset_start() or start_strm().
 */
@@ -209049,11 +214113,11 @@ static int sessionChangesetInvert(
   }
 
   assert( rc==SQLITE_OK );
-  if( pnInverted ){
+  if( pnInverted && ALWAYS(ppInverted) ){
     *pnInverted = sOut.nBuf;
     *ppInverted = sOut.aBuf;
     sOut.aBuf = 0;
-  }else if( sOut.nBuf>0 ){
+  }else if( sOut.nBuf>0 && ALWAYS(xOutput!=0) ){
     rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
   }
 
@@ -209509,7 +214573,7 @@ static int sessionBindRow(
 
   for(i=0; rc==SQLITE_OK && i<nCol; i++){
     if( !abPK || abPK[i] ){
-      sqlite3_value *pVal;
+      sqlite3_value *pVal = 0;
       (void)xValue(pIter, i, &pVal);
       if( pVal==0 ){
         /* The value in the changeset was "undefined". This indicates a
@@ -210652,9 +215716,9 @@ static int sessionChangegroupOutput(
   if( rc==SQLITE_OK ){
     if( xOutput ){
       if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
-    }else{
+    }else if( ppOut ){
       *ppOut = buf.aBuf;
-      *pnOut = buf.nBuf;
+      if( pnOut ) *pnOut = buf.nBuf;
       buf.aBuf = 0;
     }
   }
@@ -211054,7 +216118,7 @@ static int sessionRebase(
       if( sOut.nBuf>0 ){
         rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
       }
-    }else{
+    }else if( ppOut ){
       *ppOut = (void*)sOut.aBuf;
       *pnOut = sOut.nBuf;
       sOut.aBuf = 0;
@@ -211797,8 +216861,20 @@ typedef sqlite3_uint64 u64;
 #endif
 
 #define testcase(x)
-#define ALWAYS(x) 1
-#define NEVER(x) 0
+
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
+# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
+#endif
+#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
+# define ALWAYS(X)      (1)
+# define NEVER(X)       (0)
+#elif !defined(NDEBUG)
+# define ALWAYS(X)      ((X)?1:(assert(0),0))
+# define NEVER(X)       ((X)?(assert(0),1):0)
+#else
+# define ALWAYS(X)      (X)
+# define NEVER(X)       (X)
+#endif
 
 #define MIN(x,y) (((x) < (y)) ? (x) : (y))
 #define MAX(x,y) (((x) > (y)) ? (x) : (y))
@@ -211858,7 +216934,7 @@ SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
 ** A version of memcmp() that does not cause asan errors if one of the pointer
 ** parameters is NULL and the number of bytes to compare is zero.
 */
-#define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n)))
+#define fts5Memcmp(s1, s2, n) ((n)<=0 ? 0 : memcmp((s1), (s2), (n)))
 
 /* Mark a function parameter as unused, to suppress nuisance compiler
 ** warnings. */
@@ -212197,6 +217273,9 @@ static void sqlite3Fts5IndexCloseReader(Fts5Index*);
 */
 static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
 static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
+static void *sqlite3Fts5StructureRef(Fts5Index*);
+static void sqlite3Fts5StructureRelease(void*);
+static int sqlite3Fts5StructureTest(Fts5Index*, void*);
 
 
 /*
@@ -212974,9 +218053,9 @@ struct fts5yyParser {
 };
 typedef struct fts5yyParser fts5yyParser;
 
+/* #include <assert.h> */
 #ifndef NDEBUG
 /* #include <stdio.h> */
-/* #include <assert.h> */
 static FILE *fts5yyTraceFILE = 0;
 static char *fts5yyTracePrompt = 0;
 #endif /* NDEBUG */
@@ -213913,8 +218992,8 @@ static void sqlite3Fts5Parser(
     fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
     if( fts5yyact >= fts5YY_MIN_REDUCE ){
       unsigned int fts5yyruleno = fts5yyact - fts5YY_MIN_REDUCE; /* Reduce by this rule */
-      assert( fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) );
 #ifndef NDEBUG
+      assert( fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) );
       if( fts5yyTraceFILE ){
         int fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
         if( fts5yysize ){
@@ -214012,14 +219091,13 @@ static void sqlite3Fts5Parser(
         fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
         fts5yymajor = fts5YYNOCODE;
       }else{
-        while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
-            && (fts5yyact = fts5yy_find_reduce_action(
-                        fts5yypParser->fts5yytos->stateno,
-                        fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE
-        ){
+        while( fts5yypParser->fts5yytos > fts5yypParser->fts5yystack ){
+          fts5yyact = fts5yy_find_reduce_action(fts5yypParser->fts5yytos->stateno,
+                                        fts5YYERRORSYMBOL);
+          if( fts5yyact<=fts5YY_MAX_SHIFTREDUCE ) break;
           fts5yy_pop_parser_stack(fts5yypParser);
         }
-        if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
+        if( fts5yypParser->fts5yytos <= fts5yypParser->fts5yystack || fts5yymajor==0 ){
           fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
           fts5yy_parse_failed(fts5yypParser);
 #ifndef fts5YYNOERRORRECOVERY
@@ -214882,7 +219960,6 @@ static void sqlite3Fts5BufferAppendBlob(
   u32 nData,
   const u8 *pData
 ){
-  assert_nc( *pRc || nData>=0 );
   if( nData ){
     if( fts5BufferGrow(pRc, pBuf, nData) ) return;
     memcpy(&pBuf->p[pBuf->n], pData, nData);
@@ -214992,7 +220069,7 @@ static int sqlite3Fts5PoslistNext64(
     return 1;
   }else{
     i64 iOff = *piOff;
-    int iVal;
+    u32 iVal;
     fts5FastGetVarint32(a, i, iVal);
     if( iVal<=1 ){
       if( iVal==0 ){
@@ -215001,15 +220078,19 @@ static int sqlite3Fts5PoslistNext64(
       }
       fts5FastGetVarint32(a, i, iVal);
       iOff = ((i64)iVal) << 32;
+      assert( iOff>=0 );
       fts5FastGetVarint32(a, i, iVal);
       if( iVal<2 ){
         /* This is a corrupt record. So stop parsing it here. */
         *piOff = -1;
         return 1;
       }
+      *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
+    }else{
+      *piOff = (iOff & (i64)0x7FFFFFFF<<32)+((iOff + (iVal-2)) & 0x7FFFFFFF);
     }
-    *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
     *pi = i;
+    assert_nc( *piOff>=iOff );
     return 0;
   }
 }
@@ -215048,14 +220129,16 @@ static void sqlite3Fts5PoslistSafeAppend(
   i64 *piPrev,
   i64 iPos
 ){
-  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
-  if( (iPos & colmask) != (*piPrev & colmask) ){
-    pBuf->p[pBuf->n++] = 1;
-    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
-    *piPrev = (iPos & colmask);
+  if( iPos>=*piPrev ){
+    static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
+    if( (iPos & colmask) != (*piPrev & colmask) ){
+      pBuf->p[pBuf->n++] = 1;
+      pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
+      *piPrev = (iPos & colmask);
+    }
+    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
+    *piPrev = iPos;
   }
-  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
-  *piPrev = iPos;
 }
 
 static int sqlite3Fts5PoslistWriterAppend(
@@ -215757,7 +220840,7 @@ static int sqlite3Fts5ConfigParse(
 
   nByte = nArg * (sizeof(char*) + sizeof(u8));
   pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
-  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
+  pRet->abUnindexed = pRet->azCol ? (u8*)&pRet->azCol[nArg] : 0;
   pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
   pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
   pRet->bColumnsize = 1;
@@ -215782,6 +220865,7 @@ static int sqlite3Fts5ConfigParse(
     z = fts5ConfigSkipWhitespace(z);
     if( z && *z=='=' ){
       bOption = 1;
+      assert( zOne!=0 );
       z++;
       if( bMustBeCol ) z = 0;
     }
@@ -215798,7 +220882,11 @@ static int sqlite3Fts5ConfigParse(
         rc = SQLITE_ERROR;
       }else{
         if( bOption ){
-          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
+          rc = fts5ConfigParseSpecial(pGlobal, pRet,
+            ALWAYS(zOne)?zOne:"",
+            zTwo?zTwo:"",
+            pzErr
+          );
         }else{
           rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
           zOne = 0;
@@ -216316,6 +221404,7 @@ static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
   va_list ap;
   va_start(ap, zFmt);
   if( pParse->rc==SQLITE_OK ){
+    assert( pParse->zErr==0 );
     pParse->zErr = sqlite3_vmprintf(zFmt, ap);
     pParse->rc = SQLITE_ERROR;
   }
@@ -216614,6 +221703,7 @@ static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
   int bRetValid = 0;
   Fts5ExprTerm *p;
 
+  assert( pTerm );
   assert( pTerm->pSynonym );
   assert( bDesc==0 || bDesc==1 );
   for(p=pTerm; p; p=p->pSynonym){
@@ -218054,7 +223144,7 @@ static int sqlite3Fts5ExprClonePhrase(
     sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
   }
 
-  if( rc==SQLITE_OK ){
+  if( rc==SQLITE_OK && ALWAYS(sCtx.pPhrase) ){
     /* All the allocations succeeded. Put the expression object together. */
     pNew->pIndex = pExpr->pIndex;
     pNew->pConfig = pExpr->pConfig;
@@ -218325,9 +223415,8 @@ static void sqlite3Fts5ParseSetColset(
 ){
   Fts5Colset *pFree = pColset;
   if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
-    pParse->rc = SQLITE_ERROR;
-    pParse->zErr = sqlite3_mprintf(
-      "fts5: column queries are not supported (detail=none)"
+    sqlite3Fts5ParseError(pParse,
+        "fts5: column queries are not supported (detail=none)"
     );
   }else{
     fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
@@ -218501,13 +223590,10 @@ static Fts5ExprNode *sqlite3Fts5ParseNode(
                 || pPhrase->nTerm>1
                 || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
               ){
-              assert( pParse->rc==SQLITE_OK );
-              pParse->rc = SQLITE_ERROR;
-              assert( pParse->zErr==0 );
-              pParse->zErr = sqlite3_mprintf(
+              sqlite3Fts5ParseError(pParse,
                   "fts5: %s queries are not supported (detail!=full)",
                   pNear->nPhrase==1 ? "phrase": "NEAR"
-                  );
+              );
               sqlite3_free(pRet);
               pRet = 0;
             }
@@ -218593,6 +223679,7 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
   return pRet;
 }
 
+#ifdef SQLITE_TEST
 static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
   sqlite3_int64 nByte = 0;
   Fts5ExprTerm *p;
@@ -218959,12 +224046,14 @@ static void fts5ExprFold(
     sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
   }
 }
+#endif /* ifdef SQLITE_TEST */
 
 /*
 ** This is called during initialization to register the fts5_expr() scalar
 ** UDF with the SQLite handle passed as the only argument.
 */
 static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
+#ifdef SQLITE_TEST
   struct Fts5ExprFunc {
     const char *z;
     void (*x)(sqlite3_context*,int,sqlite3_value**);
@@ -218982,6 +224071,10 @@ static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
     struct Fts5ExprFunc *p = &aFunc[i];
     rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
   }
+#else
+  int rc = SQLITE_OK;
+  UNUSED_PARAM2(pGlobal,db);
+#endif
 
   /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
   ** sqlite3Fts5ParserFallback() are unused */
@@ -219032,6 +224125,15 @@ struct Fts5PoslistPopulator {
   int bMiss;
 };
 
+/*
+** Clear the position lists associated with all phrases in the expression
+** passed as the first argument. Argument bLive is true if the expression
+** might be pointing to a real entry, otherwise it has just been reset.
+**
+** At present this function is only used for detail=col and detail=none
+** fts5 tables. This implies that all phrases must be at most 1 token
+** in size, as phrase matches are not supported without detail=full.
+*/
 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
   Fts5PoslistPopulator *pRet;
   pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
@@ -219041,7 +224143,7 @@ static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int b
     for(i=0; i<pExpr->nPhrase; i++){
       Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
       Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
-      assert( pExpr->apExprPhrase[i]->nTerm==1 );
+      assert( pExpr->apExprPhrase[i]->nTerm<=1 );
       if( bLive &&
           (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
       ){
@@ -219592,7 +224694,7 @@ static int sqlite3Fts5HashWrite(
       p->bContent = 1;
     }else{
       /* Append a new column value, if necessary */
-      assert( iCol>=p->iCol );
+      assert_nc( iCol>=p->iCol );
       if( iCol!=p->iCol ){
         if( pHash->eDetail==FTS5_DETAIL_FULL ){
           pPtr[p->nData++] = 0x01;
@@ -220228,7 +225330,7 @@ struct Fts5SegIter {
   int iLeafPgno;                  /* Current leaf page number */
   Fts5Data *pLeaf;                /* Current leaf data */
   Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
-  int iLeafOffset;                /* Byte offset within current leaf */
+  i64 iLeafOffset;                /* Byte offset within current leaf */
 
   /* Next method */
   void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
@@ -220397,8 +225499,11 @@ static int fts5BufferCompareBlob(
 **     res = *pLeft - *pRight
 */
 static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
-  int nCmp = MIN(pLeft->n, pRight->n);
-  int res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
+  int nCmp, res;
+  nCmp = MIN(pLeft->n, pRight->n);
+  assert( nCmp<=0 || pLeft->p!=0 );
+  assert( nCmp<=0 || pRight->p!=0 );
+  res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
   return (res==0 ? (pLeft->n - pRight->n) : res);
 }
 
@@ -220494,6 +225599,7 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
   return pRet;
 }
 
+
 /*
 ** Release a reference to data record returned by an earlier call to
 ** fts5DataRead().
@@ -220618,6 +225724,58 @@ static void fts5StructureRef(Fts5Structure *pStruct){
   pStruct->nRef++;
 }
 
+static void *sqlite3Fts5StructureRef(Fts5Index *p){
+  fts5StructureRef(p->pStruct);
+  return (void*)p->pStruct;
+}
+static void sqlite3Fts5StructureRelease(void *p){
+  if( p ){
+    fts5StructureRelease((Fts5Structure*)p);
+  }
+}
+static int sqlite3Fts5StructureTest(Fts5Index *p, void *pStruct){
+  if( p->pStruct!=(Fts5Structure*)pStruct ){
+    return SQLITE_ABORT;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Ensure that structure object (*pp) is writable.
+**
+** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. If
+** an error occurs, (*pRc) is set to an SQLite error code before returning.
+*/
+static void fts5StructureMakeWritable(int *pRc, Fts5Structure **pp){
+  Fts5Structure *p = *pp;
+  if( *pRc==SQLITE_OK && p->nRef>1 ){
+    i64 nByte = sizeof(Fts5Structure)+(p->nLevel-1)*sizeof(Fts5StructureLevel);
+    Fts5Structure *pNew;
+    pNew = (Fts5Structure*)sqlite3Fts5MallocZero(pRc, nByte);
+    if( pNew ){
+      int i;
+      memcpy(pNew, p, nByte);
+      for(i=0; i<p->nLevel; i++) pNew->aLevel[i].aSeg = 0;
+      for(i=0; i<p->nLevel; i++){
+        Fts5StructureLevel *pLvl = &pNew->aLevel[i];
+        nByte = sizeof(Fts5StructureSegment) * pNew->aLevel[i].nSeg;
+        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(pRc, nByte);
+        if( pLvl->aSeg==0 ){
+          for(i=0; i<p->nLevel; i++){
+            sqlite3_free(pNew->aLevel[i].aSeg);
+          }
+          sqlite3_free(pNew);
+          return;
+        }
+        memcpy(pLvl->aSeg, p->aLevel[i].aSeg, nByte);
+      }
+      p->nRef--;
+      pNew->nRef = 1;
+    }
+    *pp = pNew;
+  }
+}
+
 /*
 ** Deserialize and return the structure record currently stored in serialized
 ** form within buffer pData/nData.
@@ -220719,9 +225877,11 @@ static int fts5StructureDecode(
 }
 
 /*
-**
+** Add a level to the Fts5Structure.aLevel[] array of structure object
+** (*ppStruct).
 */
 static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
+  fts5StructureMakeWritable(pRc, ppStruct);
   if( *pRc==SQLITE_OK ){
     Fts5Structure *pStruct = *ppStruct;
     int nLevel = pStruct->nLevel;
@@ -221408,7 +226568,7 @@ static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
 
 static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
   u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
-  int iOff = pIter->iLeafOffset;
+  i64 iOff = pIter->iLeafOffset;
 
   ASSERT_SZLEAF_OK(pIter->pLeaf);
   if( iOff>=pIter->pLeaf->szLeaf ){
@@ -221441,7 +226601,7 @@ static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
 */
 static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
   u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
-  int iOff = pIter->iLeafOffset;  /* Offset to read at */
+  i64 iOff = pIter->iLeafOffset;  /* Offset to read at */
   int nNew;                       /* Bytes of new data */
 
   iOff += fts5GetVarint32(&a[iOff], nNew);
@@ -221515,6 +226675,7 @@ static void fts5SegIterInit(
 
   if( p->rc==SQLITE_OK ){
     pIter->iLeafOffset = 4;
+    assert( pIter->pLeaf!=0 );
     assert_nc( pIter->pLeaf->nn>4 );
     assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
     pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
@@ -221617,8 +226778,12 @@ static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
         int iRowidOff;
         iRowidOff = fts5LeafFirstRowidOff(pNew);
         if( iRowidOff ){
-          pIter->pLeaf = pNew;
-          pIter->iLeafOffset = iRowidOff;
+          if( iRowidOff>=pNew->szLeaf ){
+            p->rc = FTS5_CORRUPT;
+          }else{
+            pIter->pLeaf = pNew;
+            pIter->iLeafOffset = iRowidOff;
+          }
         }
       }
 
@@ -221869,7 +227034,6 @@ static void fts5SegIterNext(
       ** this block is particularly performance critical, so equivalent
       ** code is inlined.  */
       int nSz;
-      assert( p->rc==SQLITE_OK );
       assert_nc( pIter->iLeafOffset<=pIter->pLeaf->nn );
       fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
       pIter->bDel = (nSz & 0x0001);
@@ -221899,7 +227063,7 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
   if( pDlidx ){
     int iSegid = pIter->pSeg->iSegid;
     pgnoLast = fts5DlidxIterPgno(pDlidx);
-    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
+    pLast = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
   }else{
     Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
 
@@ -221926,7 +227090,7 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
       ** forward to find the page containing the last rowid.  */
       for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
         i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
-        Fts5Data *pNew = fts5DataRead(p, iAbs);
+        Fts5Data *pNew = fts5LeafRead(p, iAbs);
         if( pNew ){
           int iRowid, bTermless;
           iRowid = fts5LeafFirstRowidOff(pNew);
@@ -221957,6 +227121,10 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
     pIter->pLeaf = pLast;
     pIter->iLeafPgno = pgnoLast;
     iOff = fts5LeafFirstRowidOff(pLast);
+    if( iOff>pLast->szLeaf ){
+      p->rc = FTS5_CORRUPT;
+      return;
+    }
     iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
     pIter->iLeafOffset = iOff;
 
@@ -221965,7 +227133,6 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
     }else{
       pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
     }
-
   }
 
   fts5SegIterReverseInitPage(p, pIter);
@@ -222017,21 +227184,20 @@ static void fts5LeafSeek(
   Fts5SegIter *pIter,             /* Iterator to seek */
   const u8 *pTerm, int nTerm      /* Term to search for */
 ){
-  int iOff;
+  u32 iOff;
   const u8 *a = pIter->pLeaf->p;
-  int szLeaf = pIter->pLeaf->szLeaf;
-  int n = pIter->pLeaf->nn;
+  u32 n = (u32)pIter->pLeaf->nn;
 
   u32 nMatch = 0;
   u32 nKeep = 0;
   u32 nNew = 0;
   u32 iTermOff;
-  int iPgidx;                     /* Current offset in pgidx */
+  u32 iPgidx;                     /* Current offset in pgidx */
   int bEndOfPage = 0;
 
   assert( p->rc==SQLITE_OK );
 
-  iPgidx = szLeaf;
+  iPgidx = (u32)pIter->pLeaf->szLeaf;
   iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
   iOff = iTermOff;
   if( iOff>n ){
@@ -222097,15 +227263,15 @@ static void fts5LeafSeek(
       if( pIter->pLeaf==0 ) return;
       a = pIter->pLeaf->p;
       if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
-        iPgidx = pIter->pLeaf->szLeaf;
+        iPgidx = (u32)pIter->pLeaf->szLeaf;
         iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
-        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
+        if( iOff<4 || (i64)iOff>=pIter->pLeaf->szLeaf ){
           p->rc = FTS5_CORRUPT;
           return;
         }else{
           nKeep = 0;
           iTermOff = iOff;
-          n = pIter->pLeaf->nn;
+          n = (u32)pIter->pLeaf->nn;
           iOff += fts5GetVarint32(&a[iOff], nNew);
           break;
         }
@@ -222473,7 +227639,7 @@ static void fts5SegIterGotoPage(
     fts5SegIterNextPage(p, pIter);
     assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
 
-    if( p->rc==SQLITE_OK ){
+    if( p->rc==SQLITE_OK && ALWAYS(pIter->pLeaf!=0) ){
       int iOff;
       u8 *a = pIter->pLeaf->p;
       int n = pIter->pLeaf->szLeaf;
@@ -222905,7 +228071,11 @@ static void fts5SegiterPoslist(
   Fts5Colset *pColset,
   Fts5Buffer *pBuf
 ){
+  assert( pBuf!=0 );
+  assert( pSeg!=0 );
   if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
+    assert( pBuf->p!=0 );
+    assert( pBuf->nSpace >= pBuf->n+pSeg->nPos+FTS5_DATA_ZERO_PADDING );
     memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
     if( pColset==0 ){
       fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
@@ -222981,7 +228151,7 @@ static void fts5IndexExtractColset(
         }
         fts5BufferSafeAppendBlob(&pIter->poslist, aCopy, p-aCopy);
       }
-      if( p==pEnd ){
+      if( p>=pEnd ){
         pIter->base.pData = pIter->poslist.p;
         pIter->base.nData = pIter->poslist.n;
         return;
@@ -223129,6 +228299,7 @@ static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
 }
 
 static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
+  assert( pIter!=0 || (*pRc)!=SQLITE_OK );
   if( *pRc==SQLITE_OK ){
     Fts5Config *pConfig = pIter->pIndex->pConfig;
     if( pConfig->eDetail==FTS5_DETAIL_NONE ){
@@ -223200,7 +228371,10 @@ static void fts5MultiIterNew(
     }
   }
   *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
-  if( pNew==0 ) return;
+  if( pNew==0 ){
+    assert( p->rc!=SQLITE_OK );
+    goto fts5MultiIterNew_post_check;
+  }
   pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
   pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
   pNew->pColset = pColset;
@@ -223264,6 +228438,10 @@ static void fts5MultiIterNew(
     fts5MultiIterFree(pNew);
     *ppOut = 0;
   }
+
+fts5MultiIterNew_post_check:
+  assert( (*ppOut)!=0 || p->rc!=SQLITE_OK );
+  return;
 }
 
 /*
@@ -223311,7 +228489,8 @@ static void fts5MultiIterNew2(
 ** False otherwise.
 */
 static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
-  assert( p->rc
+  assert( pIter!=0 || p->rc!=SQLITE_OK );
+  assert( p->rc!=SQLITE_OK
       || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
   );
   return (p->rc || pIter->base.bEof);
@@ -224115,6 +229294,7 @@ static void fts5IndexMergeLevel(
   ** and last leaf page number at the same time.  */
   fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
 
+  assert( pIter!=0 || p->rc!=SQLITE_OK );
   if( fts5MultiIterEof(p, pIter) ){
     int i;
 
@@ -224215,7 +229395,7 @@ static void fts5IndexAutomerge(
   Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
   int nLeaf                       /* Number of output leaves just written */
 ){
-  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
+  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 && ALWAYS((*ppStruct)!=0) ){
     Fts5Structure *pStruct = *ppStruct;
     u64 nWrite;                   /* Initial value of write-counter */
     int nWork;                    /* Number of work-quanta to perform */
@@ -224338,14 +229518,14 @@ static void fts5FlushOneHash(Fts5Index *p){
         fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
       }else{
         i64 iRowid = 0;
-        i64 iDelta = 0;
+        u64 iDelta = 0;
         int iOff = 0;
 
         /* The entire doclist will not fit on this leaf. The following
         ** loop iterates through the poslists that make up the current
         ** doclist.  */
         while( p->rc==SQLITE_OK && iOff<nDoclist ){
-          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
+          iOff += fts5GetVarint(&pDoclist[iOff], &iDelta);
           iRowid += iDelta;
 
           if( writer.bFirstRowidInPage ){
@@ -224777,7 +229957,7 @@ static void fts5MergePrefixLists(
   Fts5Buffer *aBuf                /* Other lists to merge in */
 ){
 #define fts5PrefixMergerNextPosition(p) \
-  sqlite3Fts5PoslistNext64((p)->aPos,(p)->iter.nPoslist,&(p)->iOff,&(p)->iPos);
+  sqlite3Fts5PoslistNext64((p)->aPos,(p)->iter.nPoslist,&(p)->iOff,&(p)->iPos)
 #define FTS5_MERGE_NLIST 16
   PrefixMerger aMerger[FTS5_MERGE_NLIST];
   PrefixMerger *pHead = 0;
@@ -224876,7 +230056,8 @@ static void fts5MergePrefixLists(
       nTail = pHead->iter.nPoslist - pHead->iOff;
 
       /* WRITEPOSLISTSIZE */
-      assert( tmp.n+nTail<=nTmp );
+      assert_nc( tmp.n+nTail<=nTmp );
+      assert( tmp.n+nTail<=nTmp+nMerge*10 );
       if( tmp.n+nTail>nTmp-FTS5_DATA_ZERO_PADDING ){
         if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
         break;
@@ -225283,7 +230464,7 @@ static int sqlite3Fts5IndexQuery(
   if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
     int iIdx = 0;                 /* Index to search */
     int iPrefixIdx = 0;           /* +1 prefix index */
-    if( nToken ) memcpy(&buf.p[1], pToken, nToken);
+    if( nToken>0 ) memcpy(&buf.p[1], pToken, nToken);
 
     /* Figure out which index to search and set iIdx accordingly. If this
     ** is a prefix query for which there is no prefix index, set iIdx to
@@ -225324,11 +230505,15 @@ static int sqlite3Fts5IndexQuery(
       /* Scan multiple terms in the main index */
       int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
       fts5SetupPrefixIter(p, bDesc, iPrefixIdx, buf.p, nToken+1, pColset,&pRet);
-      assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
-      fts5IterSetOutputCb(&p->rc, pRet);
-      if( p->rc==SQLITE_OK ){
-        Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
-        if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
+      if( pRet==0 ){
+        assert( p->rc!=SQLITE_OK );
+      }else{
+        assert( pRet->pColset==0 );
+        fts5IterSetOutputCb(&p->rc, pRet);
+        if( p->rc==SQLITE_OK ){
+          Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
+          if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
+        }
       }
     }
 
@@ -225576,7 +230761,7 @@ static int fts5QueryCksum(
   Fts5IndexIter *pIter = 0;
   int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
 
-  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
+  while( rc==SQLITE_OK && ALWAYS(pIter!=0) && 0==sqlite3Fts5IterEof(pIter) ){
     i64 rowid = pIter->iRowid;
 
     if( eDetail==FTS5_DETAIL_NONE ){
@@ -225941,6 +231126,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum
   Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
   Fts5Iter *pIter;                /* Used to iterate through entire index */
   Fts5Structure *pStruct;         /* Index structure */
+  int iLvl, iSeg;
 
 #ifdef SQLITE_DEBUG
   /* Used by extra internal tests only run if NDEBUG is not defined */
@@ -225951,15 +231137,16 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum
 
   /* Load the FTS index structure */
   pStruct = fts5StructureRead(p);
+  if( pStruct==0 ){
+    assert( p->rc!=SQLITE_OK );
+    return fts5IndexReturn(p);
+  }
 
   /* Check that the internal nodes of each segment match the leaves */
-  if( pStruct ){
-    int iLvl, iSeg;
-    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
-      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
-        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
-        fts5IndexIntegrityCheckSegment(p, pSeg);
-      }
+  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
+    for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
+      Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
+      fts5IndexIntegrityCheckSegment(p, pSeg);
     }
   }
 
@@ -226023,6 +231210,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum
 ** function only.
 */
 
+#ifdef SQLITE_TEST
 /*
 ** Decode a segment-data rowid from the %_data table. This function is
 ** the opposite of macro FTS5_SEGMENT_ROWID().
@@ -226045,7 +231233,9 @@ static void fts5DecodeRowid(
 
   *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
   int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
   fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
@@ -226063,7 +231253,9 @@ static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
     );
   }
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 static void fts5DebugStructure(
   int *pRc,                       /* IN/OUT: error code */
   Fts5Buffer *pBuf,
@@ -226085,7 +231277,9 @@ static void fts5DebugStructure(
     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
   }
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 /*
 ** This is part of the fts5_decode() debugging aid.
 **
@@ -226110,7 +231304,9 @@ static void fts5DecodeStructure(
   fts5DebugStructure(pRc, pBuf, p);
   fts5StructureRelease(p);
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 /*
 ** This is part of the fts5_decode() debugging aid.
 **
@@ -226133,7 +231329,9 @@ static void fts5DecodeAverages(
     zSpace = " ";
   }
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 /*
 ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
 ** each varint and append its string representation to buffer pBuf. Return
@@ -226150,7 +231348,9 @@ static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
   }
   return iOff;
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 /*
 ** The start of buffer (a/n) contains the start of a doclist. The doclist
 ** may or may not finish within the buffer. This function appends a text
@@ -226183,7 +231383,9 @@ static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
 
   return iOff;
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 /*
 ** This function is part of the fts5_decode() debugging function. It is
 ** only ever used with detail=none tables.
@@ -226224,7 +231426,9 @@ static void fts5DecodeRowidList(
     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
   }
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 /*
 ** The implementation of user-defined scalar function fts5_decode().
 */
@@ -226433,7 +231637,9 @@ static void fts5DecodeFunction(
   }
   fts5BufferFree(&s);
 }
+#endif /* SQLITE_TEST */
 
+#ifdef SQLITE_TEST
 /*
 ** The implementation of user-defined scalar function fts5_rowid().
 */
@@ -226467,6 +231673,7 @@ static void fts5RowidFunction(
     }
   }
 }
+#endif /* SQLITE_TEST */
 
 /*
 ** This is called as part of registering the FTS5 module with database
@@ -226477,6 +231684,7 @@ static void fts5RowidFunction(
 ** SQLite error code is returned instead.
 */
 static int sqlite3Fts5IndexInit(sqlite3 *db){
+#ifdef SQLITE_TEST
   int rc = sqlite3_create_function(
       db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
   );
@@ -226494,6 +231702,10 @@ static int sqlite3Fts5IndexInit(sqlite3 *db){
     );
   }
   return rc;
+#else
+  return SQLITE_OK;
+  UNUSED_PARAM(db);
+#endif
 }
 
 
@@ -226529,7 +231741,9 @@ static int sqlite3Fts5IndexReset(Fts5Index *p){
 ** assert() conditions in the fts5 code are activated - conditions that are
 ** only true if it is guaranteed that the fts5 database is not corrupt.
 */
+#ifdef SQLITE_DEBUG
 SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
+#endif
 
 
 typedef struct Fts5Auxdata Fts5Auxdata;
@@ -227309,7 +232523,7 @@ static int fts5SorterNext(Fts5Cursor *pCsr){
   rc = sqlite3_step(pSorter->pStmt);
   if( rc==SQLITE_DONE ){
     rc = SQLITE_OK;
-    CsrFlagSet(pCsr, FTS5CSR_EOF);
+    CsrFlagSet(pCsr, FTS5CSR_EOF|FTS5CSR_REQUIRE_CONTENT);
   }else if( rc==SQLITE_ROW ){
     const u8 *a;
     const u8 *aBlob;
@@ -227879,7 +233093,8 @@ static int fts5FilterMethod(
         pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
     );
     if( rc==SQLITE_OK ){
-      if( pCsr->ePlan==FTS5_PLAN_ROWID ){
+      if( pRowidEq!=0 ){
+        assert( pCsr->ePlan==FTS5_PLAN_ROWID );
         sqlite3_bind_value(pCsr->pStmt, 1, pRowidEq);
       }else{
         sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
@@ -228454,13 +233669,15 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){
 
         nInst++;
         if( nInst>=pCsr->nInstAlloc ){
-          pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
+          int nNewSize = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
           aInst = (int*)sqlite3_realloc64(
-              pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
+              pCsr->aInst, nNewSize*sizeof(int)*3
               );
           if( aInst ){
             pCsr->aInst = aInst;
+            pCsr->nInstAlloc = nNewSize;
           }else{
+            nInst--;
             rc = SQLITE_NOMEM;
             break;
           }
@@ -229295,7 +234512,7 @@ static void fts5SourceIdFunc(
 ){
   assert( nArg==0 );
   UNUSED_PARAM2(nArg, apUnused);
-  sqlite3_result_text(pCtx, "fts5: 2021-04-02 15:20:15 5d4c65779dab868b285519b19e4cf9d451d50c6048f06f653aa701ec212df45e", -1, SQLITE_TRANSIENT);
+  sqlite3_result_text(pCtx, "fts5: 2022-05-06 15:25:27 78d9c993d404cdfaa7fdd2973fa1052e3da9f66215cff9c5540ebe55c407d9fe", -1, SQLITE_TRANSIENT);
 }
 
 /*
@@ -229846,12 +235063,16 @@ static int fts5StorageDeleteFromIndex(
     if( pConfig->abUnindexed[iCol-1]==0 ){
       const char *zText;
       int nText;
+      assert( pSeek==0 || apVal==0 );
+      assert( pSeek!=0 || apVal!=0 );
       if( pSeek ){
         zText = (const char*)sqlite3_column_text(pSeek, iCol);
         nText = sqlite3_column_bytes(pSeek, iCol);
-      }else{
+      }else if( ALWAYS(apVal) ){
         zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
         nText = sqlite3_value_bytes(apVal[iCol-1]);
+      }else{
+        continue;
       }
       ctx.szCol = 0;
       rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
@@ -230487,8 +235708,9 @@ static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
 
   assert( p->pConfig->bColumnsize );
   rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
-  if( rc==SQLITE_OK ){
+  if( pLookup ){
     int bCorrupt = 1;
+    assert( rc==SQLITE_OK );
     sqlite3_bind_int64(pLookup, 1, iRowid);
     if( SQLITE_ROW==sqlite3_step(pLookup) ){
       const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
@@ -230501,6 +235723,8 @@ static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
     if( bCorrupt && rc==SQLITE_OK ){
       rc = FTS5_CORRUPT;
     }
+  }else{
+    assert( rc!=SQLITE_OK );
   }
 
   return rc;
@@ -233191,6 +238415,7 @@ struct Fts5VocabCursor {
 
   int bEof;                       /* True if this cursor is at EOF */
   Fts5IndexIter *pIter;           /* Term/rowid iterator object */
+  void *pStruct;                  /* From sqlite3Fts5StructureRef() */
 
   int nLeTerm;                    /* Size of zLeTerm in bytes */
   char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
@@ -233504,7 +238729,7 @@ static int fts5VocabOpenMethod(
   }
 
   if( rc==SQLITE_OK ){
-    int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
+    i64 nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
     pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
   }
 
@@ -233524,6 +238749,8 @@ static int fts5VocabOpenMethod(
 static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
   pCsr->rowid = 0;
   sqlite3Fts5IterClose(pCsr->pIter);
+  sqlite3Fts5StructureRelease(pCsr->pStruct);
+  pCsr->pStruct = 0;
   pCsr->pIter = 0;
   sqlite3_free(pCsr->zLeTerm);
   pCsr->nLeTerm = -1;
@@ -233601,9 +238828,11 @@ static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
 static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
   Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
-  int rc = SQLITE_OK;
   int nCol = pCsr->pFts5->pConfig->nCol;
+  int rc;
 
+  rc = sqlite3Fts5StructureTest(pCsr->pFts5->pIndex, pCsr->pStruct);
+  if( rc!=SQLITE_OK ) return rc;
   pCsr->rowid++;
 
   if( pTab->eType==FTS5_VOCAB_INSTANCE ){
@@ -233777,6 +239006,9 @@ static int fts5VocabFilterMethod(
   if( rc==SQLITE_OK ){
     Fts5Index *pIndex = pCsr->pFts5->pIndex;
     rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
+    if( rc==SQLITE_OK ){
+      pCsr->pStruct = sqlite3Fts5StructureRef(pIndex);
+    }
   }
   if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
     rc = fts5VocabInstanceNewTerm(pCsr);
@@ -234221,10 +239453,6 @@ SQLITE_API int sqlite3_stmt_init(
 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
 
 /************** End of stmt.c ************************************************/
-#if __LINE__!=234223
-#undef SQLITE_SOURCE_ID
-#define SQLITE_SOURCE_ID      "2021-04-02 15:20:15 5d4c65779dab868b285519b19e4cf9d451d50c6048f06f653aa701ec212dalt2"
-#endif
 /* Return the source-id for this library */
 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
 /************************** End of sqlite3.c ******************************/
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h
index f1c44f1..1c267a4 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h
@@ -44,7 +44,30 @@ extern "C" {
 
 
 /*
-** Provide the ability to override linkage features of the interface.
+** Facilitate override of interface linkage and calling conventions.
+** Be aware that these macros may not be used within this particular
+** translation of the amalgamation and its associated header file.
+**
+** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
+** compiler that the target identifier should have external linkage.
+**
+** The SQLITE_CDECL macro is used to set the calling convention for
+** public functions that accept a variable number of arguments.
+**
+** The SQLITE_APICALL macro is used to set the calling convention for
+** public functions that accept a fixed number of arguments.
+**
+** The SQLITE_STDCALL macro is no longer used and is now deprecated.
+**
+** The SQLITE_CALLBACK macro is used to set the calling convention for
+** function pointers.
+**
+** The SQLITE_SYSAPI macro is used to set the calling convention for
+** functions provided by the operating system.
+**
+** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
+** SQLITE_SYSAPI macros are used only when building for environments
+** that require non-default calling conventions.
 */
 #ifndef SQLITE_EXTERN
 # define SQLITE_EXTERN extern
@@ -124,9 +147,9 @@ extern "C" {
 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
 ** [sqlite_version()] and [sqlite_source_id()].
 */
-#define SQLITE_VERSION        "3.35.4"
-#define SQLITE_VERSION_NUMBER 3035004
-#define SQLITE_SOURCE_ID      "2021-04-02 15:20:15 5d4c65779dab868b285519b19e4cf9d451d50c6048f06f653aa701ec212df45e"
+#define SQLITE_VERSION        "3.38.5"
+#define SQLITE_VERSION_NUMBER 3038005
+#define SQLITE_SOURCE_ID      "2022-05-06 15:25:27 78d9c993d404cdfaa7fdd2973fa1052e3da9f66215cff9c5540ebe55c407d9fe"
 
 /*
 ** CAPI3REF: Run-Time Library Version Numbers
@@ -538,12 +561,13 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
 #define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
+#define SQLITE_CONSTRAINT_DATATYPE     (SQLITE_CONSTRAINT |(12<<8))
 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
 #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
-#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))
+#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8)) /* internal use only */
 
 /*
 ** CAPI3REF: Flags For File Open Operations
@@ -551,6 +575,19 @@ SQLITE_API int sqlite3_exec(
 ** These bit values are intended for use in the
 ** 3rd parameter to the [sqlite3_open_v2()] interface and
 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
+**
+** Only those flags marked as "Ok for sqlite3_open_v2()" may be
+** used as the third argument to the [sqlite3_open_v2()] interface.
+** The other flags have historically been ignored by sqlite3_open_v2(),
+** though future versions of SQLite might change so that an error is
+** raised if any of the disallowed bits are passed into sqlite3_open_v2().
+** Applications should not depend on the historical behavior.
+**
+** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
+** [sqlite3_open_v2()] does *not* cause the underlying database file
+** to be opened using O_EXCL.  Passing SQLITE_OPEN_EXCLUSIVE into
+** [sqlite3_open_v2()] has historically be a no-op and might become an
+** error in future versions of SQLite.
 */
 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
@@ -573,6 +610,7 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
 #define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */
+#define SQLITE_OPEN_EXRESCODE        0x02000000  /* Extended result codes */
 
 /* Reserved:                         0x00F00000 */
 /* Legacy compatibility: */
@@ -1129,6 +1167,23 @@ struct sqlite3_io_methods {
 ** file to the database file, but before the *-shm file is updated to
 ** record the fact that the pages have been checkpointed.
 ** </ul>
+**
+** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
+** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
+** whether or not there is a database client in another process with a wal-mode
+** transaction open on the database or not. It is only available on unix.The
+** (void*) argument passed with this file-control should be a pointer to a
+** value of type (int). The integer value is set to 1 if the database is a wal
+** mode database and there exists at least one client in another process that
+** currently has an SQL transaction open on the database. It is set to 0 if
+** the database is not a wal-mode db, or if there is no such connection in any
+** other process. This opcode cannot be used to detect transactions opened
+** by clients within the current process, only within other processes.
+** </ul>
+**
+** <li>[[SQLITE_FCNTL_CKSM_FILE]]
+** Used by the cksmvfs VFS module only.
+** </ul>
 */
 #define SQLITE_FCNTL_LOCKSTATE               1
 #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
@@ -1168,6 +1223,8 @@ struct sqlite3_io_methods {
 #define SQLITE_FCNTL_CKPT_DONE              37
 #define SQLITE_FCNTL_RESERVE_BYTES          38
 #define SQLITE_FCNTL_CKPT_START             39
+#define SQLITE_FCNTL_EXTERNAL_READER        40
+#define SQLITE_FCNTL_CKSM_FILE              41
 
 /* deprecated names */
 #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
@@ -2446,11 +2503,14 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
 ** CAPI3REF: Count The Number Of Rows Modified
 ** METHOD: sqlite3
 **
-** ^This function returns the number of rows modified, inserted or
+** ^These functions return the number of rows modified, inserted or
 ** deleted by the most recently completed INSERT, UPDATE or DELETE
 ** statement on the database connection specified by the only parameter.
-** ^Executing any other type of SQL statement does not modify the value
-** returned by this function.
+** The two functions are identical except for the type of the return value
+** and that if the number of rows modified by the most recent INSERT, UPDATE
+** or DELETE is greater than the maximum value supported by type "int", then
+** the return value of sqlite3_changes() is undefined. ^Executing any other
+** type of SQL statement does not modify the value returned by these functions.
 **
 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
@@ -2499,16 +2559,21 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
 ** </ul>
 */
 SQLITE_API int sqlite3_changes(sqlite3*);
+SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*);
 
 /*
 ** CAPI3REF: Total Number Of Rows Modified
 ** METHOD: sqlite3
 **
-** ^This function returns the total number of rows inserted, modified or
+** ^These functions return the total number of rows inserted, modified or
 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
 ** since the database connection was opened, including those executed as
-** part of trigger programs. ^Executing any other type of SQL statement
-** does not affect the value returned by sqlite3_total_changes().
+** part of trigger programs. The two functions are identical except for the
+** type of the return value and that if the number of rows modified by the
+** connection exceeds the maximum value supported by type "int", then
+** the return value of sqlite3_total_changes() is undefined. ^Executing
+** any other type of SQL statement does not affect the value returned by
+** sqlite3_total_changes().
 **
 ** ^Changes made as part of [foreign key actions] are included in the
 ** count, but those made as part of REPLACE constraint resolution are
@@ -2536,6 +2601,7 @@ SQLITE_API int sqlite3_changes(sqlite3*);
 ** </ul>
 */
 SQLITE_API int sqlite3_total_changes(sqlite3*);
+SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*);
 
 /*
 ** CAPI3REF: Interrupt A Long-Running Query
@@ -3365,6 +3431,14 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** the default shared cache setting provided by
 ** [sqlite3_enable_shared_cache()].)^
 **
+** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
+** <dd>The database connection comes up in "extended result code mode".
+** In other words, the database behaves has if
+** [sqlite3_extended_result_codes(db,1)] where called on the database
+** connection as soon as the connection is created. In addition to setting
+** the extended result code mode, this flag also causes [sqlite3_open_v2()]
+** to return an extended result code.</dd>
+**
 ** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
 ** <dd>The database filename is not allowed to be a symbolic link</dd>
 ** </dl>)^
@@ -3372,7 +3446,15 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
 ** required combinations shown above optionally combined with other
 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
-** then the behavior is undefined.
+** then the behavior is undefined.  Historic versions of SQLite
+** have silently ignored surplus bits in the flags parameter to
+** sqlite3_open_v2(), however that behavior might not be carried through
+** into future versions of SQLite and so applications should not rely
+** upon it.  Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
+** for sqlite3_open_v2().  The SQLITE_OPEN_EXCLUSIVE does *not* cause
+** the open to fail if the database already exists.  The SQLITE_OPEN_EXCLUSIVE
+** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not
+** by sqlite3_open_v2().
 **
 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
 ** [sqlite3_vfs] object that defines the operating system interface that
@@ -3743,13 +3825,14 @@ SQLITE_API void sqlite3_free_filename(char*);
 ** sqlite3_extended_errcode() might change with each API call.
 ** Except, there are some interfaces that are guaranteed to never
 ** change the value of the error code.  The error-code preserving
-** interfaces are:
+** interfaces include the following:
 **
 ** <ul>
 ** <li> sqlite3_errcode()
 ** <li> sqlite3_extended_errcode()
 ** <li> sqlite3_errmsg()
 ** <li> sqlite3_errmsg16()
+** <li> sqlite3_error_offset()
 ** </ul>
 **
 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
@@ -3764,6 +3847,13 @@ SQLITE_API void sqlite3_free_filename(char*);
 ** ^(Memory to hold the error message string is managed internally
 ** and must not be freed by the application)^.
 **
+** ^If the most recent error references a specific token in the input
+** SQL, the sqlite3_error_offset() interface returns the byte offset
+** of the start of that token.  ^The byte offset returned by
+** sqlite3_error_offset() assumes that the input SQL is UTF8.
+** ^If the most recent error does not reference a specific token in the input
+** SQL, then the sqlite3_error_offset() function returns -1.
+**
 ** When the serialized [threading mode] is in use, it might be the
 ** case that a second error occurs on a separate thread in between
 ** the time of the first error and the call to these interfaces.
@@ -3783,6 +3873,7 @@ SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
 SQLITE_API const char *sqlite3_errstr(int);
+SQLITE_API int sqlite3_error_offset(sqlite3 *db);
 
 /*
 ** CAPI3REF: Prepared Statement Object
@@ -4140,12 +4231,17 @@ SQLITE_API int sqlite3_prepare16_v3(
 ** are managed by SQLite and are automatically freed when the prepared
 ** statement is finalized.
 ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
-** is obtained from [sqlite3_malloc()] and must be free by the application
+** is obtained from [sqlite3_malloc()] and must be freed by the application
 ** by passing it to [sqlite3_free()].
+**
+** ^The sqlite3_normalized_sql() interface is only available if
+** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
 */
 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
 SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
+#ifdef SQLITE_ENABLE_NORMALIZE
 SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
+#endif
 
 /*
 ** CAPI3REF: Determine If An SQL Statement Writes The Database
@@ -4180,6 +4276,19 @@ SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
 ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
 ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
 ** sqlite3_stmt_readonly() returns false for those commands.
+**
+** ^This routine returns false if there is any possibility that the
+** statement might change the database file.  ^A false return does
+** not guarantee that the statement will change the database file.
+** ^For example, an UPDATE statement might have a WHERE clause that
+** makes it a no-op, but the sqlite3_stmt_readonly() result would still
+** be false.  ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
+** read-only no-op if the table already exists, but
+** sqlite3_stmt_readonly() still returns false for such a statement.
+**
+** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN]
+** statement, then sqlite3_stmt_readonly(X) returns the same value as
+** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted.
 */
 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
 
@@ -4248,6 +4357,8 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
 **
 ** ^The sqlite3_value objects that are passed as parameters into the
 ** implementation of [application-defined SQL functions] are protected.
+** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()]
+** are protected.
 ** ^The sqlite3_value object returned by
 ** [sqlite3_column_value()] is unprotected.
 ** Unprotected sqlite3_value objects may only be used as arguments
@@ -4349,18 +4460,22 @@ typedef struct sqlite3_context sqlite3_context;
 ** contain embedded NULs.  The result of expressions involving strings
 ** with embedded NULs is undefined.
 **
-** ^The fifth argument to the BLOB and string binding interfaces
-** is a destructor used to dispose of the BLOB or
-** string after SQLite has finished with it.  ^The destructor is called
-** to dispose of the BLOB or string even if the call to the bind API fails,
-** except the destructor is not called if the third parameter is a NULL
-** pointer or the fourth parameter is negative.
-** ^If the fifth argument is
-** the special value [SQLITE_STATIC], then SQLite assumes that the
-** information is in static, unmanaged space and does not need to be freed.
-** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
-** SQLite makes its own private copy of the data immediately, before
-** the sqlite3_bind_*() routine returns.
+** ^The fifth argument to the BLOB and string binding interfaces controls
+** or indicates the lifetime of the object referenced by the third parameter.
+** These three options exist:
+** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
+** with it may be passed. ^It is called to dispose of the BLOB or string even
+** if the call to the bind API fails, except the destructor is not called if
+** the third parameter is a NULL pointer or the fourth parameter is negative.
+** ^ (2) The special constant, [SQLITE_STATIC], may be passsed to indicate that
+** the application remains responsible for disposing of the object. ^In this
+** case, the object and the provided pointer to it must remain valid until
+** either the prepared statement is finalized or the same SQL parameter is
+** bound to something else, whichever occurs sooner.
+** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the
+** object is to be copied prior to the return from sqlite3_bind_*(). ^The
+** object and pointer to it must remain valid until then. ^SQLite will then
+** manage the lifetime of its private copy.
 **
 ** ^The sixth argument to sqlite3_bind_text64() must be one of
 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
@@ -4865,6 +4980,10 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** even empty strings, are always zero-terminated.  ^The return
 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
 **
+** ^Strings returned by sqlite3_column_text16() always have the endianness
+** which is native to the platform, regardless of the text encoding set
+** for the database.
+**
 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
 ** [unprotected sqlite3_value] object.  In a multithreaded environment,
 ** an unprotected sqlite3_value object may only be used safely with
@@ -4878,7 +4997,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** [application-defined SQL functions] or [virtual tables], not within
 ** top-level application code.
 **
-** The these routines may attempt to convert the datatype of the result.
+** These routines may attempt to convert the datatype of the result.
 ** ^For example, if the internal representation is FLOAT and a text result
 ** is requested, [sqlite3_snprintf()] is used internally to perform the
 ** conversion automatically.  ^(The following table details the conversions
@@ -4903,7 +5022,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
-** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
+** <tr><td>  BLOB    <td>   TEXT    <td> [CAST] to TEXT, ensure zero terminator
 ** </table>
 ** </blockquote>)^
 **
@@ -5102,7 +5221,6 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
 ** index expressions, or the WHERE clause of partial indexes.
 **
-** <span style="background-color:#ffff90;">
 ** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
 ** all application-defined SQL functions that do not need to be
 ** used inside of triggers, view, CHECK constraints, or other elements of
@@ -5112,7 +5230,6 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** a database file to include invocations of the function with parameters
 ** chosen by the attacker, which the application will then execute when
 ** the database file is opened and read.
-** </span>
 **
 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
 ** function can gain access to this pointer using [sqlite3_user_data()].)^
@@ -6318,6 +6435,72 @@ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
 
+/*
+** CAPI3REF: Autovacuum Compaction Amount Callback
+** METHOD: sqlite3
+**
+** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback
+** function C that is invoked prior to each autovacuum of the database
+** file.  ^The callback is passed a copy of the generic data pointer (P),
+** the schema-name of the attached database that is being autovacuumed,
+** the the size of the database file in pages, the number of free pages,
+** and the number of bytes per page, respectively.  The callback should
+** return the number of free pages that should be removed by the
+** autovacuum.  ^If the callback returns zero, then no autovacuum happens.
+** ^If the value returned is greater than or equal to the number of
+** free pages, then a complete autovacuum happens.
+**
+** <p>^If there are multiple ATTACH-ed database files that are being
+** modified as part of a transaction commit, then the autovacuum pages
+** callback is invoked separately for each file.
+**
+** <p><b>The callback is not reentrant.</b> The callback function should
+** not attempt to invoke any other SQLite interface.  If it does, bad
+** things may happen, including segmentation faults and corrupt database
+** files.  The callback function should be a simple function that
+** does some arithmetic on its input parameters and returns a result.
+**
+** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
+** destructor for the P parameter.  ^If X is not NULL, then X(P) is
+** invoked whenever the database connection closes or when the callback
+** is overwritten by another invocation of sqlite3_autovacuum_pages().
+**
+** <p>^There is only one autovacuum pages callback per database connection.
+** ^Each call to the sqlite3_autovacuum_pages() interface overrides all
+** previous invocations for that database connection.  ^If the callback
+** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,
+** then the autovacuum steps callback is cancelled.  The return value
+** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might
+** be some other error code if something goes wrong.  The current
+** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other
+** return codes might be added in future releases.
+**
+** <p>If no autovacuum pages callback is specified (the usual case) or
+** a NULL pointer is provided for the callback,
+** then the default behavior is to vacuum all free pages.  So, in other
+** words, the default behavior is the same as if the callback function
+** were something like this:
+**
+** <blockquote><pre>
+** &nbsp;   unsigned int demonstration_autovac_pages_callback(
+** &nbsp;     void *pClientData,
+** &nbsp;     const char *zSchema,
+** &nbsp;     unsigned int nDbPage,
+** &nbsp;     unsigned int nFreePage,
+** &nbsp;     unsigned int nBytePerPage
+** &nbsp;   ){
+** &nbsp;     return nFreePage;
+** &nbsp;   }
+** </pre></blockquote>
+*/
+SQLITE_API int sqlite3_autovacuum_pages(
+  sqlite3 *db,
+  unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
+  void*,
+  void(*)(void*)
+);
+
+
 /*
 ** CAPI3REF: Data Change Notification Callbacks
 ** METHOD: sqlite3
@@ -6959,24 +7142,56 @@ struct sqlite3_index_info {
 **
 ** These macros define the allowed values for the
 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
-** an operator that is part of a constraint term in the wHERE clause of
+** an operator that is part of a constraint term in the WHERE clause of
 ** a query that uses a [virtual table].
-*/
-#define SQLITE_INDEX_CONSTRAINT_EQ         2
-#define SQLITE_INDEX_CONSTRAINT_GT         4
-#define SQLITE_INDEX_CONSTRAINT_LE         8
-#define SQLITE_INDEX_CONSTRAINT_LT        16
-#define SQLITE_INDEX_CONSTRAINT_GE        32
-#define SQLITE_INDEX_CONSTRAINT_MATCH     64
-#define SQLITE_INDEX_CONSTRAINT_LIKE      65
-#define SQLITE_INDEX_CONSTRAINT_GLOB      66
-#define SQLITE_INDEX_CONSTRAINT_REGEXP    67
-#define SQLITE_INDEX_CONSTRAINT_NE        68
-#define SQLITE_INDEX_CONSTRAINT_ISNOT     69
-#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
-#define SQLITE_INDEX_CONSTRAINT_ISNULL    71
-#define SQLITE_INDEX_CONSTRAINT_IS        72
-#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
+**
+** ^The left-hand operand of the operator is given by the corresponding
+** aConstraint[].iColumn field.  ^An iColumn of -1 indicates the left-hand
+** operand is the rowid.
+** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET
+** operators have no left-hand operand, and so for those operators the
+** corresponding aConstraint[].iColumn is meaningless and should not be
+** used.
+**
+** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through
+** value 255 are reserved to represent functions that are overloaded
+** by the [xFindFunction|xFindFunction method] of the virtual table
+** implementation.
+**
+** The right-hand operands for each constraint might be accessible using
+** the [sqlite3_vtab_rhs_value()] interface.  Usually the right-hand
+** operand is only available if it appears as a single constant literal
+** in the input SQL.  If the right-hand operand is another column or an
+** expression (even a constant expression) or a parameter, then the
+** sqlite3_vtab_rhs_value() probably will not be able to extract it.
+** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and
+** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand
+** and hence calls to sqlite3_vtab_rhs_value() for those operators will
+** always return SQLITE_NOTFOUND.
+**
+** The collating sequence to be used for comparison can be found using
+** the [sqlite3_vtab_collation()] interface.  For most real-world virtual
+** tables, the collating sequence of constraints does not matter (for example
+** because the constraints are numeric) and so the sqlite3_vtab_collation()
+** interface is no commonly needed.
+*/
+#define SQLITE_INDEX_CONSTRAINT_EQ          2
+#define SQLITE_INDEX_CONSTRAINT_GT          4
+#define SQLITE_INDEX_CONSTRAINT_LE          8
+#define SQLITE_INDEX_CONSTRAINT_LT         16
+#define SQLITE_INDEX_CONSTRAINT_GE         32
+#define SQLITE_INDEX_CONSTRAINT_MATCH      64
+#define SQLITE_INDEX_CONSTRAINT_LIKE       65
+#define SQLITE_INDEX_CONSTRAINT_GLOB       66
+#define SQLITE_INDEX_CONSTRAINT_REGEXP     67
+#define SQLITE_INDEX_CONSTRAINT_NE         68
+#define SQLITE_INDEX_CONSTRAINT_ISNOT      69
+#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL  70
+#define SQLITE_INDEX_CONSTRAINT_ISNULL     71
+#define SQLITE_INDEX_CONSTRAINT_IS         72
+#define SQLITE_INDEX_CONSTRAINT_LIMIT      73
+#define SQLITE_INDEX_CONSTRAINT_OFFSET     74
+#define SQLITE_INDEX_CONSTRAINT_FUNCTION  150
 
 /*
 ** CAPI3REF: Register A Virtual Table Implementation
@@ -7005,7 +7220,7 @@ struct sqlite3_index_info {
 ** destructor.
 **
 ** ^If the third parameter (the pointer to the sqlite3_module object) is
-** NULL then no new module is create and any existing modules with the
+** NULL then no new module is created and any existing modules with the
 ** same name are dropped.
 **
 ** See also: [sqlite3_drop_modules()]
@@ -7780,7 +7995,9 @@ SQLITE_API int sqlite3_test_control(int op, ...);
 #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
 #define SQLITE_TESTCTRL_SEEK_COUNT              30
 #define SQLITE_TESTCTRL_TRACEFLAGS              31
-#define SQLITE_TESTCTRL_LAST                    31  /* Largest TESTCTRL */
+#define SQLITE_TESTCTRL_TUNE                    32
+#define SQLITE_TESTCTRL_LOGEST                  33
+#define SQLITE_TESTCTRL_LAST                    33  /* Largest TESTCTRL */
 
 /*
 ** CAPI3REF: SQL Keyword Checking
@@ -8303,6 +8520,16 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 ** The counter is incremented on the first [sqlite3_step()] call of each
 ** cycle.
 **
+** [[SQLITE_STMTSTATUS_FILTER_MISS]]
+** [[SQLITE_STMTSTATUS_FILTER HIT]]
+** <dt>SQLITE_STMTSTATUS_FILTER_HIT<br>
+** SQLITE_STMTSTATUS_FILTER_MISS</dt>
+** <dd>^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join
+** step was bypassed because a Bloom filter returned not-found.  The
+** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of
+** times that the Bloom filter returned a find, and thus the join step
+** had to be processed as normal.
+**
 ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
 ** <dd>^This is the approximate number of bytes of heap memory
 ** used to store the prepared statement.  ^This value is not actually
@@ -8317,6 +8544,8 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 #define SQLITE_STMTSTATUS_VM_STEP           4
 #define SQLITE_STMTSTATUS_REPREPARE         5
 #define SQLITE_STMTSTATUS_RUN               6
+#define SQLITE_STMTSTATUS_FILTER_MISS       7
+#define SQLITE_STMTSTATUS_FILTER_HIT        8
 #define SQLITE_STMTSTATUS_MEMUSED           99
 
 /*
@@ -8980,8 +9209,9 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 **
 ** A single database handle may have at most a single write-ahead log callback
 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
-** previously registered write-ahead log callback. ^Note that the
-** [sqlite3_wal_autocheckpoint()] interface and the
+** previously registered write-ahead log callback. ^The return value is
+** a copy of the third parameter from the previous call, if any, or 0.
+** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the
 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
 ** overwrite any prior [sqlite3_wal_hook()] settings.
 */
@@ -9284,19 +9514,269 @@ SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
 
 /*
 ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
+** METHOD: sqlite3_index_info
 **
 ** This function may only be called from within a call to the [xBestIndex]
-** method of a [virtual table].
+** method of a [virtual table].  This function returns a pointer to a string
+** that is the name of the appropriate collation sequence to use for text
+** comparisons on the constraint identified by its arguments.
+**
+** The first argument must be the pointer to the [sqlite3_index_info] object
+** that is the first parameter to the xBestIndex() method. The second argument
+** must be an index into the aConstraint[] array belonging to the
+** sqlite3_index_info structure passed to xBestIndex.
+**
+** Important:
+** The first parameter must be the same pointer that is passed into the
+** xBestMethod() method.  The first parameter may not be a pointer to a
+** different [sqlite3_index_info] object, even an exact copy.
 **
-** The first argument must be the sqlite3_index_info object that is the
-** first parameter to the xBestIndex() method. The second argument must be
-** an index into the aConstraint[] array belonging to the sqlite3_index_info
-** structure passed to xBestIndex. This function returns a pointer to a buffer
-** containing the name of the collation sequence for the corresponding
-** constraint.
+** The return value is computed as follows:
+**
+** <ol>
+** <li><p> If the constraint comes from a WHERE clause expression that contains
+**         a [COLLATE operator], then the name of the collation specified by
+**         that COLLATE operator is returned.
+** <li><p> If there is no COLLATE operator, but the column that is the subject
+**         of the constraint specifies an alternative collating sequence via
+**         a [COLLATE clause] on the column definition within the CREATE TABLE
+**         statement that was passed into [sqlite3_declare_vtab()], then the
+**         name of that alternative collating sequence is returned.
+** <li><p> Otherwise, "BINARY" is returned.
+** </ol>
 */
 SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
 
+/*
+** CAPI3REF: Determine if a virtual table query is DISTINCT
+** METHOD: sqlite3_index_info
+**
+** This API may only be used from within an [xBestIndex|xBestIndex method]
+** of a [virtual table] implementation. The result of calling this
+** interface from outside of xBestIndex() is undefined and probably harmful.
+**
+** ^The sqlite3_vtab_distinct() interface returns an integer that is
+** either 0, 1, or 2.  The integer returned by sqlite3_vtab_distinct()
+** gives the virtual table additional information about how the query
+** planner wants the output to be ordered. As long as the virtual table
+** can meet the ordering requirements of the query planner, it may set
+** the "orderByConsumed" flag.
+**
+** <ol><li value="0"><p>
+** ^If the sqlite3_vtab_distinct() interface returns 0, that means
+** that the query planner needs the virtual table to return all rows in the
+** sort order defined by the "nOrderBy" and "aOrderBy" fields of the
+** [sqlite3_index_info] object.  This is the default expectation.  If the
+** virtual table outputs all rows in sorted order, then it is always safe for
+** the xBestIndex method to set the "orderByConsumed" flag, regardless of
+** the return value from sqlite3_vtab_distinct().
+** <li value="1"><p>
+** ^(If the sqlite3_vtab_distinct() interface returns 1, that means
+** that the query planner does not need the rows to be returned in sorted order
+** as long as all rows with the same values in all columns identified by the
+** "aOrderBy" field are adjacent.)^  This mode is used when the query planner
+** is doing a GROUP BY.
+** <li value="2"><p>
+** ^(If the sqlite3_vtab_distinct() interface returns 2, that means
+** that the query planner does not need the rows returned in any particular
+** order, as long as rows with the same values in all "aOrderBy" columns
+** are adjacent.)^  ^(Furthermore, only a single row for each particular
+** combination of values in the columns identified by the "aOrderBy" field
+** needs to be returned.)^  ^It is always ok for two or more rows with the same
+** values in all "aOrderBy" columns to be returned, as long as all such rows
+** are adjacent.  ^The virtual table may, if it chooses, omit extra rows
+** that have the same value for all columns identified by "aOrderBy".
+** ^However omitting the extra rows is optional.
+** This mode is used for a DISTINCT query.
+** </ol>
+**
+** ^For the purposes of comparing virtual table output values to see if the
+** values are same value for sorting purposes, two NULL values are considered
+** to be the same.  In other words, the comparison operator is "IS"
+** (or "IS NOT DISTINCT FROM") and not "==".
+**
+** If a virtual table implementation is unable to meet the requirements
+** specified above, then it must not set the "orderByConsumed" flag in the
+** [sqlite3_index_info] object or an incorrect answer may result.
+**
+** ^A virtual table implementation is always free to return rows in any order
+** it wants, as long as the "orderByConsumed" flag is not set.  ^When the
+** the "orderByConsumed" flag is unset, the query planner will add extra
+** [bytecode] to ensure that the final results returned by the SQL query are
+** ordered correctly.  The use of the "orderByConsumed" flag and the
+** sqlite3_vtab_distinct() interface is merely an optimization.  ^Careful
+** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed"
+** flag might help queries against a virtual table to run faster.  Being
+** overly aggressive and setting the "orderByConsumed" flag when it is not
+** valid to do so, on the other hand, might cause SQLite to return incorrect
+** results.
+*/
+SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*);
+
+/*
+** CAPI3REF: Identify and handle IN constraints in xBestIndex
+**
+** This interface may only be used from within an
+** [xBestIndex|xBestIndex() method] of a [virtual table] implementation.
+** The result of invoking this interface from any other context is
+** undefined and probably harmful.
+**
+** ^(A constraint on a virtual table of the form
+** "[IN operator|column IN (...)]" is
+** communicated to the xBestIndex method as a
+** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^  If xBestIndex wants to use
+** this constraint, it must set the corresponding
+** aConstraintUsage[].argvIndex to a postive integer.  ^(Then, under
+** the usual mode of handling IN operators, SQLite generates [bytecode]
+** that invokes the [xFilter|xFilter() method] once for each value
+** on the right-hand side of the IN operator.)^  Thus the virtual table
+** only sees a single value from the right-hand side of the IN operator
+** at a time.
+**
+** In some cases, however, it would be advantageous for the virtual
+** table to see all values on the right-hand of the IN operator all at
+** once.  The sqlite3_vtab_in() interfaces facilitates this in two ways:
+**
+** <ol>
+** <li><p>
+**   ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)
+**   if and only if the [sqlite3_index_info|P->aConstraint][N] constraint
+**   is an [IN operator] that can be processed all at once.  ^In other words,
+**   sqlite3_vtab_in() with -1 in the third argument is a mechanism
+**   by which the virtual table can ask SQLite if all-at-once processing
+**   of the IN operator is even possible.
+**
+** <li><p>
+**   ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates
+**   to SQLite that the virtual table does or does not want to process
+**   the IN operator all-at-once, respectively.  ^Thus when the third
+**   parameter (F) is non-negative, this interface is the mechanism by
+**   which the virtual table tells SQLite how it wants to process the
+**   IN operator.
+** </ol>
+**
+** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times
+** within the same xBestIndex method call.  ^For any given P,N pair,
+** the return value from sqlite3_vtab_in(P,N,F) will always be the same
+** within the same xBestIndex call.  ^If the interface returns true
+** (non-zero), that means that the constraint is an IN operator
+** that can be processed all-at-once.  ^If the constraint is not an IN
+** operator or cannot be processed all-at-once, then the interface returns
+** false.
+**
+** ^(All-at-once processing of the IN operator is selected if both of the
+** following conditions are met:
+**
+** <ol>
+** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive
+** integer.  This is how the virtual table tells SQLite that it wants to
+** use the N-th constraint.
+**
+** <li><p> The last call to sqlite3_vtab_in(P,N,F) for which F was
+** non-negative had F>=1.
+** </ol>)^
+**
+** ^If either or both of the conditions above are false, then SQLite uses
+** the traditional one-at-a-time processing strategy for the IN constraint.
+** ^If both conditions are true, then the argvIndex-th parameter to the
+** xFilter method will be an [sqlite3_value] that appears to be NULL,
+** but which can be passed to [sqlite3_vtab_in_first()] and
+** [sqlite3_vtab_in_next()] to find all values on the right-hand side
+** of the IN constraint.
+*/
+SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);
+
+/*
+** CAPI3REF: Find all elements on the right-hand side of an IN constraint.
+**
+** These interfaces are only useful from within the
+** [xFilter|xFilter() method] of a [virtual table] implementation.
+** The result of invoking these interfaces from any other context
+** is undefined and probably harmful.
+**
+** The X parameter in a call to sqlite3_vtab_in_first(X,P) or
+** sqlite3_vtab_in_next(X,P) must be one of the parameters to the
+** xFilter method which invokes these routines, and specifically
+** a parameter that was previously selected for all-at-once IN constraint
+** processing use the [sqlite3_vtab_in()] interface in the
+** [xBestIndex|xBestIndex method].  ^(If the X parameter is not
+** an xFilter argument that was selected for all-at-once IN constraint
+** processing, then these routines return [SQLITE_MISUSE])^ or perhaps
+** exhibit some other undefined or harmful behavior.
+**
+** ^(Use these routines to access all values on the right-hand side
+** of the IN constraint using code like the following:
+**
+** <blockquote><pre>
+** &nbsp;  for(rc=sqlite3_vtab_in_first(pList, &pVal);
+** &nbsp;      rc==SQLITE_OK && pVal
+** &nbsp;      rc=sqlite3_vtab_in_next(pList, &pVal)
+** &nbsp;  ){
+** &nbsp;    // do something with pVal
+** &nbsp;  }
+** &nbsp;  if( rc!=SQLITE_OK ){
+** &nbsp;    // an error has occurred
+** &nbsp;  }
+** </pre></blockquote>)^
+**
+** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P)
+** routines return SQLITE_OK and set *P to point to the first or next value
+** on the RHS of the IN constraint.  ^If there are no more values on the
+** right hand side of the IN constraint, then *P is set to NULL and these
+** routines return [SQLITE_DONE].  ^The return value might be
+** some other value, such as SQLITE_NOMEM, in the event of a malfunction.
+**
+** The *ppOut values returned by these routines are only valid until the
+** next call to either of these routines or until the end of the xFilter
+** method from which these routines were called.  If the virtual table
+** implementation needs to retain the *ppOut values for longer, it must make
+** copies.  The *ppOut values are [protected sqlite3_value|protected].
+*/
+SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut);
+SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);
+
+/*
+** CAPI3REF: Constraint values in xBestIndex()
+** METHOD: sqlite3_index_info
+**
+** This API may only be used from within the [xBestIndex|xBestIndex method]
+** of a [virtual table] implementation. The result of calling this interface
+** from outside of an xBestIndex method are undefined and probably harmful.
+**
+** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within
+** the [xBestIndex] method of a [virtual table] implementation, with P being
+** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and
+** J being a 0-based index into P->aConstraint[], then this routine
+** attempts to set *V to the value of the right-hand operand of
+** that constraint if the right-hand operand is known.  ^If the
+** right-hand operand is not known, then *V is set to a NULL pointer.
+** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if
+** and only if *V is set to a value.  ^The sqlite3_vtab_rhs_value(P,J,V)
+** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th
+** constraint is not available.  ^The sqlite3_vtab_rhs_value() interface
+** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if
+** something goes wrong.
+**
+** The sqlite3_vtab_rhs_value() interface is usually only successful if
+** the right-hand operand of a constraint is a literal value in the original
+** SQL statement.  If the right-hand operand is an expression or a reference
+** to some other column or a [host parameter], then sqlite3_vtab_rhs_value()
+** will probably return [SQLITE_NOTFOUND].
+**
+** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and
+** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand.  For such
+** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^
+**
+** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value
+** and remains valid for the duration of the xBestIndex method call.
+** ^When xBestIndex returns, the sqlite3_value object returned by
+** sqlite3_vtab_rhs_value() is automatically deallocated.
+**
+** The "_rhs_" in the name of this routine is an abbreviation for
+** "Right-Hand Side".
+*/
+SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal);
+
 /*
 ** CAPI3REF: Conflict resolution modes
 ** KEYWORDS: {conflict resolution mode}
@@ -9532,6 +10012,15 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 ** triggers; or 2 for changes resulting from triggers called by top-level
 ** triggers; and so forth.
 **
+** When the [sqlite3_blob_write()] API is used to update a blob column,
+** the pre-update hook is invoked with SQLITE_DELETE. This is because the
+** in this case the new values are not available. In this case, when a
+** callback made with op==SQLITE_DELETE is actuall a write using the
+** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns
+** the index of the column being written. In other cases, where the
+** pre-update hook is being invoked for some other reason, including a
+** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
+**
 ** See also:  [sqlite3_update_hook()]
 */
 #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
@@ -9552,6 +10041,7 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
 SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
 SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
 SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
+SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *);
 #endif
 
 /*
@@ -9790,8 +10280,8 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c
 ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
 ** allocation error occurs.
 **
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_DESERIALIZE] option.
+** This interface is omitted if SQLite is compiled with the
+** [SQLITE_OMIT_DESERIALIZE] option.
 */
 SQLITE_API unsigned char *sqlite3_serialize(
   sqlite3 *db,           /* The database connection */
@@ -9838,12 +10328,16 @@ SQLITE_API unsigned char *sqlite3_serialize(
 ** database is currently in a read transaction or is involved in a backup
 ** operation.
 **
+** It is not possible to deserialized into the TEMP database.  If the
+** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
+** function returns SQLITE_ERROR.
+**
 ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
 ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
 ** [sqlite3_free()] is invoked on argument P prior to returning.
 **
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_DESERIALIZE] option.
+** This interface is omitted if SQLite is compiled with the
+** [SQLITE_OMIT_DESERIALIZE] option.
 */
 SQLITE_API int sqlite3_deserialize(
   sqlite3 *db,            /* The database connection */
@@ -10092,6 +10586,38 @@ SQLITE_API int sqlite3session_create(
 */
 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
 
+/*
+** CAPIREF: Conigure a Session Object
+** METHOD: sqlite3_session
+**
+** This method is used to configure a session object after it has been
+** created. At present the only valid value for the second parameter is
+** [SQLITE_SESSION_OBJCONFIG_SIZE].
+**
+** Arguments for sqlite3session_object_config()
+**
+** The following values may passed as the the 4th parameter to
+** sqlite3session_object_config().
+**
+** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
+**   This option is used to set, clear or query the flag that enables
+**   the [sqlite3session_changeset_size()] API. Because it imposes some
+**   computational overhead, this API is disabled by default. Argument
+**   pArg must point to a value of type (int). If the value is initially
+**   0, then the sqlite3session_changeset_size() API is disabled. If it
+**   is greater than 0, then the same API is enabled. Or, if the initial
+**   value is less than zero, no change is made. In all cases the (int)
+**   variable is set to 1 if the sqlite3session_changeset_size() API is
+**   enabled following the current call, or 0 otherwise.
+**
+**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
+**   the first table has been attached to the session object.
+*/
+SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);
+
+/*
+*/
+#define SQLITE_SESSION_OBJCONFIG_SIZE 1
 
 /*
 ** CAPI3REF: Enable Or Disable A Session Object
@@ -10336,6 +10862,22 @@ SQLITE_API int sqlite3session_changeset(
   void **ppChangeset              /* OUT: Buffer containing changeset */
 );
 
+/*
+** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
+** METHOD: sqlite3_session
+**
+** By default, this function always returns 0. For it to return
+** a useful result, the sqlite3_session object must have been configured
+** to enable this API using sqlite3session_object_config() with the
+** SQLITE_SESSION_OBJCONFIG_SIZE verb.
+**
+** When enabled, this function returns an upper limit, in bytes, for the size
+** of the changeset that might be produced if sqlite3session_changeset() were
+** called. The final changeset size might be equal to or smaller than the
+** size in bytes returned by this function.
+*/
+SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession);
+
 /*
 ** CAPI3REF: Load The Difference Between Tables Into A Session
 ** METHOD: sqlite3_session
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3.go b/vendor/github.com/mattn/go-sqlite3/sqlite3.go
index 5ac9570..e037857 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3.go
@@ -4,6 +4,7 @@
 // Use of this source code is governed by an MIT-style
 // license that can be found in the LICENSE file.
 
+//go:build cgo
 // +build cgo
 
 package sqlite3
@@ -21,8 +22,10 @@ package sqlite3
 #cgo CFLAGS: -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT
 #cgo CFLAGS: -Wno-deprecated-declarations
 #cgo linux,!android CFLAGS: -DHAVE_PREAD64=1 -DHAVE_PWRITE64=1
+#cgo openbsd CFLAGS: -I/usr/local/include
+#cgo openbsd LDFLAGS: -L/usr/local/lib
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
@@ -231,8 +234,14 @@ const (
 	columnTimestamp string = "timestamp"
 )
 
+// This variable can be replaced with -ldflags like below:
+// go build -ldflags="-X 'github.com/mattn/go-sqlite3.driverName=my-sqlite3'"
+var driverName = "sqlite3"
+
 func init() {
-	sql.Register("sqlite3", &SQLiteDriver{})
+	if driverName != "" {
+		sql.Register(driverName, &SQLiteDriver{})
+	}
 }
 
 // Version returns SQLite library version information.
@@ -288,6 +297,51 @@ const (
 	/*SQLITE_RECURSIVE           = C.SQLITE_RECURSIVE*/
 )
 
+// Standard File Control Opcodes
+// See: https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html
+const (
+	SQLITE_FCNTL_LOCKSTATE             = int(1)
+	SQLITE_FCNTL_GET_LOCKPROXYFILE     = int(2)
+	SQLITE_FCNTL_SET_LOCKPROXYFILE     = int(3)
+	SQLITE_FCNTL_LAST_ERRNO            = int(4)
+	SQLITE_FCNTL_SIZE_HINT             = int(5)
+	SQLITE_FCNTL_CHUNK_SIZE            = int(6)
+	SQLITE_FCNTL_FILE_POINTER          = int(7)
+	SQLITE_FCNTL_SYNC_OMITTED          = int(8)
+	SQLITE_FCNTL_WIN32_AV_RETRY        = int(9)
+	SQLITE_FCNTL_PERSIST_WAL           = int(10)
+	SQLITE_FCNTL_OVERWRITE             = int(11)
+	SQLITE_FCNTL_VFSNAME               = int(12)
+	SQLITE_FCNTL_POWERSAFE_OVERWRITE   = int(13)
+	SQLITE_FCNTL_PRAGMA                = int(14)
+	SQLITE_FCNTL_BUSYHANDLER           = int(15)
+	SQLITE_FCNTL_TEMPFILENAME          = int(16)
+	SQLITE_FCNTL_MMAP_SIZE             = int(18)
+	SQLITE_FCNTL_TRACE                 = int(19)
+	SQLITE_FCNTL_HAS_MOVED             = int(20)
+	SQLITE_FCNTL_SYNC                  = int(21)
+	SQLITE_FCNTL_COMMIT_PHASETWO       = int(22)
+	SQLITE_FCNTL_WIN32_SET_HANDLE      = int(23)
+	SQLITE_FCNTL_WAL_BLOCK             = int(24)
+	SQLITE_FCNTL_ZIPVFS                = int(25)
+	SQLITE_FCNTL_RBU                   = int(26)
+	SQLITE_FCNTL_VFS_POINTER           = int(27)
+	SQLITE_FCNTL_JOURNAL_POINTER       = int(28)
+	SQLITE_FCNTL_WIN32_GET_HANDLE      = int(29)
+	SQLITE_FCNTL_PDB                   = int(30)
+	SQLITE_FCNTL_BEGIN_ATOMIC_WRITE    = int(31)
+	SQLITE_FCNTL_COMMIT_ATOMIC_WRITE   = int(32)
+	SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = int(33)
+	SQLITE_FCNTL_LOCK_TIMEOUT          = int(34)
+	SQLITE_FCNTL_DATA_VERSION          = int(35)
+	SQLITE_FCNTL_SIZE_LIMIT            = int(36)
+	SQLITE_FCNTL_CKPT_DONE             = int(37)
+	SQLITE_FCNTL_RESERVE_BYTES         = int(38)
+	SQLITE_FCNTL_CKPT_START            = int(39)
+	SQLITE_FCNTL_EXTERNAL_READER       = int(40)
+	SQLITE_FCNTL_CKSM_FILE             = int(41)
+)
+
 // SQLiteDriver implements driver.Driver.
 type SQLiteDriver struct {
 	Extensions  []string
@@ -828,6 +882,10 @@ func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue)
 		tail := s.(*SQLiteStmt).t
 		s.Close()
 		if tail == "" {
+			if res == nil {
+				// https://github.com/mattn/go-sqlite3/issues/963
+				res = &SQLiteResult{0, 0}
+			}
 			return res, nil
 		}
 		query = tail
@@ -1409,12 +1467,6 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
 		return nil, errors.New("sqlite succeeded without returning a database")
 	}
 
-	rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
-	if rv != C.SQLITE_OK {
-		C.sqlite3_close_v2(db)
-		return nil, Error{Code: ErrNo(rv)}
-	}
-
 	exec := func(s string) error {
 		cs := C.CString(s)
 		rv := C.sqlite3_exec(db, cs, nil, nil, nil)
@@ -1425,6 +1477,12 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
 		return nil
 	}
 
+	// Busy timeout
+	if err := exec(fmt.Sprintf("PRAGMA busy_timeout = %d;", busyTimeout)); err != nil {
+		C.sqlite3_close_v2(db)
+		return nil, err
+	}
+
 	// USER AUTHENTICATION
 	//
 	// User Authentication is always performed even when
@@ -1800,6 +1858,31 @@ func (c *SQLiteConn) SetLimit(id int, newVal int) int {
 	return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
 }
 
+// SetFileControlInt invokes the xFileControl method on a given database. The
+// dbName is the name of the database. It will default to "main" if left blank.
+// The op is one of the opcodes prefixed by "SQLITE_FCNTL_". The arg argument
+// and return code are both opcode-specific. Please see the SQLite documentation.
+//
+// This method is not thread-safe as the returned error code can be changed by
+// another call if invoked concurrently.
+//
+// See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html
+func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error {
+	if dbName == "" {
+		dbName = "main"
+	}
+
+	cDBName := C.CString(dbName)
+	defer C.free(unsafe.Pointer(cDBName))
+
+	cArg := C.int(arg)
+	rv := C.sqlite3_file_control(c.db, cDBName, C.int(op), unsafe.Pointer(&cArg))
+	if rv != C.SQLITE_OK {
+		return c.lastError()
+	}
+	return nil
+}
+
 // Close the statement.
 func (s *SQLiteStmt) Close() error {
 	s.mu.Lock()
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go
index 90800fe..7c7431d 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go
@@ -8,7 +8,7 @@ package sqlite3
 /*
 
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go
index f241819..9433fea 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go
@@ -9,7 +9,7 @@ package sqlite3
 
 /*
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_json1.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_json1.go
deleted file mode 100644
index 7cfce76..0000000
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_json1.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// +build sqlite_json sqlite_json1 json1
-
-package sqlite3
-
-/*
-#cgo CFLAGS: -DSQLITE_ENABLE_JSON1
-*/
-import "C"
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go
index db7a666..b43e482 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go
@@ -13,7 +13,7 @@ package sqlite3
 #cgo LDFLAGS: -lm
 
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
@@ -33,7 +33,7 @@ import (
 // The callback is passed a SQLitePreUpdateData struct with the data for
 // the update, as well as methods for fetching copies of impacted data.
 //
-// If there is an existing update hook for this connection, it will be
+// If there is an existing preupdate hook for this connection, it will be
 // removed. If callback is nil the existing hook (if any) will be removed
 // without creating a new one.
 func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData)) {
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_omit.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_omit.go
index 8df453d..c510a15 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_omit.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_omit.go
@@ -13,7 +13,7 @@ package sqlite3
 // The callback is passed a SQLitePreUpdateData struct with the data for
 // the update, as well as methods for fetching copies of impacted data.
 //
-// If there is an existing update hook for this connection, it will be
+// If there is an existing preupdate hook for this connection, it will be
 // removed. If callback is nil the existing hook (if any) will be removed
 // without creating a new one.
 func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData)) {
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.c b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.c
index 1af1726..fc37b33 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.c
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.c
@@ -5,7 +5,7 @@
 
 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 #include <stdio.h>
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 
 extern int unlock_notify_wait(sqlite3 *db);
 
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go
index 43f53e8..adfa26c 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go
@@ -12,7 +12,7 @@ package sqlite3
 #cgo CFLAGS: -DSQLITE_ENABLE_UNLOCK_NOTIFY
 
 #include <stdlib.h>
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 
 extern void unlock_notify_callback(void *arg, int argc);
 */
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go
index 94203b3..b62b608 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go
@@ -11,7 +11,7 @@ package sqlite3
 #cgo CFLAGS: -DSQLITE_USER_AUTHENTICATION
 #cgo LDFLAGS: -lm
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go
index 8fd6cdf..4a93c46 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go
@@ -19,7 +19,7 @@ package sqlite3
 #cgo CFLAGS: -Wno-deprecated-declarations
 
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
@@ -472,10 +472,21 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
 	}
 
 	info.idxNum = C.int(res.IdxNum)
-	idxStr := C.CString(res.IdxStr)
-	defer C.free(unsafe.Pointer(idxStr))
-	info.idxStr = idxStr
-	info.needToFreeIdxStr = C.int(0)
+	info.idxStr = (*C.char)(C.sqlite3_malloc(C.int(len(res.IdxStr) + 1)))
+	if info.idxStr == nil {
+		// C.malloc and C.CString ordinarily do this for you. See https://golang.org/cmd/cgo/
+		panic("out of memory")
+	}
+	info.needToFreeIdxStr = C.int(1)
+
+	idxStr := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
+		Data: uintptr(unsafe.Pointer(info.idxStr)),
+		Len:  len(res.IdxStr) + 1,
+		Cap:  len(res.IdxStr) + 1,
+	}))
+	copy(idxStr, res.IdxStr)
+	idxStr[len(idxStr)-1] = 0 // null-terminated string
+
 	if res.AlreadyOrdered {
 		info.orderByConsumed = C.int(1)
 	}
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go
index 4c8d992..56bb914 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go
@@ -9,7 +9,7 @@ package sqlite3
 
 /*
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go
index b4128db..0fd8210 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go
@@ -1,5 +1,4 @@
 // Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
-//
 // Use of this source code is governed by an MIT-style
 // license that can be found in the LICENSE file.
 
@@ -7,15 +6,16 @@ package sqlite3
 
 /*
 #ifndef USE_LIBSQLITE3
-#include <sqlite3-binding.h>
+#include "sqlite3-binding.h"
 #else
 #include <sqlite3.h>
 #endif
 */
 import "C"
 import (
+	"database/sql"
 	"reflect"
-	"time"
+	"strings"
 )
 
 // ColumnTypeDatabaseTypeName implement RowsColumnTypeDatabaseTypeName.
@@ -31,32 +31,78 @@ func (rc *SQLiteRows) ColumnTypeLength(index int) (length int64, ok bool) {
 func (rc *SQLiteRows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
 	return 0, 0, false
 }
+*/
 
 // ColumnTypeNullable implement RowsColumnTypeNullable.
 func (rc *SQLiteRows) ColumnTypeNullable(i int) (nullable, ok bool) {
-	return false, false
+	return true, true
 }
-*/
 
 // ColumnTypeScanType implement RowsColumnTypeScanType.
 func (rc *SQLiteRows) ColumnTypeScanType(i int) reflect.Type {
-	switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
-	case C.SQLITE_INTEGER:
-		switch C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))) {
-		case "timestamp", "datetime", "date":
-			return reflect.TypeOf(time.Time{})
-		case "boolean":
-			return reflect.TypeOf(false)
-		}
-		return reflect.TypeOf(int64(0))
-	case C.SQLITE_FLOAT:
-		return reflect.TypeOf(float64(0))
-	case C.SQLITE_BLOB:
-		return reflect.SliceOf(reflect.TypeOf(byte(0)))
-	case C.SQLITE_NULL:
-		return reflect.TypeOf(nil)
-	case C.SQLITE_TEXT:
-		return reflect.TypeOf("")
-	}
-	return reflect.SliceOf(reflect.TypeOf(byte(0)))
+	//ct := C.sqlite3_column_type(rc.s.s, C.int(i))  // Always returns 5
+	return scanType(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
+}
+
+const (
+	SQLITE_INTEGER = iota
+	SQLITE_TEXT
+	SQLITE_BLOB
+	SQLITE_REAL
+	SQLITE_NUMERIC
+	SQLITE_TIME
+	SQLITE_BOOL
+	SQLITE_NULL
+)
+
+func scanType(cdt string) reflect.Type {
+	t := strings.ToUpper(cdt)
+	i := databaseTypeConvSqlite(t)
+	switch i {
+	case SQLITE_INTEGER:
+		return reflect.TypeOf(sql.NullInt64{})
+	case SQLITE_TEXT:
+		return reflect.TypeOf(sql.NullString{})
+	case SQLITE_BLOB:
+		return reflect.TypeOf(sql.RawBytes{})
+	case SQLITE_REAL:
+		return reflect.TypeOf(sql.NullFloat64{})
+	case SQLITE_NUMERIC:
+		return reflect.TypeOf(sql.NullFloat64{})
+	case SQLITE_BOOL:
+		return reflect.TypeOf(sql.NullBool{})
+	case SQLITE_TIME:
+		return reflect.TypeOf(sql.NullTime{})
+	}
+	return reflect.TypeOf(new(interface{}))
+}
+
+func databaseTypeConvSqlite(t string) int {
+	if strings.Contains(t, "INT") {
+		return SQLITE_INTEGER
+	}
+	if t == "CLOB" || t == "TEXT" ||
+		strings.Contains(t, "CHAR") {
+		return SQLITE_TEXT
+	}
+	if t == "BLOB" {
+		return SQLITE_BLOB
+	}
+	if t == "REAL" || t == "FLOAT" ||
+		strings.Contains(t, "DOUBLE") {
+		return SQLITE_REAL
+	}
+	if t == "DATE" || t == "DATETIME" ||
+		t == "TIMESTAMP" {
+		return SQLITE_TIME
+	}
+	if t == "NUMERIC" ||
+		strings.Contains(t, "DECIMAL") {
+		return SQLITE_NUMERIC
+	}
+	if t == "BOOLEAN" {
+		return SQLITE_BOOL
+	}
+
+	return SQLITE_NULL
 }
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3ext.h b/vendor/github.com/mattn/go-sqlite3/sqlite3ext.h
index b2b6e0c..301cba6 100644
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3ext.h
+++ b/vendor/github.com/mattn/go-sqlite3/sqlite3ext.h
@@ -19,6 +19,10 @@
 #ifndef SQLITE3EXT_H
 #define SQLITE3EXT_H
 #include "sqlite3-binding.h"
+#ifdef __clang__
+#define assert(condition) ((void)0)
+#endif
+
 
 /*
 ** The following structure holds pointers to all of the SQLite API
@@ -338,6 +342,20 @@ struct sqlite3_api_routines {
   sqlite3_file *(*database_file_object)(const char*);
   /* Version 3.34.0 and later */
   int (*txn_state)(sqlite3*,const char*);
+  /* Version 3.36.1 and later */
+  sqlite3_int64 (*changes64)(sqlite3*);
+  sqlite3_int64 (*total_changes64)(sqlite3*);
+  /* Version 3.37.0 and later */
+  int (*autovacuum_pages)(sqlite3*,
+     unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
+     void*, void(*)(void*));
+  /* Version 3.38.0 and later */
+  int (*error_offset)(sqlite3*);
+  int (*vtab_rhs_value)(sqlite3_index_info*,int,sqlite3_value**);
+  int (*vtab_distinct)(sqlite3_index_info*);
+  int (*vtab_in)(sqlite3_index_info*,int,int);
+  int (*vtab_in_first)(sqlite3_value*,sqlite3_value**);
+  int (*vtab_in_next)(sqlite3_value*,sqlite3_value**);
 };
 
 /*
@@ -644,6 +662,18 @@ typedef int (*sqlite3_loadext_entry)(
 #define sqlite3_database_file_object   sqlite3_api->database_file_object
 /* Version 3.34.0 and later */
 #define sqlite3_txn_state              sqlite3_api->txn_state
+/* Version 3.36.1 and later */
+#define sqlite3_changes64              sqlite3_api->changes64
+#define sqlite3_total_changes64        sqlite3_api->total_changes64
+/* Version 3.37.0 and later */
+#define sqlite3_autovacuum_pages       sqlite3_api->autovacuum_pages
+/* Version 3.38.0 and later */
+#define sqlite3_error_offset           sqlite3_api->error_offset
+#define sqlite3_vtab_rhs_value         sqlite3_api->vtab_rhs_value
+#define sqlite3_vtab_distinct          sqlite3_api->vtab_distinct
+#define sqlite3_vtab_in                sqlite3_api->vtab_in
+#define sqlite3_vtab_in_first          sqlite3_api->vtab_in_first
+#define sqlite3_vtab_in_next           sqlite3_api->vtab_in_next
 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
 
 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
diff --git a/vendor/modules.txt b/vendor/modules.txt
index d27039d..fe6d049 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -49,7 +49,7 @@ github.com/grpc-ecosystem/go-grpc-prometheus
 github.com/hashicorp/errwrap
 # github.com/hashicorp/go-multierror v1.1.0
 github.com/hashicorp/go-multierror
-# github.com/mattn/go-sqlite3 v1.14.7
+# github.com/mattn/go-sqlite3 v1.14.14
 ## explicit
 github.com/mattn/go-sqlite3
 # github.com/matttproud/golang_protobuf_extensions v1.0.1
-- 
GitLab