Radish alpha
H
rad:z3QDZAW2FAfuLvihrhiyDC9fAD8G9
HardenedBSD Package Manager
Radicle
Git
sqlite: update to 3.44.2
Baptiste Daroussin committed 2 years ago
commit 721a02833a841471f02a349ecb1c85b2e7a19c30
parent 69e28e7
3 files changed +6633 -3631
modified external/sqlite/shell.c
@@ -252,29 +252,1019 @@ typedef unsigned char u8;

/* string conversion routines only needed on Win32 */
extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
-
extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
-
extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
#endif

-
/* On Windows, we normally run with output mode of TEXT so that \n characters
-
** are automatically translated into \r\n.  However, this behavior needs
-
** to be disabled in some cases (ex: when generating CSV output and when
-
** rendering quoted strings that contain \n characters).  The following
-
** routines take care of that.
+
/* Use console I/O package as a direct INCLUDE. */
+
#define SQLITE_INTERNAL_LINKAGE static
+

+
#ifdef SQLITE_SHELL_FIDDLE
+
/* Deselect most features from the console I/O package for Fiddle. */
+
# define SQLITE_CIO_NO_REDIRECT
+
# define SQLITE_CIO_NO_CLASSIFY
+
# define SQLITE_CIO_NO_TRANSLATE
+
# define SQLITE_CIO_NO_SETMODE
+
#endif
+
/************************* Begin ../ext/consio/console_io.h ******************/
+
/*
+
** 2023 November 1
+
**
+
** 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 exposes various interfaces used for console and other I/O
+
** by the SQLite project command-line tools. These interfaces are used
+
** at either source conglomeration time, compilation time, or run time.
+
** This source provides for either inclusion into conglomerated,
+
** "single-source" forms or separate compilation then linking.
+
**
+
** Platform dependencies are "hidden" here by various stratagems so
+
** that, provided certain conditions are met, the programs using this
+
** source or object code compiled from it need no explicit conditional
+
** compilation in their source for their console and stream I/O.
+
**
+
** The symbols and functionality exposed here are not a public API.
+
** This code may change in tandem with other project code as needed.
+
**
+
** When this .h file and its companion .c are directly incorporated into
+
** a source conglomeration (such as shell.c), the preprocessor symbol
+
** CIO_WIN_WC_XLATE is defined as 0 or 1, reflecting whether console I/O
+
** translation for Windows is effected for the build.
+
*/
+

+
#ifndef SQLITE_INTERNAL_LINKAGE
+
# define SQLITE_INTERNAL_LINKAGE extern /* external to translation unit */
+
# include <stdio.h>
+
#else
+
# define SHELL_NO_SYSINC /* Better yet, modify mkshellc.tcl for this. */
+
#endif
+

+
#ifndef SQLITE3_H
+
/* # include "sqlite3.h" */
+
#endif
+

+
#ifndef SQLITE_CIO_NO_CLASSIFY
+

+
/* Define enum for use with following function. */
+
typedef enum StreamsAreConsole {
+
  SAC_NoConsole = 0,
+
  SAC_InConsole = 1, SAC_OutConsole = 2, SAC_ErrConsole = 4,
+
  SAC_AnyConsole = 0x7
+
} StreamsAreConsole;
+

+
/*
+
** Classify the three standard I/O streams according to whether
+
** they are connected to a console attached to the process.
+
**
+
** Returns the bit-wise OR of SAC_{In,Out,Err}Console values,
+
** or SAC_NoConsole if none of the streams reaches a console.
+
**
+
** This function should be called before any I/O is done with
+
** the given streams. As a side-effect, the given inputs are
+
** recorded so that later I/O operations on them may be done
+
** differently than the C library FILE* I/O would be done,
+
** iff the stream is used for the I/O functions that follow,
+
** and to support the ones that use an implicit stream.
+
**
+
** On some platforms, stream or console mode alteration (aka
+
** "Setup") may be made which is undone by consoleRestore().
+
*/
+
SQLITE_INTERNAL_LINKAGE StreamsAreConsole
+
consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr );
+
/* A usual call for convenience: */
+
#define SQLITE_STD_CONSOLE_INIT() consoleClassifySetup(stdin,stdout,stderr)
+

+
/*
+
** After an initial call to consoleClassifySetup(...), renew
+
** the same setup it effected. (A call not after is an error.)
+
** This will restore state altered by consoleRestore();
+
**
+
** Applications which run an inferior (child) process which
+
** inherits the same I/O streams may call this function after
+
** such a process exits to guard against console mode changes.
+
*/
+
SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void);
+

+
/*
+
** Undo any side-effects left by consoleClassifySetup(...).
+
**
+
** This should be called after consoleClassifySetup() and
+
** before the process terminates normally. It is suitable
+
** for use with the atexit() C library procedure. After
+
** this call, no console I/O should be done until one of
+
** console{Classify or Renew}Setup(...) is called again.
+
**
+
** Applications which run an inferior (child) process that
+
** inherits the same I/O streams might call this procedure
+
** before so that said process will have a console setup
+
** however users have configured it or come to expect.
+
*/
+
SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void );
+

+
#else /* defined(SQLITE_CIO_NO_CLASSIFY) */
+
# define consoleClassifySetup(i,o,e)
+
# define consoleRenewSetup()
+
# define consoleRestore()
+
#endif /* defined(SQLITE_CIO_NO_CLASSIFY) */
+

+
#ifndef SQLITE_CIO_NO_REDIRECT
+
/*
+
** Set stream to be used for the functions below which write
+
** to "the designated X stream", where X is Output or Error.
+
** Returns the previous value.
+
**
+
** Alternatively, pass the special value, invalidFileStream,
+
** to get the designated stream value without setting it.
+
**
+
** Before the designated streams are set, they default to
+
** those passed to consoleClassifySetup(...), and before
+
** that is called they default to stdout and stderr.
+
**
+
** It is error to close a stream so designated, then, without
+
** designating another, use the corresponding {o,e}Emit(...).
+
*/
+
SQLITE_INTERNAL_LINKAGE FILE *invalidFileStream;
+
SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf);
+
# ifdef CONSIO_SET_ERROR_STREAM
+
SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf);
+
# endif
+
#else
+
# define setOutputStream(pf)
+
# define setErrorStream(pf)
+
#endif /* !defined(SQLITE_CIO_NO_REDIRECT) */
+

+
#ifndef SQLITE_CIO_NO_TRANSLATE
+
/*
+
** Emit output like fprintf(). If the output is going to the
+
** console and translation from UTF-8 is necessary, perform
+
** the needed translation. Otherwise, write formatted output
+
** to the provided stream almost as-is, possibly with newline
+
** translation as specified by set{Binary,Text}Mode().
+
*/
+
SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...);
+
/* Like fPrintfUtf8 except stream is always the designated output. */
+
SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...);
+
/* Like fPrintfUtf8 except stream is always the designated error. */
+
SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...);
+

+
/*
+
** Emit output like fputs(). If the output is going to the
+
** console and translation from UTF-8 is necessary, perform
+
** the needed translation. Otherwise, write given text to the
+
** provided stream almost as-is, possibly with newline
+
** translation as specified by set{Binary,Text}Mode().
+
*/
+
SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO);
+
/* Like fPutsUtf8 except stream is always the designated output. */
+
SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z);
+
/* Like fPutsUtf8 except stream is always the designated error. */
+
SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z);
+

+
/*
+
** Emit output like fPutsUtf8(), except that the length of the
+
** accepted char or character sequence is limited by nAccept.
+
**
+
** Returns the number of accepted char values.
+
*/
+
#ifdef CONSIO_SPUTB
+
SQLITE_INTERNAL_LINKAGE int
+
fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
+
#endif
+
/* Like fPutbUtf8 except stream is always the designated output. */
+
SQLITE_INTERNAL_LINKAGE int
+
oPutbUtf8(const char *cBuf, int nAccept);
+
/* Like fPutbUtf8 except stream is always the designated error. */
+
#ifdef CONSIO_EPUTB
+
SQLITE_INTERNAL_LINKAGE int
+
ePutbUtf8(const char *cBuf, int nAccept);
+
#endif
+

+
/*
+
** Collect input like fgets(...) with special provisions for input
+
** from the console on platforms that require same. Defers to the
+
** C library fgets() when input is not from the console. Newline
+
** translation may be done as set by set{Binary,Text}Mode(). As a
+
** convenience, pfIn==NULL is treated as stdin.
+
*/
+
SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn);
+
/* Like fGetsUtf8 except stream is always the designated input. */
+
/* SQLITE_INTERNAL_LINKAGE char* iGetsUtf8(char *cBuf, int ncMax); */
+

+
#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
+

+
#ifndef SQLITE_CIO_NO_SETMODE
+
/*
+
** Set given stream for binary mode, where newline translation is
+
** not done, or for text mode where, for some platforms, newlines
+
** are translated to the platform's conventional char sequence.
+
** If bFlush true, flush the stream.
+
**
+
** An additional side-effect is that if the stream is one passed
+
** to consoleClassifySetup() as an output, it is flushed first.
+
**
+
** Note that binary/text mode has no effect on console I/O
+
** translation. On all platforms, newline to the console starts
+
** a new line and CR,LF chars from the console become a newline.
+
*/
+
SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *, short bFlush);
+
SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *, short bFlush);
+
#endif
+

+
#ifdef SQLITE_CIO_PROMPTED_IN
+
typedef struct Prompts {
+
  int numPrompts;
+
  const char **azPrompts;
+
} Prompts;
+

+
/*
+
** Macros for use of a line editor.
+
**
+
** The following macros define operations involving use of a
+
** line-editing library or simple console interaction.
+
** A "T" argument is a text (char *) buffer or filename.
+
** A "N" argument is an integer.
+
**
+
** SHELL_ADD_HISTORY(T) // Record text as line(s) of history.
+
** SHELL_READ_HISTORY(T) // Read history from file named by T.
+
** SHELL_WRITE_HISTORY(T) // Write history to file named by T.
+
** SHELL_STIFLE_HISTORY(N) // Limit history to N entries.
+
**
+
** A console program which does interactive console input is
+
** expected to call:
+
** SHELL_READ_HISTORY(T) before collecting such input;
+
** SHELL_ADD_HISTORY(T) as record-worthy input is taken;
+
** SHELL_STIFLE_HISTORY(N) after console input ceases; then
+
** SHELL_WRITE_HISTORY(T) before the program exits.
+
*/
+

+
/*
+
** Retrieve a single line of input text from an input stream.
+
**
+
** If pfIn is the input stream passed to consoleClassifySetup(),
+
** and azPrompt is not NULL, then a prompt is issued before the
+
** line is collected, as selected by the isContinuation flag.
+
** Array azPrompt[{0,1}] holds the {main,continuation} prompt.
+
**
+
** If zBufPrior is not NULL then it is a buffer from a prior
+
** call to this routine that can be reused, or will be freed.
+
**
+
** The result is stored in space obtained from malloc() and
+
** must either be freed by the caller or else passed back to
+
** this function as zBufPrior for reuse.
+
**
+
** This function may call upon services of a line-editing
+
** library to interactively collect line edited input.
+
*/
+
SQLITE_INTERNAL_LINKAGE char *
+
shellGetLine(FILE *pfIn, char *zBufPrior, int nLen,
+
             short isContinuation, Prompts azPrompt);
+
#endif /* defined(SQLITE_CIO_PROMPTED_IN) */
+
/*
+
** TBD: Define an interface for application(s) to generate
+
** completion candidates for use by the line-editor.
+
**
+
** This may be premature; the CLI is the only application
+
** that does this. Yet, getting line-editing melded into
+
** console I/O is desirable because a line-editing library
+
** may have to establish console operating mode, possibly
+
** in a way that interferes with the above functionality.
+
*/
+

+
#if !(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))
+
/* Skip over as much z[] input char sequence as is valid UTF-8,
+
** limited per nAccept char's or whole characters and containing
+
** no char cn such that ((1<<cn) & ccm)!=0. On return, the
+
** sequence z:return (inclusive:exclusive) is validated UTF-8.
+
** Limit: nAccept>=0 => char count, nAccept<0 => character
+
 */
+
SQLITE_INTERNAL_LINKAGE const char*
+
zSkipValidUtf8(const char *z, int nAccept, long ccm);
+

+
#endif
+

+
/************************* End ../ext/consio/console_io.h ********************/
+
/************************* Begin ../ext/consio/console_io.c ******************/
+
/*
+
** 2023 November 4
+
**
+
** 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 various interfaces used for console and stream I/O
+
** by the SQLite project command-line tools, as explained in console_io.h .
+
** Functions prefixed by "SQLITE_INTERNAL_LINKAGE" behave as described there.
*/
-
#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
-
static void setBinaryMode(FILE *file, int isOutput){
-
  if( isOutput ) fflush(file);
-
  _setmode(_fileno(file), _O_BINARY);
+

+
#ifndef SQLITE_CDECL
+
# define SQLITE_CDECL
+
#endif
+

+
#ifndef SHELL_NO_SYSINC
+
# include <stdarg.h>
+
# include <string.h>
+
# include <stdlib.h>
+
# include <limits.h>
+
# include <assert.h>
+
# include "console_io.h"
+
/* # include "sqlite3.h" */
+
#endif
+

+
#ifndef SQLITE_CIO_NO_TRANSLATE
+
# if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
+
#  ifndef SHELL_NO_SYSINC
+
#   include <io.h>
+
#   include <fcntl.h>
+
#   undef WIN32_LEAN_AND_MEAN
+
#   define WIN32_LEAN_AND_MEAN
+
#   include <windows.h>
+
#  endif
+
#  define CIO_WIN_WC_XLATE 1 /* Use WCHAR Windows APIs for console I/O */
+
# else
+
#  ifndef SHELL_NO_SYSINC
+
#   include <unistd.h>
+
#  endif
+
#  define CIO_WIN_WC_XLATE 0 /* Use plain C library stream I/O at console */
+
# endif
+
#else
+
# define CIO_WIN_WC_XLATE 0 /* Not exposing translation routines at all */
+
#endif
+

+
#if CIO_WIN_WC_XLATE
+
/* Character used to represent a known-incomplete UTF-8 char group (�) */
+
static WCHAR cBadGroup = 0xfffd;
+
#endif
+

+
#if CIO_WIN_WC_XLATE
+
static HANDLE handleOfFile(FILE *pf){
+
  int fileDesc = _fileno(pf);
+
  union { intptr_t osfh; HANDLE fh; } fid = {
+
    (fileDesc>=0)? _get_osfhandle(fileDesc) : (intptr_t)INVALID_HANDLE_VALUE
+
  };
+
  return fid.fh;
}
-
static void setTextMode(FILE *file, int isOutput){
-
  if( isOutput ) fflush(file);
-
  _setmode(_fileno(file), _O_TEXT);
+
#endif
+

+
#ifndef SQLITE_CIO_NO_TRANSLATE
+
typedef struct PerStreamTags {
+
# if CIO_WIN_WC_XLATE
+
  HANDLE hx;
+
  DWORD consMode;
+
  char acIncomplete[4];
+
# else
+
  short reachesConsole;
+
# endif
+
  FILE *pf;
+
} PerStreamTags;
+

+
/* Define NULL-like value for things which can validly be 0. */
+
# define SHELL_INVALID_FILE_PTR ((FILE *)~0)
+
# if CIO_WIN_WC_XLATE
+
#  define SHELL_INVALID_CONS_MODE 0xFFFF0000
+
# endif
+

+
# if CIO_WIN_WC_XLATE
+
#  define PST_INITIALIZER { INVALID_HANDLE_VALUE, SHELL_INVALID_CONS_MODE, \
+
      {0,0,0,0}, SHELL_INVALID_FILE_PTR }
+
# else
+
#  define PST_INITIALIZER { 0, SHELL_INVALID_FILE_PTR }
+
# endif
+

+
/* Quickly say whether a known output is going to the console. */
+
# if CIO_WIN_WC_XLATE
+
static short pstReachesConsole(PerStreamTags *ppst){
+
  return (ppst->hx != INVALID_HANDLE_VALUE);
}
+
# else
+
#  define pstReachesConsole(ppst) 0
+
# endif
+

+
# if CIO_WIN_WC_XLATE
+
static void restoreConsoleArb(PerStreamTags *ppst){
+
  if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode);
+
}
+
# else
+
#  define restoreConsoleArb(ppst)
+
# endif
+

+
/* Say whether FILE* appears to be a console, collect associated info. */
+
static short streamOfConsole(FILE *pf, /* out */ PerStreamTags *ppst){
+
# if CIO_WIN_WC_XLATE
+
  short rv = 0;
+
  DWORD dwCM = SHELL_INVALID_CONS_MODE;
+
  HANDLE fh = handleOfFile(pf);
+
  ppst->pf = pf;
+
  if( INVALID_HANDLE_VALUE != fh ){
+
    rv = (GetFileType(fh) == FILE_TYPE_CHAR && GetConsoleMode(fh,&dwCM));
+
  }
+
  ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE;
+
  ppst->consMode = dwCM;
+
  return rv;
+
# else
+
  ppst->pf = pf;
+
  ppst->reachesConsole = ( (short)isatty(fileno(pf)) );
+
  return ppst->reachesConsole;
+
# endif
+
}
+

+
# if CIO_WIN_WC_XLATE
+
/* Define console modes for use with the Windows Console API. */
+
#  define SHELL_CONI_MODE \
+
  (ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE | ENABLE_LINE_INPUT | 0x80 \
+
  | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS | ENABLE_PROCESSED_INPUT)
+
#  define SHELL_CONO_MODE (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT \
+
  | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
+
# endif
+

+
typedef struct ConsoleInfo {
+
  PerStreamTags pstSetup[3];
+
  PerStreamTags pstDesignated[3];
+
  StreamsAreConsole sacSetup;
+
} ConsoleInfo;
+

+
static short isValidStreamInfo(PerStreamTags *ppst){
+
  return (ppst->pf != SHELL_INVALID_FILE_PTR);
+
}
+

+
static ConsoleInfo consoleInfo = {
+
  { /* pstSetup */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
+
  { /* pstDesignated[] */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
+
  SAC_NoConsole /* sacSetup */
+
};
+

+
SQLITE_INTERNAL_LINKAGE FILE* invalidFileStream = (FILE *)~0;
+

+
# if CIO_WIN_WC_XLATE
+
static void maybeSetupAsConsole(PerStreamTags *ppst, short odir){
+
  if( pstReachesConsole(ppst) ){
+
    DWORD cm = odir? SHELL_CONO_MODE : SHELL_CONI_MODE;
+
    SetConsoleMode(ppst->hx, cm);
+
  }
+
}
+
# else
+
#  define maybeSetupAsConsole(ppst,odir)
+
# endif
+

+
SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void){
+
# if CIO_WIN_WC_XLATE
+
  int ix = 0;
+
  while( ix < 6 ){
+
    PerStreamTags *ppst = (ix<3)?
+
      &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3];
+
    maybeSetupAsConsole(ppst, (ix % 3)>0);
+
    ++ix;
+
  }
+
# endif
+
}
+

+
SQLITE_INTERNAL_LINKAGE StreamsAreConsole
+
consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr ){
+
  StreamsAreConsole rv = SAC_NoConsole;
+
  FILE* apf[3] = { pfIn, pfOut, pfErr };
+
  int ix;
+
  for( ix = 2; ix >= 0; --ix ){
+
    PerStreamTags *ppst = &consoleInfo.pstSetup[ix];
+
    if( streamOfConsole(apf[ix], ppst) ){
+
      rv |= (SAC_InConsole<<ix);
+
    }
+
    consoleInfo.pstDesignated[ix] = *ppst;
+
    if( ix > 0 ) fflush(apf[ix]);
+
  }
+
  consoleInfo.sacSetup = rv;
+
  consoleRenewSetup();
+
  return rv;
+
}
+

+
SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void ){
+
# if CIO_WIN_WC_XLATE
+
  static ConsoleInfo *pci = &consoleInfo;
+
  if( pci->sacSetup ){
+
    int ix;
+
    for( ix=0; ix<3; ++ix ){
+
      if( pci->sacSetup & (SAC_InConsole<<ix) ){
+
        PerStreamTags *ppst = &pci->pstSetup[ix];
+
        SetConsoleMode(ppst->hx, ppst->consMode);
+
      }
+
    }
+
  }
+
# endif
+
}
+
#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
+

+
#ifdef SQLITE_CIO_INPUT_REDIR
+
/* Say whether given FILE* is among those known, via either
+
** consoleClassifySetup() or set{Output,Error}Stream, as
+
** readable, and return an associated PerStreamTags pointer
+
** if so. Otherwise, return 0.
+
*/
+
static PerStreamTags * isKnownReadable(FILE *pf){
+
  static PerStreamTags *apst[] = {
+
    &consoleInfo.pstDesignated[0], &consoleInfo.pstSetup[0], 0
+
  };
+
  int ix = 0;
+
  do {
+
    if( apst[ix]->pf == pf ) break;
+
  } while( apst[++ix] != 0 );
+
  return apst[ix];
+
}
+
#endif
+

+
#ifndef SQLITE_CIO_NO_TRANSLATE
+
/* Say whether given FILE* is among those known, via either
+
** consoleClassifySetup() or set{Output,Error}Stream, as
+
** writable, and return an associated PerStreamTags pointer
+
** if so. Otherwise, return 0.
+
*/
+
static PerStreamTags * isKnownWritable(FILE *pf){
+
  static PerStreamTags *apst[] = {
+
    &consoleInfo.pstDesignated[1], &consoleInfo.pstDesignated[2],
+
    &consoleInfo.pstSetup[1], &consoleInfo.pstSetup[2], 0
+
  };
+
  int ix = 0;
+
  do {
+
    if( apst[ix]->pf == pf ) break;
+
  } while( apst[++ix] != 0 );
+
  return apst[ix];
+
}
+

+
static FILE *designateEmitStream(FILE *pf, unsigned chix){
+
  FILE *rv = consoleInfo.pstDesignated[chix].pf;
+
  if( pf == invalidFileStream ) return rv;
+
  else{
+
    /* Setting a possibly new output stream. */
+
    PerStreamTags *ppst = isKnownWritable(pf);
+
    if( ppst != 0 ){
+
      PerStreamTags pst = *ppst;
+
      consoleInfo.pstDesignated[chix] = pst;
+
    }else streamOfConsole(pf, &consoleInfo.pstDesignated[chix]);
+
  }
+
  return rv;
+
}
+

+
SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf){
+
  return designateEmitStream(pf, 1);
+
}
+
# ifdef CONSIO_SET_ERROR_STREAM
+
SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf){
+
  return designateEmitStream(pf, 2);
+
}
+
# endif
+
#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
+

+
#ifndef SQLITE_CIO_NO_SETMODE
+
# if CIO_WIN_WC_XLATE
+
static void setModeFlushQ(FILE *pf, short bFlush, int mode){
+
  if( bFlush ) fflush(pf);
+
  _setmode(_fileno(pf), mode);
+
}
+
# else
+
#  define setModeFlushQ(f, b, m) if(b) fflush(f)
+
# endif
+

+
SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *pf, short bFlush){
+
  setModeFlushQ(pf, bFlush, _O_BINARY);
+
}
+
SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *pf, short bFlush){
+
  setModeFlushQ(pf, bFlush, _O_TEXT);
+
}
+
# undef setModeFlushQ
+

+
#else /* defined(SQLITE_CIO_NO_SETMODE) */
+
# define setBinaryMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
+
# define setTextMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
+
#endif /* defined(SQLITE_CIO_NO_SETMODE) */
+

+
#ifndef SQLITE_CIO_NO_TRANSLATE
+
# if CIO_WIN_WC_XLATE
+
/* Write buffer cBuf as output to stream known to reach console,
+
** limited to ncTake char's. Return ncTake on success, else 0. */
+
static int conZstrEmit(PerStreamTags *ppst, const char *z, int ncTake){
+
  int rv = 0;
+
  if( z!=NULL ){
+
    int nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, 0,0);
+
    if( nwc > 0 ){
+
      WCHAR *zw = sqlite3_malloc64(nwc*sizeof(WCHAR));
+
      if( zw!=NULL ){
+
        nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, zw,nwc);
+
        if( nwc > 0 ){
+
          /* Translation from UTF-8 to UTF-16, then WCHARs out. */
+
          if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){
+
            rv = ncTake;
+
          }
+
        }
+
        sqlite3_free(zw);
+
      }
+
    }
+
  }
+
  return rv;
+
}
+

+
/* For {f,o,e}PrintfUtf8() when stream is known to reach console. */
+
static int conioVmPrintf(PerStreamTags *ppst, const char *zFormat, va_list ap){
+
  char *z = sqlite3_vmprintf(zFormat, ap);
+
  if( z ){
+
    int rv = conZstrEmit(ppst, z, (int)strlen(z));
+
    sqlite3_free(z);
+
    return rv;
+
  }else return 0;
+
}
+
# endif /* CIO_WIN_WC_XLATE */
+

+
# ifdef CONSIO_GET_EMIT_STREAM
+
static PerStreamTags * getDesignatedEmitStream(FILE *pf, unsigned chix,
+
                                               PerStreamTags *ppst){
+
  PerStreamTags *rv = isKnownWritable(pf);
+
  short isValid = (rv!=0)? isValidStreamInfo(rv) : 0;
+
  if( rv != 0 && isValid ) return rv;
+
  streamOfConsole(pf, ppst);
+
  return ppst;
+
}
+
# endif
+

+
/* Get stream info, either for designated output or error stream when
+
** chix equals 1 or 2, or for an arbitrary stream when chix == 0.
+
** In either case, ppst references a caller-owned PerStreamTags
+
** struct which may be filled in if none of the known writable
+
** streams is being held by consoleInfo. The ppf parameter is a
+
** byref output when chix!=0 and a byref input when chix==0.
+
 */
+
static PerStreamTags *
+
getEmitStreamInfo(unsigned chix, PerStreamTags *ppst,
+
                  /* in/out */ FILE **ppf){
+
  PerStreamTags *ppstTry;
+
  FILE *pfEmit;
+
  if( chix > 0 ){
+
    ppstTry = &consoleInfo.pstDesignated[chix];
+
    if( !isValidStreamInfo(ppstTry) ){
+
      ppstTry = &consoleInfo.pstSetup[chix];
+
      pfEmit = ppst->pf;
+
    }else pfEmit = ppstTry->pf;
+
    if( !isValidStreamInfo(ppstTry) ){
+
      pfEmit = (chix > 1)? stderr : stdout;
+
      ppstTry = ppst;
+
      streamOfConsole(pfEmit, ppstTry);
+
    }
+
    *ppf = pfEmit;
+
  }else{
+
    ppstTry = isKnownWritable(*ppf);
+
    if( ppstTry != 0 ) return ppstTry;
+
    streamOfConsole(*ppf, ppst);
+
    return ppst;
+
  }
+
  return ppstTry;
+
}
+

+
SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...){
+
  va_list ap;
+
  int rv;
+
  FILE *pfOut;
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
+
# else
+
  getEmitStreamInfo(1, &pst, &pfOut);
+
# endif
+
  assert(zFormat!=0);
+
  va_start(ap, zFormat);
+
# if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ){
+
    rv = conioVmPrintf(ppst, zFormat, ap);
+
  }else{
+
# endif
+
    rv = vfprintf(pfOut, zFormat, ap);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
  va_end(ap);
+
  return rv;
+
}
+

+
SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...){
+
  va_list ap;
+
  int rv;
+
  FILE *pfErr;
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
+
# else
+
  getEmitStreamInfo(2, &pst, &pfErr);
+
# endif
+
  assert(zFormat!=0);
+
  va_start(ap, zFormat);
+
# if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ){
+
    rv = conioVmPrintf(ppst, zFormat, ap);
+
  }else{
+
# endif
+
    rv = vfprintf(pfErr, zFormat, ap);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
  va_end(ap);
+
  return rv;
+
}
+

+
SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...){
+
  va_list ap;
+
  int rv;
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
+
# else
+
  getEmitStreamInfo(0, &pst, &pfO);
+
# endif
+
  assert(zFormat!=0);
+
  va_start(ap, zFormat);
+
# if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ){
+
    maybeSetupAsConsole(ppst, 1);
+
    rv = conioVmPrintf(ppst, zFormat, ap);
+
    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
+
  }else{
+
# endif
+
    rv = vfprintf(pfO, zFormat, ap);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
  va_end(ap);
+
  return rv;
+
}
+

+
SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO){
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
+
# else
+
  getEmitStreamInfo(0, &pst, &pfO);
+
# endif
+
  assert(z!=0);
+
# if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ){
+
    int rv;
+
    maybeSetupAsConsole(ppst, 1);
+
    rv = conZstrEmit(ppst, z, (int)strlen(z));
+
    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
+
    return rv;
+
  }else {
+
# endif
+
    return (fputs(z, pfO)<0)? 0 : (int)strlen(z);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
}
+

+
SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z){
+
  FILE *pfErr;
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
+
# else
+
  getEmitStreamInfo(2, &pst, &pfErr);
+
# endif
+
  assert(z!=0);
+
# if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
+
  else {
+
# endif
+
    return (fputs(z, pfErr)<0)? 0 : (int)strlen(z);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
}
+

+
SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z){
+
  FILE *pfOut;
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
+
# else
+
  getEmitStreamInfo(1, &pst, &pfOut);
+
# endif
+
  assert(z!=0);
+
# if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
+
  else {
+
# endif
+
    return (fputs(z, pfOut)<0)? 0 : (int)strlen(z);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
}
+

+
#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
+

+
#if !(defined(SQLITE_CIO_NO_UTF8SCAN) && defined(SQLITE_CIO_NO_TRANSLATE))
+
/* Skip over as much z[] input char sequence as is valid UTF-8,
+
** limited per nAccept char's or whole characters and containing
+
** no char cn such that ((1<<cn) & ccm)!=0. On return, the
+
** sequence z:return (inclusive:exclusive) is validated UTF-8.
+
** Limit: nAccept>=0 => char count, nAccept<0 => character
+
 */
+
SQLITE_INTERNAL_LINKAGE const char*
+
zSkipValidUtf8(const char *z, int nAccept, long ccm){
+
  int ng = (nAccept<0)? -nAccept : 0;
+
  const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
+
  assert(z!=0);
+
  while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
+
    char c = *z;
+
    if( (c & 0x80) == 0 ){
+
      if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
+
      ++z; /* ASCII */
+
    }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
+
    else{
+
      const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
+
      do{
+
        if( pcLimit && zt >= pcLimit ) return z;
+
        else{
+
          char ct = *zt++;
+
          if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
+
            /* Trailing bytes are too few, too many, or invalid. */
+
            return z;
+
          }
+
        }
+
      } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
+
      z = zt;
+
    }
+
  }
+
  return z;
+
}
+
#endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
+

+
#ifndef SQLITE_CIO_NO_TRANSLATE
+

+
#ifdef CONSIO_SPUTB
+
SQLITE_INTERNAL_LINKAGE int
+
fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
+
  assert(pfO!=0);
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
+
  if( pstReachesConsole(ppst) ){
+
    int rv;
+
    maybeSetupAsConsole(ppst, 1);
+
    rv = conZstrEmit(ppst, cBuf, nAccept);
+
    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
+
    return rv;
+
  }else {
+
# endif
+
    return (int)fwrite(cBuf, 1, nAccept, pfO);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
}
+
#endif /* defined(CONSIO_SPUTB) */
+

+
SQLITE_INTERNAL_LINKAGE int
+
oPutbUtf8(const char *cBuf, int nAccept){
+
  FILE *pfOut;
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
# if CIO_WIN_WC_XLATE
+
  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
+
# else
+
  getEmitStreamInfo(1, &pst, &pfOut);
+
# endif
+
# if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ){
+
    return conZstrEmit(ppst, cBuf, nAccept);
+
  }else {
+
# endif
+
    return (int)fwrite(cBuf, 1, nAccept, pfOut);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
}
+

+
# ifdef CONSIO_EPUTB
+
SQLITE_INTERNAL_LINKAGE int
+
ePutbUtf8(const char *cBuf, int nAccept){
+
  FILE *pfErr;
+
  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
+
  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
+
#  if CIO_WIN_WC_XLATE
+
  if( pstReachesConsole(ppst) ){
+
    return conZstrEmit(ppst, cBuf, nAccept);
+
  }else {
+
#  endif
+
    return (int)fwrite(cBuf, 1, nAccept, pfErr);
+
#  if CIO_WIN_WC_XLATE
+
  }
+
#  endif
+
}
+
# endif /* defined(CONSIO_EPUTB) */
+

+
SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn){
+
  if( pfIn==0 ) pfIn = stdin;
+
# if CIO_WIN_WC_XLATE
+
  if( pfIn == consoleInfo.pstSetup[0].pf
+
      && (consoleInfo.sacSetup & SAC_InConsole)!=0 ){
+
#  if CIO_WIN_WC_XLATE==1
+
#   define SHELL_GULP 150 /* Count of WCHARS to be gulped at a time */
+
    WCHAR wcBuf[SHELL_GULP+1];
+
    int lend = 0, noc = 0;
+
    if( ncMax > 0 ) cBuf[0] = 0;
+
    while( noc < ncMax-8-1 && !lend ){
+
      /* There is room for at least 2 more characters and a 0-terminator. */
+
      int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4;
+
#   undef SHELL_GULP
+
      DWORD nbr = 0;
+
      BOOL bRC = ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf, na, &nbr, 0);
+
      if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){
+
        /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */
+
        DWORD nbrx;
+
        bRC &= ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf+nbr, 1, &nbrx, 0);
+
        if( bRC ) nbr += nbrx;
+
      }
+
      if( !bRC || (noc==0 && nbr==0) ) return 0;
+
      if( nbr > 0 ){
+
        int nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,0,0,0,0);
+
        if( nmb != 0 && noc+nmb <= ncMax ){
+
          int iseg = noc;
+
          nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,cBuf+noc,nmb,0,0);
+
          noc += nmb;
+
          /* Fixup line-ends as coded by Windows for CR (or "Enter".)
+
          ** This is done without regard for any setMode{Text,Binary}()
+
          ** call that might have been done on the interactive input.
+
          */
+
          if( noc > 0 ){
+
            if( cBuf[noc-1]=='\n' ){
+
              lend = 1;
+
              if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n';
+
            }
+
          }
+
          /* Check for ^Z (anywhere in line) too, to act as EOF. */
+
          while( iseg < noc ){
+
            if( cBuf[iseg]=='\x1a' ){
+
              noc = iseg; /* Chop ^Z and anything following. */
+
              lend = 1; /* Counts as end of line too. */
+
              break;
+
            }
+
            ++iseg;
+
          }
+
        }else break; /* Drop apparent garbage in. (Could assert.) */
+
      }else break;
+
    }
+
    /* If got nothing, (after ^Z chop), must be at end-of-file. */
+
    if( noc > 0 ){
+
      cBuf[noc] = 0;
+
      return cBuf;
+
    }else return 0;
+
#  endif
+
  }else{
+
# endif
+
    return fgets(cBuf, ncMax, pfIn);
+
# if CIO_WIN_WC_XLATE
+
  }
+
# endif
+
}
+
#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
+

+
#undef SHELL_INVALID_FILE_PTR
+

+
/************************* End ../ext/consio/console_io.c ********************/
+

+
#ifndef SQLITE_SHELL_FIDDLE
+
/* From here onward, fgets() is redirected to the console_io library. */
+
# define fgets(b,n,f) fGetsUtf8(b,n,f)
+
/*
+
 * Define macros for emitting output text in various ways:
+
 *  sputz(s, z)      => emit 0-terminated string z to given stream s
+
 *  sputf(s, f, ...) => emit varargs per format f to given stream s
+
 *  oputz(z)         => emit 0-terminated string z to default stream
+
 *  oputf(f, ...)    => emit varargs per format f to default stream
+
 *  eputz(z)         => emit 0-terminated string z to error stream
+
 *  eputf(f, ...)    => emit varargs per format f to error stream
+
 *  oputb(b, n)      => emit char buffer b[0..n-1] to default stream
+
 *
+
 * Note that the default stream is whatever has been last set via:
+
 *   setOutputStream(FILE *pf)
+
 * This is normally the stream that CLI normal output goes to.
+
 * For the stand-alone CLI, it is stdout with no .output redirect.
+
 */
+
# define sputz(s,z) fPutsUtf8(z,s)
+
# define sputf fPrintfUtf8
+
# define oputz(z) oPutsUtf8(z)
+
# define oputf oPrintfUtf8
+
# define eputz(z) ePutsUtf8(z)
+
# define eputf ePrintfUtf8
+
# define oputb(buf,na) oPutbUtf8(buf,na)
#else
-
# define setBinaryMode(X,Y)
-
# define setTextMode(X,Y)
+
/* For Fiddle, all console handling and emit redirection is omitted. */
+
# define sputz(fp,z) fputs(z,fp)
+
# define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
+
# define oputz(z) fputs(z,stdout)
+
# define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
+
# define eputz(z) fputs(z,stderr)
+
# define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
+
# define oputb(buf,na) fwrite(buf,1,na,stdout)
#endif

/* True if the timer is enabled */
@@ -349,10 +1339,10 @@ static void endTimer(void){
    sqlite3_int64 iEnd = timeOfDay();
    struct rusage sEnd;
    getrusage(RUSAGE_SELF, &sEnd);
-
    printf("Run Time: real %.3f user %f sys %f\n",
-
       (iEnd - iBegin)*0.001,
-
       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
-
       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
+
    oputf("Run Time: real %.3f user %f sys %f\n",
+
          (iEnd - iBegin)*0.001,
+
          timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
+
          timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  }
}

@@ -428,10 +1418,10 @@ static void endTimer(void){
    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
    sqlite3_int64 ftWallEnd = timeOfDay();
    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
-
    printf("Run Time: real %.3f user %f sys %f\n",
-
       (ftWallEnd - ftWallBegin)*0.001,
-
       timeDiff(&ftUserBegin, &ftUserEnd),
-
       timeDiff(&ftKernelBegin, &ftKernelEnd));
+
    oputf("Run Time: real %.3f user %f sys %f\n",
+
          (ftWallEnd - ftWallBegin)*0.001,
+
          timeDiff(&ftUserBegin, &ftUserEnd),
+
          timeDiff(&ftKernelBegin, &ftKernelEnd));
  }
}

@@ -467,24 +1457,10 @@ static int bail_on_error = 0;
*/
static int stdin_is_interactive = 1;

-
#if (defined(_WIN32) || defined(WIN32)) && SHELL_USE_LOCAL_GETLINE \
-
  && !defined(SHELL_OMIT_WIN_UTF8)
-
# define SHELL_WIN_UTF8_OPT 1
-
#else
-
# define SHELL_WIN_UTF8_OPT 0
-
#endif
-

-
#if SHELL_WIN_UTF8_OPT
/*
-
** Setup console for UTF-8 input/output when following variable true.
-
*/
-
static int console_utf8 = 0;
-
#endif
-

-
/*
-
** On Windows systems we have to know if standard output is a console
-
** in order to translate UTF-8 into MBCS.  The following variable is
-
** true if translation is required.
+
** On Windows systems we need to know if standard output is a console
+
** in order to show that UTF-16 translation is done in the sign-on
+
** banner. The following variable is true if it is the console.
*/
static int stdout_is_console = 1;

@@ -606,182 +1582,17 @@ static char *dynamicContinuePrompt(void){
        shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
        dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
      }
-
      shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, PROMPT_LEN_MAX-4);
+
      shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
+
                    PROMPT_LEN_MAX-4);
    }
  }
  return dynPrompt.dynamicPrompt;
}
#endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */

-
#if SHELL_WIN_UTF8_OPT
-
/* Following struct is used for -utf8 operation. */
-
static struct ConsoleState {
-
  int stdinEof;      /* EOF has been seen on console input */
-
  int infsMode;      /* Input file stream mode upon shell start */
-
  UINT inCodePage;   /* Input code page upon shell start */
-
  UINT outCodePage;  /* Output code page upon shell start */
-
  HANDLE hConsoleIn; /* Console input handle */
-
  DWORD consoleMode; /* Console mode upon shell start */
-
} conState = { 0, 0, 0, 0, INVALID_HANDLE_VALUE, 0 };
-

-
#ifndef _O_U16TEXT /* For build environments lacking this constant: */
-
# define _O_U16TEXT 0x20000
-
#endif
-

-
/*
-
** Prepare console, (if known to be a WIN32 console), for UTF-8
-
** input (from either typing or suitable paste operations) and for
-
** UTF-8 rendering. This may "fail" with a message to stderr, where
-
** the preparation is not done and common "code page" issues occur.
-
*/
-
static void console_prepare(void){
-
  HANDLE hCI = GetStdHandle(STD_INPUT_HANDLE);
-
  DWORD consoleMode = 0;
-
  if( isatty(0) && GetFileType(hCI)==FILE_TYPE_CHAR
-
      && GetConsoleMode( hCI, &consoleMode) ){
-
    if( !IsValidCodePage(CP_UTF8) ){
-
      fprintf(stderr, "Cannot use UTF-8 code page.\n");
-
      console_utf8 = 0;
-
      return;
-
    }
-
    conState.hConsoleIn = hCI;
-
    conState.consoleMode = consoleMode;
-
    conState.inCodePage = GetConsoleCP();
-
    conState.outCodePage = GetConsoleOutputCP();
-
    SetConsoleCP(CP_UTF8);
-
    SetConsoleOutputCP(CP_UTF8);
-
    consoleMode |= ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
-
    SetConsoleMode(conState.hConsoleIn, consoleMode);
-
    conState.infsMode = _setmode(_fileno(stdin), _O_U16TEXT);
-
    console_utf8 = 1;
-
  }else{
-
    console_utf8 = 0;
-
  }
-
}
-

-
/*
-
** Undo the effects of console_prepare(), if any.
-
*/
-
static void SQLITE_CDECL console_restore(void){
-
  if( console_utf8 && conState.inCodePage!=0
-
      && conState.hConsoleIn!=INVALID_HANDLE_VALUE ){
-
    _setmode(_fileno(stdin), conState.infsMode);
-
    SetConsoleCP(conState.inCodePage);
-
    SetConsoleOutputCP(conState.outCodePage);
-
    SetConsoleMode(conState.hConsoleIn, conState.consoleMode);
-
    /* Avoid multiple calls. */
-
    conState.hConsoleIn = INVALID_HANDLE_VALUE;
-
    conState.consoleMode = 0;
-
    console_utf8 = 0;
-
  }
-
}
-

-
/*
-
** Collect input like fgets(...) with special provisions for input
-
** from the Windows console to get around its strange coding issues.
-
** Defers to plain fgets() when input is not interactive or when the
-
** startup option, -utf8, has not been provided or taken effect.
-
*/
-
static char* utf8_fgets(char *buf, int ncmax, FILE *fin){
-
  if( fin==0 ) fin = stdin;
-
  if( fin==stdin && stdin_is_interactive && console_utf8 ){
-
# define SQLITE_IALIM 150
-
    wchar_t wbuf[SQLITE_IALIM];
-
    int lend = 0;
-
    int noc = 0;
-
    if( ncmax==0 || conState.stdinEof ) return 0;
-
    buf[0] = 0;
-
    while( noc<ncmax-7-1 && !lend ){
-
      /* There is room for at least 2 more characters and a 0-terminator. */
-
      int na = (ncmax > SQLITE_IALIM*4+1 + noc)
-
        ? SQLITE_IALIM : (ncmax-1 - noc)/4;
-
# undef SQLITE_IALIM
-
      DWORD nbr = 0;
-
      BOOL bRC = ReadConsoleW(conState.hConsoleIn, wbuf, na, &nbr, 0);
-
      if( !bRC || (noc==0 && nbr==0) ) return 0;
-
      if( nbr > 0 ){
-
        int nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
-
                                      wbuf,nbr,0,0,0,0);
-
        if( nmb !=0 && noc+nmb <= ncmax ){
-
          int iseg = noc;
-
          nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
-
                                    wbuf,nbr,buf+noc,nmb,0,0);
-
          noc += nmb;
-
          /* Fixup line-ends as coded by Windows for CR (or "Enter".)*/
-
          if( noc > 0 ){
-
            if( buf[noc-1]=='\n' ){
-
              lend = 1;
-
              if( noc > 1 && buf[noc-2]=='\r' ){
-
                buf[noc-2] = '\n';
-
                --noc;
-
              }
-
            }
-
          }
-
          /* Check for ^Z (anywhere in line) too. */
-
          while( iseg < noc ){
-
            if( buf[iseg]==0x1a ){
-
              conState.stdinEof = 1;
-
              noc = iseg; /* Chop ^Z and anything following. */
-
              break;
-
            }
-
            ++iseg;
-
          }
-
        }else break; /* Drop apparent garbage in. (Could assert.) */
-
      }else break;
-
    }
-
    /* If got nothing, (after ^Z chop), must be at end-of-file. */
-
    if( noc == 0 ) return 0;
-
    buf[noc] = 0;
-
    return buf;
-
  }else{
-
    return fgets(buf, ncmax, fin);
-
  }
-
}
-

-
# define fgets(b,n,f) utf8_fgets(b,n,f)
-
#endif /* SHELL_WIN_UTF8_OPT */
-

-
/*
-
** Render output like fprintf().  Except, if the output is going to the
-
** console and if this is running on a Windows machine, and if the -utf8
-
** option is unavailable or (available and inactive), translate the
-
** output from UTF-8 into MBCS for output through 8-bit stdout stream.
-
** (With -utf8 active, no translation is needed and must not be done.)
-
*/
-
#if defined(_WIN32) || defined(WIN32)
-
void utf8_printf(FILE *out, const char *zFormat, ...){
-
  va_list ap;
-
  va_start(ap, zFormat);
-
  if( stdout_is_console && (out==stdout || out==stderr)
-
# if SHELL_WIN_UTF8_OPT
-
      && !console_utf8
-
# endif
-
  ){
-
    char *z1 = sqlite3_vmprintf(zFormat, ap);
-
    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
-
    sqlite3_free(z1);
-
    fputs(z2, out);
-
    sqlite3_free(z2);
-
  }else{
-
    vfprintf(out, zFormat, ap);
-
  }
-
  va_end(ap);
-
}
-
#elif !defined(utf8_printf)
-
# define utf8_printf fprintf
-
#endif
-

-
/*
-
** Render output like fprintf().  This should not be used on anything that
-
** includes string formatting (e.g. "%s").
-
*/
-
#if !defined(raw_printf)
-
# define raw_printf fprintf
-
#endif
-

/* Indicate out-of-memory and exit. */
static void shell_out_of_memory(void){
-
  raw_printf(stderr,"Error: out of memory\n");
+
  eputz("Error: out of memory\n");
  exit(1);
}

@@ -813,18 +1624,18 @@ static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  va_start(ap, zFormat);
  z = sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
-
  utf8_printf(iotrace, "%s", z);
+
  sputf(iotrace, "%s", z);
  sqlite3_free(z);
}
#endif

/*
-
** Output string zUtf to stream pOut as w characters.  If w is negative,
+
** Output string zUtf to Out stream as w characters.  If w is negative,
** then right-justify the text.  W is the width in UTF-8 characters, not
** in bytes.  This is different from the %*.*s specification in printf
** since with %*.*s the width is measured in bytes, not characters.
*/
-
static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
+
static void utf8_width_print(int w, const char *zUtf){
  int i;
  int n;
  int aw = w<0 ? -w : w;
@@ -839,11 +1650,11 @@ static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
    }
  }
  if( n>=aw ){
-
    utf8_printf(pOut, "%.*s", i, zUtf);
+
    oputf("%.*s", i, zUtf);
  }else if( w<0 ){
-
    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
+
    oputf("%*s%s", aw-n, "", zUtf);
  }else{
-
    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
+
    oputf("%s%*s", zUtf, aw-n, "");
  }
}

@@ -903,7 +1714,7 @@ static int strlenChar(const char *z){
** Otherwise return 0.
*/
static FILE * openChrSource(const char *zFile){
-
#ifdef _WIN32
+
#if defined(_WIN32) || defined(WIN32)
  struct _stat x = {0};
# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
  /* On Windows, open first, then check the stream nature. This order
@@ -966,27 +1777,6 @@ static char *local_getline(char *zLine, FILE *in){
      break;
    }
  }
-
#if defined(_WIN32) || defined(WIN32)
-
  /* For interactive input on Windows systems, without -utf8,
-
  ** translate the multi-byte characterset characters into UTF-8.
-
  ** This is the translation that predates the -utf8 option. */
-
  if( stdin_is_interactive && in==stdin
-
# if SHELL_WIN_UTF8_OPT
-
      && !console_utf8
-
# endif /* SHELL_WIN_UTF8_OPT */
-
  ){
-
    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
-
    if( zTrans ){
-
      i64 nTrans = strlen(zTrans)+1;
-
      if( nTrans>nLine ){
-
        zLine = realloc(zLine, nTrans);
-
        shell_check_oom(zLine);
-
      }
-
      memcpy(zLine, zTrans, nTrans);
-
      sqlite3_free(zTrans);
-
    }
-
  }
-
#endif /* defined(_WIN32) || defined(WIN32) */
  return zLine;
}

@@ -1013,7 +1803,7 @@ static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  }else{
    zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
#if SHELL_USE_LOCAL_GETLINE
-
    printf("%s", zPrompt);
+
    sputz(stdout, zPrompt);
    fflush(stdout);
    do{
      zResult = local_getline(zPrior, stdin);
@@ -1260,7 +2050,7 @@ static void shellDtostr(
  char z[400];
  if( n<1 ) n = 1;
  if( n>350 ) n = 350;
-
  sprintf(z, "%#+.*e", n, r);
+
  sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
  sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
}

@@ -5372,7 +6162,8 @@ static sqlite3_module seriesModule = {
  0,                         /* xSavepoint */
  0,                         /* xRelease */
  0,                         /* xRollbackTo */
-
  0                          /* xShadowName */
+
  0,                         /* xShadowName */
+
  0                          /* xIntegrity */
};

#endif /* SQLITE_OMIT_VIRTUALTABLE */
@@ -7270,6 +8061,7 @@ static int fsdirRegister(sqlite3 *db){
    0,                         /* xRelease */
    0,                         /* xRollbackTo */
    0,                         /* xShadowName */
+
    0                          /* xIntegrity */
  };

  int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
@@ -7790,7 +8582,8 @@ static sqlite3_module completionModule = {
  0,                         /* xSavepoint */
  0,                         /* xRelease */
  0,                         /* xRollbackTo */
-
  0                          /* xShadowName */
+
  0,                         /* xShadowName */
+
  0                          /* xIntegrity */
};

#endif /* SQLITE_OMIT_VIRTUALTABLE */
@@ -8530,6 +9323,7 @@ SQLITE_EXTENSION_INIT1
#include <stdio.h>
#include <string.h>
#include <assert.h>
+
#include <stdint.h>

#include <zlib.h>

@@ -10701,7 +11495,8 @@ static int zipfileRegister(sqlite3 *db){
    0,                         /* xSavepoint */
    0,                         /* xRelease */
    0,                         /* xRollback */
-
    0                          /* xShadowName */
+
    0,                         /* xShadowName */
+
    0                          /* xIntegrity */
  };

  int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
@@ -11070,7 +11865,7 @@ void sqlite3_expert_destroy(sqlite3expert*);
#endif /* !defined(SQLITE_AMALGAMATION) */


-
#ifndef SQLITE_OMIT_VIRTUALTABLE 
+
#ifndef SQLITE_OMIT_VIRTUALTABLE

/* typedef sqlite3_int64 i64; */
/* typedef sqlite3_uint64 u64; */
@@ -11700,6 +12495,7 @@ static int idxRegisterVtab(sqlite3expert *p){
    0,                            /* xRelease */
    0,                            /* xRollbackTo */
    0,                            /* xShadowName */
+
    0,                            /* xIntegrity */
  };

  return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
@@ -12857,6 +13653,88 @@ static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
}

/*
+
** Define and possibly pretend to use a useless collation sequence.
+
** This pretense allows expert to accept SQL using custom collations.
+
*/
+
int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
+
  (void)up1;
+
  (void)up2;
+
  (void)up3;
+
  (void)up4;
+
  (void)up5;
+
  assert(0); /* VDBE should never be run. */
+
  return 0;
+
}
+
/* And a callback to register above upon actual need */
+
void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
+
  (void)up1;
+
  sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
+
}
+

+
#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
+
  && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
+
/*
+
** dummy functions for no-op implementation of UDFs during expert's work
+
*/
+
void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
+
  (void)up1;
+
  (void)up2;
+
  (void)up3;
+
  assert(0); /* VDBE should never be run. */
+
}
+
void dummyUDFvalue(sqlite3_context *up1){
+
  (void)up1;
+
  assert(0); /* VDBE should never be run. */
+
}
+

+
/*
+
** Register UDFs from user database with another.
+
*/
+
int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
+
  sqlite3_stmt *pStmt;
+
  int rc = sqlite3_prepare_v2(dbSrc,
+
            "SELECT name,type,enc,narg,flags "
+
            "FROM pragma_function_list() "
+
            "WHERE builtin==0", -1, &pStmt, 0);
+
  if( rc==SQLITE_OK ){
+
    while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
+
      int nargs = sqlite3_column_int(pStmt,3);
+
      int flags = sqlite3_column_int(pStmt,4);
+
      const char *name = (char*)sqlite3_column_text(pStmt,0);
+
      const char *type = (char*)sqlite3_column_text(pStmt,1);
+
      const char *enc = (char*)sqlite3_column_text(pStmt,2);
+
      if( name==0 || type==0 || enc==0 ){
+
        /* no-op.  Only happens on OOM */
+
      }else{
+
        int ienc = SQLITE_UTF8;
+
        int rcf = SQLITE_ERROR;
+
        if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
+
        else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
+
        ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
+
        if( strcmp(type,"w")==0 ){
+
          rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
+
                                               dummyUDF,dummyUDFvalue,0,0,0);
+
        }else if( strcmp(type,"a")==0 ){
+
          rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
+
                                        0,dummyUDF,dummyUDFvalue);
+
        }else if( strcmp(type,"s")==0 ){
+
          rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
+
                                        dummyUDF,0,0);
+
        }
+
        if( rcf!=SQLITE_OK ){
+
          rc = rcf;
+
          break;
+
        }
+
      }
+
    }
+
    sqlite3_finalize(pStmt);
+
    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
+
  }
+
  return rc;
+
}
+
#endif
+

+
/*
** Allocate a new sqlite3expert object.
*/
sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
@@ -12882,7 +13760,21 @@ sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
      sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
    }
  }
-
  
+

+
  /* Allow custom collations to be dealt with through prepare. */
+
  if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
+
  if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
+

+
#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
+
  && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
+
  /* Register UDFs from database [db] with [dbm] and [dbv]. */
+
  if( rc==SQLITE_OK ){
+
    rc = registerUDFs(pNew->db, pNew->dbm);
+
  }
+
  if( rc==SQLITE_OK ){
+
    rc = registerUDFs(pNew->db, pNew->dbv);
+
  }
+
#endif

  /* Copy the entire schema of database [db] into [dbm]. */
  if( rc==SQLITE_OK ){
@@ -12958,6 +13850,10 @@ int sqlite3_expert_sql(

  while( rc==SQLITE_OK && zStmt && zStmt[0] ){
    sqlite3_stmt *pStmt = 0;
+
    /* Ensure that the provided statement compiles against user's DB. */
+
    rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
+
    if( rc!=SQLITE_OK ) break;
+
    sqlite3_finalize(pStmt);
    rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
    if( rc==SQLITE_OK ){
      if( pStmt ){
@@ -14282,7 +15178,8 @@ static int sqlite3DbdataRegister(sqlite3 *db){
    0,                            /* xSavepoint */
    0,                            /* xRelease */
    0,                            /* xRollbackTo */
-
    0                             /* xShadowName */
+
    0,                            /* xShadowName */
+
    0                             /* xIntegrity */
  };

  int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
@@ -17439,7 +18336,7 @@ static const char *modeDescr[] = {
static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  ShellState *p = (ShellState*)pArg;
  if( p->pLog==0 ) return;
-
  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
+
  sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  fflush(p->pLog);
}

@@ -17454,9 +18351,9 @@ static void shellPutsFunc(
  int nVal,
  sqlite3_value **apVal
){
-
  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
+
  /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
  (void)nVal;
-
  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
+
  oputf("%s\n", sqlite3_value_text(apVal[0]));
  sqlite3_result_value(pCtx, apVal[0]);
}

@@ -17475,8 +18372,7 @@ static void failIfSafeMode(
    va_start(ap, zErrMsg);
    zMsg = sqlite3_vmprintf(zErrMsg, ap);
    va_end(ap);
-
    raw_printf(stderr, "line %d: ", p->lineno);
-
    utf8_printf(stderr, "%s\n", zMsg);
+
    eputf("line %d: %s\n", p->lineno, zMsg);
    exit(1);
  }
}
@@ -17644,7 +18540,7 @@ static void outputModePop(ShellState *p){
/*
** Output the given string as a hex-encoded blob (eg. X'1234' )
*/
-
static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
+
static void output_hex_blob(const void *pBlob, int nBlob){
  int i;
  unsigned char *aBlob = (unsigned char*)pBlob;

@@ -17661,7 +18557,7 @@ static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  }
  zStr[i*2] = '\0';

-
  raw_printf(out,"X'%s'", zStr);
+
  oputf("X'%s'", zStr);
  sqlite3_free(zStr);
}

@@ -17691,25 +18587,28 @@ static const char *unused_string(
**
** See also: output_quoted_escaped_string()
*/
-
static void output_quoted_string(FILE *out, const char *z){
+
static void output_quoted_string(const char *z){
  int i;
  char c;
-
  setBinaryMode(out, 1);
+
#ifndef SQLITE_SHELL_FIDDLE
+
  FILE *pfO = setOutputStream(invalidFileStream);
+
  setBinaryMode(pfO, 1);
+
#endif
  if( z==0 ) return;
  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  if( c==0 ){
-
    utf8_printf(out,"'%s'",z);
+
    oputf("'%s'",z);
  }else{
-
    raw_printf(out, "'");
+
    oputz("'");
    while( *z ){
      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
      if( c=='\'' ) i++;
      if( i ){
-
        utf8_printf(out, "%.*s", i, z);
+
        oputf("%.*s", i, z);
        z += i;
      }
      if( c=='\'' ){
-
        raw_printf(out, "'");
+
        oputz("'");
        continue;
      }
      if( c==0 ){
@@ -17717,9 +18616,13 @@ static void output_quoted_string(FILE *out, const char *z){
      }
      z++;
    }
-
    raw_printf(out, "'");
+
    oputz("'");
  }
-
  setTextMode(out, 1);
+
#ifndef SQLITE_SHELL_FIDDLE
+
  setTextMode(pfO, 1);
+
#else
+
  setTextMode(stdout, 1);
+
#endif
}

/*
@@ -17731,13 +18634,16 @@ static void output_quoted_string(FILE *out, const char *z){
** This is like output_quoted_string() but with the addition of the \r\n
** escape mechanism.
*/
-
static void output_quoted_escaped_string(FILE *out, const char *z){
+
static void output_quoted_escaped_string(const char *z){
  int i;
  char c;
-
  setBinaryMode(out, 1);
+
#ifndef SQLITE_SHELL_FIDDLE
+
  FILE *pfO = setOutputStream(invalidFileStream);
+
  setBinaryMode(pfO, 1);
+
#endif
  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  if( c==0 ){
-
    utf8_printf(out,"'%s'",z);
+
    oputf("'%s'",z);
  }else{
    const char *zNL = 0;
    const char *zCR = 0;
@@ -17749,23 +18655,23 @@ static void output_quoted_escaped_string(FILE *out, const char *z){
      if( z[i]=='\r' ) nCR++;
    }
    if( nNL ){
-
      raw_printf(out, "replace(");
+
      oputz("replace(");
      zNL = unused_string(z, "\\n", "\\012", zBuf1);
    }
    if( nCR ){
-
      raw_printf(out, "replace(");
+
      oputz("replace(");
      zCR = unused_string(z, "\\r", "\\015", zBuf2);
    }
-
    raw_printf(out, "'");
+
    oputz("'");
    while( *z ){
      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
      if( c=='\'' ) i++;
      if( i ){
-
        utf8_printf(out, "%.*s", i, z);
+
        oputf("%.*s", i, z);
        z += i;
      }
      if( c=='\'' ){
-
        raw_printf(out, "'");
+
        oputz("'");
        continue;
      }
      if( c==0 ){
@@ -17773,93 +18679,139 @@ static void output_quoted_escaped_string(FILE *out, const char *z){
      }
      z++;
      if( c=='\n' ){
-
        raw_printf(out, "%s", zNL);
+
        oputz(zNL);
        continue;
      }
-
      raw_printf(out, "%s", zCR);
+
      oputz(zCR);
    }
-
    raw_printf(out, "'");
+
    oputz("'");
    if( nCR ){
-
      raw_printf(out, ",'%s',char(13))", zCR);
+
      oputf(",'%s',char(13))", zCR);
    }
    if( nNL ){
-
      raw_printf(out, ",'%s',char(10))", zNL);
+
      oputf(",'%s',char(10))", zNL);
    }
  }
-
  setTextMode(out, 1);
+
#ifndef SQLITE_SHELL_FIDDLE
+
  setTextMode(pfO, 1);
+
#else
+
  setTextMode(stdout, 1);
+
#endif
}

/*
+
** Find earliest of chars within s specified in zAny.
+
** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
+
*/
+
static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
+
  const char *pcFirst = 0;
+
  if( ns == ~(size_t)0 ) ns = strlen(s);
+
  while(*zAny){
+
    const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
+
    if( pc ){
+
      pcFirst = pc;
+
      ns = pcFirst - s;
+
    }
+
    ++zAny;
+
  }
+
  return pcFirst;
+
}
+
/*
** Output the given string as a quoted according to C or TCL quoting rules.
*/
-
static void output_c_string(FILE *out, const char *z){
-
  unsigned int c;
-
  fputc('"', out);
-
  while( (c = *(z++))!=0 ){
-
    if( c=='\\' ){
-
      fputc(c, out);
-
      fputc(c, out);
-
    }else if( c=='"' ){
-
      fputc('\\', out);
-
      fputc('"', out);
-
    }else if( c=='\t' ){
-
      fputc('\\', out);
-
      fputc('t', out);
-
    }else if( c=='\n' ){
-
      fputc('\\', out);
-
      fputc('n', out);
-
    }else if( c=='\r' ){
-
      fputc('\\', out);
-
      fputc('r', out);
+
static void output_c_string(const char *z){
+
  char c;
+
  static const char *zq = "\"";
+
  static long ctrlMask = ~0L;
+
  static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
+
  char ace[3] = "\\?";
+
  char cbsSay;
+
  oputz(zq);
+
  while( *z!=0 ){
+
    const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
+
    const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
+
    const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
+
    if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
+
    if( (c = *pcEnd)==0 ) break;
+
    ++pcEnd;
+
    switch( c ){
+
    case '\\': case '"':
+
      cbsSay = (char)c;
+
      break;
+
    case '\t': cbsSay = 't'; break;
+
    case '\n': cbsSay = 'n'; break;
+
    case '\r': cbsSay = 'r'; break;
+
    case '\f': cbsSay = 'f'; break;
+
    default: cbsSay = 0; break;
+
    }
+
    if( cbsSay ){
+
      ace[1] = cbsSay;
+
      oputz(ace);
    }else if( !isprint(c&0xff) ){
-
      raw_printf(out, "\\%03o", c&0xff);
+
      oputf("\\%03o", c&0xff);
    }else{
-
      fputc(c, out);
+
      ace[1] = (char)c;
+
      oputz(ace+1);
    }
+
    z = pcEnd;
  }
-
  fputc('"', out);
+
  oputz(zq);
}

/*
** Output the given string as a quoted according to JSON quoting rules.
*/
-
static void output_json_string(FILE *out, const char *z, i64 n){
-
  unsigned int c;
+
static void output_json_string(const char *z, i64 n){
+
  char c;
+
  static const char *zq = "\"";
+
  static long ctrlMask = ~0L;
+
  static const char *zDQBS = "\"\\";
+
  const char *pcLimit;
+
  char ace[3] = "\\?";
+
  char cbsSay;
+

  if( z==0 ) z = "";
-
  if( n<0 ) n = strlen(z);
-
  fputc('"', out);
-
  while( n-- ){
+
  pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
+
  oputz(zq);
+
  while( z < pcLimit ){
+
    const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
+
    const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
+
    const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
+
    if( pcEnd > z ){
+
      oputb(z, (int)(pcEnd-z));
+
      z = pcEnd;
+
    }
+
    if( z >= pcLimit ) break;
    c = *(z++);
-
    if( c=='\\' || c=='"' ){
-
      fputc('\\', out);
-
      fputc(c, out);
+
    switch( c ){
+
    case '"': case '\\':
+
      cbsSay = (char)c;
+
      break;
+
    case '\b': cbsSay = 'b'; break;
+
    case '\f': cbsSay = 'f'; break;
+
    case '\n': cbsSay = 'n'; break;
+
    case '\r': cbsSay = 'r'; break;
+
    case '\t': cbsSay = 't'; break;
+
    default: cbsSay = 0; break;
+
    }
+
    if( cbsSay ){
+
      ace[1] = cbsSay;
+
      oputz(ace);
    }else if( c<=0x1f ){
-
      fputc('\\', out);
-
      if( c=='\b' ){
-
        fputc('b', out);
-
      }else if( c=='\f' ){
-
        fputc('f', out);
-
      }else if( c=='\n' ){
-
        fputc('n', out);
-
      }else if( c=='\r' ){
-
        fputc('r', out);
-
      }else if( c=='\t' ){
-
        fputc('t', out);
-
      }else{
-
         raw_printf(out, "u%04x",c);
-
      }
+
      oputf("u%04x", c);
    }else{
-
      fputc(c, out);
+
      ace[1] = (char)c;
+
      oputz(ace+1);
    }
  }
-
  fputc('"', out);
+
  oputz(zq);
}

/*
** Output the given string with characters that are special to
** HTML escaped.
*/
-
static void output_html_string(FILE *out, const char *z){
+
static void output_html_string(const char *z){
  int i;
  if( z==0 ) z = "";
  while( *z ){
@@ -17871,18 +18823,18 @@ static void output_html_string(FILE *out, const char *z){
            && z[i]!='\'';
        i++){}
    if( i>0 ){
-
      utf8_printf(out,"%.*s",i,z);
+
      oputf("%.*s",i,z);
    }
    if( z[i]=='<' ){
-
      raw_printf(out,"&lt;");
+
      oputz("&lt;");
    }else if( z[i]=='&' ){
-
      raw_printf(out,"&amp;");
+
      oputz("&amp;");
    }else if( z[i]=='>' ){
-
      raw_printf(out,"&gt;");
+
      oputz("&gt;");
    }else if( z[i]=='\"' ){
-
      raw_printf(out,"&quot;");
+
      oputz("&quot;");
    }else if( z[i]=='\'' ){
-
      raw_printf(out,"&#39;");
+
      oputz("&#39;");
    }else{
      break;
    }
@@ -17920,9 +18872,8 @@ static const char needCsvQuote[] = {
** is only issued if bSep is true.
*/
static void output_csv(ShellState *p, const char *z, int bSep){
-
  FILE *out = p->out;
  if( z==0 ){
-
    utf8_printf(out,"%s",p->nullValue);
+
    oputf("%s",p->nullValue);
  }else{
    unsigned i;
    for(i=0; z[i]; i++){
@@ -17934,14 +18885,14 @@ static void output_csv(ShellState *p, const char *z, int bSep){
    if( i==0 || strstr(z, p->colSeparator)!=0 ){
      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
      shell_check_oom(zQuoted);
-
      utf8_printf(out, "%s", zQuoted);
+
      oputz(zQuoted);
      sqlite3_free(zQuoted);
    }else{
-
      utf8_printf(out, "%s", z);
+
      oputz(z);
    }
  }
  if( bSep ){
-
    utf8_printf(p->out, "%s", p->colSeparator);
+
    oputz(p->colSeparator);
  }
}

@@ -18049,16 +19000,16 @@ static int shellAuth(
  az[1] = zA2;
  az[2] = zA3;
  az[3] = zA4;
-
  utf8_printf(p->out, "authorizer: %s", azAction[op]);
+
  oputf("authorizer: %s", azAction[op]);
  for(i=0; i<4; i++){
-
    raw_printf(p->out, " ");
+
    oputz(" ");
    if( az[i] ){
-
      output_c_string(p->out, az[i]);
+
      output_c_string(az[i]);
    }else{
-
      raw_printf(p->out, "NULL");
+
      oputz("NULL");
    }
  }
-
  raw_printf(p->out, "\n");
+
  oputz("\n");
  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
  return SQLITE_OK;
}
@@ -18074,7 +19025,7 @@ static int shellAuth(
** sqlite3_complete() returns false, try to terminate the comment before
** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
*/
-
static void printSchemaLine(FILE *out, const char *z, const char *zTail){
+
static void printSchemaLine(const char *z, const char *zTail){
  char *zToFree = 0;
  if( z==0 ) return;
  if( zTail==0 ) return;
@@ -18096,16 +19047,16 @@ static void printSchemaLine(FILE *out, const char *z, const char *zTail){
    }
  }
  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
-
    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
+
    oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
  }else{
-
    utf8_printf(out, "%s%s", z, zTail);
+
    oputf("%s%s", z, zTail);
  }
  sqlite3_free(zToFree);
}
-
static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
+
static void printSchemaLineN(char *z, int n, const char *zTail){
  char c = z[n];
  z[n] = 0;
-
  printSchemaLine(out, z, zTail);
+
  printSchemaLine(z, zTail);
  z[n] = c;
}

@@ -18133,7 +19084,7 @@ static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
  if( zText==0 ) return;
  nText = strlen(zText);
  if( p->autoEQPtest ){
-
    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
+
    oputf("%d,%d,%s\n", iEqpId, p2, zText);
  }
  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
  shell_check_oom(pNew);
@@ -18181,8 +19132,7 @@ static void eqp_render_level(ShellState *p, int iEqpId){
  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
    pNext = eqp_next_row(p, iEqpId, pRow);
    z = pRow->zText;
-
    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
-
                pNext ? "|--" : "`--", z);
+
    oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
    if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
      eqp_render_level(p, pRow->iEqpId);
@@ -18202,13 +19152,13 @@ static void eqp_render(ShellState *p, i64 nCycle){
        eqp_reset(p);
        return;
      }
-
      utf8_printf(p->out, "%s\n", pRow->zText+3);
+
      oputf("%s\n", pRow->zText+3);
      p->sGraph.pRow = pRow->pNext;
      sqlite3_free(pRow);
    }else if( nCycle>0 ){
-
      utf8_printf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
+
      oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
    }else{
-
      utf8_printf(p->out, "QUERY PLAN\n");
+
      oputz("QUERY PLAN\n");
    }
    p->sGraph.zPrefix[0] = 0;
    eqp_render_level(p, 0);
@@ -18224,13 +19174,13 @@ static int progress_handler(void *pClientData) {
  ShellState *p = (ShellState*)pClientData;
  p->nProgress++;
  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
-
    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
+
    oputf("Progress limit reached (%u)\n", p->nProgress);
    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
    return 1;
  }
  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
-
    raw_printf(p->out, "Progress %u\n", p->nProgress);
+
    oputf("Progress %u\n", p->nProgress);
  }
  return 0;
}
@@ -18239,14 +19189,14 @@ static int progress_handler(void *pClientData) {
/*
** Print N dashes
*/
-
static void print_dashes(FILE *out, int N){
+
static void print_dashes(int N){
  const char zDash[] = "--------------------------------------------------";
  const int nDash = sizeof(zDash) - 1;
  while( N>nDash ){
-
    fputs(zDash, out);
+
    oputz(zDash);
    N -= nDash;
  }
-
  raw_printf(out, "%.*s", N, zDash);
+
  oputf("%.*s", N, zDash);
}

/*
@@ -18259,15 +19209,15 @@ static void print_row_separator(
){
  int i;
  if( nArg>0 ){
-
    fputs(zSep, p->out);
-
    print_dashes(p->out, p->actualWidth[0]+2);
+
    oputz(zSep);
+
    print_dashes(p->actualWidth[0]+2);
    for(i=1; i<nArg; i++){
-
      fputs(zSep, p->out);
-
      print_dashes(p->out, p->actualWidth[i]+2);
+
      oputz(zSep);
+
      print_dashes(p->actualWidth[i]+2);
    }
-
    fputs(zSep, p->out);
+
    oputz(zSep);
  }
-
  fputs("\n", p->out);
+
  oputz("\n");
}

/*
@@ -18297,10 +19247,10 @@ static int shell_callback(
        int len = strlen30(azCol[i] ? azCol[i] : "");
        if( len>w ) w = len;
      }
-
      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
+
      if( p->cnt++>0 ) oputz(p->rowSeparator);
      for(i=0; i<nArg; i++){
-
        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
-
                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
+
        oputf("%*s = %s%s", w, azCol[i],
+
              azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
      }
      break;
    }
@@ -18327,12 +19277,12 @@ static int shell_callback(
      /* If this is the first row seen, print out the headers */
      if( p->cnt++==0 ){
        for(i=0; i<nArg; i++){
-
          utf8_width_print(p->out, aWidth[i], azCol[ aMap[i] ]);
-
          fputs(i==nArg-1 ? "\n" : "  ", p->out);
+
          utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
+
          oputz(i==nArg-1 ? "\n" : "  ");
        }
        for(i=0; i<nArg; i++){
-
          print_dashes(p->out, aWidth[i]);
-
          fputs(i==nArg-1 ? "\n" : "  ", p->out);
+
          print_dashes(aWidth[i]);
+
          oputz(i==nArg-1 ? "\n" : "  ");
        }
      }

@@ -18350,17 +19300,17 @@ static int shell_callback(
        }
        if( i==iIndent && p->aiIndent && p->pStmt ){
          if( p->iIndent<p->nIndent ){
-
            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
+
            oputf("%*.s", p->aiIndent[p->iIndent], "");
          }
          p->iIndent++;
        }
-
        utf8_width_print(p->out, w, zVal ? zVal : p->nullValue);
-
        fputs(i==nArg-1 ? "\n" : zSep, p->out);
+
        utf8_width_print(w, zVal ? zVal : p->nullValue);
+
        oputz(i==nArg-1 ? "\n" : zSep);
      }
      break;
    }
    case MODE_Semi: {   /* .schema and .fullschema output */
-
      printSchemaLine(p->out, azArg[0], ";\n");
+
      printSchemaLine(azArg[0], ";\n");
      break;
    }
    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
@@ -18375,7 +19325,7 @@ static int shell_callback(
      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
      ){
-
        utf8_printf(p->out, "%s;\n", azArg[0]);
+
        oputf("%s;\n", azArg[0]);
        break;
      }
      z = sqlite3_mprintf("%s", azArg[0]);
@@ -18408,7 +19358,7 @@ static int shell_callback(
          }else if( c==')' ){
            nParen--;
            if( nLine>0 && nParen==0 && j>0 ){
-
              printSchemaLineN(p->out, z, j, "\n");
+
              printSchemaLineN(z, j, "\n");
              j = 0;
            }
          }
@@ -18417,7 +19367,7 @@ static int shell_callback(
           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
          ){
            if( c=='\n' ) j--;
-
            printSchemaLineN(p->out, z, j, "\n  ");
+
            printSchemaLineN(z, j, "\n  ");
            j = 0;
            nLine++;
            while( IsSpace(z[i+1]) ){ i++; }
@@ -18425,64 +19375,59 @@ static int shell_callback(
        }
        z[j] = 0;
      }
-
      printSchemaLine(p->out, z, ";\n");
+
      printSchemaLine(z, ";\n");
      sqlite3_free(z);
      break;
    }
    case MODE_List: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
-
          utf8_printf(p->out,"%s%s",azCol[i],
-
                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
+
          oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
        }
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
        char *z = azArg[i];
        if( z==0 ) z = p->nullValue;
-
        utf8_printf(p->out, "%s", z);
-
        if( i<nArg-1 ){
-
          utf8_printf(p->out, "%s", p->colSeparator);
-
        }else{
-
          utf8_printf(p->out, "%s", p->rowSeparator);
-
        }
+
        oputz(z);
+
        oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
      }
      break;
    }
    case MODE_Html: {
      if( p->cnt++==0 && p->showHeader ){
-
        raw_printf(p->out,"<TR>");
+
        oputz("<TR>");
        for(i=0; i<nArg; i++){
-
          raw_printf(p->out,"<TH>");
-
          output_html_string(p->out, azCol[i]);
-
          raw_printf(p->out,"</TH>\n");
+
          oputz("<TH>");
+
          output_html_string(azCol[i]);
+
          oputz("</TH>\n");
        }
-
        raw_printf(p->out,"</TR>\n");
+
        oputz("</TR>\n");
      }
      if( azArg==0 ) break;
-
      raw_printf(p->out,"<TR>");
+
      oputz("<TR>");
      for(i=0; i<nArg; i++){
-
        raw_printf(p->out,"<TD>");
-
        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
-
        raw_printf(p->out,"</TD>\n");
+
        oputz("<TD>");
+
        output_html_string(azArg[i] ? azArg[i] : p->nullValue);
+
        oputz("</TD>\n");
      }
-
      raw_printf(p->out,"</TR>\n");
+
      oputz("</TR>\n");
      break;
    }
    case MODE_Tcl: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
-
          output_c_string(p->out,azCol[i] ? azCol[i] : "");
-
          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
+
          output_c_string(azCol[i] ? azCol[i] : "");
+
          if(i<nArg-1) oputz(p->colSeparator);
        }
-
        utf8_printf(p->out, "%s", p->rowSeparator);
+
        oputz(p->rowSeparator);
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
-
        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
-
        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
+
        output_c_string(azArg[i] ? azArg[i] : p->nullValue);
+
        if(i<nArg-1) oputz(p->colSeparator);
      }
-
      utf8_printf(p->out, "%s", p->rowSeparator);
+
      oputz(p->rowSeparator);
      break;
    }
    case MODE_Csv: {
@@ -18491,57 +19436,57 @@ static int shell_callback(
        for(i=0; i<nArg; i++){
          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
        }
-
        utf8_printf(p->out, "%s", p->rowSeparator);
+
        oputz(p->rowSeparator);
      }
      if( nArg>0 ){
        for(i=0; i<nArg; i++){
          output_csv(p, azArg[i], i<nArg-1);
        }
-
        utf8_printf(p->out, "%s", p->rowSeparator);
+
        oputz(p->rowSeparator);
      }
      setTextMode(p->out, 1);
      break;
    }
    case MODE_Insert: {
      if( azArg==0 ) break;
-
      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
+
      oputf("INSERT INTO %s",p->zDestTable);
      if( p->showHeader ){
-
        raw_printf(p->out,"(");
+
        oputz("(");
        for(i=0; i<nArg; i++){
-
          if( i>0 ) raw_printf(p->out, ",");
+
          if( i>0 ) oputz(",");
          if( quoteChar(azCol[i]) ){
            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
            shell_check_oom(z);
-
            utf8_printf(p->out, "%s", z);
+
            oputz(z);
            sqlite3_free(z);
          }else{
-
            raw_printf(p->out, "%s", azCol[i]);
+
            oputf("%s", azCol[i]);
          }
        }
-
        raw_printf(p->out,")");
+
        oputz(")");
      }
      p->cnt++;
      for(i=0; i<nArg; i++){
-
        raw_printf(p->out, i>0 ? "," : " VALUES(");
+
        oputz(i>0 ? "," : " VALUES(");
        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
-
          utf8_printf(p->out,"NULL");
+
          oputz("NULL");
        }else if( aiType && aiType[i]==SQLITE_TEXT ){
          if( ShellHasFlag(p, SHFLG_Newlines) ){
-
            output_quoted_string(p->out, azArg[i]);
+
            output_quoted_string(azArg[i]);
          }else{
-
            output_quoted_escaped_string(p->out, azArg[i]);
+
            output_quoted_escaped_string(azArg[i]);
          }
        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
-
          utf8_printf(p->out,"%s", azArg[i]);
+
          oputz(azArg[i]);
        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
          char z[50];
          double r = sqlite3_column_double(p->pStmt, i);
          sqlite3_uint64 ur;
          memcpy(&ur,&r,sizeof(r));
          if( ur==0x7ff0000000000000LL ){
-
            raw_printf(p->out, "9.0e+999");
+
            oputz("9.0e+999");
          }else if( ur==0xfff0000000000000LL ){
-
            raw_printf(p->out, "-9.0e+999");
+
            oputz("-9.0e+999");
          }else{
            sqlite3_int64 ir = (sqlite3_int64)r;
            if( r==(double)ir ){
@@ -18549,21 +19494,21 @@ static int shell_callback(
            }else{
              sqlite3_snprintf(50,z,"%!.20g", r);
            }
-
            raw_printf(p->out, "%s", z);
+
            oputz(z);
          }
        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
          int nBlob = sqlite3_column_bytes(p->pStmt, i);
-
          output_hex_blob(p->out, pBlob, nBlob);
+
          output_hex_blob(pBlob, nBlob);
        }else if( isNumber(azArg[i], 0) ){
-
          utf8_printf(p->out,"%s", azArg[i]);
+
          oputz(azArg[i]);
        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
-
          output_quoted_string(p->out, azArg[i]);
+
          output_quoted_string(azArg[i]);
        }else{
-
          output_quoted_escaped_string(p->out, azArg[i]);
+
          output_quoted_escaped_string(azArg[i]);
        }
      }
-
      raw_printf(p->out,");\n");
+
      oputz(");\n");
      break;
    }
    case MODE_Json: {
@@ -18575,37 +19520,37 @@ static int shell_callback(
      }
      p->cnt++;
      for(i=0; i<nArg; i++){
-
        output_json_string(p->out, azCol[i], -1);
-
        putc(':', p->out);
+
        output_json_string(azCol[i], -1);
+
        oputz(":");
        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
-
          fputs("null",p->out);
+
          oputz("null");
        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
          char z[50];
          double r = sqlite3_column_double(p->pStmt, i);
          sqlite3_uint64 ur;
          memcpy(&ur,&r,sizeof(r));
          if( ur==0x7ff0000000000000LL ){
-
            raw_printf(p->out, "9.0e+999");
+
            oputz("9.0e+999");
          }else if( ur==0xfff0000000000000LL ){
-
            raw_printf(p->out, "-9.0e+999");
+
            oputz("-9.0e+999");
          }else{
            sqlite3_snprintf(50,z,"%!.20g", r);
-
            raw_printf(p->out, "%s", z);
+
            oputz(z);
          }
        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
          int nBlob = sqlite3_column_bytes(p->pStmt, i);
-
          output_json_string(p->out, pBlob, nBlob);
+
          output_json_string(pBlob, nBlob);
        }else if( aiType && aiType[i]==SQLITE_TEXT ){
-
          output_json_string(p->out, azArg[i], -1);
+
          output_json_string(azArg[i], -1);
        }else{
-
          utf8_printf(p->out,"%s", azArg[i]);
+
          oputz(azArg[i]);
        }
        if( i<nArg-1 ){
-
          putc(',', p->out);
+
          oputz(",");
        }
      }
-
      putc('}', p->out);
+
      oputz("}");
      break;
    }
    case MODE_Quote: {
@@ -18613,7 +19558,7 @@ static int shell_callback(
      if( p->cnt==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
          if( i>0 ) fputs(p->colSeparator, p->out);
-
          output_quoted_string(p->out, azCol[i]);
+
          output_quoted_string(azCol[i]);
        }
        fputs(p->rowSeparator, p->out);
      }
@@ -18621,24 +19566,24 @@ static int shell_callback(
      for(i=0; i<nArg; i++){
        if( i>0 ) fputs(p->colSeparator, p->out);
        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
-
          utf8_printf(p->out,"NULL");
+
          oputz("NULL");
        }else if( aiType && aiType[i]==SQLITE_TEXT ){
-
          output_quoted_string(p->out, azArg[i]);
+
          output_quoted_string(azArg[i]);
        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
-
          utf8_printf(p->out,"%s", azArg[i]);
+
          oputz(azArg[i]);
        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
          char z[50];
          double r = sqlite3_column_double(p->pStmt, i);
          sqlite3_snprintf(50,z,"%!.20g", r);
-
          raw_printf(p->out, "%s", z);
+
          oputz(z);
        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
          int nBlob = sqlite3_column_bytes(p->pStmt, i);
-
          output_hex_blob(p->out, pBlob, nBlob);
+
          output_hex_blob(pBlob, nBlob);
        }else if( isNumber(azArg[i], 0) ){
-
          utf8_printf(p->out,"%s", azArg[i]);
+
          oputz(azArg[i]);
        }else{
-
          output_quoted_string(p->out, azArg[i]);
+
          output_quoted_string(azArg[i]);
        }
      }
      fputs(p->rowSeparator, p->out);
@@ -18647,17 +19592,17 @@ static int shell_callback(
    case MODE_Ascii: {
      if( p->cnt++==0 && p->showHeader ){
        for(i=0; i<nArg; i++){
-
          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
-
          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
+
          if( i>0 ) oputz(p->colSeparator);
+
          oputz(azCol[i] ? azCol[i] : "");
        }
-
        utf8_printf(p->out, "%s", p->rowSeparator);
+
        oputz(p->rowSeparator);
      }
      if( azArg==0 ) break;
      for(i=0; i<nArg; i++){
-
        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
-
        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
+
        if( i>0 ) oputz(p->colSeparator);
+
        oputz(azArg[i] ? azArg[i] : p->nullValue);
      }
-
      utf8_printf(p->out, "%s", p->rowSeparator);
+
      oputz(p->rowSeparator);
      break;
    }
    case MODE_EQP: {
@@ -18736,7 +19681,7 @@ static void createSelftestTable(ShellState *p){
    "DROP TABLE [_shell$self];"
    ,0,0,&zErrMsg);
  if( zErrMsg ){
-
    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
+
    eputf("SELFTEST initialization failure: %s\n", zErrMsg);
    sqlite3_free(zErrMsg);
  }
  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
@@ -18839,8 +19784,8 @@ static int run_table_dump_query(
  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  if( rc!=SQLITE_OK || !pSelect ){
    char *zContext = shell_error_context(zSelect, p->db);
-
    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
-
                sqlite3_errmsg(p->db), zContext);
+
    oputf("/**** ERROR: (%d) %s *****/\n%s",
+
          rc, sqlite3_errmsg(p->db), zContext);
    sqlite3_free(zContext);
    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
    return rc;
@@ -18849,23 +19794,22 @@ static int run_table_dump_query(
  nResult = sqlite3_column_count(pSelect);
  while( rc==SQLITE_ROW ){
    z = (const char*)sqlite3_column_text(pSelect, 0);
-
    utf8_printf(p->out, "%s", z);
+
    oputf("%s", z);
    for(i=1; i<nResult; i++){
-
      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
+
      oputf(",%s", sqlite3_column_text(pSelect, i));
    }
    if( z==0 ) z = "";
    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
    if( z[0] ){
-
      raw_printf(p->out, "\n;\n");
+
      oputz("\n;\n");
    }else{
-
      raw_printf(p->out, ";\n");
+
      oputz(";\n");
    }
    rc = sqlite3_step(pSelect);
  }
  rc = sqlite3_finalize(pSelect);
  if( rc!=SQLITE_OK ){
-
    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
-
                sqlite3_errmsg(p->db));
+
    oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  }
  return rc;
@@ -18901,7 +19845,7 @@ static char *save_err_msg(
/*
** Attempt to display I/O stats on Linux using /proc/PID/io
*/
-
static void displayLinuxIoStats(FILE *out){
+
static void displayLinuxIoStats(void){
  FILE *in;
  char z[200];
  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
@@ -18924,7 +19868,7 @@ static void displayLinuxIoStats(FILE *out){
    for(i=0; i<ArraySize(aTrans); i++){
      int n = strlen30(aTrans[i].zPattern);
      if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
-
        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
+
        oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
        break;
      }
    }
@@ -18937,7 +19881,6 @@ static void displayLinuxIoStats(FILE *out){
** Display a single line of status using 64-bit values.
*/
static void displayStatLine(
-
  ShellState *p,            /* The shell context */
  char *zLabel,             /* Label for this one line */
  char *zFormat,            /* Format for the result */
  int iStatusCtrl,          /* Which status to display */
@@ -18956,7 +19899,7 @@ static void displayStatLine(
  }else{
    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
  }
-
  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
+
  oputf("%-36s %s\n", zLabel, zLine);
}

/*
@@ -18969,30 +19912,28 @@ static int display_stats(
){
  int iCur;
  int iHiwtr;
-
  FILE *out;
  if( pArg==0 || pArg->out==0 ) return 0;
-
  out = pArg->out;

  if( pArg->pStmt && pArg->statsOn==2 ){
    int nCol, i, x;
    sqlite3_stmt *pStmt = pArg->pStmt;
    char z[100];
    nCol = sqlite3_column_count(pStmt);
-
    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
+
    oputf("%-36s %d\n", "Number of output columns:", nCol);
    for(i=0; i<nCol; i++){
      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
-
      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
+
      oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
#ifndef SQLITE_OMIT_DECLTYPE
      sqlite3_snprintf(30, z+x, "declared type:");
-
      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
+
      oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
#endif
#ifdef SQLITE_ENABLE_COLUMN_METADATA
      sqlite3_snprintf(30, z+x, "database name:");
-
      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
+
      oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
      sqlite3_snprintf(30, z+x, "table name:");
-
      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
+
      oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
      sqlite3_snprintf(30, z+x, "origin name:");
-
      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
+
      oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
#endif
    }
  }
@@ -19000,27 +19941,27 @@ static int display_stats(
  if( pArg->statsOn==3 ){
    if( pArg->pStmt ){
      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
-
      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
+
      oputf("VM-steps: %d\n", iCur);
    }
    return 0;
  }

-
  displayStatLine(pArg, "Memory Used:",
+
  displayStatLine("Memory Used:",
     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
-
  displayStatLine(pArg, "Number of Outstanding Allocations:",
+
  displayStatLine("Number of Outstanding Allocations:",
     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
  if( pArg->shellFlgs & SHFLG_Pagecache ){
-
    displayStatLine(pArg, "Number of Pcache Pages Used:",
+
    displayStatLine("Number of Pcache Pages Used:",
       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  }
-
  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
+
  displayStatLine("Number of Pcache Overflow Bytes:",
     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
-
  displayStatLine(pArg, "Largest Allocation:",
+
  displayStatLine("Largest Allocation:",
     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
-
  displayStatLine(pArg, "Largest Pcache Allocation:",
+
  displayStatLine("Largest Pcache Allocation:",
     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
#ifdef YYTRACKMAXSTACKDEPTH
-
  displayStatLine(pArg, "Deepest Parser Stack:",
+
  displayStatLine("Deepest Parser Stack:",
     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
#endif

@@ -19029,77 +19970,68 @@ static int display_stats(
      iHiwtr = iCur = -1;
      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
                        &iCur, &iHiwtr, bReset);
-
      raw_printf(pArg->out,
-
              "Lookaside Slots Used:                %d (max %d)\n",
-
              iCur, iHiwtr);
+
      oputf("Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
                        &iCur, &iHiwtr, bReset);
-
      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
-
              iHiwtr);
+
      oputf("Successful lookaside attempts:       %d\n", iHiwtr);
      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
                        &iCur, &iHiwtr, bReset);
-
      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
-
              iHiwtr);
+
      oputf("Lookaside failures due to size:      %d\n", iHiwtr);
      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
                        &iCur, &iHiwtr, bReset);
-
      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
-
              iHiwtr);
+
      oputf("Lookaside failures due to OOM:       %d\n", iHiwtr);
    }
    iHiwtr = iCur = -1;
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
-
    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
-
            iCur);
+
    oputf("Pager Heap Usage:                    %d bytes\n", iCur);
    iHiwtr = iCur = -1;
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
-
    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
+
    oputf("Page cache hits:                     %d\n", iCur);
    iHiwtr = iCur = -1;
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
-
    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
+
    oputf("Page cache misses:                   %d\n", iCur);
    iHiwtr = iCur = -1;
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
-
    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
+
    oputf("Page cache writes:                   %d\n", iCur);
    iHiwtr = iCur = -1;
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
-
    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
+
    oputf("Page cache spills:                   %d\n", iCur);
    iHiwtr = iCur = -1;
    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
-
    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
-
            iCur);
+
    oputf("Schema Heap Usage:                   %d bytes\n", iCur);
    iHiwtr = iCur = -1;
    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
-
    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
-
            iCur);
+
    oputf("Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
  }

  if( pArg->pStmt ){
    int iHit, iMiss;
    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
                               bReset);
-
    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
+
    oputf("Fullscan Steps:                      %d\n", iCur);
    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
-
    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
+
    oputf("Sort Operations:                     %d\n", iCur);
    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
-
    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
+
    oputf("Autoindex Inserts:                   %d\n", iCur);
    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
                               bReset);
    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
                                bReset);
    if( iHit || iMiss ){
-
      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
-
            iHit, iHit+iMiss);
+
      oputf("Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
    }
    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
-
    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
+
    oputf("Virtual Machine Steps:               %d\n", iCur);
    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
-
    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
+
    oputf("Reprepare operations:                %d\n", iCur);
    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
-
    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
+
    oputf("Number of times run:                 %d\n", iCur);
    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
-
    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
+
    oputf("Memory used by prepared stmt:        %d\n", iCur);
  }

#ifdef __linux__
-
  displayLinuxIoStats(pArg->out);
+
  displayLinuxIoStats();
#endif

  /* Do not remove this machine readable comment: extra-stats-output-here */
@@ -19154,7 +20086,7 @@ static void display_explain_scanstats(
    if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
      break;
    }
-
    n = strlen(z) + scanStatsHeight(p, ii)*3;
+
    n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
    if( n>nWidth ) nWidth = n;
  }
  nWidth += 4;
@@ -19166,12 +20098,12 @@ static void display_explain_scanstats(
    i64 nCycle = 0;
    int iId = 0;
    int iPid = 0;
-
    const char *z = 0;
+
    const char *zo = 0;
    const char *zName = 0;
    char *zText = 0;
    double rEst = 0.0;

-
    if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
+
    if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
      break;
    }
    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
@@ -19182,7 +20114,7 @@ static void display_explain_scanstats(
    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);

-
    zText = sqlite3_mprintf("%s", z);
+
    zText = sqlite3_mprintf("%s", zo);
    if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
      char *z = 0;
      if( nCycle>=0 && nTotal>0 ){
@@ -19334,7 +20266,7 @@ static void display_scanstats(
  UNUSED_PARAMETER(pArg);
#else
  if( pArg->scanstatsOn==3 ){
-
    const char *zSql = 
+
    const char *zSql =
      "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
      "   round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
      "   FROM bytecode(?)";
@@ -19480,17 +20412,17 @@ static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
/* Draw horizontal line N characters long using unicode box
** characters
*/
-
static void print_box_line(FILE *out, int N){
+
static void print_box_line(int N){
  const char zDash[] =
      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
  const int nDash = sizeof(zDash) - 1;
  N *= 3;
  while( N>nDash ){
-
    utf8_printf(out, zDash);
+
    oputz(zDash);
    N -= nDash;
  }
-
  utf8_printf(out, "%.*s", N, zDash);
+
  oputf("%.*s", N, zDash);
}

/*
@@ -19505,15 +20437,15 @@ static void print_box_row_separator(
){
  int i;
  if( nArg>0 ){
-
    utf8_printf(p->out, "%s", zSep1);
-
    print_box_line(p->out, p->actualWidth[0]+2);
+
    oputz(zSep1);
+
    print_box_line(p->actualWidth[0]+2);
    for(i=1; i<nArg; i++){
-
      utf8_printf(p->out, "%s", zSep2);
-
      print_box_line(p->out, p->actualWidth[i]+2);
+
      oputz(zSep2);
+
      print_box_line(p->actualWidth[i]+2);
    }
-
    utf8_printf(p->out, "%s", zSep3);
+
    oputz(zSep3);
  }
-
  fputs("\n", p->out);
+
  oputz("\n");
}

/*
@@ -19776,11 +20708,11 @@ static void exec_prepared_stmt_columnar(
        for(i=0; i<nColumn; i++){
          w = p->actualWidth[i];
          if( p->colWidth[i]<0 ) w = -w;
-
          utf8_width_print(p->out, w, azData[i]);
+
          utf8_width_print(w, azData[i]);
          fputs(i==nColumn-1?"\n":"  ", p->out);
        }
        for(i=0; i<nColumn; i++){
-
          print_dashes(p->out, p->actualWidth[i]);
+
          print_dashes(p->actualWidth[i]);
          fputs(i==nColumn-1?"\n":"  ", p->out);
        }
      }
@@ -19794,8 +20726,8 @@ static void exec_prepared_stmt_columnar(
      for(i=0; i<nColumn; i++){
        w = p->actualWidth[i];
        n = strlenChar(azData[i]);
-
        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
-
        fputs(i==nColumn-1?" |\n":" | ", p->out);
+
        oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
+
        oputz(i==nColumn-1?" |\n":" | ");
      }
      print_row_separator(p, nColumn, "+");
      break;
@@ -19807,8 +20739,8 @@ static void exec_prepared_stmt_columnar(
      for(i=0; i<nColumn; i++){
        w = p->actualWidth[i];
        n = strlenChar(azData[i]);
-
        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
-
        fputs(i==nColumn-1?" |\n":" | ", p->out);
+
        oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
+
        oputz(i==nColumn-1?" |\n":" | ");
      }
      print_row_separator(p, nColumn, "|");
      break;
@@ -19817,13 +20749,13 @@ static void exec_prepared_stmt_columnar(
      colSep = " " BOX_13 " ";
      rowSep = " " BOX_13 "\n";
      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
-
      utf8_printf(p->out, BOX_13 " ");
+
      oputz(BOX_13 " ");
      for(i=0; i<nColumn; i++){
        w = p->actualWidth[i];
        n = strlenChar(azData[i]);
-
        utf8_printf(p->out, "%*s%s%*s%s",
-
            (w-n)/2, "", azData[i], (w-n+1)/2, "",
-
            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
+
        oputf("%*s%s%*s%s",
+
              (w-n)/2, "", azData[i], (w-n+1)/2, "",
+
              i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
      }
      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
      break;
@@ -19831,28 +20763,28 @@ static void exec_prepared_stmt_columnar(
  }
  for(i=nColumn, j=0; i<nTotal; i++, j++){
    if( j==0 && p->cMode!=MODE_Column ){
-
      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
+
      oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
    }
    z = azData[i];
    if( z==0 ) z = p->nullValue;
    w = p->actualWidth[j];
    if( p->colWidth[j]<0 ) w = -w;
-
    utf8_width_print(p->out, w, z);
+
    utf8_width_print(w, z);
    if( j==nColumn-1 ){
-
      utf8_printf(p->out, "%s", rowSep);
+
      oputz(rowSep);
      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
        if( p->cMode==MODE_Table ){
          print_row_separator(p, nColumn, "+");
        }else if( p->cMode==MODE_Box ){
          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
        }else if( p->cMode==MODE_Column ){
-
          raw_printf(p->out, "\n");
+
          oputz("\n");
        }
      }
      j = -1;
      if( seenInterrupt ) goto columnar_end;
    }else{
-
      utf8_printf(p->out, "%s", colSep);
+
      oputz(colSep);
    }
  }
  if( p->cMode==MODE_Table ){
@@ -19862,7 +20794,7 @@ static void exec_prepared_stmt_columnar(
  }
columnar_end:
  if( seenInterrupt ){
-
    utf8_printf(p->out, "Interrupt\n");
+
    oputz("Interrupt\n");
  }
  nData = (nRow+1)*nColumn;
  for(i=0; i<nData; i++){
@@ -20001,7 +20933,6 @@ static int expertFinish(
  assert( p );
  assert( bCancel || pzErr==0 || *pzErr==0 );
  if( bCancel==0 ){
-
    FILE *out = pState->out;
    int bVerbose = pState->expert.bVerbose;

    rc = sqlite3_expert_analyze(p, pzErr);
@@ -20011,8 +20942,8 @@ static int expertFinish(

      if( bVerbose ){
        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
-
        raw_printf(out, "-- Candidates -----------------------------\n");
-
        raw_printf(out, "%s\n", zCand);
+
        oputz("-- Candidates -----------------------------\n");
+
        oputf("%s\n", zCand);
      }
      for(i=0; i<nQuery; i++){
        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
@@ -20020,11 +20951,11 @@ static int expertFinish(
        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
        if( zIdx==0 ) zIdx = "(no new indexes)\n";
        if( bVerbose ){
-
          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
-
          raw_printf(out, "%s\n\n", zSql);
+
          oputf("-- Query %d --------------------------------\n",i+1);
+
          oputf("%s\n\n", zSql);
        }
-
        raw_printf(out, "%s\n", zIdx);
-
        raw_printf(out, "%s\n", zEQP);
+
        oputf("%s\n", zIdx);
+
        oputf("%s\n", zEQP);
      }
    }
  }
@@ -20059,18 +20990,18 @@ static int expertDotCommand(
    }
    else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
      if( i==(nArg-1) ){
-
        raw_printf(stderr, "option requires an argument: %s\n", z);
+
        eputf("option requires an argument: %s\n", z);
        rc = SQLITE_ERROR;
      }else{
        iSample = (int)integerValue(azArg[++i]);
        if( iSample<0 || iSample>100 ){
-
          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
+
          eputf("value out of range: %s\n", azArg[i]);
          rc = SQLITE_ERROR;
        }
      }
    }
    else{
-
      raw_printf(stderr, "unknown option: %s\n", z);
+
      eputf("unknown option: %s\n", z);
      rc = SQLITE_ERROR;
    }
  }
@@ -20078,8 +21009,7 @@ static int expertDotCommand(
  if( rc==SQLITE_OK ){
    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
    if( pState->expert.pExpert==0 ){
-
      raw_printf(stderr, "sqlite3_expert_new: %s\n",
-
                 zErr ? zErr : "out of memory");
+
      eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
      rc = SQLITE_ERROR;
    }else{
      sqlite3_expert_config(
@@ -20406,9 +21336,9 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;

  if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
-
    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
+
    if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
-
    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
+
    if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
  }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
    return 0;
  }else if( dataOnly ){
@@ -20416,7 +21346,7 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
    char *zIns;
    if( !p->writableSchema ){
-
      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
+
      oputz("PRAGMA writable_schema=ON;\n");
      p->writableSchema = 1;
    }
    zIns = sqlite3_mprintf(
@@ -20424,11 +21354,11 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
       "VALUES('table','%q','%q',0,'%q');",
       zTable, zTable, zSql);
    shell_check_oom(zIns);
-
    utf8_printf(p->out, "%s\n", zIns);
+
    oputf("%s\n", zIns);
    sqlite3_free(zIns);
    return 0;
  }else{
-
    printSchemaLine(p->out, zSql, ";\n");
+
    printSchemaLine(zSql, ";\n");
  }

  if( cli_strcmp(zType, "table")==0 ){
@@ -20486,7 +21416,7 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
    p->mode = p->cMode = MODE_Insert;
    rc = shell_exec(p, sSelect.z, 0);
    if( (rc&0xff)==SQLITE_CORRUPT ){
-
      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
+
      oputz("/****** CORRUPTION ERROR *******/\n");
      toggleSelectOrder(p->db);
      shell_exec(p, sSelect.z, 0);
      toggleSelectOrder(p->db);
@@ -20517,9 +21447,9 @@ static int run_schema_dump_query(
  if( rc==SQLITE_CORRUPT ){
    char *zQ2;
    int len = strlen30(zQuery);
-
    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
+
    oputz("/****** CORRUPTION ERROR *******/\n");
    if( zErr ){
-
      utf8_printf(p->out, "/****** %s ******/\n", zErr);
+
      oputf("/****** %s ******/\n", zErr);
      sqlite3_free(zErr);
      zErr = 0;
    }
@@ -20528,7 +21458,7 @@ static int run_schema_dump_query(
    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
    if( rc ){
-
      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
+
      oputf("/****** ERROR: %s ******/\n", zErr);
    }else{
      rc = SQLITE_CORRUPT;
    }
@@ -20884,10 +21814,10 @@ static int showHelp(FILE *out, const char *zPattern){
      }
      if( ((hw^hh)&HH_Undoc)==0 ){
        if( (hh&HH_Summary)!=0 ){
-
          utf8_printf(out, ".%s\n", azHelp[i]+1);
+
          sputf(out, ".%s\n", azHelp[i]+1);
          ++n;
        }else if( (hw&HW_SummaryOnly)==0 ){
-
          utf8_printf(out, "%s\n", azHelp[i]);
+
          sputf(out, "%s\n", azHelp[i]);
        }
      }
    }
@@ -20897,7 +21827,7 @@ static int showHelp(FILE *out, const char *zPattern){
    shell_check_oom(zPat);
    for(i=0; i<ArraySize(azHelp); i++){
      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
-
        utf8_printf(out, "%s\n", azHelp[i]);
+
        sputf(out, "%s\n", azHelp[i]);
        j = i+1;
        n++;
      }
@@ -20908,7 +21838,7 @@ static int showHelp(FILE *out, const char *zPattern){
        /* when zPattern is a prefix of exactly one command, then include
        ** the details of that command, which should begin at offset j */
        while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
-
          utf8_printf(out, "%s\n", azHelp[j]);
+
          sputf(out, "%s\n", azHelp[j]);
          j++;
        }
      }
@@ -20925,10 +21855,10 @@ static int showHelp(FILE *out, const char *zPattern){
      }
      if( azHelp[i][0]=='.' ) j = i;
      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
-
        utf8_printf(out, "%s\n", azHelp[j]);
+
        sputf(out, "%s\n", azHelp[j]);
        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
          j++;
-
          utf8_printf(out, "%s\n", azHelp[j]);
+
          sputf(out, "%s\n", azHelp[j]);
        }
        i = j;
        n++;
@@ -20966,7 +21896,7 @@ static char *readFile(const char *zName, int *pnByte){
  if( in==0 ) return 0;
  rc = fseek(in, 0, SEEK_END);
  if( rc!=0 ){
-
    raw_printf(stderr, "Error: '%s' not seekable\n", zName);
+
    eputf("Error: '%s' not seekable\n", zName);
    fclose(in);
    return 0;
  }
@@ -20974,7 +21904,7 @@ static char *readFile(const char *zName, int *pnByte){
  rewind(in);
  pBuf = sqlite3_malloc64( nIn+1 );
  if( pBuf==0 ){
-
    raw_printf(stderr, "Error: out of memory\n");
+
    eputz("Error: out of memory\n");
    fclose(in);
    return 0;
  }
@@ -20982,7 +21912,7 @@ static char *readFile(const char *zName, int *pnByte){
  fclose(in);
  if( nRead!=1 ){
    sqlite3_free(pBuf);
-
    raw_printf(stderr, "Error: cannot read '%s'\n", zName);
+
    eputf("Error: cannot read '%s'\n", zName);
    return 0;
  }
  pBuf[nIn] = 0;
@@ -21103,7 +22033,7 @@ static unsigned char *readHexDb(ShellState *p, int *pnData){
  if( zDbFilename ){
    in = fopen(zDbFilename, "r");
    if( in==0 ){
-
      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
+
      eputf("cannot open \"%s\" for reading\n", zDbFilename);
      return 0;
    }
    nLine = 0;
@@ -21124,7 +22054,7 @@ static unsigned char *readHexDb(ShellState *p, int *pnData){
  shell_check_oom(a);
  memset(a, 0, n);
  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
-
    utf8_printf(stderr, "invalid pagesize\n");
+
    eputz("invalid pagesize\n");
    goto readHexDb_error;
  }
  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
@@ -21166,7 +22096,7 @@ readHexDb_error:
    p->lineno = nLine;
  }
  sqlite3_free(a);
-
  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
+
  eputf("Error on line %d of --hexdb input\n", nLine);
  return 0;
}
#endif /* SQLITE_OMIT_DESERIALIZE */
@@ -21242,22 +22172,19 @@ static void open_db(ShellState *p, int openFlags){
    }
    globalDb = p->db;
    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
-
      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
-
          zDbFilename, sqlite3_errmsg(p->db));
+
      eputf("Error: unable to open database \"%s\": %s\n",
+
            zDbFilename, sqlite3_errmsg(p->db));
      if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
        exit(1);
      }
      sqlite3_close(p->db);
      sqlite3_open(":memory:", &p->db);
      if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
-
        utf8_printf(stderr,
-
          "Also: unable to open substitute in-memory database.\n"
-
        );
+
        eputz("Also: unable to open substitute in-memory database.\n");
        exit(1);
      }else{
-
        utf8_printf(stderr,
-
          "Notice: using substitute in-memory database instead of \"%s\"\n",
-
          zDbFilename);
+
        eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
+
              zDbFilename);
      }
    }
    sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
@@ -21364,7 +22291,7 @@ static void open_db(ShellState *p, int openFlags){
                   SQLITE_DESERIALIZE_RESIZEABLE |
                   SQLITE_DESERIALIZE_FREEONCLOSE);
      if( rc ){
-
        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
+
        eputf("Error: sqlite3_deserialize() returns %d\n", rc);
      }
      if( p->szMax>0 ){
        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
@@ -21388,8 +22315,7 @@ static void open_db(ShellState *p, int openFlags){
void close_db(sqlite3 *db){
  int rc = sqlite3_close(db);
  if( rc ){
-
    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
-
        rc, sqlite3_errmsg(db));
+
    eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
  }
}

@@ -21550,8 +22476,7 @@ static int booleanValue(const char *zArg){
  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
    return 0;
  }
-
  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
-
          zArg);
+
  eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
  return 0;
}

@@ -21589,7 +22514,7 @@ static FILE *output_file_open(const char *zFile, int bTextMode){
  }else{
    f = fopen(zFile, bTextMode ? "w" : "wb");
    if( f==0 ){
-
      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
+
      eputf("Error: cannot open \"%s\"\n", zFile);
    }
  }
  return f;
@@ -21611,7 +22536,7 @@ static int sql_trace_callback(
  i64 nSql;
  if( p->traceOut==0 ) return 0;
  if( mType==SQLITE_TRACE_CLOSE ){
-
    utf8_printf(p->traceOut, "-- closing database connection\n");
+
    sputz(p->traceOut, "-- closing database connection\n");
    return 0;
  }
  if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
@@ -21642,12 +22567,12 @@ static int sql_trace_callback(
  switch( mType ){
    case SQLITE_TRACE_ROW:
    case SQLITE_TRACE_STMT: {
-
      utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
+
      sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
      break;
    }
    case SQLITE_TRACE_PROFILE: {
      sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
-
      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
+
      sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
      break;
    }
  }
@@ -21754,12 +22679,11 @@ static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
        break;
      }
      if( pc==cQuote && c!='\r' ){
-
        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
-
                p->zFile, p->nLine, cQuote);
+
        eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
      }
      if( c==EOF ){
-
        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
-
                p->zFile, startLine, cQuote);
+
        eputf("%s:%d: unterminated %c-quoted field\n",
+
              p->zFile, startLine, cQuote);
        p->cTerm = c;
        break;
      }
@@ -21857,9 +22781,8 @@ static void tryToCloneData(
  shell_check_oom(zQuery);
  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  if( rc ){
-
    utf8_printf(stderr, "Error %d: %s on [%s]\n",
-
            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
-
            zQuery);
+
    eputf("Error %d: %s on [%s]\n",
+
          sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
    goto end_data_xfer;
  }
  n = sqlite3_column_count(pQuery);
@@ -21875,9 +22798,8 @@ static void tryToCloneData(
  memcpy(zInsert+i, ");", 3);
  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  if( rc ){
-
    utf8_printf(stderr, "Error %d: %s on [%s]\n",
-
            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
-
            zInsert);
+
    eputf("Error %d: %s on [%s]\n",
+
          sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
    goto end_data_xfer;
  }
  for(k=0; k<2; k++){
@@ -21912,8 +22834,8 @@ static void tryToCloneData(
      } /* End for */
      rc = sqlite3_step(pInsert);
      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
-
        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
-
                        sqlite3_errmsg(newDb));
+
        eputf("Error %d: %s\n",
+
              sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
      }
      sqlite3_reset(pInsert);
      cnt++;
@@ -21930,7 +22852,7 @@ static void tryToCloneData(
    shell_check_oom(zQuery);
    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
    if( rc ){
-
      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
+
      eputf("Warning: cannot step \"%s\" backwards", zTable);
      break;
    }
  } /* End for(k=0...) */
@@ -21967,9 +22889,8 @@ static void tryToCloneSchema(
  shell_check_oom(zQuery);
  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  if( rc ){
-
    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
-
                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
-
                    zQuery);
+
    eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
+
          sqlite3_errmsg(p->db), zQuery);
    goto end_schema_xfer;
  }
  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
@@ -21977,10 +22898,10 @@ static void tryToCloneSchema(
    zSql = sqlite3_column_text(pQuery, 1);
    if( zName==0 || zSql==0 ) continue;
    if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
-
      printf("%s... ", zName); fflush(stdout);
+
      sputf(stdout, "%s... ", zName); fflush(stdout);
      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
      if( zErrMsg ){
-
        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
+
        eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
        sqlite3_free(zErrMsg);
        zErrMsg = 0;
      }
@@ -21988,7 +22909,7 @@ static void tryToCloneSchema(
    if( xForEach ){
      xForEach(p, newDb, (const char*)zName);
    }
-
    printf("done\n");
+
    sputz(stdout, "done\n");
  }
  if( rc!=SQLITE_DONE ){
    sqlite3_finalize(pQuery);
@@ -21998,9 +22919,8 @@ static void tryToCloneSchema(
    shell_check_oom(zQuery);
    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
    if( rc ){
-
      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
-
                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
-
                      zQuery);
+
      eputf("Error: (%d) %s on [%s]\n",
+
            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
      goto end_schema_xfer;
    }
    while( sqlite3_step(pQuery)==SQLITE_ROW ){
@@ -22008,17 +22928,17 @@ static void tryToCloneSchema(
      zSql = sqlite3_column_text(pQuery, 1);
      if( zName==0 || zSql==0 ) continue;
      if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
-
      printf("%s... ", zName); fflush(stdout);
+
      sputf(stdout, "%s... ", zName); fflush(stdout);
      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
      if( zErrMsg ){
-
        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
+
        eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
        sqlite3_free(zErrMsg);
        zErrMsg = 0;
      }
      if( xForEach ){
        xForEach(p, newDb, (const char*)zName);
      }
-
      printf("done\n");
+
      sputz(stdout, "done\n");
    }
  }
end_schema_xfer:
@@ -22035,13 +22955,12 @@ static void tryToClone(ShellState *p, const char *zNewDb){
  int rc;
  sqlite3 *newDb = 0;
  if( access(zNewDb,0)==0 ){
-
    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
+
    eputf("File \"%s\" already exists.\n", zNewDb);
    return;
  }
  rc = sqlite3_open(zNewDb, &newDb);
  if( rc ){
-
    utf8_printf(stderr, "Cannot create output database: %s\n",
-
            sqlite3_errmsg(newDb));
+
    eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
  }else{
    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
@@ -22053,6 +22972,18 @@ static void tryToClone(ShellState *p, const char *zNewDb){
  close_db(newDb);
}

+
#ifndef SQLITE_SHELL_FIDDLE
+
/*
+
** Change the output stream (file or pipe or console) to something else.
+
*/
+
static void output_redir(ShellState *p, FILE *pfNew){
+
  if( p->out != stdout ) eputz("Output already redirected.\n");
+
  else{
+
    p->out = pfNew;
+
    setOutputStream(pfNew);
+
  }
+
}
+

/*
** Change the output file back to stdout.
**
@@ -22080,7 +23011,7 @@ static void output_reset(ShellState *p){
      char *zCmd;
      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
      if( system(zCmd) ){
-
        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
+
        eputf("Failed: [%s]\n", zCmd);
      }else{
        /* Give the start/open/xdg-open command some time to get
        ** going before we continue, and potential delete the
@@ -22095,7 +23026,12 @@ static void output_reset(ShellState *p){
  }
  p->outfile[0] = 0;
  p->out = stdout;
+
  setOutputStream(stdout);
}
+
#else
+
# define output_redir(SS,pfO)
+
# define output_reset(SS)
+
#endif

/*
** Run an SQL command and return the single integer result.
@@ -22166,7 +23102,7 @@ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
             -1, &pStmt, 0);
  if( rc ){
-
    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
+
    eputf("error: %s\n", sqlite3_errmsg(p->db));
    sqlite3_finalize(pStmt);
    return 1;
  }
@@ -22179,28 +23115,28 @@ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
    memcpy(aHdr, pb, 100);
    sqlite3_finalize(pStmt);
  }else{
-
    raw_printf(stderr, "unable to read database header\n");
+
    eputz("unable to read database header\n");
    sqlite3_finalize(pStmt);
    return 1;
  }
  i = get2byteInt(aHdr+16);
  if( i==1 ) i = 65536;
-
  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
-
  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
-
  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
-
  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
+
  oputf("%-20s %d\n", "database page size:", i);
+
  oputf("%-20s %d\n", "write format:", aHdr[18]);
+
  oputf("%-20s %d\n", "read format:", aHdr[19]);
+
  oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
  for(i=0; i<ArraySize(aField); i++){
    int ofst = aField[i].ofst;
    unsigned int val = get4byteInt(aHdr + ofst);
-
    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
+
    oputf("%-20s %u", aField[i].zName, val);
    switch( ofst ){
      case 56: {
-
        if( val==1 ) raw_printf(p->out, " (utf8)");
-
        if( val==2 ) raw_printf(p->out, " (utf16le)");
-
        if( val==3 ) raw_printf(p->out, " (utf16be)");
+
        if( val==1 ) oputz(" (utf8)");
+
        if( val==2 ) oputz(" (utf16le)");
+
        if( val==3 ) oputz(" (utf16be)");
      }
    }
-
    raw_printf(p->out, "\n");
+
    oputz("\n");
  }
  if( zDb==0 ){
    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
@@ -22213,11 +23149,11 @@ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
    int val = db_int(p->db, zSql);
    sqlite3_free(zSql);
-
    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
+
    oputf("%-20s %d\n", aQuery[i].zName, val);
  }
  sqlite3_free(zSchemaTab);
  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
-
  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
+
  oputf("%-20s %u\n", "data version", iDataVersion);
  return 0;
}
#endif /* SQLITE_SHELL_HAVE_RECOVER */
@@ -22227,7 +23163,7 @@ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
*/
static int shellDatabaseError(sqlite3 *db){
  const char *zErr = sqlite3_errmsg(db);
-
  utf8_printf(stderr, "Error: %s\n", zErr);
+
  eputf("Error: %s\n", zErr);
  return 1;
}

@@ -22462,7 +23398,6 @@ static int lintFkeyIndexes(
  int nArg                        /* Number of entries in azArg[] */
){
  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
-
  FILE *out = pState->out;        /* Stream to write non-error output to */
  int bVerbose = 0;               /* If -verbose is present */
  int bGroupByParent = 0;         /* If -groupbyparent is present */
  int i;                          /* To iterate through azArg[] */
@@ -22544,9 +23479,7 @@ static int lintFkeyIndexes(
      zIndent = "    ";
    }
    else{
-
      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
-
          azArg[0], azArg[1]
-
      );
+
      eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
      return SQLITE_ERROR;
    }
  }
@@ -22590,23 +23523,23 @@ static int lintFkeyIndexes(
      if( rc!=SQLITE_OK ) break;

      if( res<0 ){
-
        raw_printf(stderr, "Error: internal error");
+
        eputz("Error: internal error");
        break;
      }else{
        if( bGroupByParent
        && (bVerbose || res==0)
        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
        ){
-
          raw_printf(out, "-- Parent table %s\n", zParent);
+
          oputf("-- Parent table %s\n", zParent);
          sqlite3_free(zPrev);
          zPrev = sqlite3_mprintf("%s", zParent);
        }

        if( res==0 ){
-
          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
+
          oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
        }else if( bVerbose ){
-
          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
-
              zIndent, zFrom, zTarget
+
          oputf("%s/* no extra indexes required for %s -> %s */\n",
+
                zIndent, zFrom, zTarget
          );
        }
      }
@@ -22614,16 +23547,16 @@ static int lintFkeyIndexes(
    sqlite3_free(zPrev);

    if( rc!=SQLITE_OK ){
-
      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
+
      eputf("%s\n", sqlite3_errmsg(db));
    }

    rc2 = sqlite3_finalize(pSql);
    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
      rc = rc2;
-
      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
+
      eputf("%s\n", sqlite3_errmsg(db));
    }
  }else{
-
    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
+
    eputf("%s\n", sqlite3_errmsg(db));
  }

  return rc;
@@ -22643,9 +23576,9 @@ static int lintDotCommand(
  return lintFkeyIndexes(pState, azArg, nArg);

 usage:
-
  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
-
  raw_printf(stderr, "Where sub-commands are:\n");
-
  raw_printf(stderr, "    fkey-indexes\n");
+
  eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
+
  eputz("Where sub-commands are:\n");
+
  eputz("    fkey-indexes\n");
  return SQLITE_ERROR;
}

@@ -22660,9 +23593,7 @@ static void shellPrepare(
  if( *pRc==SQLITE_OK ){
    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
    if( rc!=SQLITE_OK ){
-
      raw_printf(stderr, "sql error: %s (%d)\n",
-
          sqlite3_errmsg(db), sqlite3_errcode(db)
-
      );
+
      eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
      *pRc = rc;
    }
  }
@@ -22713,7 +23644,7 @@ void shellFinalize(
    int rc = sqlite3_finalize(pStmt);
    if( *pRc==SQLITE_OK ){
      if( rc!=SQLITE_OK ){
-
        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
+
        eputf("SQL error: %s\n", sqlite3_errmsg(db));
      }
      *pRc = rc;
    }
@@ -22734,7 +23665,7 @@ void shellReset(
  if( *pRc==SQLITE_OK ){
    if( rc!=SQLITE_OK ){
      sqlite3 *db = sqlite3_db_handle(pStmt);
-
      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
+
      eputf("SQL error: %s\n", sqlite3_errmsg(db));
    }
    *pRc = rc;
  }
@@ -22784,11 +23715,11 @@ static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
  va_start(ap, zFmt);
  z = sqlite3_vmprintf(zFmt, ap);
  va_end(ap);
-
  utf8_printf(stderr, "Error: %s\n", z);
+
  eputf("Error: %s\n", z);
  if( pAr->fromCmdLine ){
-
    utf8_printf(stderr, "Use \"-A\" for more help\n");
+
    eputz("Use \"-A\" for more help\n");
  }else{
-
    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
+
    eputz("Use \".archive --help\" for more help\n");
  }
  sqlite3_free(z);
  return SQLITE_ERROR;
@@ -22888,7 +23819,7 @@ static int arParseCommand(
  struct ArSwitch *pEnd = &aSwitch[nSwitch];

  if( nArg<=1 ){
-
    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
+
    eputz("Wrong number of arguments.  Usage:\n");
    return arUsage(stderr);
  }else{
    char *z = azArg[1];
@@ -22994,7 +23925,7 @@ static int arParseCommand(
    }
  }
  if( pAr->eCmd==0 ){
-
    utf8_printf(stderr, "Required argument missing.  Usage:\n");
+
    eputz("Required argument missing.  Usage:\n");
    return arUsage(stderr);
  }
  return SQLITE_OK;
@@ -23037,7 +23968,7 @@ static int arCheckEntries(ArCommand *pAr){
      }
      shellReset(&rc, pTest);
      if( rc==SQLITE_OK && bOk==0 ){
-
        utf8_printf(stderr, "not found in archive: %s\n", z);
+
        eputf("not found in archive: %s\n", z);
        rc = SQLITE_ERROR;
      }
    }
@@ -23104,18 +24035,15 @@ static int arListCommand(ArCommand *pAr){
  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
                     pAr->zSrcTable, zWhere);
  if( pAr->bDryRun ){
-
    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
+
    oputf("%s\n", sqlite3_sql(pSql));
  }else{
    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
      if( pAr->bVerbose ){
-
        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
-
            sqlite3_column_text(pSql, 0),
-
            sqlite3_column_int(pSql, 1),
-
            sqlite3_column_text(pSql, 2),
-
            sqlite3_column_text(pSql, 3)
-
        );
+
        oputf("%s % 10d  %s  %s\n",
+
              sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
+
              sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
      }else{
-
        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
+
        oputf("%s\n", sqlite3_column_text(pSql, 0));
      }
    }
  }
@@ -23124,7 +24052,6 @@ static int arListCommand(ArCommand *pAr){
  return rc;
}

-

/*
** Implementation of .ar "Remove" command.
*/
@@ -23143,7 +24070,7 @@ static int arRemoveCommand(ArCommand *pAr){
    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
                           pAr->zSrcTable, zWhere);
    if( pAr->bDryRun ){
-
      utf8_printf(pAr->p->out, "%s\n", zSql);
+
      oputf("%s\n", zSql);
    }else{
      char *zErr = 0;
      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
@@ -23156,7 +24083,7 @@ static int arRemoveCommand(ArCommand *pAr){
        }
      }
      if( zErr ){
-
        utf8_printf(stdout, "ERROR: %s\n", zErr);
+
        sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
        sqlite3_free(zErr);
      }
    }
@@ -23220,11 +24147,11 @@ static int arExtractCommand(ArCommand *pAr){
      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
      sqlite3_bind_int(pSql, j, i);
      if( pAr->bDryRun ){
-
        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
+
        oputf("%s\n", sqlite3_sql(pSql));
      }else{
        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
          if( i==0 && pAr->bVerbose ){
-
            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
+
            oputf("%s\n", sqlite3_column_text(pSql, 0));
          }
        }
      }
@@ -23244,13 +24171,13 @@ static int arExtractCommand(ArCommand *pAr){
static int arExecSql(ArCommand *pAr, const char *zSql){
  int rc;
  if( pAr->bDryRun ){
-
    utf8_printf(pAr->p->out, "%s\n", zSql);
+
    oputf("%s\n", zSql);
    rc = SQLITE_OK;
  }else{
    char *zErr = 0;
    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
    if( zErr ){
-
      utf8_printf(stdout, "ERROR: %s\n", zErr);
+
      sputf(stdout, "ERROR: %s\n", zErr);
      sqlite3_free(zErr);
    }
  }
@@ -23425,15 +24352,13 @@ static int arDotCommand(
      }
      cmd.db = 0;
      if( cmd.bDryRun ){
-
        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
-
             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
+
        oputf("-- open database '%s'%s\n", cmd.zFile,
+
              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
      }
      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
      if( rc!=SQLITE_OK ){
-
        utf8_printf(stderr, "cannot open file: %s (%s)\n",
-
            cmd.zFile, sqlite3_errmsg(cmd.db)
-
        );
+
        eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
        goto end_ar_command;
      }
      sqlite3_fileio_init(cmd.db, 0, 0);
@@ -23446,7 +24371,7 @@ static int arDotCommand(
      if( cmd.eCmd!=AR_CMD_CREATE
       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
      ){
-
        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
+
        eputz("database does not contain an 'sqlar' table\n");
        rc = SQLITE_ERROR;
        goto end_ar_command;
      }
@@ -23504,7 +24429,7 @@ end_ar_command:
*/
static int recoverSqlCb(void *pCtx, const char *zSql){
  ShellState *pState = (ShellState*)pCtx;
-
  utf8_printf(pState->out, "%s;\n", zSql);
+
  sputf(pState->out, "%s;\n", zSql);
  return SQLITE_OK;
}

@@ -23547,7 +24472,7 @@ static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
      bRowids = 0;
    }
    else{
-
      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
+
      eputf("unexpected option: %s\n", azArg[i]);
      showHelp(pState->out, azArg[0]);
      return 1;
    }
@@ -23566,7 +24491,7 @@ static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
  if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
    const char *zErr = sqlite3_recover_errmsg(p);
    int errCode = sqlite3_recover_errcode(p);
-
    raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
+
    eputf("sql error: %s (%d)\n", zErr, errCode);
  }
  rc = sqlite3_recover_finish(p);
  return rc;
@@ -23591,7 +24516,7 @@ static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
#define rc_err_oom_die(rc) \
  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
-
    fprintf(stderr,"E:%d\n",rc), assert(0)
+
    eputf("E:%d\n",rc), assert(0)
#else
static void rc_err_oom_die(int rc){
  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
@@ -23731,6 +24656,7 @@ FROM (\
        sqlite3_exec(*pDb,"drop table if exists ColNames;"
                     "drop view if exists RepeatedNames;",0,0,0);
#endif
+
#undef SHELL_COLFIX_DB
      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
      rc_err_oom_die(rc);
    }
@@ -23830,7 +24756,6 @@ static int do_meta_command(char *zLine, ShellState *p){
      azArg[nArg++] = &zLine[h];
      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
      if( zLine[h] ) zLine[h++] = 0;
-
      resolve_backslashes(azArg[nArg-1]);
    }
  }
  azArg[nArg] = 0;
@@ -23845,7 +24770,7 @@ static int do_meta_command(char *zLine, ShellState *p){
#ifndef SQLITE_OMIT_AUTHORIZATION
  if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
    if( nArg!=2 ){
-
      raw_printf(stderr, "Usage: .auth ON|OFF\n");
+
      eputz("Usage: .auth ON|OFF\n");
      rc = 1;
      goto meta_command_exit;
    }
@@ -23892,7 +24817,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          bAsync = 1;
        }else
        {
-
          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
+
          eputf("unknown option: %s\n", azArg[j]);
          return 1;
        }
      }else if( zDestFile==0 ){
@@ -23901,19 +24826,19 @@ static int do_meta_command(char *zLine, ShellState *p){
        zDb = zDestFile;
        zDestFile = azArg[j];
      }else{
-
        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
+
        eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
        return 1;
      }
    }
    if( zDestFile==0 ){
-
      raw_printf(stderr, "missing FILENAME argument on .backup\n");
+
      eputz("missing FILENAME argument on .backup\n");
      return 1;
    }
    if( zDb==0 ) zDb = "main";
    rc = sqlite3_open_v2(zDestFile, &pDest,
                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
    if( rc!=SQLITE_OK ){
-
      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
+
      eputf("Error: cannot open \"%s\"\n", zDestFile);
      close_db(pDest);
      return 1;
    }
@@ -23924,7 +24849,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    open_db(p, 0);
    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
    if( pBackup==0 ){
-
      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
+
      eputf("Error: %s\n", sqlite3_errmsg(pDest));
      close_db(pDest);
      return 1;
    }
@@ -23933,7 +24858,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( rc==SQLITE_DONE ){
      rc = 0;
    }else{
-
      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
+
      eputf("Error: %s\n", sqlite3_errmsg(pDest));
      rc = 1;
    }
    close_db(pDest);
@@ -23944,7 +24869,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( nArg==2 ){
      bail_on_error = booleanValue(azArg[1]);
    }else{
-
      raw_printf(stderr, "Usage: .bail on|off\n");
+
      eputz("Usage: .bail on|off\n");
      rc = 1;
    }
  }else
@@ -23958,9 +24883,8 @@ static int do_meta_command(char *zLine, ShellState *p){
        setTextMode(p->out, 1);
      }
    }else{
-
      raw_printf(stderr, "The \".binary\" command is deprecated."
-
                         " Use \".crnl\" instead.\n");
-
      raw_printf(stderr, "Usage: .binary on|off\n");
+
      eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
+
            "Usage: .binary on|off\n");
      rc = 1;
    }
  }else
@@ -23984,11 +24908,11 @@ static int do_meta_command(char *zLine, ShellState *p){
      rc = chdir(azArg[1]);
#endif
      if( rc ){
-
        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
+
        eputf("Cannot change to directory \"%s\"\n", azArg[1]);
        rc = 1;
      }
    }else{
-
      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
+
      eputz("Usage: .cd DIRECTORY\n");
      rc = 1;
    }
  }else
@@ -23998,7 +24922,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( nArg==2 ){
      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
    }else{
-
      raw_printf(stderr, "Usage: .changes on|off\n");
+
      eputz("Usage: .changes on|off\n");
      rc = 1;
    }
  }else
@@ -24012,17 +24936,16 @@ static int do_meta_command(char *zLine, ShellState *p){
    char *zRes = 0;
    output_reset(p);
    if( nArg!=2 ){
-
      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
+
      eputz("Usage: .check GLOB-PATTERN\n");
      rc = 2;
    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
      rc = 2;
    }else if( testcase_glob(azArg[1],zRes)==0 ){
-
      utf8_printf(stderr,
-
                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
-
                 p->zTestcase, azArg[1], zRes);
+
      eputf("testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
+
            p->zTestcase, azArg[1], zRes);
      rc = 1;
    }else{
-
      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
+
      oputf("testcase-%s ok\n", p->zTestcase);
      p->nCheck++;
    }
    sqlite3_free(zRes);
@@ -24035,7 +24958,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( nArg==2 ){
      tryToClone(p, azArg[1]);
    }else{
-
      raw_printf(stderr, "Usage: .clone FILENAME\n");
+
      eputz("Usage: .clone FILENAME\n");
      rc = 1;
    }
  }else
@@ -24055,9 +24978,9 @@ static int do_meta_command(char *zLine, ShellState *p){
          zFile = "(temporary-file)";
        }
        if( p->pAuxDb == &p->aAuxDb[i] ){
-
          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
+
          sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
        }else if( p->aAuxDb[i].db!=0 ){
-
          utf8_printf(stdout, "       %d: %s\n", i, zFile);
+
          sputf(stdout, "       %d: %s\n", i, zFile);
        }
      }
    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
@@ -24074,7 +24997,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      if( i<0 || i>=ArraySize(p->aAuxDb) ){
        /* No-op */
      }else if( p->pAuxDb == &p->aAuxDb[i] ){
-
        raw_printf(stderr, "cannot close the active database connection\n");
+
        eputz("cannot close the active database connection\n");
        rc = 1;
      }else if( p->aAuxDb[i].db ){
        session_close_all(p, i);
@@ -24082,7 +25005,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        p->aAuxDb[i].db = 0;
      }
    }else{
-
      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
+
      eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
      rc = 1;
    }
  }else
@@ -24096,9 +25019,9 @@ static int do_meta_command(char *zLine, ShellState *p){
      }
    }else{
#if !defined(_WIN32) && !defined(WIN32)
-
      raw_printf(stderr, "The \".crnl\" is a no-op on non-Windows machines.\n");
+
      eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
#endif
-
      raw_printf(stderr, "Usage: .crnl on|off\n");
+
      eputz("Usage: .crnl on|off\n");
      rc = 1;
    }
  }else
@@ -24111,7 +25034,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    open_db(p, 0);
    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
    if( rc ){
-
      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
+
      eputf("Error: %s\n", sqlite3_errmsg(p->db));
      rc = 1;
    }else{
      while( sqlite3_step(pStmt)==SQLITE_ROW ){
@@ -24130,11 +25053,9 @@ static int do_meta_command(char *zLine, ShellState *p){
      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
      const char *z = azName[i*2+1];
-
      utf8_printf(p->out, "%s: %s %s%s\n",
-
         azName[i*2],
-
         z && z[0] ? z : "\"\"",
-
         bRdonly ? "r/o" : "r/w",
-
         eTxn==SQLITE_TXN_NONE ? "" :
+
      oputf("%s: %s %s%s\n",
+
            azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
+
            eTxn==SQLITE_TXN_NONE ? "" :
            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
      free(azName[i*2]);
      free(azName[i*2+1]);
@@ -24174,12 +25095,12 @@ static int do_meta_command(char *zLine, ShellState *p){
        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
      }
      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
-
      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
+
      oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
      if( nArg>1 ) break;
    }
    if( nArg>1 && ii==ArraySize(aDbConfig) ){
-
      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
-
      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
+
      eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
+
      eputz("Enter \".dbconfig\" with no arguments for a list\n");
    }
  }else

@@ -24209,8 +25130,8 @@ static int do_meta_command(char *zLine, ShellState *p){
        if( z[0]=='-' ) z++;
        if( cli_strcmp(z,"preserve-rowids")==0 ){
#ifdef SQLITE_OMIT_VIRTUALTABLE
-
          raw_printf(stderr, "The --preserve-rowids option is not compatible"
-
                             " with SQLITE_OMIT_VIRTUALTABLE\n");
+
          eputz("The --preserve-rowids option is not compatible"
+
                " with SQLITE_OMIT_VIRTUALTABLE\n");
          rc = 1;
          sqlite3_free(zLike);
          goto meta_command_exit;
@@ -24228,7 +25149,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          ShellSetFlag(p, SHFLG_DumpNoSys);
        }else
        {
-
          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
+
          eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
          rc = 1;
          sqlite3_free(zLike);
          goto meta_command_exit;
@@ -24262,8 +25183,8 @@ static int do_meta_command(char *zLine, ShellState *p){
      /* When playing back a "dump", the content might appear in an order
      ** which causes immediate foreign key constraints to be violated.
      ** So disable foreign-key constraint enforcement to prevent problems. */
-
      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
-
      raw_printf(p->out, "BEGIN TRANSACTION;\n");
+
      oputz("PRAGMA foreign_keys=OFF;\n");
+
      oputz("BEGIN TRANSACTION;\n");
    }
    p->writableSchema = 0;
    p->showHeader = 0;
@@ -24294,13 +25215,13 @@ static int do_meta_command(char *zLine, ShellState *p){
    }
    sqlite3_free(zLike);
    if( p->writableSchema ){
-
      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
+
      oputz("PRAGMA writable_schema=OFF;\n");
      p->writableSchema = 0;
    }
    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
-
      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
+
      oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
    }
    p->showHeader = savedShowHeader;
    p->shellFlgs = savedShellFlags;
@@ -24310,7 +25231,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( nArg==2 ){
      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
    }else{
-
      raw_printf(stderr, "Usage: .echo on|off\n");
+
      eputz("Usage: .echo on|off\n");
      rc = 1;
    }
  }else
@@ -24341,7 +25262,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        p->autoEQP = (u8)booleanValue(azArg[1]);
      }
    }else{
-
      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
+
      eputz("Usage: .eqp off|on|trace|trigger|full\n");
      rc = 1;
    }
  }else
@@ -24380,9 +25301,8 @@ static int do_meta_command(char *zLine, ShellState *p){
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
    if( p->bSafeMode ){
-
      raw_printf(stderr,
-
        "Cannot run experimental commands such as \"%s\" in safe mode\n",
-
        azArg[0]);
+
      eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
+
            azArg[0]);
      rc = 1;
    }else{
      open_db(p, 0);
@@ -24438,10 +25358,9 @@ static int do_meta_command(char *zLine, ShellState *p){

    /* --help lists all file-controls */
    if( cli_strcmp(zCmd,"help")==0 ){
-
      utf8_printf(p->out, "Available file-controls:\n");
+
      oputz("Available file-controls:\n");
      for(i=0; i<ArraySize(aCtrl); i++){
-
        utf8_printf(p->out, "  .filectrl %s %s\n",
-
                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
+
        oputf("  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
      }
      rc = 1;
      goto meta_command_exit;
@@ -24456,16 +25375,16 @@ static int do_meta_command(char *zLine, ShellState *p){
          filectrl = aCtrl[i].ctrlCode;
          iCtrl = i;
        }else{
-
          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
-
                              "Use \".filectrl --help\" for help\n", zCmd);
+
          eputf("Error: ambiguous file-control: \"%s\"\n"
+
                "Use \".filectrl --help\" for help\n", zCmd);
          rc = 1;
          goto meta_command_exit;
        }
      }
    }
    if( filectrl<0 ){
-
      utf8_printf(stderr,"Error: unknown file-control: %s\n"
-
                         "Use \".filectrl --help\" for help\n", zCmd);
+
      eputf("Error: unknown file-control: %s\n"
+
            "Use \".filectrl --help\" for help\n", zCmd);
    }else{
      switch(filectrl){
        case SQLITE_FCNTL_SIZE_LIMIT: {
@@ -24508,7 +25427,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          if( nArg!=2 ) break;
          sqlite3_file_control(p->db, zSchema, filectrl, &z);
          if( z ){
-
            utf8_printf(p->out, "%s\n", z);
+
            oputf("%s\n", z);
            sqlite3_free(z);
          }
          isOk = 2;
@@ -24522,19 +25441,19 @@ static int do_meta_command(char *zLine, ShellState *p){
          }
          x = -1;
          sqlite3_file_control(p->db, zSchema, filectrl, &x);
-
          utf8_printf(p->out,"%d\n", x);
+
          oputf("%d\n", x);
          isOk = 2;
          break;
        }
      }
    }
    if( isOk==0 && iCtrl>=0 ){
-
      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
+
      oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
      rc = 1;
    }else if( isOk==1 ){
      char zBuf[100];
      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
-
      raw_printf(p->out, "%s\n", zBuf);
+
      oputf("%s\n", zBuf);
    }
  }else

@@ -24549,7 +25468,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      nArg = 1;
    }
    if( nArg!=1 ){
-
      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
+
      eputz("Usage: .fullschema ?--indent?\n");
      rc = 1;
      goto meta_command_exit;
    }
@@ -24569,19 +25488,21 @@ static int do_meta_command(char *zLine, ShellState *p){
               "SELECT rowid FROM sqlite_schema"
               " WHERE name GLOB 'sqlite_stat[134]'",
               -1, &pStmt, 0);
-
      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
-
      sqlite3_finalize(pStmt);
+
      if( rc==SQLITE_OK ){
+
        doStats = sqlite3_step(pStmt)==SQLITE_ROW;
+
        sqlite3_finalize(pStmt);
+
      }
    }
    if( doStats==0 ){
-
      raw_printf(p->out, "/* No STAT tables available */\n");
+
      oputz("/* No STAT tables available */\n");
    }else{
-
      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
+
      oputz("ANALYZE sqlite_schema;\n");
      data.cMode = data.mode = MODE_Insert;
      data.zDestTable = "sqlite_stat1";
      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
      data.zDestTable = "sqlite_stat4";
      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
-
      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
+
      oputz("ANALYZE sqlite_schema;\n");
    }
  }else

@@ -24590,7 +25511,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      p->showHeader = booleanValue(azArg[1]);
      p->shellFlgs |= SHFLG_HeaderSet;
    }else{
-
      raw_printf(stderr, "Usage: .headers on|off\n");
+
      eputz("Usage: .headers on|off\n");
      rc = 1;
    }
  }else
@@ -24599,7 +25520,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( nArg>=2 ){
      n = showHelp(p->out, azArg[1]);
      if( n==0 ){
-
        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
+
        oputf("Nothing matches '%s'\n", azArg[1]);
      }
    }else{
      showHelp(p->out, 0);
@@ -24643,7 +25564,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        }else if( zTable==0 ){
          zTable = z;
        }else{
-
          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
+
          oputf("ERROR: extra argument: \"%s\".  Usage:\n", z);
          showHelp(p->out, "import");
          goto meta_command_exit;
        }
@@ -24664,14 +25585,14 @@ static int do_meta_command(char *zLine, ShellState *p){
        xRead = csv_read_one_field;
        useOutputMode = 0;
      }else{
-
        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
+
        oputf("ERROR: unknown option: \"%s\".  Usage:\n", z);
        showHelp(p->out, "import");
        goto meta_command_exit;
      }
    }
    if( zTable==0 ){
-
      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
-
                  zFile==0 ? "FILE" : "TABLE");
+
      oputf("ERROR: missing %s argument. Usage:\n",
+
            zFile==0 ? "FILE" : "TABLE");
      showHelp(p->out, "import");
      goto meta_command_exit;
    }
@@ -24682,20 +25603,17 @@ static int do_meta_command(char *zLine, ShellState *p){
      ** the column and row separator characters from the output mode. */
      nSep = strlen30(p->colSeparator);
      if( nSep==0 ){
-
        raw_printf(stderr,
-
                   "Error: non-null column separator required for import\n");
+
        eputz("Error: non-null column separator required for import\n");
        goto meta_command_exit;
      }
      if( nSep>1 ){
-
        raw_printf(stderr,
-
              "Error: multi-character column separators not allowed"
+
        eputz("Error: multi-character column separators not allowed"
              " for import\n");
        goto meta_command_exit;
      }
      nSep = strlen30(p->rowSeparator);
      if( nSep==0 ){
-
        raw_printf(stderr,
-
            "Error: non-null row separator required for import\n");
+
        eputz("Error: non-null row separator required for import\n");
        goto meta_command_exit;
      }
      if( nSep==2 && p->mode==MODE_Csv
@@ -24709,8 +25627,8 @@ static int do_meta_command(char *zLine, ShellState *p){
        nSep = strlen30(p->rowSeparator);
      }
      if( nSep>1 ){
-
        raw_printf(stderr, "Error: multi-character row separators not allowed"
-
                           " for import\n");
+
        eputz("Error: multi-character row separators not allowed"
+
              " for import\n");
        goto meta_command_exit;
      }
      sCtx.cColSep = (u8)p->colSeparator[0];
@@ -24720,7 +25638,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    sCtx.nLine = 1;
    if( sCtx.zFile[0]=='|' ){
#ifdef SQLITE_OMIT_POPEN
-
      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
+
      eputz("Error: pipes are not supported in this OS\n");
      goto meta_command_exit;
#else
      sCtx.in = popen(sCtx.zFile+1, "r");
@@ -24732,19 +25650,19 @@ static int do_meta_command(char *zLine, ShellState *p){
      sCtx.xCloser = fclose;
    }
    if( sCtx.in==0 ){
-
      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
+
      eputf("Error: cannot open \"%s\"\n", zFile);
      goto meta_command_exit;
    }
    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
      char zSep[2];
      zSep[1] = 0;
      zSep[0] = sCtx.cColSep;
-
      utf8_printf(p->out, "Column separator ");
-
      output_c_string(p->out, zSep);
-
      utf8_printf(p->out, ", row separator ");
+
      oputz("Column separator ");
+
      output_c_string(zSep);
+
      oputz(", row separator ");
      zSep[0] = sCtx.cRowSep;
-
      output_c_string(p->out, zSep);
-
      utf8_printf(p->out, "\n");
+
      output_c_string(zSep);
+
      oputz("\n");
    }
    sCtx.z = sqlite3_malloc64(120);
    if( sCtx.z==0 ){
@@ -24779,14 +25697,14 @@ static int do_meta_command(char *zLine, ShellState *p){
      }
      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
      if( zRenames!=0 ){
-
        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
-
                    "Columns renamed during .import %s due to duplicates:\n"
-
                    "%s\n", sCtx.zFile, zRenames);
+
        sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
+
              "Columns renamed during .import %s due to duplicates:\n"
+
              "%s\n", sCtx.zFile, zRenames);
        sqlite3_free(zRenames);
      }
      assert(dbCols==0);
      if( zColDefs==0 ){
-
        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
+
        eputf("%s: empty file\n", sCtx.zFile);
      import_fail:
        sqlite3_free(zCreate);
        sqlite3_free(zSql);
@@ -24797,11 +25715,11 @@ static int do_meta_command(char *zLine, ShellState *p){
      }
      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
      if( eVerbose>=1 ){
-
        utf8_printf(p->out, "%s\n", zCreate);
+
        oputf("%s\n", zCreate);
      }
      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
      if( rc ){
-
        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
+
        eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
        goto import_fail;
      }
      sqlite3_free(zCreate);
@@ -24810,7 +25728,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    }
    if( rc ){
      if (pStmt) sqlite3_finalize(pStmt);
-
      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
+
      eputf("Error: %s\n", sqlite3_errmsg(p->db));
      goto import_fail;
    }
    sqlite3_free(zSql);
@@ -24832,11 +25750,11 @@ static int do_meta_command(char *zLine, ShellState *p){
    zSql[j++] = ')';
    zSql[j] = 0;
    if( eVerbose>=2 ){
-
      utf8_printf(p->out, "Insert using: %s\n", zSql);
+
      oputf("Insert using: %s\n", zSql);
    }
    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
    if( rc ){
-
      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
+
      eputf("Error: %s\n", sqlite3_errmsg(p->db));
      if (pStmt) sqlite3_finalize(pStmt);
      goto import_fail;
    }
@@ -24859,11 +25777,19 @@ static int do_meta_command(char *zLine, ShellState *p){
        ** the remaining columns.
        */
        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
+
        /*
+
        ** For CSV mode, per RFC 4180, accept EOF in lieu of final
+
        ** record terminator but only for last field of multi-field row.
+
        ** (If there are too few fields, it's not valid CSV anyway.)
+
        */
+
        if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
+
          z = "";
+
        }
        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
-
          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
-
                          "filling the rest with NULL\n",
-
                          sCtx.zFile, startLine, nCol, i+1);
+
          eputf("%s:%d: expected %d columns but found %d"
+
                " - filling the rest with NULL\n",
+
                sCtx.zFile, startLine, nCol, i+1);
          i += 2;
          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
        }
@@ -24873,16 +25799,15 @@ static int do_meta_command(char *zLine, ShellState *p){
          xRead(&sCtx);
          i++;
        }while( sCtx.cTerm==sCtx.cColSep );
-
        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
-
                        "extras ignored\n",
-
                        sCtx.zFile, startLine, nCol, i);
+
        eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
+
              sCtx.zFile, startLine, nCol, i);
      }
      if( i>=nCol ){
        sqlite3_step(pStmt);
        rc = sqlite3_reset(pStmt);
        if( rc!=SQLITE_OK ){
-
          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
-
                      startLine, sqlite3_errmsg(p->db));
+
          eputf("%s:%d: INSERT failed: %s\n",
+
                sCtx.zFile, startLine, sqlite3_errmsg(p->db));
          sCtx.nErr++;
        }else{
          sCtx.nRow++;
@@ -24894,9 +25819,8 @@ static int do_meta_command(char *zLine, ShellState *p){
    sqlite3_finalize(pStmt);
    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
    if( eVerbose>0 ){
-
      utf8_printf(p->out,
-
          "Added %d rows with %d errors using %d lines of input\n",
-
          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
+
      oputf("Added %d rows with %d errors using %d lines of input\n",
+
            sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
    }
  }else
#endif /* !defined(SQLITE_SHELL_FIDDLE) */
@@ -24911,14 +25835,14 @@ static int do_meta_command(char *zLine, ShellState *p){
    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
    int i;
    if( !ShellHasFlag(p,SHFLG_TestingMode) ){
-
      utf8_printf(stderr, ".%s unavailable without --unsafe-testing\n",
-
                  "imposter");
+
      eputf(".%s unavailable without --unsafe-testing\n",
+
            "imposter");
      rc = 1;
      goto meta_command_exit;
    }
    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
-
      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
-
                          "       .imposter off\n");
+
      eputz("Usage: .imposter INDEX IMPOSTER\n"
+
            "       .imposter off\n");
      /* Also allowed, but not documented:
      **
      **    .imposter TABLE IMPOSTER
@@ -24977,7 +25901,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    }
    sqlite3_finalize(pStmt);
    if( i==0 || tnum==0 ){
-
      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
+
      eputf("no such index: \"%s\"\n", azArg[1]);
      rc = 1;
      sqlite3_free(zCollist);
      goto meta_command_exit;
@@ -24992,16 +25916,14 @@ static int do_meta_command(char *zLine, ShellState *p){
      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
      if( rc ){
-
        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
+
        eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
      }else{
-
        utf8_printf(stdout, "%s;\n", zSql);
-
        raw_printf(stdout,
-
          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
-
          azArg[1], isWO ? "table" : "index"
-
        );
+
        sputf(stdout, "%s;\n", zSql);
+
        sputf(stdout, "WARNING: writing to an imposter table will corrupt"
+
              " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
      }
    }else{
-
      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
+
      eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
      rc = 1;
    }
    sqlite3_free(zSql);
@@ -25021,7 +25943,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    }else{
      iotrace = fopen(azArg[1], "w");
      if( iotrace==0 ){
-
        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
+
        eputf("Error: cannot open \"%s\"\n", azArg[1]);
        sqlite3IoTrace = 0;
        rc = 1;
      }else{
@@ -25053,11 +25975,11 @@ static int do_meta_command(char *zLine, ShellState *p){
    open_db(p, 0);
    if( nArg==1 ){
      for(i=0; i<ArraySize(aLimit); i++){
-
        printf("%20s %d\n", aLimit[i].zLimitName,
-
               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
+
        sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
+
              sqlite3_limit(p->db, aLimit[i].limitCode, -1));
      }
    }else if( nArg>3 ){
-
      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
+
      eputz("Usage: .limit NAME ?NEW-VALUE?\n");
      rc = 1;
      goto meta_command_exit;
    }else{
@@ -25068,16 +25990,16 @@ static int do_meta_command(char *zLine, ShellState *p){
          if( iLimit<0 ){
            iLimit = i;
          }else{
-
            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
+
            eputf("ambiguous limit: \"%s\"\n", azArg[1]);
            rc = 1;
            goto meta_command_exit;
          }
        }
      }
      if( iLimit<0 ){
-
        utf8_printf(stderr, "unknown limit: \"%s\"\n"
-
                        "enter \".limits\" with no arguments for a list.\n",
-
                         azArg[1]);
+
        eputf("unknown limit: \"%s\"\n"
+
              "enter \".limits\" with no arguments for a list.\n",
+
              azArg[1]);
        rc = 1;
        goto meta_command_exit;
      }
@@ -25085,8 +26007,8 @@ static int do_meta_command(char *zLine, ShellState *p){
        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
                      (int)integerValue(azArg[2]));
      }
-
      printf("%20s %d\n", aLimit[iLimit].zLimitName,
-
             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
+
      sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
+
            sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
    }
  }else

@@ -25102,7 +26024,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    failIfSafeMode(p, "cannot run .load in safe mode");
    if( nArg<2 || azArg[1][0]==0 ){
      /* Must have a non-empty FILE. (Will not load self.) */
-
      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
+
      eputz("Usage: .load FILE ?ENTRYPOINT?\n");
      rc = 1;
      goto meta_command_exit;
    }
@@ -25111,7 +26033,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    open_db(p, 0);
    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
    if( rc!=SQLITE_OK ){
-
      utf8_printf(stderr, "Error: %s\n", zErrMsg);
+
      eputf("Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      rc = 1;
    }
@@ -25120,7 +26042,7 @@ static int do_meta_command(char *zLine, ShellState *p){

  if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
    if( nArg!=2 ){
-
      raw_printf(stderr, "Usage: .log FILENAME\n");
+
      eputz("Usage: .log FILENAME\n");
      rc = 1;
    }else{
      const char *zFile = azArg[1];
@@ -25128,8 +26050,8 @@ static int do_meta_command(char *zLine, ShellState *p){
       && cli_strcmp(zFile,"on")!=0
       && cli_strcmp(zFile,"off")!=0
      ){
-
        raw_printf(stdout, "cannot set .log to anything other "
-
                   "than \"on\" or \"off\"\n");
+
        sputz(stdout, "cannot set .log to anything other"
+
              " than \"on\" or \"off\"\n");
        zFile = "off";
      }
      output_file_close(p->pLog);
@@ -25168,17 +26090,17 @@ static int do_meta_command(char *zLine, ShellState *p){
      }else if( zTabname==0 ){
        zTabname = z;
      }else if( z[0]=='-' ){
-
        utf8_printf(stderr, "unknown option: %s\n", z);
-
        utf8_printf(stderr, "options:\n"
-
                            "  --noquote\n"
-
                            "  --quote\n"
-
                            "  --wordwrap on/off\n"
-
                            "  --wrap N\n"
-
                            "  --ww\n");
+
        eputf("unknown option: %s\n", z);
+
        eputz("options:\n"
+
              "  --noquote\n"
+
              "  --quote\n"
+
              "  --wordwrap on/off\n"
+
              "  --wrap N\n"
+
              "  --ww\n");
        rc = 1;
        goto meta_command_exit;
      }else{
-
        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
+
        eputf("extra argument: \"%s\"\n", z);
        rc = 1;
        goto meta_command_exit;
      }
@@ -25187,14 +26109,12 @@ static int do_meta_command(char *zLine, ShellState *p){
      if( p->mode==MODE_Column
       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
      ){
-
        raw_printf
-
          (p->out,
-
           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
-
           modeDescr[p->mode], p->cmOpts.iWrap,
-
           p->cmOpts.bWordWrap ? "on" : "off",
-
           p->cmOpts.bQuote ? "" : "no");
+
        oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
+
              modeDescr[p->mode], p->cmOpts.iWrap,
+
              p->cmOpts.bWordWrap ? "on" : "off",
+
              p->cmOpts.bQuote ? "" : "no");
      }else{
-
        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
+
        oputf("current output mode: %s\n", modeDescr[p->mode]);
      }
      zMode = modeDescr[p->mode];
    }
@@ -25253,9 +26173,9 @@ static int do_meta_command(char *zLine, ShellState *p){
    }else if( cli_strncmp(zMode,"json",n2)==0 ){
      p->mode = MODE_Json;
    }else{
-
      raw_printf(stderr, "Error: mode should be one of: "
-
         "ascii box column csv html insert json line list markdown "
-
         "qbox quote table tabs tcl\n");
+
      eputz("Error: mode should be one of: "
+
            "ascii box column csv html insert json line list markdown "
+
            "qbox quote table tabs tcl\n");
      rc = 1;
    }
    p->cMode = p->mode;
@@ -25264,11 +26184,11 @@ static int do_meta_command(char *zLine, ShellState *p){
#ifndef SQLITE_SHELL_FIDDLE
  if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
    if( nArg!=2 ){
-
      raw_printf(stderr, "Usage: .nonce NONCE\n");
+
      eputz("Usage: .nonce NONCE\n");
      rc = 1;
    }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
-
      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
-
                 p->lineno, azArg[1]);
+
      eputf("line %d: incorrect nonce: \"%s\"\n",
+
            p->lineno, azArg[1]);
      exit(1);
    }else{
      p->bSafeMode = 0;
@@ -25283,7 +26203,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
    }else{
-
      raw_printf(stderr, "Usage: .nullvalue STRING\n");
+
      eputz("Usage: .nullvalue STRING\n");
      rc = 1;
    }
  }else
@@ -25322,11 +26242,11 @@ static int do_meta_command(char *zLine, ShellState *p){
      }else
#endif /* !SQLITE_SHELL_FIDDLE */
      if( z[0]=='-' ){
-
        utf8_printf(stderr, "unknown option: %s\n", z);
+
        eputf("unknown option: %s\n", z);
        rc = 1;
        goto meta_command_exit;
      }else if( zFN ){
-
        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
+
        eputf("extra argument: \"%s\"\n", z);
        rc = 1;
        goto meta_command_exit;
      }else{
@@ -25368,7 +26288,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      p->pAuxDb->zDbFilename = zNewFilename;
      open_db(p, OPEN_DB_KEEPALIVE);
      if( p->db==0 ){
-
        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
+
        eputf("Error: cannot open '%s'\n", zNewFilename);
        sqlite3_free(zNewFilename);
      }else{
        p->pAuxDb->zFreeOnClose = zNewFilename;
@@ -25392,9 +26312,9 @@ static int do_meta_command(char *zLine, ShellState *p){
    int i;
    int eMode = 0;
    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
-
    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
+
    static const char *zBomUtf8 = "\xef\xbb\xbf";
+
    const char *zBom = 0;

-
    zBOM[0] = 0;
    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
    if( c=='e' ){
      eMode = 'x';
@@ -25407,17 +26327,13 @@ static int do_meta_command(char *zLine, ShellState *p){
      if( z[0]=='-' ){
        if( z[1]=='-' ) z++;
        if( cli_strcmp(z,"-bom")==0 ){
-
          zBOM[0] = 0xef;
-
          zBOM[1] = 0xbb;
-
          zBOM[2] = 0xbf;
-
          zBOM[3] = 0;
+
          zBom = zBomUtf8;
        }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
          eMode = 'x';  /* spreadsheet */
        }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
          eMode = 'e';  /* text editor */
        }else{
-
          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
-
                      azArg[i]);
+
          oputf("ERROR: unknown option: \"%s\".  Usage:\n", azArg[i]);
          showHelp(p->out, azArg[0]);
          rc = 1;
          goto meta_command_exit;
@@ -25429,8 +26345,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          break;
        }
      }else{
-
        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
-
                    azArg[i]);
+
        oputf("ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
        showHelp(p->out, azArg[0]);
        rc = 1;
        sqlite3_free(zFile);
@@ -25469,30 +26384,30 @@ static int do_meta_command(char *zLine, ShellState *p){
    shell_check_oom(zFile);
    if( zFile[0]=='|' ){
#ifdef SQLITE_OMIT_POPEN
-
      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
+
      eputz("Error: pipes are not supported in this OS\n");
      rc = 1;
-
      p->out = stdout;
+
      output_redir(p, stdout);
#else
-
      p->out = popen(zFile + 1, "w");
-
      if( p->out==0 ){
-
        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
-
        p->out = stdout;
+
      FILE *pfPipe = popen(zFile + 1, "w");
+
      if( pfPipe==0 ){
+
        eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
        rc = 1;
      }else{
-
        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
+
        output_redir(p, pfPipe);
+
        if( zBom ) oputz(zBom);
        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
      }
#endif
    }else{
-
      p->out = output_file_open(zFile, bTxtMode);
-
      if( p->out==0 ){
+
      FILE *pfFile = output_file_open(zFile, bTxtMode);
+
      if( pfFile==0 ){
        if( cli_strcmp(zFile,"off")!=0 ){
-
          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
+
          eputf("Error: cannot write to \"%s\"\n", zFile);
        }
-
        p->out = stdout;
        rc = 1;
      } else {
-
        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
+
        output_redir(p, pfFile);
+
        if( zBom ) oputz(zBom);
        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
      }
    }
@@ -25533,8 +26448,8 @@ static int do_meta_command(char *zLine, ShellState *p){
             "SELECT key, quote(value) "
             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
-
          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
-
                      sqlite3_column_text(pStmt,1));
+
          oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
+
                sqlite3_column_text(pStmt,1));
        }
        sqlite3_finalize(pStmt);
      }
@@ -25578,7 +26493,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
        sqlite3_free(zSql);
        if( rx!=SQLITE_OK ){
-
          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
+
          oputf("Error: %s\n", sqlite3_errmsg(p->db));
          sqlite3_finalize(pStmt);
          pStmt = 0;
          rc = 1;
@@ -25607,10 +26522,10 @@ static int do_meta_command(char *zLine, ShellState *p){
  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
    int i;
    for(i=1; i<nArg; i++){
-
      if( i>1 ) raw_printf(p->out, " ");
-
      utf8_printf(p->out, "%s", azArg[i]);
+
      if( i>1 ) oputz(" ");
+
      oputz(azArg[i]);
    }
-
    raw_printf(p->out, "\n");
+
    oputz("\n");
  }else

#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
@@ -25639,7 +26554,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        }
        if( cli_strcmp(z,"limit")==0 ){
          if( i+1>=nArg ){
-
            utf8_printf(stderr, "Error: missing argument on --limit\n");
+
            eputz("Error: missing argument on --limit\n");
            rc = 1;
            goto meta_command_exit;
          }else{
@@ -25647,7 +26562,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          }
          continue;
        }
-
        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
+
        eputf("Error: unknown option: \"%s\"\n", azArg[i]);
        rc = 1;
        goto meta_command_exit;
      }else{
@@ -25680,19 +26595,19 @@ static int do_meta_command(char *zLine, ShellState *p){
    int savedLineno = p->lineno;
    failIfSafeMode(p, "cannot run .read in safe mode");
    if( nArg!=2 ){
-
      raw_printf(stderr, "Usage: .read FILE\n");
+
      eputz("Usage: .read FILE\n");
      rc = 1;
      goto meta_command_exit;
    }
    if( azArg[1][0]=='|' ){
#ifdef SQLITE_OMIT_POPEN
-
      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
+
      eputz("Error: pipes are not supported in this OS\n");
      rc = 1;
      p->out = stdout;
#else
      p->in = popen(azArg[1]+1, "r");
      if( p->in==0 ){
-
        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
+
        eputf("Error: cannot open \"%s\"\n", azArg[1]);
        rc = 1;
      }else{
        rc = process_input(p);
@@ -25700,7 +26615,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      }
#endif
    }else if( (p->in = openChrSource(azArg[1]))==0 ){
-
      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
+
      eputf("Error: cannot open \"%s\"\n", azArg[1]);
      rc = 1;
    }else{
      rc = process_input(p);
@@ -25727,20 +26642,20 @@ static int do_meta_command(char *zLine, ShellState *p){
      zSrcFile = azArg[2];
      zDb = azArg[1];
    }else{
-
      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
+
      eputz("Usage: .restore ?DB? FILE\n");
      rc = 1;
      goto meta_command_exit;
    }
    rc = sqlite3_open(zSrcFile, &pSrc);
    if( rc!=SQLITE_OK ){
-
      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
+
      eputf("Error: cannot open \"%s\"\n", zSrcFile);
      close_db(pSrc);
      return 1;
    }
    open_db(p, 0);
    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
    if( pBackup==0 ){
-
      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
+
      eputf("Error: %s\n", sqlite3_errmsg(p->db));
      close_db(pSrc);
      return 1;
    }
@@ -25755,10 +26670,10 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( rc==SQLITE_DONE ){
      rc = 0;
    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
-
      raw_printf(stderr, "Error: source database is busy\n");
+
      eputz("Error: source database is busy\n");
      rc = 1;
    }else{
-
      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
+
      eputf("Error: %s\n", sqlite3_errmsg(p->db));
      rc = 1;
    }
    close_db(pSrc);
@@ -25779,11 +26694,15 @@ static int do_meta_command(char *zLine, ShellState *p){
      sqlite3_db_config(
          p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
      );
-
#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
-
      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
+
#if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
+
      eputz("Warning: .scanstats not available in this build.\n");
+
#elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
+
      if( p->scanstatsOn==3 ){
+
        eputz("Warning: \".scanstats vm\" not available in this build.\n");
+
      }
#endif
    }else{
-
      raw_printf(stderr, "Usage: .scanstats on|off|est\n");
+
      eputz("Usage: .scanstats on|off|est\n");
      rc = 1;
    }
  }else
@@ -25812,14 +26731,13 @@ static int do_meta_command(char *zLine, ShellState *p){
      }else if( optionMatch(azArg[ii],"nosys") ){
        bNoSystemTabs = 1;
      }else if( azArg[ii][0]=='-' ){
-
        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
+
        eputf("Unknown option: \"%s\"\n", azArg[ii]);
        rc = 1;
        goto meta_command_exit;
      }else if( zName==0 ){
        zName = azArg[ii];
      }else{
-
        raw_printf(stderr,
-
                   "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
+
        eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
        rc = 1;
        goto meta_command_exit;
      }
@@ -25852,7 +26770,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
                              -1, &pStmt, 0);
      if( rc ){
-
        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
+
        eputf("Error: %s\n", sqlite3_errmsg(p->db));
        sqlite3_finalize(pStmt);
        rc = 1;
        goto meta_command_exit;
@@ -25914,18 +26832,18 @@ static int do_meta_command(char *zLine, ShellState *p){
      appendText(&sSelect, "sql IS NOT NULL"
                           " ORDER BY snum, rowid", 0);
      if( bDebug ){
-
        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
+
        oputf("SQL: %s;\n", sSelect.z);
      }else{
        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
      }
      freeText(&sSelect);
    }
    if( zErrMsg ){
-
      utf8_printf(stderr,"Error: %s\n", zErrMsg);
+
      eputf("Error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      rc = 1;
    }else if( rc != SQLITE_OK ){
-
      raw_printf(stderr,"Error: querying schema information\n");
+
      eputz("Error: querying schema information\n");
      rc = 1;
    }else{
      rc = 0;
@@ -25971,11 +26889,11 @@ static int do_meta_command(char *zLine, ShellState *p){
      if( nCmd!=2 ) goto session_syntax_error;
      if( pSession->p==0 ){
        session_not_open:
-
        raw_printf(stderr, "ERROR: No sessions are open\n");
+
        eputz("ERROR: No sessions are open\n");
      }else{
        rc = sqlite3session_attach(pSession->p, azCmd[1]);
        if( rc ){
-
          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
+
          eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
          rc = 0;
        }
      }
@@ -25994,8 +26912,8 @@ static int do_meta_command(char *zLine, ShellState *p){
      if( pSession->p==0 ) goto session_not_open;
      out = fopen(azCmd[1], "wb");
      if( out==0 ){
-
        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
-
                    azCmd[1]);
+
        eputf("ERROR: cannot open \"%s\" for writing\n",
+
              azCmd[1]);
      }else{
        int szChng;
        void *pChng;
@@ -26005,13 +26923,12 @@ static int do_meta_command(char *zLine, ShellState *p){
          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
        }
        if( rc ){
-
          printf("Error: error code %d\n", rc);
+
          sputf(stdout, "Error: error code %d\n", rc);
          rc = 0;
        }
        if( pChng
          && fwrite(pChng, szChng, 1, out)!=1 ){
-
          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
-
                  szChng);
+
          eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
        }
        sqlite3_free(pChng);
        fclose(out);
@@ -26038,8 +26955,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
      if( pAuxDb->nSession ){
        ii = sqlite3session_enable(pSession->p, ii);
-
        utf8_printf(p->out, "session %s enable flag = %d\n",
-
                    pSession->zName, ii);
+
        oputf("session %s enable flag = %d\n", pSession->zName, ii);
      }
    }else

@@ -26056,10 +26972,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        sqlite3_free(pSession->azFilter);
        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
        pSession->azFilter = sqlite3_malloc( nByte );
-
        if( pSession->azFilter==0 ){
-
          raw_printf(stderr, "Error: out or memory\n");
-
          exit(1);
-
        }
+
        shell_check_oom( pSession->azFilter );
        for(ii=1; ii<nCmd; ii++){
          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
          shell_check_oom(x);
@@ -26077,8 +26990,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
      if( pAuxDb->nSession ){
        ii = sqlite3session_indirect(pSession->p, ii);
-
        utf8_printf(p->out, "session %s indirect flag = %d\n",
-
                    pSession->zName, ii);
+
        oputf("session %s indirect flag = %d\n", pSession->zName, ii);
      }
    }else

@@ -26090,8 +27002,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      if( nCmd!=1 ) goto session_syntax_error;
      if( pAuxDb->nSession ){
        ii = sqlite3session_isempty(pSession->p);
-
        utf8_printf(p->out, "session %s isempty flag = %d\n",
-
                    pSession->zName, ii);
+
        oputf("session %s isempty flag = %d\n", pSession->zName, ii);
      }
    }else

@@ -26100,7 +27011,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    */
    if( cli_strcmp(azCmd[0],"list")==0 ){
      for(i=0; i<pAuxDb->nSession; i++){
-
        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
+
        oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
      }
    }else

@@ -26115,19 +27026,18 @@ static int do_meta_command(char *zLine, ShellState *p){
      if( zName[0]==0 ) goto session_syntax_error;
      for(i=0; i<pAuxDb->nSession; i++){
        if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
-
          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
+
          eputf("Session \"%s\" already exists\n", zName);
          goto meta_command_exit;
        }
      }
      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
-
        raw_printf(stderr,
-
                   "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
+
        eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
        goto meta_command_exit;
      }
      pSession = &pAuxDb->aSession[pAuxDb->nSession];
      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
      if( rc ){
-
        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
+
        eputf("Cannot open session: error code=%d\n", rc);
        rc = 0;
        goto meta_command_exit;
      }
@@ -26151,7 +27061,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      int i, v;
      for(i=1; i<nArg; i++){
        v = booleanValue(azArg[i]);
-
        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
+
        oputf("%s: %d 0x%x\n", azArg[i], v, v);
      }
    }
    if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
@@ -26160,7 +27070,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        char zBuf[200];
        v = integerValue(azArg[i]);
        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
-
        utf8_printf(p->out, "%s", zBuf);
+
        oputz(zBuf);
      }
    }
  }else
@@ -26187,9 +27097,8 @@ static int do_meta_command(char *zLine, ShellState *p){
        bVerbose++;
      }else
      {
-
        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
-
                    azArg[i], azArg[0]);
-
        raw_printf(stderr, "Should be one of: --init -v\n");
+
        eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
+
        eputz("Should be one of: --init -v\n");
        rc = 1;
        goto meta_command_exit;
      }
@@ -26218,7 +27127,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          -1, &pStmt, 0);
      }
      if( rc ){
-
        raw_printf(stderr, "Error querying the selftest table\n");
+
        eputz("Error querying the selftest table\n");
        rc = 1;
        sqlite3_finalize(pStmt);
        goto meta_command_exit;
@@ -26234,10 +27143,10 @@ static int do_meta_command(char *zLine, ShellState *p){
        if( zAns==0 ) continue;
        k = 0;
        if( bVerbose>0 ){
-
          printf("%d: %s %s\n", tno, zOp, zSql);
+
          sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
        }
        if( cli_strcmp(zOp,"memo")==0 ){
-
          utf8_printf(p->out, "%s\n", zSql);
+
          oputf("%s\n", zSql);
        }else
        if( cli_strcmp(zOp,"run")==0 ){
          char *zErrMsg = 0;
@@ -26246,23 +27155,22 @@ static int do_meta_command(char *zLine, ShellState *p){
          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
          nTest++;
          if( bVerbose ){
-
            utf8_printf(p->out, "Result: %s\n", str.z);
+
            oputf("Result: %s\n", str.z);
          }
          if( rc || zErrMsg ){
            nErr++;
            rc = 1;
-
            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
+
            oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
            sqlite3_free(zErrMsg);
          }else if( cli_strcmp(zAns,str.z)!=0 ){
            nErr++;
            rc = 1;
-
            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
-
            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
+
            oputf("%d: Expected: [%s]\n", tno, zAns);
+
            oputf("%d:      Got: [%s]\n", tno, str.z);
          }
-
        }else
-
        {
-
          utf8_printf(stderr,
-
            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
+
        }
+
        else{
+
          eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
          rc = 1;
          break;
        }
@@ -26270,12 +27178,12 @@ static int do_meta_command(char *zLine, ShellState *p){
      sqlite3_finalize(pStmt);
    } /* End loop over k */
    freeText(&str);
-
    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
+
    oputf("%d errors out of %d tests\n", nErr, nTest);
  }else

  if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
    if( nArg<2 || nArg>3 ){
-
      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
+
      eputz("Usage: .separator COL ?ROW?\n");
      rc = 1;
    }
    if( nArg>=2 ){
@@ -26318,14 +27226,13 @@ static int do_meta_command(char *zLine, ShellState *p){
          bDebug = 1;
        }else
        {
-
          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
-
                      azArg[i], azArg[0]);
+
          eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
          showHelp(p->out, azArg[0]);
          rc = 1;
          goto meta_command_exit;
        }
      }else if( zLike ){
-
        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
+
        eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
        rc = 1;
        goto meta_command_exit;
      }else{
@@ -26397,7 +27304,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    freeText(&sQuery);
    freeText(&sSql);
    if( bDebug ){
-
      utf8_printf(p->out, "%s\n", zSql);
+
      oputf("%s\n", zSql);
    }else{
      shell_exec(p, zSql, 0);
    }
@@ -26427,7 +27334,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          "' OR ') as query, tname from tabcols group by tname)"
          , zRevText);
      shell_check_oom(zRevText);
-
      if( bDebug ) utf8_printf(p->out, "%s\n", zRevText);
+
      if( bDebug ) oputf("%s\n", zRevText);
      lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
      if( lrc!=SQLITE_OK ){
        /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
@@ -26440,7 +27347,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
          sqlite3_stmt *pCheckStmt;
          lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
-
          if( bDebug ) utf8_printf(p->out, "%s\n", zGenQuery);
+
          if( bDebug ) oputf("%s\n", zGenQuery);
          if( lrc!=SQLITE_OK ){
            rc = 1;
          }else{
@@ -26448,9 +27355,8 @@ static int do_meta_command(char *zLine, ShellState *p){
              double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
              if( countIrreversible>0 ){
                int sz = (int)(countIrreversible + 0.5);
-
                utf8_printf(stderr,
-
                     "Digest includes %d invalidly encoded text field%s.\n",
-
                            sz, (sz>1)? "s": "");
+
                eputf("Digest includes %d invalidly encoded text field%s.\n",
+
                      sz, (sz>1)? "s": "");
              }
            }
            sqlite3_finalize(pCheckStmt);
@@ -26458,7 +27364,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          sqlite3_finalize(pStmt);
        }
      }
-
      if( rc ) utf8_printf(stderr, ".sha3sum failed.\n");
+
      if( rc ) eputz(".sha3sum failed.\n");
      sqlite3_free(zRevText);
    }
#endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
@@ -26474,7 +27380,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    int i, x;
    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
    if( nArg<2 ){
-
      raw_printf(stderr, "Usage: .system COMMAND\n");
+
      eputz("Usage: .system COMMAND\n");
      rc = 1;
      goto meta_command_exit;
    }
@@ -26483,9 +27389,11 @@ static int do_meta_command(char *zLine, ShellState *p){
      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
                             zCmd, azArg[i]);
    }
+
    consoleRestore();
    x = zCmd!=0 ? system(zCmd) : 1;
+
    consoleRenewSetup();
    sqlite3_free(zCmd);
-
    if( x ) raw_printf(stderr, "System command returns %d\n", x);
+
    if( x ) eputf("System command returns %d\n", x);
  }else
#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */

@@ -26494,52 +27402,51 @@ static int do_meta_command(char *zLine, ShellState *p){
    const char *zOut;
    int i;
    if( nArg!=1 ){
-
      raw_printf(stderr, "Usage: .show\n");
+
      eputz("Usage: .show\n");
      rc = 1;
      goto meta_command_exit;
    }
-
    utf8_printf(p->out, "%12.12s: %s\n","echo",
-
                azBool[ShellHasFlag(p, SHFLG_Echo)]);
-
    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
-
    utf8_printf(p->out, "%12.12s: %s\n","explain",
-
         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
-
    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
+
    oputf("%12.12s: %s\n","echo",
+
          azBool[ShellHasFlag(p, SHFLG_Echo)]);
+
    oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
+
    oputf("%12.12s: %s\n","explain",
+
          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
+
    oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
    if( p->mode==MODE_Column
     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
    ){
-
      utf8_printf
-
        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
-
         modeDescr[p->mode], p->cmOpts.iWrap,
-
         p->cmOpts.bWordWrap ? "on" : "off",
-
         p->cmOpts.bQuote ? "" : "no");
+
      oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
+
            modeDescr[p->mode], p->cmOpts.iWrap,
+
            p->cmOpts.bWordWrap ? "on" : "off",
+
            p->cmOpts.bQuote ? "" : "no");
    }else{
-
      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
-
    }
-
    utf8_printf(p->out, "%12.12s: ", "nullvalue");
-
      output_c_string(p->out, p->nullValue);
-
      raw_printf(p->out, "\n");
-
    utf8_printf(p->out,"%12.12s: %s\n","output",
-
            strlen30(p->outfile) ? p->outfile : "stdout");
-
    utf8_printf(p->out,"%12.12s: ", "colseparator");
-
      output_c_string(p->out, p->colSeparator);
-
      raw_printf(p->out, "\n");
-
    utf8_printf(p->out,"%12.12s: ", "rowseparator");
-
      output_c_string(p->out, p->rowSeparator);
-
      raw_printf(p->out, "\n");
+
      oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
+
    }
+
    oputf("%12.12s: ", "nullvalue");
+
    output_c_string(p->nullValue);
+
    oputz("\n");
+
    oputf("%12.12s: %s\n","output",
+
          strlen30(p->outfile) ? p->outfile : "stdout");
+
    oputf("%12.12s: ", "colseparator");
+
     output_c_string(p->colSeparator);
+
     oputz("\n");
+
    oputf("%12.12s: ", "rowseparator");
+
     output_c_string(p->rowSeparator);
+
     oputz("\n");
    switch( p->statsOn ){
      case 0:  zOut = "off";     break;
      default: zOut = "on";      break;
      case 2:  zOut = "stmt";    break;
      case 3:  zOut = "vmstep";  break;
    }
-
    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
-
    utf8_printf(p->out, "%12.12s: ", "width");
+
    oputf("%12.12s: %s\n","stats", zOut);
+
    oputf("%12.12s: ", "width");
    for (i=0;i<p->nWidth;i++) {
-
      raw_printf(p->out, "%d ", p->colWidth[i]);
+
      oputf("%d ", p->colWidth[i]);
    }
-
    raw_printf(p->out, "\n");
-
    utf8_printf(p->out, "%12.12s: %s\n", "filename",
-
                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
+
    oputz("\n");
+
    oputf("%12.12s: %s\n", "filename",
+
          p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
  }else

  if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
@@ -26554,7 +27461,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    }else if( nArg==1 ){
      display_stats(p->db, p, 0);
    }else{
-
      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
+
      eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
      rc = 1;
    }
  }else
@@ -26580,7 +27487,7 @@ static int do_meta_command(char *zLine, ShellState *p){
      /* It is an historical accident that the .indexes command shows an error
      ** when called with the wrong number of arguments whereas the .tables
      ** command does not. */
-
      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
+
      eputz("Usage: .indexes ?LIKE-PATTERN?\n");
      rc = 1;
      sqlite3_finalize(pStmt);
      goto meta_command_exit;
@@ -26656,10 +27563,9 @@ static int do_meta_command(char *zLine, ShellState *p){
      for(i=0; i<nPrintRow; i++){
        for(j=i; j<nRow; j+=nPrintRow){
          char *zSp = j<nPrintRow ? "" : "  ";
-
          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
-
                      azResult[j] ? azResult[j]:"");
+
          oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
        }
-
        raw_printf(p->out, "\n");
+
        oputz("\n");
      }
    }

@@ -26673,7 +27579,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    output_reset(p);
    p->out = output_file_open("testcase-out.txt", 0);
    if( p->out==0 ){
-
      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
+
      eputz("Error: cannot open 'testcase-out.txt'\n");
    }
    if( nArg>=2 ){
      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
@@ -26698,6 +27604,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
    {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
  /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
+
    {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
    {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
    {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
    {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
@@ -26713,7 +27620,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
    {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
    {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
-
    {"uselongdouble",    SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
+
    {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
    };
    int testctrl = -1;
    int iCtrl = -1;
@@ -26733,11 +27640,11 @@ static int do_meta_command(char *zLine, ShellState *p){

    /* --help lists all test-controls */
    if( cli_strcmp(zCmd,"help")==0 ){
-
      utf8_printf(p->out, "Available test-controls:\n");
+
      oputz("Available test-controls:\n");
      for(i=0; i<ArraySize(aCtrl); i++){
        if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
-
        utf8_printf(p->out, "  .testctrl %s %s\n",
-
                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
+
        oputf("  .testctrl %s %s\n",
+
              aCtrl[i].zCtrlName, aCtrl[i].zUsage);
      }
      rc = 1;
      goto meta_command_exit;
@@ -26753,21 +27660,22 @@ static int do_meta_command(char *zLine, ShellState *p){
          testctrl = aCtrl[i].ctrlCode;
          iCtrl = i;
        }else{
-
          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
-
                              "Use \".testctrl --help\" for help\n", zCmd);
+
          eputf("Error: ambiguous test-control: \"%s\"\n"
+
                "Use \".testctrl --help\" for help\n", zCmd);
          rc = 1;
          goto meta_command_exit;
        }
      }
    }
    if( testctrl<0 ){
-
      utf8_printf(stderr,"Error: unknown test-control: %s\n"
-
                         "Use \".testctrl --help\" for help\n", zCmd);
+
      eputf("Error: unknown test-control: %s\n"
+
            "Use \".testctrl --help\" for help\n", zCmd);
    }else{
      switch(testctrl){

        /* sqlite3_test_control(int, db, int) */
        case SQLITE_TESTCTRL_OPTIMIZATIONS:
+
        case SQLITE_TESTCTRL_FK_NO_ACTION:
          if( nArg==3 ){
            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
            rc2 = sqlite3_test_control(testctrl, p->db, opt);
@@ -26801,7 +27709,7 @@ static int do_meta_command(char *zLine, ShellState *p){
            sqlite3 *db;
            if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
              sqlite3_randomness(sizeof(ii),&ii);
-
              printf("-- random seed: %d\n", ii);
+
              sputf(stdout, "-- random seed: %d\n", ii);
            }
            if( nArg==3 ){
              db = 0;
@@ -26869,7 +27777,7 @@ static int do_meta_command(char *zLine, ShellState *p){
        case SQLITE_TESTCTRL_SEEK_COUNT: {
          u64 x = 0;
          rc2 = sqlite3_test_control(testctrl, p->db, &x);
-
          utf8_printf(p->out, "%llu\n", x);
+
          oputf("%llu\n", x);
          isOk = 3;
          break;
        }
@@ -26900,11 +27808,11 @@ static int do_meta_command(char *zLine, ShellState *p){
              int val = 0;
              rc2 = sqlite3_test_control(testctrl, -id, &val);
              if( rc2!=SQLITE_OK ) break;
-
              if( id>1 ) utf8_printf(p->out, "  ");
-
              utf8_printf(p->out, "%d: %d", id, val);
+
              if( id>1 ) oputz("  ");
+
              oputf("%d: %d", id, val);
              id++;
            }
-
            if( id>1 ) utf8_printf(p->out, "\n");
+
            if( id>1 ) oputz("\n");
            isOk = 3;
          }
          break;
@@ -26920,12 +27828,12 @@ static int do_meta_command(char *zLine, ShellState *p){
      }
    }
    if( isOk==0 && iCtrl>=0 ){
-
      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
+
      oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
      rc = 1;
    }else if( isOk==1 ){
-
      raw_printf(p->out, "%d\n", rc2);
+
      oputf("%d\n", rc2);
    }else if( isOk==2 ){
-
      raw_printf(p->out, "0x%08x\n", rc2);
+
      oputf("0x%08x\n", rc2);
    }
  }else
#endif /* !defined(SQLITE_UNTESTABLE) */
@@ -26939,11 +27847,11 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( nArg==2 ){
      enableTimer = booleanValue(azArg[1]);
      if( enableTimer && !HAS_TIMER ){
-
        raw_printf(stderr, "Error: timer not available on this system.\n");
+
        eputz("Error: timer not available on this system.\n");
        enableTimer = 0;
      }
    }else{
-
      raw_printf(stderr, "Usage: .timer on|off\n");
+
      eputz("Usage: .timer on|off\n");
      rc = 1;
    }
  }else
@@ -26980,7 +27888,7 @@ static int do_meta_command(char *zLine, ShellState *p){
          mType |= SQLITE_TRACE_CLOSE;
        }
        else {
-
          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
+
          eputf("Unknown option \"%s\" on \".trace\"\n", z);
          rc = 1;
          goto meta_command_exit;
        }
@@ -27004,7 +27912,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    int lenOpt;
    char *zOpt;
    if( nArg<2 ){
-
      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
+
      eputz("Usage: .unmodule [--allexcept] NAME ...\n");
      rc = 1;
      goto meta_command_exit;
    }
@@ -27026,60 +27934,60 @@ static int do_meta_command(char *zLine, ShellState *p){
#if SQLITE_USER_AUTHENTICATION
  if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
    if( nArg<2 ){
-
      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
+
      eputz("Usage: .user SUBCOMMAND ...\n");
      rc = 1;
      goto meta_command_exit;
    }
    open_db(p, 0);
    if( cli_strcmp(azArg[1],"login")==0 ){
      if( nArg!=4 ){
-
        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
+
        eputz("Usage: .user login USER PASSWORD\n");
        rc = 1;
        goto meta_command_exit;
      }
      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
                                     strlen30(azArg[3]));
      if( rc ){
-
        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
+
        eputf("Authentication failed for user %s\n", azArg[2]);
        rc = 1;
      }
    }else if( cli_strcmp(azArg[1],"add")==0 ){
      if( nArg!=5 ){
-
        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
+
        eputz("Usage: .user add USER PASSWORD ISADMIN\n");
        rc = 1;
        goto meta_command_exit;
      }
      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
                            booleanValue(azArg[4]));
      if( rc ){
-
        raw_printf(stderr, "User-Add failed: %d\n", rc);
+
        eputf("User-Add failed: %d\n", rc);
        rc = 1;
      }
    }else if( cli_strcmp(azArg[1],"edit")==0 ){
      if( nArg!=5 ){
-
        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
+
        eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
        rc = 1;
        goto meta_command_exit;
      }
      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
                              booleanValue(azArg[4]));
      if( rc ){
-
        raw_printf(stderr, "User-Edit failed: %d\n", rc);
+
        eputf("User-Edit failed: %d\n", rc);
        rc = 1;
      }
    }else if( cli_strcmp(azArg[1],"delete")==0 ){
      if( nArg!=3 ){
-
        raw_printf(stderr, "Usage: .user delete USER\n");
+
        eputz("Usage: .user delete USER\n");
        rc = 1;
        goto meta_command_exit;
      }
      rc = sqlite3_user_delete(p->db, azArg[2]);
      if( rc ){
-
        raw_printf(stderr, "User-Delete failed: %d\n", rc);
+
        eputf("User-Delete failed: %d\n", rc);
        rc = 1;
      }
    }else{
-
      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
+
      eputz("Usage: .user login|add|edit|delete ...\n");
      rc = 1;
      goto meta_command_exit;
    }
@@ -27088,21 +27996,21 @@ static int do_meta_command(char *zLine, ShellState *p){

  if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
    char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
-
    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
-
        sqlite3_libversion(), sqlite3_sourceid());
+
    oputf("SQLite %s %s\n" /*extra-version-info*/,
+
          sqlite3_libversion(), sqlite3_sourceid());
#if SQLITE_HAVE_ZLIB
-
    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
+
    oputf("zlib version %s\n", zlibVersion());
#endif
#define CTIMEOPT_VAL_(opt) #opt
#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
#if defined(__clang__) && defined(__clang_major__)
-
    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
-
                    CTIMEOPT_VAL(__clang_minor__) "."
-
                    CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
+
    oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
+
          CTIMEOPT_VAL(__clang_minor__) "."
+
          CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
#elif defined(_MSC_VER)
-
    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
+
    oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
#elif defined(__GNUC__) && defined(__VERSION__)
-
    utf8_printf(p->out, "gcc-" __VERSION__ " (%s)\n", zPtrSz);
+
    oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
#endif
  }else

@@ -27112,10 +28020,10 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( p->db ){
      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
      if( pVfs ){
-
        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
-
        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
-
        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
-
        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
+
        oputf("vfs.zName      = \"%s\"\n", pVfs->zName);
+
        oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
+
        oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
+
        oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
      }
    }
  }else
@@ -27127,13 +28035,13 @@ static int do_meta_command(char *zLine, ShellState *p){
      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
    }
    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
-
      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
-
           pVfs==pCurrent ? "  <--- CURRENT" : "");
-
      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
-
      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
-
      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
+
      oputf("vfs.zName      = \"%s\"%s\n", pVfs->zName,
+
            pVfs==pCurrent ? "  <--- CURRENT" : "");
+
      oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
+
      oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
+
      oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
      if( pVfs->pNext ){
-
        raw_printf(p->out, "-----------------------------------\n");
+
        oputz("-----------------------------------\n");
      }
    }
  }else
@@ -27144,7 +28052,7 @@ static int do_meta_command(char *zLine, ShellState *p){
    if( p->db ){
      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
      if( zVfsName ){
-
        utf8_printf(p->out, "%s\n", zVfsName);
+
        oputf("%s\n", zVfsName);
        sqlite3_free(zVfsName);
      }
    }
@@ -27168,8 +28076,8 @@ static int do_meta_command(char *zLine, ShellState *p){
  }else

  {
-
    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
-
      " \"%s\". Enter \".help\" for help\n", azArg[0]);
+
    eputf("Error: unknown command or invalid arguments: "
+
          " \"%s\". Enter \".help\" for help\n", azArg[0]);
    rc = 1;
  }

@@ -27359,7 +28267,7 @@ static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
    }else{
      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
    }
-
    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
+
    eputf("%s %s\n", zPrefix, zErrorTail);
    sqlite3_free(zErrMsg);
    zErrMsg = 0;
    return 1;
@@ -27368,13 +28276,13 @@ static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
            "changes: %lld   total_changes: %lld",
            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
-
    raw_printf(p->out, "%s\n", zLineBuf);
+
    oputf("%s\n", zLineBuf);
  }
  return 0;
}

static void echo_group_input(ShellState *p, const char *zDo){
-
  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
+
  if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
}

#ifdef SQLITE_SHELL_FIDDLE
@@ -27432,8 +28340,8 @@ static int process_input(ShellState *p){

  if( p->inputNesting==MAX_INPUT_NESTING ){
    /* This will be more informative in a later version. */
-
    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
-
                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
+
    eputf("Input nesting limit (%d) reached at line %d."
+
          " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
    return 1;
  }
  ++p->inputNesting;
@@ -27444,7 +28352,7 @@ static int process_input(ShellState *p){
    zLine = one_input_line(p->in, zLine, nSql>0);
    if( zLine==0 ){
      /* End of input */
-
      if( p->in==0 && stdin_is_interactive ) printf("\n");
+
      if( p->in==0 && stdin_is_interactive ) oputz("\n");
      break;
    }
    if( seenInterrupt ){
@@ -27654,8 +28562,8 @@ static void process_sqliterc(
  if( sqliterc == NULL ){
    home_dir = find_home_dir(0);
    if( home_dir==0 ){
-
      raw_printf(stderr, "-- warning: cannot find home directory;"
-
                      " cannot read ~/.sqliterc\n");
+
      eputz("-- warning: cannot find home directory;"
+
            " cannot read ~/.sqliterc\n");
      return;
    }
    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
@@ -27665,12 +28573,12 @@ static void process_sqliterc(
  p->in = fopen(sqliterc,"rb");
  if( p->in ){
    if( stdin_is_interactive ){
-
      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
+
      eputf("-- Loading resources from %s\n", sqliterc);
    }
    if( process_input(p) && bail_on_error ) exit(1);
    fclose(p->in);
  }else if( sqliterc_override!=0 ){
-
    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
+
    eputf("cannot open: \"%s\"\n", sqliterc);
    if( bail_on_error ) exit(1);
  }
  p->in = inSaved;
@@ -27736,9 +28644,6 @@ static const char zOptions[] =
  "   -table               set output mode to 'table'\n"
  "   -tabs                set output mode to 'tabs'\n"
  "   -unsafe-testing      allow unsafe commands and modes for testing\n"
-
#if SHELL_WIN_UTF8_OPT
-
  "   -utf8                setup interactive console code page for UTF-8\n"
-
#endif
  "   -version             show SQLite version\n"
  "   -vfs NAME            use NAME as the default VFS\n"
#ifdef SQLITE_ENABLE_VFSTRACE
@@ -27749,14 +28654,13 @@ static const char zOptions[] =
#endif
;
static void usage(int showDetail){
-
  utf8_printf(stderr,
-
      "Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
-
      "FILENAME is the name of an SQLite database. A new database is created\n"
-
      "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
+
  eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
+
       "FILENAME is the name of an SQLite database. A new database is created\n"
+
       "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
  if( showDetail ){
-
    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
+
    eputf("OPTIONS include:\n%s", zOptions);
  }else{
-
    raw_printf(stderr, "Use the -help option for additional information\n");
+
    eputz("Use the -help option for additional information\n");
  }
  exit(1);
}
@@ -27767,8 +28671,8 @@ static void usage(int showDetail){
*/
static void verify_uninitialized(void){
  if( sqlite3_config(-1)==SQLITE_MISUSE ){
-
    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
-
                        " initialization.\n");
+
    sputz(stdout, "WARNING: attempt to configure SQLite after"
+
          " initialization.\n");
  }
}

@@ -27797,7 +28701,7 @@ static void main_init(ShellState *data) {
/*
** Output text to the console in a font that attracts extra attention.
*/
-
#ifdef _WIN32
+
#if defined(_WIN32) || defined(WIN32)
static void printBold(const char *zText){
#if !SQLITE_OS_WINRT
  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
@@ -27807,14 +28711,14 @@ static void printBold(const char *zText){
         FOREGROUND_RED|FOREGROUND_INTENSITY
  );
#endif
-
  printf("%s", zText);
+
  oputz(zText);
#if !SQLITE_OS_WINRT
  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
#endif
}
#else
static void printBold(const char *zText){
-
  printf("\033[1m%s\033[0m", zText);
+
  oputf("\033[1m%s\033[0m", zText);
}
#endif

@@ -27824,15 +28728,14 @@ static void printBold(const char *zText){
*/
static char *cmdline_option_value(int argc, char **argv, int i){
  if( i==argc ){
-
    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
-
            argv[0], argv[argc-1]);
+
    eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
    exit(1);
  }
  return argv[i];
}

static void sayAbnormalExit(void){
-
  if( seenInterrupt ) fprintf(stderr, "Program interrupted.\n");
+
  if( seenInterrupt ) eputz("Program interrupted.\n");
}

#ifndef SQLITE_SHELL_IS_UTF8
@@ -27862,6 +28765,7 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
#  define data shellState
#else
  ShellState data;
+
  StreamsAreConsole consStreams = SAC_NoConsole;
#endif
  const char *zInitFile = 0;
  int i;
@@ -27883,11 +28787,10 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  stdout_is_console = 1;
  data.wasm.zDefaultDbName = "/fiddle.sqlite3";
#else
-
  stdin_is_interactive = isatty(0);
-
  stdout_is_console = isatty(1);
-
#endif
-
#if SHELL_WIN_UTF8_OPT
-
  atexit(console_restore); /* Needs revision for CLI as library call */
+
  consStreams = consoleClassifySetup(stdin, stdout, stderr);
+
  stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
+
  stdout_is_console = (consStreams & SAC_OutConsole)!=0;
+
  atexit(consoleRestore);
#endif
  atexit(sayAbnormalExit);
#ifdef SQLITE_DEBUG
@@ -27896,9 +28799,8 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
#if !defined(_WIN32_WCE)
  if( getenv("SQLITE_DEBUG_BREAK") ){
    if( isatty(0) && isatty(2) ){
-
      fprintf(stderr,
-
          "attach debugger to process %d and press any key to continue.\n",
-
          GETPID());
+
      eputf("attach debugger to process %d and press any key to continue.\n",
+
            GETPID());
      fgetc(stdin);
    }else{
#if defined(_WIN32) || defined(WIN32)
@@ -27918,14 +28820,14 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  signal(SIGINT, interrupt_handler);
#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
-
    fprintf(stderr, "No ^C handler.\n");
+
    eputz("No ^C handler.\n");
  }
#endif

#if USE_SYSTEM_SQLITE+0!=1
  if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
-
    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
-
            sqlite3_sourceid(), SQLITE_SOURCE_ID);
+
    eputf("SQLite header and source version mismatch\n%s\n%s\n",
+
          sqlite3_sourceid(), SQLITE_SOURCE_ID);
    exit(1);
  }
#endif
@@ -27974,8 +28876,8 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){

  /* Do an initial pass through the command-line argument to locate
  ** the name of the database file, the name of the initialization file,
-
  ** the size of the alternative malloc heap,
-
  ** and the first command to execute.
+
  ** the size of the alternative malloc heap, options affecting commands
+
  ** or SQL run from the command line, and the first command to execute.
  */
#ifndef SQLITE_SHELL_FIDDLE
  verify_uninitialized();
@@ -28009,12 +28911,19 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
      (void)cmdline_option_value(argc, argv, ++i);
    }else if( cli_strcmp(z,"-init")==0 ){
      zInitFile = cmdline_option_value(argc, argv, ++i);
+
    }else if( cli_strcmp(z,"-interactive")==0 ){
+
      /* Need to check for interactive override here to so that it can
+
      ** affect console setup (for Windows only) and testing thereof.
+
      */
+
      stdin_is_interactive = 1;
    }else if( cli_strcmp(z,"-batch")==0 ){
      /* Need to check for batch mode here to so we can avoid printing
      ** informational messages (like from process_sqliterc) before
      ** we do the actual processing of arguments later in a second pass.
      */
      stdin_is_interactive = 0;
+
    }else if( cli_strcmp(z,"-utf8")==0 ){
+
    }else if( cli_strcmp(z,"-no-utf8")==0 ){
    }else if( cli_strcmp(z,"-heap")==0 ){
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
      const char *zSize;
@@ -28149,7 +29058,7 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
    if( pVfs ){
      sqlite3_vfs_register(pVfs, 1);
    }else{
-
      utf8_printf(stderr, "no such VFS: \"%s\"\n", zVfs);
+
      eputf("no such VFS: \"%s\"\n", zVfs);
      exit(1);
    }
  }
@@ -28159,7 +29068,7 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
    data.pAuxDb->zDbFilename = ":memory:";
    warnInmemoryDb = argc==1;
#else
-
    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
+
    eputf("%s: Error: no database filename specified\n", Argv0);
    return 1;
#endif
  }
@@ -28276,17 +29185,17 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
    }else if( cli_strcmp(z,"-bail")==0 ){
      /* No-op.  The bail_on_error flag should already be set. */
    }else if( cli_strcmp(z,"-version")==0 ){
-
      printf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
-
             8*(int)sizeof(char*));
+
      oputf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
+
            8*(int)sizeof(char*));
      return 0;
    }else if( cli_strcmp(z,"-interactive")==0 ){
-
      stdin_is_interactive = 1;
+
      /* already handled */
    }else if( cli_strcmp(z,"-batch")==0 ){
-
      stdin_is_interactive = 0;
+
      /* already handled */
    }else if( cli_strcmp(z,"-utf8")==0 ){
-
#if SHELL_WIN_UTF8_OPT
-
      console_utf8 = 1;
-
#endif /* SHELL_WIN_UTF8_OPT */
+
      /* already handled */
+
    }else if( cli_strcmp(z,"-no-utf8")==0 ){
+
      /* already handled */
    }else if( cli_strcmp(z,"-heap")==0 ){
      i++;
    }else if( cli_strcmp(z,"-pagecache")==0 ){
@@ -28333,18 +29242,18 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
        open_db(&data, 0);
        rc = shell_exec(&data, z, &zErrMsg);
        if( zErrMsg!=0 ){
-
          utf8_printf(stderr,"Error: %s\n", zErrMsg);
+
          eputf("Error: %s\n", zErrMsg);
          if( bail_on_error ) return rc!=0 ? rc : 1;
        }else if( rc!=0 ){
-
          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
+
          eputf("Error: unable to process SQL \"%s\"\n", z);
          if( bail_on_error ) return rc;
        }
      }
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
    }else if( cli_strncmp(z, "-A", 2)==0 ){
      if( nCmd>0 ){
-
        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
-
                            " with \"%s\"\n", z);
+
        eputf("Error: cannot mix regular SQL or dot-commands"
+
              " with \"%s\"\n", z);
        return 1;
      }
      open_db(&data, OPEN_DB_ZIPFILE);
@@ -28362,20 +29271,12 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
    }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
      /* Acted upon in first pass. */
    }else{
-
      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
-
      raw_printf(stderr,"Use -help for a list of options.\n");
+
      eputf("%s: Error: unknown option: %s\n", Argv0, z);
+
      eputz("Use -help for a list of options.\n");
      return 1;
    }
    data.cMode = data.mode;
  }
-
#if SHELL_WIN_UTF8_OPT
-
  if( console_utf8 && stdin_is_interactive ){
-
    console_prepare();
-
  }else{
-
    setBinaryMode(stdin, 0);
-
    console_utf8 = 0;
-
  }
-
#endif

  if( !readStdin ){
    /* Run all arguments that do not begin with '-' as if they were separate
@@ -28395,9 +29296,9 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
        rc = shell_exec(&data, azCmd[i], &zErrMsg);
        if( zErrMsg || rc ){
          if( zErrMsg!=0 ){
-
            utf8_printf(stderr,"Error: %s\n", zErrMsg);
+
            eputf("Error: %s\n", zErrMsg);
          }else{
-
            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
+
            eputf("Error: unable to process SQL: %s\n", azCmd[i]);
          }
          sqlite3_free(zErrMsg);
          free(azCmd);
@@ -28412,16 +29313,19 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
      char *zHome;
      char *zHistory;
      int nHistory;
-
      printf(
-
        "SQLite version %s %.19s\n" /*extra-version-info*/
-
        "Enter \".help\" for usage hints.\n",
-
        sqlite3_libversion(), sqlite3_sourceid()
-
      );
+
#if CIO_WIN_WC_XLATE
+
# define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
+
#else
+
# define SHELL_CIO_CHAR_SET ""
+
#endif
+
      oputf("SQLite version %s %.19s%s\n" /*extra-version-info*/
+
            "Enter \".help\" for usage hints.\n",
+
            sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
      if( warnInmemoryDb ){
-
        printf("Connected to a ");
+
        oputz("Connected to a ");
        printBold("transient in-memory database");
-
        printf(".\nUse \".open FILENAME\" to reopen on a "
-
               "persistent database.\n");
+
        oputz(".\nUse \".open FILENAME\" to reopen on a"
+
              " persistent database.\n");
      }
      zHistory = getenv("SQLITE_HISTORY");
      if( zHistory ){
@@ -28481,8 +29385,8 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  memset(&data, 0, sizeof(data));
#ifdef SQLITE_DEBUG
  if( sqlite3_memory_used()>mem_main_enter ){
-
    utf8_printf(stderr, "Memory leaked: %u bytes\n",
-
                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
+
    eputf("Memory leaked: %u bytes\n",
+
          (unsigned int)(sqlite3_memory_used()-mem_main_enter));
  }
#endif
#endif /* !SQLITE_SHELL_FIDDLE */
modified external/sqlite/sqlite3.c
@@ -1,6 +1,6 @@
/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
-
** version 3.43.0.  By combining all the individual C code files into this
+
** version 3.44.2.  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
@@ -18,7 +18,7 @@
** separate file. This file contains only code for the core SQLite library.
**
** The content in this amalgamation comes from Fossil check-in
-
** f80b798b3f4b81a7bb4233c58294edd0f11.
+
** ebead0e7230cd33bcec9f95d2183069565b9.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1
@@ -459,9 +459,9 @@ extern "C" {
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
-
#define SQLITE_VERSION        "3.43.0"
-
#define SQLITE_VERSION_NUMBER 3043000
-
#define SQLITE_SOURCE_ID      "2023-08-24 12:36:59 0f80b798b3f4b81a7bb4233c58294edd0f1156f36b6ecf5ab8e83631d468778c"
+
#define SQLITE_VERSION        "3.44.2"
+
#define SQLITE_VERSION_NUMBER 3044002
+
#define SQLITE_SOURCE_ID      "2023-11-24 11:41:44 ebead0e7230cd33bcec9f95d2183069565b9e709bf745c9b5db65cc0cbf92c0f"

/*
** CAPI3REF: Run-Time Library Version Numbers
@@ -2440,7 +2440,7 @@ struct sqlite3_mem_methods {
** is stored in each sorted record and the required column values loaded
** from the database as records are returned in sorted order. The default
** value for this option is to never use this optimization. Specifying a
-
** negative value for this option restores the default behaviour.
+
** negative value for this option restores the default behavior.
** This option is only available if SQLite is compiled with the
** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
**
@@ -2615,7 +2615,7 @@ struct sqlite3_mem_methods {
** database handle, SQLite checks if this will mean that there are now no
** connections at all to the database. If so, it performs a checkpoint
** operation before closing the connection. This option may be used to
-
** override this behaviour. The first parameter passed to this operation
+
** override this behavior. The first parameter passed to this operation
** is an integer - positive to disable checkpoints-on-close, or zero (the
** default) to enable them, and negative to leave the setting unchanged.
** The second parameter is a pointer to an integer
@@ -4268,6 +4268,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename);
**
** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
** text that describes the error, as either UTF-8 or UTF-16 respectively.
+
** (See how SQLite handles [invalid UTF] for exceptions to this rule.)
** ^(Memory to hold the error message string is managed internally.
** The application does not need to worry about freeing the result.
** However, the error string might be overwritten or deallocated by
@@ -5638,6 +5639,7 @@ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
*/
SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);

+

/*
** CAPI3REF: Create Or Redefine SQL Functions
** KEYWORDS: {function creation routines}
@@ -5884,13 +5886,27 @@ SQLITE_API int sqlite3_create_window_function(
** </dd>
**
** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
-
** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
+
** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call
** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
-
** Specifying this flag makes no difference for scalar or aggregate user
-
** functions. However, if it is not specified for a user-defined window
-
** function, then any sub-types belonging to arguments passed to the window
-
** function may be discarded before the window function is called (i.e.
-
** sqlite3_value_subtype() will always return 0).
+
** This flag instructs SQLite to omit some corner-case optimizations that
+
** might disrupt the operation of the [sqlite3_value_subtype()] function,
+
** causing it to return zero rather than the correct subtype().
+
** SQL functions that invokes [sqlite3_value_subtype()] should have this
+
** property.  If the SQLITE_SUBTYPE property is omitted, then the return
+
** value from [sqlite3_value_subtype()] might sometimes be zero even though
+
** a non-zero subtype was specified by the function argument expression.
+
**
+
** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd>
+
** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call
+
** [sqlite3_result_subtype()] to cause a sub-type to be associated with its
+
** result.
+
** Every function that invokes [sqlite3_result_subtype()] should have this
+
** property.  If it does not, then the call to [sqlite3_result_subtype()]
+
** might become a no-op if the function is used as term in an
+
** [expression index].  On the other hand, SQL functions that never invoke
+
** [sqlite3_result_subtype()] should avoid setting this property, as the
+
** purpose of this property is to disable certain optimizations that are
+
** incompatible with subtypes.
** </dd>
** </dl>
*/
@@ -5898,6 +5914,7 @@ SQLITE_API int sqlite3_create_window_function(
#define SQLITE_DIRECTONLY       0x000080000
#define SQLITE_SUBTYPE          0x000100000
#define SQLITE_INNOCUOUS        0x000200000
+
#define SQLITE_RESULT_SUBTYPE   0x001000000

/*
** CAPI3REF: Deprecated Functions
@@ -6094,6 +6111,12 @@ SQLITE_API int sqlite3_value_encoding(sqlite3_value*);
** information can be used to pass a limited amount of context from
** one SQL function to another.  Use the [sqlite3_result_subtype()]
** routine to set the subtype for the return value of an SQL function.
+
**
+
** Every [application-defined SQL function] that invoke this interface
+
** should include the [SQLITE_SUBTYPE] property in the text
+
** encoding argument when the function is [sqlite3_create_function|registered].
+
** If the [SQLITE_SUBTYPE] property is omitted, then sqlite3_value_subtype()
+
** might return zero instead of the upstream subtype in some corner cases.
*/
SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);

@@ -6192,48 +6215,56 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
** METHOD: sqlite3_context
**
** These functions may be used by (non-aggregate) SQL functions to
-
** associate metadata with argument values. If the same value is passed to
-
** multiple invocations of the same SQL function during query execution, under
-
** some circumstances the associated metadata may be preserved.  An example
-
** of where this might be useful is in a regular-expression matching
-
** function. The compiled version of the regular expression can be stored as
-
** metadata associated with the pattern string.
+
** associate auxiliary data with argument values. If the same argument
+
** value is passed to multiple invocations of the same SQL function during
+
** query execution, under some circumstances the associated auxiliary data
+
** might be preserved.  An example of where this might be useful is in a
+
** regular-expression matching function. The compiled version of the regular
+
** expression can be stored as auxiliary data associated with the pattern string.
** Then as long as the pattern string remains the same,
** the compiled regular expression can be reused on multiple
** invocations of the same function.
**
-
** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
+
** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data
** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
** value to the application-defined function.  ^N is zero for the left-most
-
** function argument.  ^If there is no metadata
+
** function argument.  ^If there is no auxiliary data
** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
** returns a NULL pointer.
**
-
** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
-
** argument of the application-defined function.  ^Subsequent
+
** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the
+
** N-th argument of the application-defined function.  ^Subsequent
** calls to sqlite3_get_auxdata(C,N) return P from the most recent
-
** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
-
** NULL if the metadata has been discarded.
+
** sqlite3_set_auxdata(C,N,P,X) call if the auxiliary data is still valid or
+
** NULL if the auxiliary data has been discarded.
** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
** SQLite will invoke the destructor function X with parameter P exactly
-
** once, when the metadata is discarded.
-
** SQLite is free to discard the metadata at any time, including: <ul>
+
** once, when the auxiliary data is discarded.
+
** SQLite is free to discard the auxiliary data at any time, including: <ul>
** <li> ^(when the corresponding function parameter changes)^, or
** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
**      SQL statement)^, or
** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
**       parameter)^, or
** <li> ^(during the original sqlite3_set_auxdata() call when a memory
-
**      allocation error occurs.)^ </ul>
+
**      allocation error occurs.)^
+
** <li> ^(during the original sqlite3_set_auxdata() call if the function
+
**      is evaluated during query planning instead of during query execution,
+
**      as sometimes happens with [SQLITE_ENABLE_STAT4].)^ </ul>
**
-
** Note the last bullet in particular.  The destructor X in
+
** Note the last two bullets in particular.  The destructor X in
** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
** should be called near the end of the function implementation and the
** function implementation should not make any use of P after
-
** sqlite3_set_auxdata() has been called.
-
**
-
** ^(In practice, metadata is preserved between function calls for
+
** sqlite3_set_auxdata() has been called.  Furthermore, a call to
+
** sqlite3_get_auxdata() that occurs immediately after a corresponding call
+
** to sqlite3_set_auxdata() might still return NULL if an out-of-memory
+
** condition occurred during the sqlite3_set_auxdata() call or if the
+
** function is being evaluated during query planning rather than during
+
** query execution.
+
**
+
** ^(In practice, auxiliary data is preserved between function calls for
** function parameters that are compile-time constants, including literal
** values and [parameters] and expressions composed from the same.)^
**
@@ -6243,10 +6274,67 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
**
** These routines must be called from the same thread in which
** the SQL function is running.
+
**
+
** See also: [sqlite3_get_clientdata()] and [sqlite3_set_clientdata()].
*/
SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));

+
/*
+
** CAPI3REF: Database Connection Client Data
+
** METHOD: sqlite3
+
**
+
** These functions are used to associate one or more named pointers
+
** with a [database connection].
+
** A call to sqlite3_set_clientdata(D,N,P,X) causes the pointer P
+
** to be attached to [database connection] D using name N.  Subsequent
+
** calls to sqlite3_get_clientdata(D,N) will return a copy of pointer P
+
** or a NULL pointer if there were no prior calls to
+
** sqlite3_set_clientdata() with the same values of D and N.
+
** Names are compared using strcmp() and are thus case sensitive.
+
**
+
** If P and X are both non-NULL, then the destructor X is invoked with
+
** argument P on the first of the following occurrences:
+
** <ul>
+
** <li> An out-of-memory error occurs during the call to
+
**      sqlite3_set_clientdata() which attempts to register pointer P.
+
** <li> A subsequent call to sqlite3_set_clientdata(D,N,P,X) is made
+
**      with the same D and N parameters.
+
** <li> The database connection closes.  SQLite does not make any guarantees
+
**      about the order in which destructors are called, only that all
+
**      destructors will be called exactly once at some point during the
+
**      database connection closing process.
+
** </ul>
+
**
+
** SQLite does not do anything with client data other than invoke
+
** destructors on the client data at the appropriate time.  The intended
+
** use for client data is to provide a mechanism for wrapper libraries
+
** to store additional information about an SQLite database connection.
+
**
+
** There is no limit (other than available memory) on the number of different
+
** client data pointers (with different names) that can be attached to a
+
** single database connection.  However, the implementation is optimized
+
** for the case of having only one or two different client data names.
+
** Applications and wrapper libraries are discouraged from using more than
+
** one client data name each.
+
**
+
** There is no way to enumerate the client data pointers
+
** associated with a database connection.  The N parameter can be thought
+
** of as a secret key such that only code that knows the secret key is able
+
** to access the associated data.
+
**
+
** Security Warning:  These interfaces should not be exposed in scripting
+
** languages or in other circumstances where it might be possible for an
+
** an attacker to invoke them.  Any agent that can invoke these interfaces
+
** can probably also take control of the process.
+
**
+
** Database connection client data is only available for SQLite
+
** version 3.44.0 ([dateof:3.44.0]) and later.
+
**
+
** See also: [sqlite3_set_auxdata()] and [sqlite3_get_auxdata()].
+
*/
+
SQLITE_API void *sqlite3_get_clientdata(sqlite3*,const char*);
+
SQLITE_API int sqlite3_set_clientdata(sqlite3*, const char*, void*, void(*)(void*));

/*
** CAPI3REF: Constants Defining Special Destructor Behavior
@@ -6448,6 +6536,20 @@ SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
** higher order bits are discarded.
** The number of subtype bytes preserved by SQLite might increase
** in future releases of SQLite.
+
**
+
** Every [application-defined SQL function] that invokes this interface
+
** should include the [SQLITE_RESULT_SUBTYPE] property in its
+
** text encoding argument when the SQL function is
+
** [sqlite3_create_function|registered].  If the [SQLITE_RESULT_SUBTYPE]
+
** property is omitted from the function that invokes sqlite3_result_subtype(),
+
** then in some cases the sqlite3_result_subtype() might fail to set
+
** the result subtype.
+
**
+
** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any
+
** SQL function that invokes the sqlite3_result_subtype() interface
+
** and that does not have the SQLITE_RESULT_SUBTYPE property will raise
+
** an error.  Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1
+
** by default.
*/
SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);

@@ -6879,7 +6981,7 @@ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);

/*
-
** CAPI3REF: Allowed return values from [sqlite3_txn_state()]
+
** CAPI3REF: Allowed return values from sqlite3_txn_state()
** KEYWORDS: {transaction state}
**
** These constants define the current transaction state of a database file.
@@ -7011,7 +7113,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
** ^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
+
** then the autovacuum steps callback is canceled.  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
@@ -7530,6 +7632,10 @@ struct sqlite3_module {
  /* The methods above are in versions 1 and 2 of the sqlite_module object.
  ** Those below are for version 3 and greater. */
  int (*xShadowName)(const char*);
+
  /* The methods above are in versions 1 through 3 of the sqlite_module object.
+
  ** Those below are for version 4 and greater. */
+
  int (*xIntegrity)(sqlite3_vtab *pVTab, const char *zSchema,
+
                    const char *zTabName, int mFlags, char **pzErr);
};

/*
@@ -8017,7 +8123,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
** code is returned and the transaction rolled back.
**
** Calling this function with an argument that is not a NULL pointer or an
-
** open blob handle results in undefined behaviour. ^Calling this routine
+
** open blob handle results in undefined behavior. ^Calling this routine
** with a null pointer (such as would be returned by a failed call to
** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
** is passed a valid open blob handle, the values returned by the
@@ -8497,6 +8603,7 @@ SQLITE_API int sqlite3_test_control(int op, ...);
#define SQLITE_TESTCTRL_PRNG_SAVE                5
#define SQLITE_TESTCTRL_PRNG_RESTORE             6
#define SQLITE_TESTCTRL_PRNG_RESET               7  /* NOT USED */
+
#define SQLITE_TESTCTRL_FK_NO_ACTION             7
#define SQLITE_TESTCTRL_BITVEC_TEST              8
#define SQLITE_TESTCTRL_FAULT_INSTALL            9
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
@@ -9558,8 +9665,8 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
** blocked connection already has a registered unlock-notify callback,
** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
** called with a NULL pointer as its second argument, then any existing
-
** unlock-notify callback is cancelled. ^The blocked connections
-
** unlock-notify callback may also be cancelled by closing the blocked
+
** unlock-notify callback is canceled. ^The blocked connections
+
** unlock-notify callback may also be canceled by closing the blocked
** connection using [sqlite3_close()].
**
** The unlock-notify callback is not reentrant. If an application invokes
@@ -10862,6 +10969,13 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c
** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
** of the database exists.
**
+
** After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set,
+
** the returned buffer content will remain accessible and unchanged
+
** until either the next write operation on the connection or when
+
** the connection is closed, and applications must not modify the
+
** buffer. If the bit had been clear, the returned buffer will not
+
** be accessed by SQLite after the call.
+
**
** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
** allocation error occurs.
@@ -10910,6 +11024,9 @@ SQLITE_API unsigned char *sqlite3_serialize(
** SQLite will try to increase the buffer size using sqlite3_realloc64()
** if writes on the database cause it to grow larger than M bytes.
**
+
** Applications must not modify the buffer P or invalidate it before
+
** the database connection D is closed.
+
**
** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
** database is currently in a read transaction or is involved in a backup
** operation.
@@ -10918,6 +11035,13 @@ SQLITE_API unsigned char *sqlite3_serialize(
** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
** function returns SQLITE_ERROR.
**
+
** The deserialized database should not be in [WAL mode].  If the database
+
** is in WAL mode, then any attempt to use the database file will result
+
** in an [SQLITE_CANTOPEN] error.  The application can set the
+
** [file format version numbers] (bytes 18 and 19) of the input database P
+
** to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the
+
** database file into rollback mode and work around this limitation.
+
**
** 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.
@@ -11991,6 +12115,18 @@ SQLITE_API int sqlite3changeset_concat(


/*
+
** CAPI3REF: Upgrade the Schema of a Changeset/Patchset
+
*/
+
SQLITE_API int sqlite3changeset_upgrade(
+
  sqlite3 *db,
+
  const char *zDb,
+
  int nIn, const void *pIn,       /* Input changeset */
+
  int *pnOut, void **ppOut        /* OUT: Inverse of input */
+
);
+

+

+

+
/*
** CAPI3REF: Changegroup Handle
**
** A changegroup is an object used to combine two or more
@@ -12037,6 +12173,38 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);

/*
+
** CAPI3REF: Add a Schema to a Changegroup
+
** METHOD: sqlite3_changegroup_schema
+
**
+
** This method may be used to optionally enforce the rule that the changesets
+
** added to the changegroup handle must match the schema of database zDb
+
** ("main", "temp", or the name of an attached database). If
+
** sqlite3changegroup_add() is called to add a changeset that is not compatible
+
** with the configured schema, SQLITE_SCHEMA is returned and the changegroup
+
** object is left in an undefined state.
+
**
+
** A changeset schema is considered compatible with the database schema in
+
** the same way as for sqlite3changeset_apply(). Specifically, for each
+
** table in the changeset, there exists a database table with:
+
**
+
** <ul>
+
**   <li> The name identified by the changeset, and
+
**   <li> at least as many columns as recorded in the changeset, and
+
**   <li> the primary key columns in the same position as recorded in
+
**        the changeset.
+
** </ul>
+
**
+
** The output of the changegroup object always has the same schema as the
+
** database nominated using this function. In cases where changesets passed
+
** to sqlite3changegroup_add() have fewer columns than the corresponding table
+
** in the database schema, these are filled in using the default column
+
** values from the database schema. This makes it possible to combined
+
** changesets that have different numbers of columns for a single table
+
** within a changegroup, provided that they are otherwise compatible.
+
*/
+
SQLITE_API int sqlite3changegroup_schema(sqlite3_changegroup*, sqlite3*, const char *zDb);
+

+
/*
** CAPI3REF: Add A Changeset To A Changegroup
** METHOD: sqlite3_changegroup
**
@@ -12104,13 +12272,18 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
** If the new changeset contains changes to a table that is already present
** in the changegroup, then the number of columns and the position of the
** primary key columns for the table must be consistent. If this is not the
-
** case, this function fails with SQLITE_SCHEMA. If the input changeset
-
** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
-
** returned. Or, if an out-of-memory condition occurs during processing, this
-
** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
-
** of the final contents of the changegroup is undefined.
+
** case, this function fails with SQLITE_SCHEMA. Except, if the changegroup
+
** object has been configured with a database schema using the
+
** sqlite3changegroup_schema() API, then it is possible to combine changesets
+
** with different numbers of columns for a single table, provided that
+
** they are otherwise compatible.
+
**
+
** If the input changeset appears to be corrupt and the corruption is
+
** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition
+
** occurs during processing, this function returns SQLITE_NOMEM.
**
-
** If no error occurs, SQLITE_OK is returned.
+
** In all cases, if an error occurs the state of the final contents of the
+
** changegroup is undefined. If no error occurs, SQLITE_OK is returned.
*/
SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);

@@ -12375,10 +12548,17 @@ SQLITE_API int sqlite3changeset_apply_v2(
**    <li>an insert change if all fields of the conflicting row match
**        the row being inserted.
**    </ul>
+
**
+
** <dt>SQLITE_CHANGESETAPPLY_FKNOACTION <dd>
+
**   If this flag it set, then all foreign key constraints in the target
+
**   database behave as if they were declared with "ON UPDATE NO ACTION ON
+
**   DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL
+
**   or SET DEFAULT.
*/
#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
#define SQLITE_CHANGESETAPPLY_INVERT        0x0002
#define SQLITE_CHANGESETAPPLY_IGNORENOOP    0x0004
+
#define SQLITE_CHANGESETAPPLY_FKNOACTION    0x0008

/*
** CAPI3REF: Constants Passed To The Conflict Handler
@@ -13770,6 +13950,16 @@ struct fts5_api {
#endif

/*
+
** Enable SQLITE_USE_SEH by default on MSVC builds.  Only omit
+
** SEH support if the -DSQLITE_OMIT_SEH option is given.
+
*/
+
#if defined(_MSC_VER) && !defined(SQLITE_OMIT_SEH)
+
# define SQLITE_USE_SEH 1
+
#else
+
# undef SQLITE_USE_SEH
+
#endif
+

+
/*
** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
** 0 means mutexes are permanently disable and the library is never
** threadsafe.  1 means the library is serialized which is the highest
@@ -14662,16 +14852,33 @@ typedef INT16_TYPE LogEst;
** using C-preprocessor macros.  If that is unsuccessful, or if
** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
** at run-time.
+
**
+
** If you are building SQLite on some obscure platform for which the
+
** following ifdef magic does not work, you can always include either:
+
**
+
**    -DSQLITE_BYTEORDER=1234
+
**
+
** or
+
**
+
**    -DSQLITE_BYTEORDER=4321
+
**
+
** to cause the build to work for little-endian or big-endian processors,
+
** respectively.
*/
-
#ifndef SQLITE_BYTEORDER
-
# if defined(i386)      || defined(__i386__)      || defined(_M_IX86) ||    \
+
#ifndef SQLITE_BYTEORDER  /* Replicate changes at tag-20230904a */
+
# if defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__
+
#   define SQLITE_BYTEORDER 4321
+
# elif defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
+
#   define SQLITE_BYTEORDER 1234
+
# elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1
+
#   define SQLITE_BYTEORDER 4321
+
# elif defined(i386)    || defined(__i386__)      || defined(_M_IX86) ||    \
     defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \
     defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \
     defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
-
#   define SQLITE_BYTEORDER    1234
-
# elif defined(sparc)     || defined(__ppc__) || \
-
       defined(__ARMEB__) || defined(__AARCH64EB__)
-
#   define SQLITE_BYTEORDER    4321
+
#   define SQLITE_BYTEORDER 1234
+
# elif defined(sparc)   || defined(__ARMEB__)     || defined(__AARCH64EB__)
+
#   define SQLITE_BYTEORDER 4321
# else
#   define SQLITE_BYTEORDER 0
# endif
@@ -14995,6 +15202,7 @@ typedef struct Column Column;
typedef struct Cte Cte;
typedef struct CteUse CteUse;
typedef struct Db Db;
+
typedef struct DbClientData DbClientData;
typedef struct DbFixer DbFixer;
typedef struct Schema Schema;
typedef struct Expr Expr;
@@ -16435,19 +16643,20 @@ typedef struct VdbeOpList VdbeOpList;
#define OP_VCreate       171
#define OP_VDestroy      172
#define OP_VOpen         173
-
#define OP_VInitIn       174 /* synopsis: r[P2]=ValueList(P1,P3)           */
-
#define OP_VColumn       175 /* synopsis: r[P3]=vcolumn(P2)                */
-
#define OP_VRename       176
-
#define OP_Pagecount     177
-
#define OP_MaxPgcnt      178
-
#define OP_ClrSubtype    179 /* synopsis: r[P1].subtype = 0                */
-
#define OP_FilterAdd     180 /* synopsis: filter(P1) += key(P3@P4)         */
-
#define OP_Trace         181
-
#define OP_CursorHint    182
-
#define OP_ReleaseReg    183 /* synopsis: release r[P1@P2] mask P3         */
-
#define OP_Noop          184
-
#define OP_Explain       185
-
#define OP_Abortable     186
+
#define OP_VCheck        174
+
#define OP_VInitIn       175 /* synopsis: r[P2]=ValueList(P1,P3)           */
+
#define OP_VColumn       176 /* synopsis: r[P3]=vcolumn(P2)                */
+
#define OP_VRename       177
+
#define OP_Pagecount     178
+
#define OP_MaxPgcnt      179
+
#define OP_ClrSubtype    180 /* synopsis: r[P1].subtype = 0                */
+
#define OP_FilterAdd     181 /* synopsis: filter(P1) += key(P3@P4)         */
+
#define OP_Trace         182
+
#define OP_CursorHint    183
+
#define OP_ReleaseReg    184 /* synopsis: release r[P1@P2] mask P3         */
+
#define OP_Noop          185
+
#define OP_Explain       186
+
#define OP_Abortable     187

/* Properties such as "out2" or "jump" that are specified in
** comments following the "case" for each opcode in the vdbe.c
@@ -16482,9 +16691,9 @@ typedef struct VdbeOpList VdbeOpList;
/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
/* 152 */ 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-
/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x50, 0x40,\
-
/* 176 */ 0x00, 0x10, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00,\
-
/* 184 */ 0x00, 0x00, 0x00,}
+
/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\
+
/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x00, 0x00, 0x00,\
+
/* 184 */ 0x00, 0x00, 0x00, 0x00,}

/* The resolve3P2Values() routine is able to run faster if it knows
** the value of the largest JUMP opcode.  The smaller the maximum
@@ -17393,6 +17602,7 @@ struct sqlite3 {
  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
+
  DbClientData *pDbData;        /* sqlite3_set_clientdata() content */
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  /* The following variables are all protected by the STATIC_MAIN
  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
@@ -17475,6 +17685,7 @@ struct sqlite3 {
                                          /*   the count using a callback. */
#define SQLITE_CorruptRdOnly  HI(0x00002) /* Prohibit writes due to error */
#define SQLITE_ReadUncommit   HI(0x00004) /* READ UNCOMMITTED in shared-cache */
+
#define SQLITE_FkNoAction     HI(0x00008) /* Treat all FK as NO ACTION */

/* Flags used only if debugging */
#ifdef SQLITE_DEBUG
@@ -17643,14 +17854,15 @@ struct FuncDestructor {
#define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
                                    ** single query - might change over time */
#define SQLITE_FUNC_TEST     0x4000 /* Built-in testing functions */
-
/*                           0x8000 -- available for reuse */
+
#define SQLITE_FUNC_RUNONLY  0x8000 /* Cannot be used by valueFromFunction */
#define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */
#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
#define SQLITE_FUNC_DIRECT   0x00080000 /* Not for use in TRIGGERs or VIEWs */
-
#define SQLITE_FUNC_SUBTYPE  0x00100000 /* Result likely to have sub-type */
+
/* SQLITE_SUBTYPE            0x00100000 // Consumer of subtypes */
#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 */
+
/*  SQLITE_RESULT_SUBTYPE    0x01000000 // Generator of subtypes */
#define SQLITE_FUNC_ANYORDER 0x08000000 /* count/min/max aggregate */

/* Identifier numbers for each in-line function */
@@ -17742,9 +17954,10 @@ struct FuncDestructor {
#define MFUNCTION(zName, nArg, xPtr, xFunc) \
  {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_FUNC_CONSTANT|SQLITE_UTF8, \
+
#define JFUNCTION(zName, nArg, bUseCache, bWS, bRS, iArg, xFunc) \
+
  {nArg, SQLITE_FUNC_BUILTIN|SQLITE_DETERMINISTIC|SQLITE_FUNC_CONSTANT|\
+
   SQLITE_UTF8|((bUseCache)*SQLITE_FUNC_RUNONLY)|\
+
   ((bRS)*SQLITE_SUBTYPE)|((bWS)*SQLITE_RESULT_SUBTYPE), \
   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
#define INLINE_FUNC(zName, nArg, iArg, mFlags) \
  {nArg, SQLITE_FUNC_BUILTIN|\
@@ -18490,6 +18703,9 @@ struct AggInfo {
    FuncDef *pFunc;          /* The aggregate function implementation */
    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
    int iDistAddr;           /* Address of OP_OpenEphemeral */
+
    int iOBTab;              /* Ephemeral table to implement ORDER BY */
+
    u8 bOBPayload;           /* iOBTab has payload columns separate from key */
+
    u8 bOBUnique;            /* Enforce uniqueness on iOBTab keys */
  } *aFunc;
  int nFunc;              /* Number of entries in aFunc[] */
  u32 selId;              /* Select to which this AggInfo belongs */
@@ -18674,7 +18890,7 @@ struct Expr {
#define EP_Reduced    0x004000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
#define EP_Win        0x008000 /* Contains window functions */
#define EP_TokenOnly  0x010000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
-
                   /* 0x020000 // Available for reuse */
+
#define EP_FullSize   0x020000 /* Expr structure must remain full sized */
#define EP_IfNullRow  0x040000 /* The TK_IF_NULL_ROW opcode */
#define EP_Unlikely   0x080000 /* unlikely() or likelihood() function */
#define EP_ConstFunc  0x100000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
@@ -18704,6 +18920,7 @@ struct Expr {
#define ExprClearProperty(E,P)   (E)->flags&=~(P)
#define ExprAlwaysTrue(E)   (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)
#define ExprAlwaysFalse(E)  (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)
+
#define ExprIsFullSize(E)   (((E)->flags&(EP_Reduced|EP_TokenOnly))==0)

/* Macros used to ensure that the correct members of unions are accessed
** in Expr.
@@ -18821,6 +19038,7 @@ struct ExprList {
#define ENAME_NAME  0       /* The AS clause of a result set */
#define ENAME_SPAN  1       /* Complete text of the result set expression */
#define ENAME_TAB   2       /* "DB.TABLE.NAME" for the result set */
+
#define ENAME_ROWID 3       /* "DB.TABLE._rowid_" for * expansion of rowid */

/*
** An instance of this structure can hold a simple list of identifiers,
@@ -19429,6 +19647,7 @@ struct Parse {
  int *aLabel;         /* Space to hold the labels */
  ExprList *pConstExpr;/* Constant expressions */
  IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */
+
  IndexedExpr *pIdxPartExpr; /* Exprs constrained by index WHERE clauses */
  Token constraintName;/* Name of the constraint currently being parsed */
  yDbMask writeMask;   /* Start a write transaction on these databases */
  yDbMask cookieMask;  /* Bitmask of schema verified databases */
@@ -19700,6 +19919,7 @@ struct Returning {
  int iRetCur;          /* Transient table holding RETURNING results */
  int nRetCol;          /* Number of in pReturnEL after expansion */
  int iRetReg;          /* Register array for holding a row of RETURNING */
+
  char zName[40];       /* Name of trigger: "sqlite_returning_%p" */
};

/*
@@ -20000,6 +20220,16 @@ struct CteUse {
};


+
/* Client data associated with sqlite3_set_clientdata() and
+
** sqlite3_get_clientdata().
+
*/
+
struct DbClientData {
+
  DbClientData *pNext;        /* Next in a linked list */
+
  void *pData;                /* The data */
+
  void (*xDestructor)(void*); /* Destructor.  Might be NULL */
+
  char zName[1];              /* Name of this client data. MUST BE LAST */
+
};
+

#ifdef SQLITE_DEBUG
/*
** An instance of the TreeView object is used for printing the content of
@@ -20404,6 +20634,8 @@ 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*, const Token*, int);
+
SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*);
+
SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse*,Expr*);
SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
@@ -20640,6 +20872,7 @@ 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*);
+
SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab);
SQLITE_PRIVATE void sqlite3GenerateRowDelete(
    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
@@ -20911,7 +21144,8 @@ SQLITE_PRIVATE int sqlite3MatchEName(
  const struct ExprList_item*,
  const char*,
  const char*,
-
  const char*
+
  const char*,
+
  int*
);
SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);
SQLITE_PRIVATE u8 sqlite3StrIHash(const char*);
@@ -20968,7 +21202,7 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);

SQLITE_PRIVATE char *sqlite3RCStrRef(char*);
-
SQLITE_PRIVATE void sqlite3RCStrUnref(char*);
+
SQLITE_PRIVATE void sqlite3RCStrUnref(void*);
SQLITE_PRIVATE char *sqlite3RCStrNew(u64);
SQLITE_PRIVATE char *sqlite3RCStrResize(char*,u64);

@@ -21804,6 +22038,9 @@ static const char * const sqlite3azCompileOpt[] = {
#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  "EXPLAIN_ESTIMATED_ROWS",
#endif
+
#ifdef SQLITE_EXTRA_AUTOEXT
+
  "EXTRA_AUTOEXT=" CTIMEOPT_VAL(SQLITE_EXTRA_AUTOEXT),
+
#endif
#ifdef SQLITE_EXTRA_IFNULLROW
  "EXTRA_IFNULLROW",
#endif
@@ -22085,6 +22322,9 @@ static const char * const sqlite3azCompileOpt[] = {
#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  "OMIT_SCHEMA_VERSION_PRAGMAS",
#endif
+
#ifdef SQLITE_OMIT_SEH
+
  "OMIT_SEH",
+
#endif
#ifdef SQLITE_OMIT_SHARED_CACHE
  "OMIT_SHARED_CACHE",
#endif
@@ -25044,13 +25284,16 @@ static void strftimeFunc(
  computeJD(&x);
  computeYMD_HMS(&x);
  for(i=j=0; zFmt[i]; i++){
+
    char cf;
    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);
+
    cf = zFmt[i];
+
    switch( cf ){
+
      case 'd':  /* Fall thru */
+
      case 'e': {
+
        sqlite3_str_appendf(&sRes, cf=='d' ? "%02d" : "%2d", x.D);
        break;
      }
      case 'f': {
@@ -25059,8 +25302,21 @@ static void strftimeFunc(
        sqlite3_str_appendf(&sRes, "%06.3f", s);
        break;
      }
-
      case 'H': {
-
        sqlite3_str_appendf(&sRes, "%02d", x.h);
+
      case 'F': {
+
        sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
+
        break;
+
      }
+
      case 'H':
+
      case 'k': {
+
        sqlite3_str_appendf(&sRes, cf=='H' ? "%02d" : "%2d", x.h);
+
        break;
+
      }
+
      case 'I': /* Fall thru */
+
      case 'l': {
+
        int h = x.h;
+
        if( h>12 ) h -= 12;
+
        if( h==0 ) h = 12;
+
        sqlite3_str_appendf(&sRes, cf=='I' ? "%02d" : "%2d", h);
        break;
      }
      case 'W': /* Fall thru */
@@ -25072,7 +25328,7 @@ static void strftimeFunc(
        y.D = 1;
        computeJD(&y);
        nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
-
        if( zFmt[i]=='W' ){
+
        if( cf=='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);
@@ -25093,6 +25349,19 @@ static void strftimeFunc(
        sqlite3_str_appendf(&sRes,"%02d",x.m);
        break;
      }
+
      case 'p': /* Fall thru */
+
      case 'P': {
+
        if( x.h>=12 ){
+
          sqlite3_str_append(&sRes, cf=='p' ? "PM" : "pm", 2);
+
        }else{
+
          sqlite3_str_append(&sRes, cf=='p' ? "AM" : "am", 2);
+
        }
+
        break;
+
      }
+
      case 'R': {
+
        sqlite3_str_appendf(&sRes, "%02d:%02d", x.h, x.m);
+
        break;
+
      }
      case 's': {
        if( x.useSubsec ){
          sqlite3_str_appendf(&sRes,"%.3f",
@@ -25107,9 +25376,15 @@ static void strftimeFunc(
        sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
        break;
      }
+
      case 'T': {
+
        sqlite3_str_appendf(&sRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
+
        break;
+
      }
+
      case 'u': /* Fall thru */
      case 'w': {
-
        sqlite3_str_appendchar(&sRes, 1,
-
                       (char)(((x.iJD+129600000)/86400000) % 7) + '0');
+
        char c = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
+
        if( c=='0' && cf=='u' ) c = '7';
+
        sqlite3_str_appendchar(&sRes, 1, c);
        break;
      }
      case 'Y': {
@@ -28198,7 +28473,7 @@ static void checkMutexFree(sqlite3_mutex *p){
  assert( SQLITE_MUTEX_FAST<2 );
  assert( SQLITE_MUTEX_WARNONCONTENTION<2 );

-
#if SQLITE_ENABLE_API_ARMOR
+
#ifdef SQLITE_ENABLE_API_ARMOR
  if( ((CheckMutex*)p)->iType<2 )
#endif
  {
@@ -28870,7 +29145,7 @@ static sqlite3_mutex *pthreadMutexAlloc(int iType){
*/
static void pthreadMutexFree(sqlite3_mutex *p){
  assert( p->nRef==0 );
-
#if SQLITE_ENABLE_API_ARMOR
+
#ifdef SQLITE_ENABLE_API_ARMOR
  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
#endif
  {
@@ -29223,7 +29498,7 @@ SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  SQLITE_MEMORY_BARRIER;
#elif defined(__GNUC__)
  __sync_synchronize();
-
#elif MSVC_VERSION>=1300
+
#elif MSVC_VERSION>=1400
  _ReadWriteBarrier();
#elif defined(MemoryBarrier)
  MemoryBarrier();
@@ -30434,7 +30709,7 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  if( db->mallocFailed || rc ){
    return apiHandleError(db, rc);
  }
-
  return rc & db->errMask;
+
  return 0;
}

/************** End of malloc.c **********************************************/
@@ -31830,7 +32105,7 @@ SQLITE_PRIVATE char *sqlite3RCStrRef(char *z){
** Decrease the reference count by one.  Free the string when the
** reference count reaches zero.
*/
-
SQLITE_PRIVATE void sqlite3RCStrUnref(char *z){
+
SQLITE_PRIVATE void sqlite3RCStrUnref(void *z){
  RCStr *p = (RCStr*)z;
  assert( p!=0 );
  p--;
@@ -32293,6 +32568,7 @@ SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u
    sqlite3TreeViewItem(pView, "FILTER", 1);
    sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
    sqlite3TreeViewPop(&pView);
+
    if( pWin->eFrmType==TK_FILTER ) return;
  }
  sqlite3TreeViewPush(&pView, more);
  if( pWin->zName ){
@@ -32302,7 +32578,7 @@ SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u
  }
  if( pWin->zBase )    nElement++;
  if( pWin->pOrderBy ) nElement++;
-
  if( pWin->eFrmType ) nElement++;
+
  if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER ) nElement++;
  if( pWin->eExclude ) nElement++;
  if( pWin->zBase ){
    sqlite3TreeViewPush(&pView, (--nElement)>0);
@@ -32315,7 +32591,7 @@ SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u
  if( pWin->pOrderBy ){
    sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
  }
-
  if( pWin->eFrmType ){
+
  if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER ){
    char zBuf[30];
    const char *zFrmType = "ROWS";
    if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
@@ -32563,7 +32839,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
        assert( ExprUseXList(pExpr) );
        pFarg = pExpr->x.pList;
#ifndef SQLITE_OMIT_WINDOWFUNC
-
        pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;
+
        pWin = IsWindowFunc(pExpr) ? pExpr->y.pWin : 0;
#else
        pWin = 0;
#endif
@@ -32589,7 +32865,13 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
        sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs);
      }
      if( pFarg ){
-
        sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
+
        sqlite3TreeViewExprList(pView, pFarg, pWin!=0 || pExpr->pLeft, 0);
+
        if( pExpr->pLeft ){
+
          Expr *pOB = pExpr->pLeft;
+
          assert( pOB->op==TK_ORDER );
+
          assert( ExprUseXList(pOB) );
+
          sqlite3TreeViewExprList(pView, pOB->x.pList, pWin!=0, "ORDERBY");
+
        }
      }
#ifndef SQLITE_OMIT_WINDOWFUNC
      if( pWin ){
@@ -32598,6 +32880,10 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
#endif
      break;
    }
+
    case TK_ORDER: {
+
      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, "ORDERBY");
+
      break;
+
    }
#ifndef SQLITE_OMIT_SUBQUERY
    case TK_EXISTS: {
      assert( ExprUseXSelect(pExpr) );
@@ -34362,12 +34648,16 @@ SQLITE_PRIVATE void sqlite3ProgressCheck(Parse *p){
    p->rc = SQLITE_INTERRUPT;
  }
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
-
  if( db->xProgress && (++p->nProgressSteps)>=db->nProgressOps ){
-
    if( db->xProgress(db->pProgressArg) ){
-
      p->nErr++;
-
      p->rc = SQLITE_INTERRUPT;
+
  if( db->xProgress ){
+
    if( p->rc==SQLITE_INTERRUPT ){
+
      p->nProgressSteps = 0;
+
    }else if( (++p->nProgressSteps)>=db->nProgressOps ){
+
      if( db->xProgress(db->pProgressArg) ){
+
        p->nErr++;
+
        p->rc = SQLITE_INTERRUPT;
+
      }
+
      p->nProgressSteps = 0;
    }
-
    p->nProgressSteps = 0;
  }
#endif
}
@@ -35185,29 +35475,29 @@ SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRou
    double rr[2];
    rr[0] = r;
    rr[1] = 0.0;
-
    if( rr[0]>1.84e+19 ){
-
      while( rr[0]>1.84e+119 ){
+
    if( rr[0]>9.223372036854774784e+18 ){
+
      while( rr[0]>9.223372036854774784e+118 ){
        exp += 100;
        dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117);
      }
-
      while( rr[0]>1.84e+29 ){
+
      while( rr[0]>9.223372036854774784e+28 ){
        exp += 10;
        dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27);
      }
-
      while( rr[0]>1.84e+19 ){
+
      while( rr[0]>9.223372036854774784e+18 ){
        exp += 1;
        dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18);
      }
    }else{
-
      while( rr[0]<1.84e-82  ){
+
      while( rr[0]<9.223372036854774784e-83  ){
        exp -= 100;
        dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83);
      }
-
      while( rr[0]<1.84e+08  ){
+
      while( rr[0]<9.223372036854774784e+07  ){
        exp -= 10;
        dekkerMul2(rr, 1.0e+10, 0.0);
      }
-
      while( rr[0]<1.84e+18  ){
+
      while( rr[0]<9.22337203685477478e+17  ){
        exp -= 1;
        dekkerMul2(rr, 1.0e+01, 0.0);
      }
@@ -35523,121 +35813,32 @@ SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
** this function assumes the single-byte case has already been handled.
*/
SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
-
  u32 a,b;
+
  u64 v64;
+
  u8 n;

-
  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
-
  ** by the getVarin32() macro */
-
  a = *p;
-
  /* a: p0 (unmasked) */
-
#ifndef getVarint32
-
  if (!(a&0x80))
-
  {
-
    /* Values between 0 and 127 */
-
    *v = a;
-
    return 1;
-
  }
-
#endif
+
  /* Assume that the single-byte case has already been handled by
+
  ** the getVarint32() macro */
+
  assert( (p[0] & 0x80)!=0 );

-
  /* The 2-byte case */
-
  p++;
-
  b = *p;
-
  /* b: p1 (unmasked) */
-
  if (!(b&0x80))
-
  {
-
    /* Values between 128 and 16383 */
-
    a &= 0x7f;
-
    a = a<<7;
-
    *v = a | b;
+
  if( (p[1] & 0x80)==0 ){
+
    /* This is the two-byte case */
+
    *v = ((p[0]&0x7f)<<7) | p[1];
    return 2;
  }
-

-
  /* The 3-byte case */
-
  p++;
-
  a = a<<14;
-
  a |= *p;
-
  /* a: p0<<14 | p2 (unmasked) */
-
  if (!(a&0x80))
-
  {
-
    /* Values between 16384 and 2097151 */
-
    a &= (0x7f<<14)|(0x7f);
-
    b &= 0x7f;
-
    b = b<<7;
-
    *v = a | b;
+
  if( (p[2] & 0x80)==0 ){
+
    /* This is the three-byte case */
+
    *v = ((p[0]&0x7f)<<14) | ((p[1]&0x7f)<<7) | p[2];
    return 3;
  }
-

-
  /* A 32-bit varint is used to store size information in btrees.
-
  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
-
  ** A 3-byte varint is sufficient, for example, to record the size
-
  ** of a 1048569-byte BLOB or string.
-
  **
-
  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
-
  ** rare larger cases can be handled by the slower 64-bit varint
-
  ** routine.
-
  */
-
#if 1
-
  {
-
    u64 v64;
-
    u8 n;
-

-
    n = sqlite3GetVarint(p-2, &v64);
-
    assert( n>3 && n<=9 );
-
    if( (v64 & SQLITE_MAX_U32)!=v64 ){
-
      *v = 0xffffffff;
-
    }else{
-
      *v = (u32)v64;
-
    }
-
    return n;
-
  }
-

-
#else
-
  /* For following code (kept for historical record only) shows an
-
  ** unrolling for the 3- and 4-byte varint cases.  This code is
-
  ** slightly faster, but it is also larger and much harder to test.
-
  */
-
  p++;
-
  b = b<<14;
-
  b |= *p;
-
  /* b: p1<<14 | p3 (unmasked) */
-
  if (!(b&0x80))
-
  {
-
    /* Values between 2097152 and 268435455 */
-
    b &= (0x7f<<14)|(0x7f);
-
    a &= (0x7f<<14)|(0x7f);
-
    a = a<<7;
-
    *v = a | b;
-
    return 4;
-
  }
-

-
  p++;
-
  a = a<<14;
-
  a |= *p;
-
  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
-
  if (!(a&0x80))
-
  {
-
    /* Values  between 268435456 and 34359738367 */
-
    a &= SLOT_4_2_0;
-
    b &= SLOT_4_2_0;
-
    b = b<<7;
-
    *v = a | b;
-
    return 5;
-
  }
-

-
  /* We can only reach this point when reading a corrupt database
-
  ** file.  In that case we are not in any hurry.  Use the (relatively
-
  ** slow) general-purpose sqlite3GetVarint() routine to extract the
-
  ** value. */
-
  {
-
    u64 v64;
-
    u8 n;
-

-
    p -= 4;
-
    n = sqlite3GetVarint(p, &v64);
-
    assert( n>5 && n<=9 );
+
  /* four or more bytes */
+
  n = sqlite3GetVarint(p, &v64);
+
  assert( n>3 && n<=9 );
+
  if( (v64 & SQLITE_MAX_U32)!=v64 ){
+
    *v = 0xffffffff;
+
  }else{
    *v = (u32)v64;
-
    return n;
  }
-
#endif
+
  return n;
}

/*
@@ -36633,19 +36834,20 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
    /* 171 */ "VCreate"          OpHelp(""),
    /* 172 */ "VDestroy"         OpHelp(""),
    /* 173 */ "VOpen"            OpHelp(""),
-
    /* 174 */ "VInitIn"          OpHelp("r[P2]=ValueList(P1,P3)"),
-
    /* 175 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
-
    /* 176 */ "VRename"          OpHelp(""),
-
    /* 177 */ "Pagecount"        OpHelp(""),
-
    /* 178 */ "MaxPgcnt"         OpHelp(""),
-
    /* 179 */ "ClrSubtype"       OpHelp("r[P1].subtype = 0"),
-
    /* 180 */ "FilterAdd"        OpHelp("filter(P1) += key(P3@P4)"),
-
    /* 181 */ "Trace"            OpHelp(""),
-
    /* 182 */ "CursorHint"       OpHelp(""),
-
    /* 183 */ "ReleaseReg"       OpHelp("release r[P1@P2] mask P3"),
-
    /* 184 */ "Noop"             OpHelp(""),
-
    /* 185 */ "Explain"          OpHelp(""),
-
    /* 186 */ "Abortable"        OpHelp(""),
+
    /* 174 */ "VCheck"           OpHelp(""),
+
    /* 175 */ "VInitIn"          OpHelp("r[P2]=ValueList(P1,P3)"),
+
    /* 176 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
+
    /* 177 */ "VRename"          OpHelp(""),
+
    /* 178 */ "Pagecount"        OpHelp(""),
+
    /* 179 */ "MaxPgcnt"         OpHelp(""),
+
    /* 180 */ "ClrSubtype"       OpHelp("r[P1].subtype = 0"),
+
    /* 181 */ "FilterAdd"        OpHelp("filter(P1) += key(P3@P4)"),
+
    /* 182 */ "Trace"            OpHelp(""),
+
    /* 183 */ "CursorHint"       OpHelp(""),
+
    /* 184 */ "ReleaseReg"       OpHelp("release r[P1@P2] mask P3"),
+
    /* 185 */ "Noop"             OpHelp(""),
+
    /* 186 */ "Explain"          OpHelp(""),
+
    /* 187 */ "Abortable"        OpHelp(""),
  };
  return azName[i];
}
@@ -40787,9 +40989,6 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
  unixInodeInfo *pInode;
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  int skipShared = 0;
-
#ifdef SQLITE_TEST
-
  int h = pFile->h;
-
#endif

  assert( pFile );
  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
@@ -40805,9 +41004,6 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
  assert( pInode->nShared!=0 );
  if( pFile->eFileLock>SHARED_LOCK ){
    assert( pInode->eFileLock==pFile->eFileLock );
-
    SimulateIOErrorBenign(1);
-
    SimulateIOError( h=(-1) )
-
    SimulateIOErrorBenign(0);

#ifdef SQLITE_DEBUG
    /* When reducing a lock such that other processes can start
@@ -40856,9 +41052,6 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
    pInode->nShared--;
    if( pInode->nShared==0 ){
-
      SimulateIOErrorBenign(1);
-
      SimulateIOError( h=(-1) )
-
      SimulateIOErrorBenign(0);
      if( !skipShared ){
        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
      }
@@ -57729,9 +57922,32 @@ static int writeJournalHdr(Pager *pPager){
    memset(zHeader, 0, sizeof(aJournalMagic)+4);
  }

+

+

  /* The random check-hash initializer */
-
  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
+
  if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
+
    sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
+
  }
+
#ifdef SQLITE_DEBUG
+
  else{
+
    /* The Pager.cksumInit variable is usually randomized above to protect
+
    ** against there being existing records in the journal file. This is
+
    ** dangerous, as following a crash they may be mistaken for records
+
    ** written by the current transaction and rolled back into the database
+
    ** file, causing corruption. The following assert statements verify
+
    ** that this is not required in "journal_mode=memory" mode, as in that
+
    ** case the journal file is always 0 bytes in size at this point.
+
    ** It is advantageous to avoid the sqlite3_randomness() call if possible
+
    ** as it takes the global PRNG mutex.  */
+
    i64 sz = 0;
+
    sqlite3OsFileSize(pPager->jfd, &sz);
+
    assert( sz==0 );
+
    assert( pPager->journalOff==journalHdrOffset(pPager) );
+
    assert( sqlite3JournalIsInMemory(pPager->jfd) );
+
  }
+
#endif
  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
+

  /* The initial database size */
  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  /* The assumed sector size for this process */
@@ -58375,6 +58591,9 @@ static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){
  return (rc==SQLITE_OK?rc2:rc);
}

+
/* Forward reference */
+
static int pager_playback(Pager *pPager, int isHot);
+

/*
** Execute a rollback if a transaction is active and unlock the
** database file.
@@ -58403,6 +58622,21 @@ static void pagerUnlockAndRollback(Pager *pPager){
      assert( pPager->eState==PAGER_READER );
      pager_end_transaction(pPager, 0, 0);
    }
+
  }else if( pPager->eState==PAGER_ERROR
+
         && pPager->journalMode==PAGER_JOURNALMODE_MEMORY
+
         && isOpen(pPager->jfd)
+
  ){
+
    /* Special case for a ROLLBACK due to I/O error with an in-memory
+
    ** journal:  We have to rollback immediately, before the journal is
+
    ** closed, because once it is closed, all content is forgotten. */
+
    int errCode = pPager->errCode;
+
    u8 eLock = pPager->eLock;
+
    pPager->eState = PAGER_OPEN;
+
    pPager->errCode = SQLITE_OK;
+
    pPager->eLock = EXCLUSIVE_LOCK;
+
    pager_playback(pPager, 1);
+
    pPager->errCode = errCode;
+
    pPager->eLock = eLock;
  }
  pager_unlock(pPager);
}
@@ -61258,10 +61492,13 @@ act_like_temp_file:
*/
SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){
  Pager *pPager;
+
  const char *p;
  while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
    zName--;
  }
-
  pPager = *(Pager**)(zName - 4 - sizeof(Pager*));
+
  p = zName - 4 - sizeof(Pager*);
+
  assert( EIGHT_BYTE_ALIGNMENT(p) );
+
  pPager = *(Pager**)p;
  return pPager->fd;
}

@@ -61895,8 +62132,20 @@ 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); */
+
#if 0   /* Trace page fetch by setting to 1 */
+
  int rc;
+
  printf("PAGE %u\n", pgno);
+
  fflush(stdout);
+
  rc = pPager->xGet(pPager, pgno, ppPage, flags);
+
  if( rc ){
+
    printf("PAGE %u failed with 0x%02x\n", pgno, rc);
+
    fflush(stdout);
+
  }
+
  return rc;
+
#else
+
  /* Normal, high-speed version of sqlite3PagerGet() */
  return pPager->xGet(pPager, pgno, ppPage, flags);
+
#endif
}

/*
@@ -62772,6 +63021,13 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
        rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
        if( rc==SQLITE_OK ){
          rc = pager_write_pagelist(pPager, pList);
+
          if( rc==SQLITE_OK && pPager->dbSize>pPager->dbFileSize ){
+
            char *pTmp = pPager->pTmpSpace;
+
            int szPage = (int)pPager->pageSize;
+
            memset(pTmp, 0, szPage);
+
            rc = sqlite3OsWrite(pPager->fd, pTmp, szPage,
+
                      ((i64)pPager->dbSize*pPager->pageSize)-szPage);
+
          }
          if( rc==SQLITE_OK ){
            rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
          }
@@ -63583,7 +63839,7 @@ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
        }
        assert( state==pPager->eState );
      }
-
    }else if( eMode==PAGER_JOURNALMODE_OFF ){
+
    }else if( eMode==PAGER_JOURNALMODE_OFF || eMode==PAGER_JOURNALMODE_MEMORY ){
      sqlite3OsClose(pPager->jfd);
    }
  }
@@ -69196,7 +69452,7 @@ struct IntegrityCk {
  BtShared *pBt;    /* The tree being checked out */
  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
-
  Pgno nPage;       /* Number of pages in the database */
+
  Pgno nCkPage;     /* Pages in the database.  0 for partial check */
  int mxErr;        /* Stop accumulating errors when this reaches zero */
  int nErr;         /* Number of messages written to zErrMsg so far */
  int rc;           /* SQLITE_OK, SQLITE_NOMEM, or SQLITE_INTERRUPT */
@@ -69529,7 +69785,6 @@ SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){

/************** End of btmutex.c *********************************************/
/************** Begin file btree.c *******************************************/
-

/*
** 2004 April 6
**
@@ -77024,9 +77279,10 @@ static int rebuildPage(
  int k;                          /* Current slot in pCArray->apEnd[] */
  u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */

+
  assert( nCell>0 );
  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; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i; k++){}
@@ -77330,6 +77586,7 @@ static int editPage(
  return SQLITE_OK;
 editpage_fail:
  /* Unable to edit this page. Rebuild it from scratch instead. */
+
  if( nNew<1 ) return SQLITE_CORRUPT_BKPT;
  populateCellCache(pCArray, iNew, nNew);
  return rebuildPage(pCArray, iNew, nNew, pPg);
}
@@ -79989,7 +80246,8 @@ static void checkAppendMsg(
** corresponds to page iPg is already set.
*/
static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
-
  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
+
  assert( pCheck->aPgRef!=0 );
+
  assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
}

@@ -79997,7 +80255,8 @@ static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
*/
static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
-
  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
+
  assert( pCheck->aPgRef!=0 );
+
  assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
}

@@ -80011,7 +80270,7 @@ static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
** Also check that the page number is in bounds.
*/
static int checkRef(IntegrityCk *pCheck, Pgno iPage){
-
  if( iPage>pCheck->nPage || iPage==0 ){
+
  if( iPage>pCheck->nCkPage || iPage==0 ){
    checkAppendMsg(pCheck, "invalid page number %u", iPage);
    return 1;
  }
@@ -80238,6 +80497,7 @@ static int checkTreePage(
  if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
    checkAppendMsg(pCheck,
       "unable to get the page. error code=%d", rc);
+
    if( rc==SQLITE_IOERR_NOMEM ) pCheck->rc = SQLITE_NOMEM;
    goto end_of_check;
  }

@@ -80508,15 +80768,15 @@ SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck(
  sCheck.db = db;
  sCheck.pBt = pBt;
  sCheck.pPager = pBt->pPager;
-
  sCheck.nPage = btreePagecount(sCheck.pBt);
+
  sCheck.nCkPage = btreePagecount(sCheck.pBt);
  sCheck.mxErr = mxErr;
  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
-
  if( sCheck.nPage==0 ){
+
  if( sCheck.nCkPage==0 ){
    goto integrity_ck_cleanup;
  }

-
  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
+
  sCheck.aPgRef = sqlite3MallocZero((sCheck.nCkPage / 8)+ 1);
  if( !sCheck.aPgRef ){
    checkOom(&sCheck);
    goto integrity_ck_cleanup;
@@ -80528,7 +80788,7 @@ SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck(
  }

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

  /* Check the integrity of the freelist
  */
@@ -80579,7 +80839,7 @@ SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck(
  /* Make sure every page in the file is referenced
  */
  if( !bPartial ){
-
    for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
+
    for(i=1; i<=sCheck.nCkPage && sCheck.mxErr; i++){
#ifdef SQLITE_OMIT_AUTOVACUUM
      if( getPageReferenced(&sCheck, i)==0 ){
        checkAppendMsg(&sCheck, "Page %u: never used", i);
@@ -82020,7 +82280,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemZeroTerminateIfAble(Mem *pMem){
      pMem->flags |= MEM_Term;
      return;
    }
-
    if( pMem->xDel==(void(*)(void*))sqlite3RCStrUnref ){
+
    if( pMem->xDel==sqlite3RCStrUnref ){
      /* Blindly assume that all RCStr objects are zero-terminated */
      pMem->flags |= MEM_Term;
      return;
@@ -83199,7 +83459,7 @@ static int valueFromFunction(
#endif
  assert( pFunc );
  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
-
   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
+
   || (pFunc->funcFlags & (SQLITE_FUNC_NEEDCOLL|SQLITE_FUNC_RUNONLY))!=0
  ){
    return SQLITE_OK;
  }
@@ -83400,6 +83660,7 @@ static int valueFromExpr(
    if( pVal ){
      pVal->flags = MEM_Int;
      pVal->u.i = pExpr->u.zToken[4]==0;
+
      sqlite3ValueApplyAffinity(pVal, affinity, enc);
    }
  }

@@ -83922,10 +84183,11 @@ static int growOpArray(Vdbe *v, int nOp){
**   sqlite3CantopenError(lineno)
*/
static void test_addop_breakpoint(int pc, Op *pOp){
-
  static int n = 0;
+
  static u64 n = 0;
  (void)pc;
  (void)pOp;
  n++;
+
  if( n==LARGEST_UINT64 ) abort(); /* so that n is used, preventing a warning */
}
#endif

@@ -84713,6 +84975,10 @@ SQLITE_PRIVATE void sqlite3VdbeNoJumpsOutsideSubrtn(
      int iDest = pOp->p2;   /* Jump destination */
      if( iDest==0 ) continue;
      if( pOp->opcode==OP_Gosub ) continue;
+
      if( pOp->p3==20230325 && pOp->opcode==OP_NotNull ){
+
        /* This is a deliberately taken illegal branch.  tag-20230325-2 */
+
        continue;
+
      }
      if( iDest<0 ){
        int j = ADDR(iDest);
        assert( j>=0 );
@@ -88172,20 +88438,33 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem
  return n1 - n2;
}

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

/*
** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
** number.  Return negative, zero, or positive if the first (i64) is less than,
** equal to, or greater than the second (double).
*/
SQLITE_PRIVATE int sqlite3IntFloatCompare(i64 i, double r){
-
  if( sizeof(LONGDOUBLE_TYPE)>8 ){
+
  if( sqlite3IsNaN(r) ){
+
    /* SQLite considers NaN to be a NULL. And all integer values are greater
+
    ** than NULL */
+
    return 1;
+
  }
+
  if( sqlite3Config.bUseLongDouble ){
    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
    testcase( x<r );
    testcase( x>r );
    testcase( x==r );
-
    if( x<r ) return -1;
-
    if( x>r ) return +1;  /*NO_TEST*/ /* work around bugs in gcov */
-
    return 0;             /*NO_TEST*/ /* work around bugs in gcov */
+
    return (x<r) ? -1 : (x>r);
  }else{
    i64 y;
    double s;
@@ -88195,9 +88474,10 @@ SQLITE_PRIVATE int sqlite3IntFloatCompare(i64 i, double r){
    if( i<y ) return -1;
    if( i>y ) return +1;
    s = (double)i;
-
    if( s<r ) return -1;
-
    if( s>r ) return +1;
-
    return 0;
+
    testcase( doubleLt(s,r) );
+
    testcase( doubleLt(r,s) );
+
    testcase( doubleEq(r,s) );
+
    return (s<r) ? -1 : (s>r);
  }
}

@@ -89565,7 +89845,7 @@ SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
** 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.
+
** on value P if P is not going to be used and need to be destroyed.
*/
static void setResultStrOrError(
  sqlite3_context *pCtx,  /* Function context */
@@ -89595,7 +89875,7 @@ static void setResultStrOrError(
static int invokeValueDestructor(
  const void *p,             /* Value to destroy */
  void (*xDel)(void*),       /* The destructor */
-
  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
+
  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if not NULL */
){
  assert( xDel!=SQLITE_DYNAMIC );
  if( xDel==0 ){
@@ -89605,7 +89885,14 @@ static int invokeValueDestructor(
  }else{
    xDel((void*)p);
  }
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx!=0 ){
+
    sqlite3_result_error_toobig(pCtx);
+
  }
+
#else
+
  assert( pCtx!=0 );
  sqlite3_result_error_toobig(pCtx);
+
#endif
  return SQLITE_TOOBIG;
}
SQLITE_API void sqlite3_result_blob(
@@ -89614,6 +89901,12 @@ SQLITE_API void sqlite3_result_blob(
  int n,
  void (*xDel)(void *)
){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 || n<0 ){
+
    invokeValueDestructor(z, xDel, pCtx);
+
    return;
+
  }
+
#endif
  assert( n>=0 );
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  setResultStrOrError(pCtx, z, n, 0, xDel);
@@ -89624,8 +89917,14 @@ SQLITE_API void sqlite3_result_blob64(
  sqlite3_uint64 n,
  void (*xDel)(void *)
){
-
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  assert( xDel!=SQLITE_DYNAMIC );
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ){
+
    invokeValueDestructor(z, xDel, 0);
+
    return;
+
  }
+
#endif
+
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  if( n>0x7fffffff ){
    (void)invokeValueDestructor(z, xDel, pCtx);
  }else{
@@ -89633,30 +89932,48 @@ SQLITE_API void sqlite3_result_blob64(
  }
}
SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
}
SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  pCtx->isError = SQLITE_ERROR;
  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
}
#ifndef SQLITE_OMIT_UTF16
SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  pCtx->isError = SQLITE_ERROR;
  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
}
#endif
SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
}
SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
}
SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  sqlite3VdbeMemSetNull(pCtx->pOut);
}
@@ -89666,14 +89983,37 @@ SQLITE_API void sqlite3_result_pointer(
  const char *zPType,
  void (*xDestructor)(void*)
){
-
  Mem *pOut = pCtx->pOut;
+
  Mem *pOut;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ){
+
    invokeValueDestructor(pPtr, xDestructor, 0);
+
    return;
+
  }
+
#endif
+
  pOut = pCtx->pOut;
  assert( sqlite3_mutex_held(pOut->db->mutex) );
  sqlite3VdbeMemRelease(pOut);
  pOut->flags = MEM_Null;
  sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
}
SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
-
  Mem *pOut = pCtx->pOut;
+
  Mem *pOut;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
+
#if defined(SQLITE_STRICT_SUBTYPE) && SQLITE_STRICT_SUBTYPE+0!=0
+
  if( pCtx->pFunc!=0
+
   && (pCtx->pFunc->funcFlags & SQLITE_RESULT_SUBTYPE)==0
+
  ){
+
    char zErr[200];
+
    sqlite3_snprintf(sizeof(zErr), zErr,
+
                     "misuse of sqlite3_result_subtype() by %s()",
+
                     pCtx->pFunc->zName);
+
    sqlite3_result_error(pCtx, zErr, -1);
+
    return;
+
  }
+
#endif /* SQLITE_STRICT_SUBTYPE */
+
  pOut = pCtx->pOut;
  assert( sqlite3_mutex_held(pOut->db->mutex) );
  pOut->eSubtype = eSubtype & 0xff;
  pOut->flags |= MEM_Subtype;
@@ -89684,6 +90024,12 @@ SQLITE_API void sqlite3_result_text(
  int n,
  void (*xDel)(void *)
){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ){
+
    invokeValueDestructor(z, xDel, 0);
+
    return;
+
  }
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
}
@@ -89694,6 +90040,12 @@ SQLITE_API void sqlite3_result_text64(
  void (*xDel)(void *),
  unsigned char enc
){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ){
+
    invokeValueDestructor(z, xDel, 0);
+
    return;
+
  }
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  assert( xDel!=SQLITE_DYNAMIC );
  if( enc!=SQLITE_UTF8 ){
@@ -89737,7 +90089,16 @@ SQLITE_API void sqlite3_result_text16le(
}
#endif /* SQLITE_OMIT_UTF16 */
SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
-
  Mem *pOut = pCtx->pOut;
+
  Mem *pOut;
+

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
  if( pValue==0 ){
+
    sqlite3_result_null(pCtx);
+
    return;
+
  }
+
#endif
+
  pOut = pCtx->pOut;
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  sqlite3VdbeMemCopy(pOut, pValue);
  sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
@@ -89749,7 +90110,12 @@ SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  sqlite3_result_zeroblob64(pCtx, n>0 ? n : 0);
}
SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
-
  Mem *pOut = pCtx->pOut;
+
  Mem *pOut;
+

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return SQLITE_MISUSE_BKPT;
+
#endif
+
  pOut = pCtx->pOut;
  assert( sqlite3_mutex_held(pOut->db->mutex) );
  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite3_result_error_toobig(pCtx);
@@ -89763,6 +90129,9 @@ SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
#endif
}
SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  pCtx->isError = errCode ? errCode : -1;
#ifdef SQLITE_DEBUG
  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
@@ -89775,6 +90144,9 @@ SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){

/* Force an SQLITE_TOOBIG error. */
SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  pCtx->isError = SQLITE_TOOBIG;
  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
@@ -89783,6 +90155,9 @@ SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){

/* An SQLITE_NOMEM error. */
SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  sqlite3VdbeMemSetNull(pCtx->pOut);
  pCtx->isError = SQLITE_NOMEM_BKPT;
@@ -90035,7 +90410,11 @@ SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
** pointer to it.
*/
SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( p==0 ) return 0;
+
#else
  assert( p && p->pFunc );
+
#endif
  return p->pFunc->pUserData;
}

@@ -90050,7 +90429,11 @@ SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
** application defined function.
*/
SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( p==0 ) return 0;
+
#else
  assert( p && p->pOut );
+
#endif
  return p->pOut->db;
}

@@ -90069,7 +90452,11 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
** value, as a signal to the xUpdate routine that the column is unchanged.
*/
SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( p==0 ) return 0;
+
#else
  assert( p );
+
#endif
  return sqlite3_value_nochange(p->pOut);
}

@@ -90097,7 +90484,7 @@ static int valueFromValueList(
  ValueList *pRhs;

  *ppOut = 0;
-
  if( pVal==0 ) return SQLITE_MISUSE;
+
  if( pVal==0 ) return SQLITE_MISUSE_BKPT;
  if( (pVal->flags & MEM_Dyn)==0 || pVal->xDel!=sqlite3VdbeValueListFree ){
    return SQLITE_ERROR;
  }else{
@@ -90228,6 +90615,9 @@ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  AuxData *pAuxData;

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return 0;
+
#endif
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
#if SQLITE_ENABLE_STAT4
  if( pCtx->pVdbe==0 ) return 0;
@@ -90260,8 +90650,12 @@ SQLITE_API void sqlite3_set_auxdata(
  void (*xDelete)(void*)
){
  AuxData *pAuxData;
-
  Vdbe *pVdbe = pCtx->pVdbe;
+
  Vdbe *pVdbe;

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pCtx==0 ) return;
+
#endif
+
  pVdbe= pCtx->pVdbe;
  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
#ifdef SQLITE_ENABLE_STAT4
  if( pVdbe==0 ) goto failed;
@@ -90698,7 +91092,7 @@ static int vdbeUnbind(Vdbe *p, unsigned int i){
  }
  sqlite3_mutex_enter(p->db->mutex);
  if( p->eVdbeState!=VDBE_READY_STATE ){
-
    sqlite3Error(p->db, SQLITE_MISUSE);
+
    sqlite3Error(p->db, SQLITE_MISUSE_BKPT);
    sqlite3_mutex_leave(p->db->mutex);
    sqlite3_log(SQLITE_MISUSE,
        "bind on a busy prepared statement: [%s]", p->zSql);
@@ -90927,6 +91321,9 @@ SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  int rc;
  Vdbe *p = (Vdbe *)pStmt;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( p==0 ) return SQLITE_MISUSE_BKPT;
+
#endif
  sqlite3_mutex_enter(p->db->mutex);
  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
    rc = SQLITE_TOOBIG;
@@ -91053,6 +91450,9 @@ SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
SQLITE_API int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode){
  Vdbe *v = (Vdbe*)pStmt;
  int rc;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( pStmt==0 ) return SQLITE_MISUSE_BKPT;
+
#endif
  sqlite3_mutex_enter(v->db->mutex);
  if( ((int)v->explain)==eMode ){
    rc = SQLITE_OK;
@@ -91219,10 +91619,16 @@ static UnpackedRecord *vdbeUnpackRecord(
** a field of the row currently being updated or deleted.
*/
SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
-
  PreUpdate *p = db->pPreUpdate;
+
  PreUpdate *p;
  Mem *pMem;
  int rc = SQLITE_OK;

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( db==0 || ppValue==0 ){
+
    return SQLITE_MISUSE_BKPT;
+
  }
+
#endif
+
  p = db->pPreUpdate;
  /* Test that this call is being made from within an SQLITE_DELETE or
  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  if( !p || p->op==SQLITE_INSERT ){
@@ -91283,7 +91689,12 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa
** the number of columns in the row being updated, deleted or inserted.
*/
SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
-
  PreUpdate *p = db->pPreUpdate;
+
  PreUpdate *p;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  p = db!=0 ? db->pPreUpdate : 0;
+
#else
+
  p = db->pPreUpdate;
+
#endif
  return (p ? p->keyinfo.nKeyField : 0);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
@@ -91301,7 +91712,12 @@ SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
** or SET DEFAULT action is considered a trigger.
*/
SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
-
  PreUpdate *p = db->pPreUpdate;
+
  PreUpdate *p;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  p = db!=0 ? db->pPreUpdate : 0;
+
#else
+
  p = db->pPreUpdate;
+
#endif
  return (p ? p->v->nFrame : 0);
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
@@ -91312,7 +91728,12 @@ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
** only.
*/
SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *db){
-
  PreUpdate *p = db->pPreUpdate;
+
  PreUpdate *p;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  p = db!=0 ? db->pPreUpdate : 0;
+
#else
+
  p = db->pPreUpdate;
+
#endif
  return (p ? p->iBlobWrite : -1);
}
#endif
@@ -91323,10 +91744,16 @@ SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *db){
** a field of the row currently being updated or inserted.
*/
SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
-
  PreUpdate *p = db->pPreUpdate;
+
  PreUpdate *p;
  int rc = SQLITE_OK;
  Mem *pMem;

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( db==0 || ppValue==0 ){
+
    return SQLITE_MISUSE_BKPT;
+
  }
+
#endif
+
  p = db->pPreUpdate;
  if( !p || p->op==SQLITE_DELETE ){
    rc = SQLITE_MISUSE_BKPT;
    goto preupdate_new_out;
@@ -91405,11 +91832,20 @@ SQLITE_API int sqlite3_stmt_scanstatus_v2(
  void *pOut                      /* OUT: Write the answer here */
){
  Vdbe *p = (Vdbe*)pStmt;
-
  VdbeOp *aOp = p->aOp;
-
  int nOp = p->nOp;
+
  VdbeOp *aOp;
+
  int nOp;
  ScanStatus *pScan = 0;
  int idx;

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( p==0 || pOut==0
+
      || iScanStatusOp<SQLITE_SCANSTAT_NLOOP
+
      || iScanStatusOp>SQLITE_SCANSTAT_NCYCLE ){
+
    return 1;
+
  }
+
#endif
+
  aOp = p->aOp;
+
  nOp = p->nOp;
  if( p->pFrame ){
    VdbeFrame *pFrame;
    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
@@ -91556,7 +91992,7 @@ SQLITE_API int sqlite3_stmt_scanstatus(
SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  Vdbe *p = (Vdbe*)pStmt;
  int ii;
-
  for(ii=0; ii<p->nOp; ii++){
+
  for(ii=0; p!=0 && ii<p->nOp; ii++){
    Op *pOp = &p->aOp[ii];
    pOp->nExec = 0;
    pOp->nCycle = 0;
@@ -91895,11 +92331,12 @@ SQLITE_API int sqlite3_found_count = 0;
**   sqlite3CantopenError(lineno)
*/
static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
-
  static int n = 0;
+
  static u64 n = 0;
  (void)pc;
  (void)pOp;
  (void)v;
  n++;
+
  if( n==LARGEST_UINT64 ) abort(); /* So that n is used, preventing a warning */
}
#endif

@@ -92525,11 +92962,11 @@ static SQLITE_NOINLINE int vdbeColumnFromOverflow(
    sqlite3RCStrRef(pBuf);
    if( t&1 ){
      rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, encoding,
-
                                (void(*)(void*))sqlite3RCStrUnref);
+
                                sqlite3RCStrUnref);
      pDest->flags |= MEM_Term;
    }else{
      rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, 0,
-
                                (void(*)(void*))sqlite3RCStrUnref);
+
                                sqlite3RCStrUnref);
    }
  }else{
    rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, iOffset, len, pDest);
@@ -95404,7 +95841,6 @@ case OP_MakeRecord: {
        /* NULL value.  No change in zPayload */
      }else{
        u64 v;
-
        u32 i;
        if( serial_type==7 ){
          assert( sizeof(v)==sizeof(pRec->u.r) );
          memcpy(&v, &pRec->u.r, sizeof(v));
@@ -95412,12 +95848,17 @@ case OP_MakeRecord: {
        }else{
          v = pRec->u.i;
        }
-
        len = i = sqlite3SmallTypeSizes[serial_type];
-
        assert( i>0 );
-
        while( 1 /*exit-by-break*/ ){
-
          zPayload[--i] = (u8)(v&0xFF);
-
          if( i==0 ) break;
-
          v >>= 8;
+
        len = sqlite3SmallTypeSizes[serial_type];
+
        assert( len>=1 && len<=8 && len!=5 && len!=7 );
+
        switch( len ){
+
          default: zPayload[7] = (u8)(v&0xff); v >>= 8;
+
                   zPayload[6] = (u8)(v&0xff); v >>= 8;
+
          case 6:  zPayload[5] = (u8)(v&0xff); v >>= 8;
+
                   zPayload[4] = (u8)(v&0xff); v >>= 8;
+
          case 4:  zPayload[3] = (u8)(v&0xff); v >>= 8;
+
          case 3:  zPayload[2] = (u8)(v&0xff); v >>= 8;
+
          case 2:  zPayload[1] = (u8)(v&0xff); v >>= 8;
+
          case 1:  zPayload[0] = (u8)(v&0xff);
        }
        zPayload += len;
      }
@@ -97534,8 +97975,13 @@ case OP_RowCell: {
** the "primary" delete.  The others are all on OPFLAG_FORDELETE
** cursors or else are marked with the AUXDELETE flag.
**
-
** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
-
** change count is incremented (otherwise not).
+
** If the OPFLAG_NCHANGE (0x01) flag of P2 (NB: P2 not P5) is set, then
+
** the row change count is incremented (otherwise not).
+
**
+
** If the OPFLAG_ISNOOP (0x40) flag of P2 (not P5!) is set, then the
+
** pre-update-hook for deletes is run, but the btree is otherwise unchanged.
+
** This happens when the OP_Delete is to be shortly followed by an OP_Insert
+
** with the same key, causing the btree entry to be overwritten.
**
** P1 must not be pseudo-table.  It has to be a real table with
** multiple rows.
@@ -98660,13 +99106,41 @@ case OP_CreateBtree: { /* out2 */
/* Opcode: SqlExec * * * P4 *
**
** Run the SQL statement or statements specified in the P4 string.
+
** Disable Auth and Trace callbacks while those statements are running if
+
** P1 is true.
*/
case OP_SqlExec: {
+
  char *zErr;
+
#ifndef SQLITE_OMIT_AUTHORIZATION
+
  sqlite3_xauth xAuth;
+
#endif
+
  u8 mTrace;
+

  sqlite3VdbeIncrWriteCounter(p, 0);
  db->nSqlExec++;
-
  rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
+
  zErr = 0;
+
#ifndef SQLITE_OMIT_AUTHORIZATION
+
  xAuth = db->xAuth;
+
#endif
+
  mTrace = db->mTrace;
+
  if( pOp->p1 ){
+
#ifndef SQLITE_OMIT_AUTHORIZATION
+
    db->xAuth = 0;
+
#endif
+
    db->mTrace = 0;
+
  }
+
  rc = sqlite3_exec(db, pOp->p4.z, 0, 0, &zErr);
  db->nSqlExec--;
-
  if( rc ) goto abort_due_to_error;
+
#ifndef SQLITE_OMIT_AUTHORIZATION
+
  db->xAuth = xAuth;
+
#endif
+
  db->mTrace = mTrace;
+
  if( zErr || rc ){
+
    sqlite3VdbeError(p, "%s", zErr);
+
    sqlite3_free(zErr);
+
    if( rc==SQLITE_NOMEM ) goto no_mem;
+
    goto abort_due_to_error;
+
  }
  break;
}

@@ -99888,6 +100362,53 @@ case OP_VOpen: { /* ncycle */
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
+
/* Opcode: VCheck P1 P2 P3 P4 *
+
**
+
** P4 is a pointer to a Table object that is a virtual table in schema P1
+
** that supports the xIntegrity() method.  This opcode runs the xIntegrity()
+
** method for that virtual table, using P3 as the integer argument.  If
+
** an error is reported back, the table name is prepended to the error
+
** message and that message is stored in P2.  If no errors are seen,
+
** register P2 is set to NULL.
+
*/
+
case OP_VCheck: {             /* out2 */
+
  Table *pTab;
+
  sqlite3_vtab *pVtab;
+
  const sqlite3_module *pModule;
+
  char *zErr = 0;
+

+
  pOut = &aMem[pOp->p2];
+
  sqlite3VdbeMemSetNull(pOut);  /* Innocent until proven guilty */
+
  assert( pOp->p4type==P4_TABLE );
+
  pTab = pOp->p4.pTab;
+
  assert( pTab!=0 );
+
  assert( IsVirtual(pTab) );
+
  if( pTab->u.vtab.p==0 ) break;
+
  pVtab = pTab->u.vtab.p->pVtab;
+
  assert( pVtab!=0 );
+
  pModule = pVtab->pModule;
+
  assert( pModule!=0 );
+
  assert( pModule->iVersion>=4 );
+
  assert( pModule->xIntegrity!=0 );
+
  pTab->nTabRef++;
+
  sqlite3VtabLock(pTab->u.vtab.p);
+
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
+
  rc = pModule->xIntegrity(pVtab, db->aDb[pOp->p1].zDbSName, pTab->zName,
+
                           pOp->p3, &zErr);
+
  sqlite3VtabUnlock(pTab->u.vtab.p);
+
  sqlite3DeleteTable(db, pTab);
+
  if( rc ){
+
    sqlite3_free(zErr);
+
    goto abort_due_to_error;
+
  }
+
  if( zErr ){
+
    sqlite3VdbeMemSetStr(pOut, zErr, -1, SQLITE_UTF8, sqlite3_free);
+
  }
+
  break;
+
}
+
#endif /* SQLITE_OMIT_VIRTUALTABLE */
+

+
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VInitIn P1 P2 P3 * *
** Synopsis: r[P2]=ValueList(P1,P3)
**
@@ -100833,8 +101354,7 @@ static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  /* Set the value of register r[1] in the SQL statement to integer iRow.
  ** This is done directly as a performance optimization
  */
-
  v->aMem[1].flags = MEM_Int;
-
  v->aMem[1].u.i = iRow;
+
  sqlite3VdbeMemSetInt64(&v->aMem[1], iRow);

  /* If the statement has been run before (and is paused at the OP_ResultRow)
  ** then back it up to the point where it does the OP_NotExists.  This could
@@ -100917,7 +101437,7 @@ SQLITE_API int sqlite3_blob_open(
#endif
  *ppBlob = 0;
#ifdef SQLITE_ENABLE_API_ARMOR
-
  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
+
  if( !sqlite3SafetyCheckOk(db) || zTable==0 || zColumn==0 ){
    return SQLITE_MISUSE_BKPT;
  }
#endif
@@ -101479,7 +101999,7 @@ struct SorterFile {
struct SorterList {
  SorterRecord *pList;            /* Linked list of records */
  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
-
  int szPMA;                      /* Size of pList as PMA in bytes */
+
  i64 szPMA;                      /* Size of pList as PMA in bytes */
};

/*
@@ -101588,10 +102108,10 @@ typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
struct SortSubtask {
  SQLiteThread *pThread;          /* Background thread, if any */
  int bDone;                      /* Set if thread is finished but not joined */
+
  int nPMA;                       /* Number of PMAs currently in file */
  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
  SorterList list;                /* List for thread to write to a PMA */
-
  int nPMA;                       /* Number of PMAs currently in file */
  SorterCompare xCompare;         /* Compare function to use */
  SorterFile file;                /* Temp file for level-0 PMAs */
  SorterFile file2;               /* Space for other PMAs */
@@ -103065,8 +103585,8 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  int rc = SQLITE_OK;             /* Return Code */
  SorterRecord *pNew;             /* New list element */
  int bFlush;                     /* True to flush contents of memory to PMA */
-
  int nReq;                       /* Bytes of memory required */
-
  int nPMA;                       /* Bytes of PMA space required */
+
  i64 nReq;                       /* Bytes of memory required */
+
  i64 nPMA;                       /* Bytes of PMA space required */
  int t;                          /* serial type of first record field */

  assert( pCsr->eCurType==CURTYPE_SORTER );
@@ -104490,7 +105010,8 @@ static sqlite3_module bytecodevtabModule = {
  /* xSavepoint  */ 0,
  /* xRelease    */ 0,
  /* xRollbackTo */ 0,
-
  /* xShadowName */ 0
+
  /* xShadowName */ 0,
+
  /* xIntegrity  */ 0
};


@@ -105319,21 +105840,36 @@ static void resolveAlias(
}

/*
-
** Subqueries stores the original database, table and column names for their
-
** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
-
** Check to see if the zSpan given to this routine matches the zDb, zTab,
-
** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
-
** match anything.
+
** Subqueries store the original database, table and column names for their
+
** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN",
+
** and mark the expression-list item by setting ExprList.a[].fg.eEName
+
** to ENAME_TAB.
+
**
+
** Check to see if the zSpan/eEName of the expression-list item passed to this
+
** routine matches the zDb, zTab, and zCol.  If any of zDb, zTab, and zCol are
+
** NULL then those fields will match anything. Return true if there is a match,
+
** or false otherwise.
+
**
+
** SF_NestedFrom subqueries also store an entry for the implicit rowid (or
+
** _rowid_, or oid) column by setting ExprList.a[].fg.eEName to ENAME_ROWID,
+
** and setting zSpan to "DATABASE.TABLE.<rowid-alias>". This type of pItem
+
** argument matches if zCol is a rowid alias. If it is not NULL, (*pbRowid)
+
** is set to 1 if there is this kind of match.
*/
SQLITE_PRIVATE int sqlite3MatchEName(
  const struct ExprList_item *pItem,
  const char *zCol,
  const char *zTab,
-
  const char *zDb
+
  const char *zDb,
+
  int *pbRowid
){
  int n;
  const char *zSpan;
-
  if( pItem->fg.eEName!=ENAME_TAB ) return 0;
+
  int eEName = pItem->fg.eEName;
+
  if( eEName!=ENAME_TAB && (eEName!=ENAME_ROWID || NEVER(pbRowid==0)) ){
+
    return 0;
+
  }
+
  assert( pbRowid==0 || *pbRowid==0 );
  zSpan = pItem->zEName;
  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
@@ -105345,9 +105881,11 @@ SQLITE_PRIVATE int sqlite3MatchEName(
    return 0;
  }
  zSpan += n+1;
-
  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
-
    return 0;
+
  if( zCol ){
+
    if( eEName==ENAME_TAB && sqlite3StrICmp(zSpan, zCol)!=0 ) return 0;
+
    if( eEName==ENAME_ROWID && sqlite3IsRowid(zCol)==0 ) return 0;
  }
+
  if( eEName==ENAME_ROWID ) *pbRowid = 1;
  return 1;
}

@@ -105480,7 +106018,7 @@ static int lookupName(
){
  int i, j;                         /* Loop counters */
  int cnt = 0;                      /* Number of matching column names */
-
  int cntTab = 0;                   /* Number of matching table names */
+
  int cntTab = 0;                   /* Number of potential "rowid" matches */
  int nSubquery = 0;                /* How many levels of subquery */
  sqlite3 *db = pParse->db;         /* The database connection */
  SrcItem *pItem;                   /* Use for looping over pSrcList items */
@@ -105557,39 +106095,49 @@ static int lookupName(
          assert( pEList!=0 );
          assert( pEList->nExpr==pTab->nCol );
          for(j=0; j<pEList->nExpr; j++){
-
            if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
+
            int bRowid = 0;       /* True if possible rowid match */
+
            if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb, &bRowid) ){
              continue;
            }
-
            if( cnt>0 ){
-
              if( pItem->fg.isUsing==0
-
               || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
-
              ){
-
                /* Two or more tables have the same column name which is
-
                ** not joined by USING.  This is an error.  Signal as much
-
                ** by clearing pFJMatch and letting cnt go above 1. */
-
                sqlite3ExprListDelete(db, pFJMatch);
-
                pFJMatch = 0;
-
              }else
-
              if( (pItem->fg.jointype & JT_RIGHT)==0 ){
-
                /* An INNER or LEFT JOIN.  Use the left-most table */
-
                continue;
-
              }else
-
              if( (pItem->fg.jointype & JT_LEFT)==0 ){
-
                /* A RIGHT JOIN.  Use the right-most table */
-
                cnt = 0;
-
                sqlite3ExprListDelete(db, pFJMatch);
-
                pFJMatch = 0;
-
              }else{
-
                /* For a FULL JOIN, we must construct a coalesce() func */
-
                extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
+
            if( bRowid==0 ){
+
              if( cnt>0 ){
+
                if( pItem->fg.isUsing==0
+
                 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
+
                ){
+
                  /* Two or more tables have the same column name which is
+
                  ** not joined by USING.  This is an error.  Signal as much
+
                  ** by clearing pFJMatch and letting cnt go above 1. */
+
                  sqlite3ExprListDelete(db, pFJMatch);
+
                  pFJMatch = 0;
+
                }else
+
                if( (pItem->fg.jointype & JT_RIGHT)==0 ){
+
                  /* An INNER or LEFT JOIN.  Use the left-most table */
+
                  continue;
+
                }else
+
                if( (pItem->fg.jointype & JT_LEFT)==0 ){
+
                  /* A RIGHT JOIN.  Use the right-most table */
+
                  cnt = 0;
+
                  sqlite3ExprListDelete(db, pFJMatch);
+
                  pFJMatch = 0;
+
                }else{
+
                  /* For a FULL JOIN, we must construct a coalesce() func */
+
                  extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
+
                }
              }
+
              cnt++;
+
              hit = 1;
+
            }else if( cnt>0 ){
+
              /* This is a potential rowid match, but there has already been
+
              ** a real match found. So this can be ignored.  */
+
              continue;
            }
-
            cnt++;
-
            cntTab = 2;
+
            cntTab++;
            pMatch = pItem;
            pExpr->iColumn = j;
            pEList->a[j].fg.bUsed = 1;
-
            hit = 1;
+

+
            /* rowid cannot be part of a USING clause - assert() this. */
+
            assert( bRowid==0 || pEList->a[j].fg.bUsingTerm==0 );
            if( pEList->a[j].fg.bUsingTerm ) break;
          }
          if( hit || zTab==0 ) continue;
@@ -105784,10 +106332,10 @@ static int lookupName(
     && pMatch
     && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
     && sqlite3IsRowid(zCol)
-
     && ALWAYS(VisibleRowid(pMatch->pTab))
+
     && ALWAYS(VisibleRowid(pMatch->pTab) || pMatch->fg.isNestedFrom)
    ){
      cnt = 1;
-
      pExpr->iColumn = -1;
+
      if( pMatch->fg.isNestedFrom==0 ) pExpr->iColumn = -1;
      pExpr->affExpr = SQLITE_AFF_INTEGER;
    }

@@ -106240,6 +106788,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
      Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
#endif
      assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
+
      assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER );
      zId = pExpr->u.zToken;
      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
      if( pDef==0 ){
@@ -106381,6 +106930,10 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
          pNC->nNcErr++;
        }
#endif
+
        else if( is_agg==0 && pExpr->pLeft ){
+
          sqlite3ExprOrderByAggregateError(pParse, pExpr);
+
          pNC->nNcErr++;
+
        }
        if( is_agg ){
          /* Window functions may not be arguments of aggregate functions.
          ** Or arguments of other window functions. But aggregate functions
@@ -106399,6 +106952,11 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
#endif
      sqlite3WalkExprList(pWalker, pList);
      if( is_agg ){
+
        if( pExpr->pLeft ){
+
          assert( pExpr->pLeft->op==TK_ORDER );
+
          assert( ExprUseXList(pExpr->pLeft) );
+
          sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
+
        }
#ifndef SQLITE_OMIT_WINDOWFUNC
        if( pWin ){
          Select *pSel = pNC->pWinSelect;
@@ -106962,10 +107520,8 @@ 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.
    */
@@ -107971,6 +108527,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
    */
    pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
    if( pRet ){
+
      ExprSetProperty(pRet, EP_FullSize);
      pRet->iTable = nField;
      pRet->iColumn = iField;
      pRet->pLeft = pVector;
@@ -108562,6 +109119,69 @@ SQLITE_PRIVATE Expr *sqlite3ExprFunction(
}

/*
+
** Report an error when attempting to use an ORDER BY clause within
+
** the arguments of a non-aggregate function.
+
*/
+
SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse *pParse, Expr *p){
+
  sqlite3ErrorMsg(pParse,
+
     "ORDER BY may not be used with non-aggregate %#T()", p
+
  );
+
}
+

+
/*
+
** Attach an ORDER BY clause to a function call.
+
**
+
**     functionname( arguments ORDER BY sortlist )
+
**     \_____________________/          \______/
+
**             pExpr                    pOrderBy
+
**
+
** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
+
** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
+
*/
+
SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(
+
  Parse *pParse,        /* Parsing context */
+
  Expr *pExpr,          /* The function call to which ORDER BY is to be added */
+
  ExprList *pOrderBy    /* The ORDER BY clause to add */
+
){
+
  Expr *pOB;
+
  sqlite3 *db = pParse->db;
+
  if( NEVER(pOrderBy==0) ){
+
    assert( db->mallocFailed );
+
    return;
+
  }
+
  if( pExpr==0 ){
+
    assert( db->mallocFailed );
+
    sqlite3ExprListDelete(db, pOrderBy);
+
    return;
+
  }
+
  assert( pExpr->op==TK_FUNCTION );
+
  assert( pExpr->pLeft==0 );
+
  assert( ExprUseXList(pExpr) );
+
  if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){
+
    /* Ignore ORDER BY on zero-argument aggregates */
+
    sqlite3ParserAddCleanup(pParse,
+
        (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
+
        pOrderBy);
+
    return;
+
  }
+
  if( IsWindowFunc(pExpr) ){
+
    sqlite3ExprOrderByAggregateError(pParse, pExpr);
+
    sqlite3ExprListDelete(db, pOrderBy);
+
    return;
+
  }
+

+
  pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0);
+
  if( pOB==0 ){
+
    sqlite3ExprListDelete(db, pOrderBy);
+
    return;
+
  }
+
  pOB->x.pList = pOrderBy;
+
  assert( ExprUseXList(pOB) );
+
  pExpr->pLeft = pOB;
+
  ExprSetProperty(pOB, EP_FullSize);
+
}
+

+
/*
** Check to see if a function is usable according to current access
** rules:
**
@@ -108814,11 +109434,7 @@ static int dupedExprStructSize(const Expr *p, int flags){
  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  assert( EXPR_FULLSIZE<=0xfff );
  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
-
  if( 0==flags || p->op==TK_SELECT_COLUMN
-
#ifndef SQLITE_OMIT_WINDOWFUNC
-
   || ExprHasProperty(p, EP_WinFunc)
-
#endif
-
  ){
+
  if( 0==flags || ExprHasProperty(p, EP_FullSize) ){
    nSize = EXPR_FULLSIZE;
  }else{
    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
@@ -108849,56 +109465,93 @@ static int dupedExprNodeSize(const Expr *p, int flags){

/*
** Return the number of bytes required to create a duplicate of the
-
** expression passed as the first argument. The second argument is a
-
** mask containing EXPRDUP_XXX flags.
+
** expression passed as the first argument.
**
** The value returned includes space to create a copy of the Expr struct
** itself and the buffer referred to by Expr.u.zToken, if any.
**
-
** If the EXPRDUP_REDUCE flag is set, then the return value includes
-
** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
-
** and Expr.pRight variables (but not for any structures pointed to or
-
** descended from the Expr.x.pList or Expr.x.pSelect variables).
+
** The return value includes space to duplicate all Expr nodes in the
+
** tree formed by Expr.pLeft and Expr.pRight, but not any other
+
** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
*/
-
static int dupedExprSize(const Expr *p, int flags){
-
  int nByte = 0;
-
  if( p ){
-
    nByte = dupedExprNodeSize(p, flags);
-
    if( flags&EXPRDUP_REDUCE ){
-
      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
-
    }
-
  }
+
static int dupedExprSize(const Expr *p){
+
  int nByte;
+
  assert( p!=0 );
+
  nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
+
  if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
+
  if( p->pRight ) nByte += dupedExprSize(p->pRight);
+
  assert( nByte==ROUND8(nByte) );
  return nByte;
}

/*
-
** This function is similar to sqlite3ExprDup(), except that if pzBuffer
-
** is not NULL then *pzBuffer is assumed to point to a buffer large enough
-
** to store the copy of expression p, the copies of p->u.zToken
-
** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
-
** if any. Before returning, *pzBuffer is set to the first byte past the
-
** portion of the buffer copied into by this function.
+
** An EdupBuf is a memory allocation used to stored multiple Expr objects
+
** together with their Expr.zToken content.  This is used to help implement
+
** compression while doing sqlite3ExprDup().  The top-level Expr does the
+
** allocation for itself and many of its decendents, then passes an instance
+
** of the structure down into exprDup() so that they decendents can have
+
** access to that memory.
+
*/
+
typedef struct EdupBuf EdupBuf;
+
struct EdupBuf {
+
  u8 *zAlloc;          /* Memory space available for storage */
+
#ifdef SQLITE_DEBUG
+
  u8 *zEnd;            /* First byte past the end of memory */
+
#endif
+
};
+

+
/*
+
** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
+
** is not NULL then it points to memory that can be used to store a copy
+
** of the input Expr p together with its p->u.zToken (if any).  pEdupBuf
+
** is updated with the new buffer tail prior to returning.
*/
-
static Expr *exprDup(sqlite3 *db, const Expr *p, int dupFlags, u8 **pzBuffer){
+
static Expr *exprDup(
+
  sqlite3 *db,          /* Database connection (for memory allocation) */
+
  const Expr *p,        /* Expr tree to be duplicated */
+
  int dupFlags,         /* EXPRDUP_REDUCE for compression.  0 if not */
+
  EdupBuf *pEdupBuf     /* Preallocated storage space, or NULL */
+
){
  Expr *pNew;           /* Value to return */
-
  u8 *zAlloc;           /* Memory space from which to build Expr object */
+
  EdupBuf sEdupBuf;     /* Memory space from which to build Expr object */
  u32 staticFlag;       /* EP_Static if space not obtained from malloc */
+
  int nToken = -1;       /* Space needed for p->u.zToken.  -1 means unknown */

  assert( db!=0 );
  assert( p );
  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
-
  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
+
  assert( pEdupBuf==0 || dupFlags==EXPRDUP_REDUCE );

  /* Figure out where to write the new Expr structure. */
-
  if( pzBuffer ){
-
    zAlloc = *pzBuffer;
+
  if( pEdupBuf ){
+
    sEdupBuf.zAlloc = pEdupBuf->zAlloc;
+
#ifdef SQLITE_DEBUG
+
    sEdupBuf.zEnd = pEdupBuf->zEnd;
+
#endif
    staticFlag = EP_Static;
-
    assert( zAlloc!=0 );
+
    assert( sEdupBuf.zAlloc!=0 );
+
    assert( dupFlags==EXPRDUP_REDUCE );
  }else{
-
    zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
+
    int nAlloc;
+
    if( dupFlags ){
+
      nAlloc = dupedExprSize(p);
+
    }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
+
      nToken = sqlite3Strlen30NN(p->u.zToken)+1;
+
      nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
+
    }else{
+
      nToken = 0;
+
      nAlloc = ROUND8(EXPR_FULLSIZE);
+
    }
+
    assert( nAlloc==ROUND8(nAlloc) );
+
    sEdupBuf.zAlloc = sqlite3DbMallocRawNN(db, nAlloc);
+
#ifdef SQLITE_DEBUG
+
    sEdupBuf.zEnd = sEdupBuf.zAlloc ? sEdupBuf.zAlloc+nAlloc : 0;
+
#endif
+

    staticFlag = 0;
  }
-
  pNew = (Expr *)zAlloc;
+
  pNew = (Expr *)sEdupBuf.zAlloc;
+
  assert( EIGHT_BYTE_ALIGNMENT(pNew) );

  if( pNew ){
    /* Set nNewSize to the size allocated for the structure pointed to
@@ -108907,22 +109560,27 @@ static Expr *exprDup(sqlite3 *db, const Expr *p, int dupFlags, u8 **pzBuffer){
    ** by the copy of the p->u.zToken string (if any).
    */
    const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
-
    const int nNewSize = nStructSize & 0xfff;
-
    int nToken;
-
    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
-
      nToken = sqlite3Strlen30(p->u.zToken) + 1;
-
    }else{
-
      nToken = 0;
+
    int nNewSize = nStructSize & 0xfff;
+
    if( nToken<0 ){
+
      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
+
        nToken = sqlite3Strlen30(p->u.zToken) + 1;
+
      }else{
+
        nToken = 0;
+
      }
    }
    if( dupFlags ){
+
      assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken );
      assert( ExprHasProperty(p, EP_Reduced)==0 );
-
      memcpy(zAlloc, p, nNewSize);
+
      memcpy(sEdupBuf.zAlloc, p, nNewSize);
    }else{
      u32 nSize = (u32)exprStructSize(p);
-
      memcpy(zAlloc, p, nSize);
+
      assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >=
+
                                                   (int)EXPR_FULLSIZE+nToken );
+
      memcpy(sEdupBuf.zAlloc, p, nSize);
      if( nSize<EXPR_FULLSIZE ){
-
        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
+
        memset(&sEdupBuf.zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
      }
+
      nNewSize = EXPR_FULLSIZE;
    }

    /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
@@ -108935,44 +109593,50 @@ static Expr *exprDup(sqlite3 *db, const Expr *p, int dupFlags, u8 **pzBuffer){
    }

    /* Copy the p->u.zToken string, if any. */
-
    if( nToken ){
-
      char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
+
    assert( nToken>=0 );
+
    if( nToken>0 ){
+
      char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize];
      memcpy(zToken, p->u.zToken, nToken);
+
      nNewSize += nToken;
    }
+
    sEdupBuf.zAlloc += ROUND8(nNewSize);
+

+
    if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){

-
    if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
      /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
      if( ExprUseXSelect(p) ){
        pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
      }else{
-
        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
+
        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList,
+
                           p->op!=TK_ORDER ? dupFlags : 0);
      }
-
    }

-
    /* Fill in pNew->pLeft and pNew->pRight. */
-
    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
-
      zAlloc += dupedExprNodeSize(p, dupFlags);
-
      if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
-
        pNew->pLeft = p->pLeft ?
-
                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
-
        pNew->pRight = p->pRight ?
-
                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
-
      }
#ifndef SQLITE_OMIT_WINDOWFUNC
      if( ExprHasProperty(p, EP_WinFunc) ){
        pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
        assert( ExprHasProperty(pNew, EP_WinFunc) );
      }
#endif /* SQLITE_OMIT_WINDOWFUNC */
-
      if( pzBuffer ){
-
        *pzBuffer = zAlloc;
-
      }
-
    }else{
-
      if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
-
        if( pNew->op==TK_SELECT_COLUMN ){
+

+
      /* Fill in pNew->pLeft and pNew->pRight. */
+
      if( dupFlags ){
+
        if( p->op==TK_SELECT_COLUMN ){
+
          pNew->pLeft = p->pLeft;
+
          assert( p->pRight==0
+
               || p->pRight==p->pLeft
+
               || ExprHasProperty(p->pLeft, EP_Subquery) );
+
        }else{
+
          pNew->pLeft = p->pLeft ?
+
                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0;
+
        }
+
        pNew->pRight = p->pRight ?
+
                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0;
+
      }else{
+
        if( p->op==TK_SELECT_COLUMN ){
          pNew->pLeft = p->pLeft;
-
          assert( p->pRight==0  || p->pRight==p->pLeft
-
                                || ExprHasProperty(p->pLeft, EP_Subquery) );
+
          assert( p->pRight==0
+
               || p->pRight==p->pLeft
+
               || ExprHasProperty(p->pLeft, EP_Subquery) );
        }else{
          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
        }
@@ -108980,6 +109644,8 @@ static Expr *exprDup(sqlite3 *db, const Expr *p, int dupFlags, u8 **pzBuffer){
      }
    }
  }
+
  if( pEdupBuf ) memcpy(pEdupBuf, &sEdupBuf, sizeof(sEdupBuf));
+
  assert( sEdupBuf.zAlloc <= sEdupBuf.zEnd );
  return pNew;
}

@@ -109244,11 +109910,7 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags)
** initially NULL, then create a new expression list.
**
** The pList argument must be either NULL or a pointer to an ExprList
-
** obtained from a prior call to sqlite3ExprListAppend().  This routine
-
** may not be used with an ExprList obtained from sqlite3ExprListDup().
-
** Reason:  This routine assumes that the number of slots in pList->a[]
-
** is a power of two.  That is true for sqlite3ExprListAppend() returns
-
** but is not necessarily true from the return value of sqlite3ExprListDup().
+
** obtained from a prior call to sqlite3ExprListAppend().
**
** If a memory allocation error occurs, the entire list is freed and
** NULL is returned.  If non-NULL is returned, then it is guaranteed
@@ -110075,6 +110737,27 @@ SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
}

/*
+
** Return a pointer to a buffer containing a usable rowid alias for table
+
** pTab. An alias is usable if there is not an explicit user-defined column
+
** of the same name.
+
*/
+
SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab){
+
  const char *azOpt[] = {"_ROWID_", "ROWID", "OID"};
+
  int ii;
+
  assert( VisibleRowid(pTab) );
+
  for(ii=0; ii<ArraySize(azOpt); ii++){
+
    int iCol;
+
    for(iCol=0; iCol<pTab->nCol; iCol++){
+
      if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break;
+
    }
+
    if( iCol==pTab->nCol ){
+
      return azOpt[ii];
+
    }
+
  }
+
  return 0;
+
}
+

+
/*
** pX is the RHS of an IN operator.  If pX is a SELECT statement
** that can be simplified to a direct table access, then return
** a pointer to the SELECT statement.  If pX is not a SELECT statement,
@@ -111612,6 +112295,41 @@ static SQLITE_NOINLINE int sqlite3IndexedExprLookup(


/*
+
** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
+
** function checks the Parse.pIdxPartExpr list to see if this column
+
** can be replaced with a constant value. If so, it generates code to
+
** put the constant value in a register (ideally, but not necessarily,
+
** register iTarget) and returns the register number.
+
**
+
** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
+
** returned.
+
*/
+
static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){
+
  IndexedExpr *p;
+
  for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
+
    if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
+
      Vdbe *v = pParse->pVdbe;
+
      int addr = 0;
+
      int ret;
+

+
      if( p->bMaybeNullRow ){
+
        addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
+
      }
+
      ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
+
      sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
+
                        (const char*)&p->aff, 1);
+
      if( addr ){
+
        sqlite3VdbeJumpHere(v, addr);
+
        sqlite3VdbeChangeP3(v, addr, ret);
+
      }
+
      return ret;
+
    }
+
  }
+
  return 0;
+
}
+

+

+
/*
** Generate code into the current Vdbe to evaluate the given
** expression.  Attempt to store the results in register "target".
** Return the register where results are stored.
@@ -111647,6 +112365,7 @@ expr_code_doover:
    assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
    op = pExpr->op;
  }
+
  assert( op!=TK_ORDER );
  switch( op ){
    case TK_AGG_COLUMN: {
      AggInfo *pAggInfo = pExpr->pAggInfo;
@@ -111660,7 +112379,7 @@ expr_code_doover:
#ifdef SQLITE_VDBE_COVERAGE
        /* Verify that the OP_Null above is exercised by tests
        ** tag-20230325-2 */
-
        sqlite3VdbeAddOp2(v, OP_NotNull, target, 1);
+
        sqlite3VdbeAddOp3(v, OP_NotNull, target, 1, 20230325);
        VdbeCoverageNeverTaken(v);
#endif
        break;
@@ -111768,6 +112487,11 @@ expr_code_doover:
          iTab = pParse->iSelfTab - 1;
        }
      }
+
      else if( pParse->pIdxPartExpr
+
       && 0!=(r1 = exprPartidxExprLookup(pParse, pExpr, target))
+
      ){
+
        return r1;
+
      }
      assert( ExprUseYTab(pExpr) );
      assert( pExpr->y.pTab!=0 );
      iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
@@ -112428,7 +113152,7 @@ expr_code_doover:
** once. If no functions are involved, then factor the code out and put it at
** the end of the prepared statement in the initialization section.
**
-
** If regDest>=0 then the result is always stored in that register and the
+
** If regDest>0 then the result is always stored in that register and the
** result is not reusable.  If regDest<0 then this routine is free to
** store the value wherever it wants.  The register where the expression
** is stored is returned.  When regDest<0, two identical expressions might
@@ -112443,6 +113167,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(
){
  ExprList *p;
  assert( ConstFactorOk(pParse) );
+
  assert( regDest!=0 );
  p = pParse->pConstExpr;
  if( regDest<0 && p ){
    struct ExprList_item *pItem;
@@ -113254,8 +113979,8 @@ SQLITE_PRIVATE int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB
*/
SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
  return sqlite3ExprCompare(0,
-
             sqlite3ExprSkipCollateAndLikely(pA),
-
             sqlite3ExprSkipCollateAndLikely(pB),
+
             sqlite3ExprSkipCollate(pA),
+
             sqlite3ExprSkipCollate(pB),
             iTab);
}

@@ -113727,6 +114452,12 @@ SQLITE_PRIVATE int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList
  assert( pExpr->op==TK_AGG_FUNCTION );
  assert( ExprUseXList(pExpr) );
  sqlite3WalkExprList(&w, pExpr->x.pList);
+
  if( pExpr->pLeft ){
+
    assert( pExpr->pLeft->op==TK_ORDER );
+
    assert( ExprUseXList(pExpr->pLeft) );
+
    assert( pExpr->pLeft->x.pList!=0 );
+
    sqlite3WalkExprList(&w, pExpr->pLeft->x.pList);
+
  }
#ifndef SQLITE_OMIT_WINDOWFUNC
  if( ExprHasProperty(pExpr, EP_WinFunc) ){
    sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
@@ -113991,14 +114722,42 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
          u8 enc = ENC(pParse->db);
          i = addAggInfoFunc(pParse->db, pAggInfo);
          if( i>=0 ){
+
            int nArg;
            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
            pItem = &pAggInfo->aFunc[i];
            pItem->pFExpr = pExpr;
            assert( ExprUseUToken(pExpr) );
+
            nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
            pItem->pFunc = sqlite3FindFunction(pParse->db,
-
                   pExpr->u.zToken,
-
                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
-
            if( pExpr->flags & EP_Distinct ){
+
                                         pExpr->u.zToken, nArg, enc, 0);
+
            assert( pItem->bOBUnique==0 );
+
            if( pExpr->pLeft
+
             && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0
+
            ){
+
              /* The NEEDCOLL test above causes any ORDER BY clause on
+
              ** aggregate min() or max() to be ignored. */
+
              ExprList *pOBList;
+
              assert( nArg>0 );
+
              assert( pExpr->pLeft->op==TK_ORDER );
+
              assert( ExprUseXList(pExpr->pLeft) );
+
              pItem->iOBTab = pParse->nTab++;
+
              pOBList = pExpr->pLeft->x.pList;
+
              assert( pOBList->nExpr>0 );
+
              assert( pItem->bOBUnique==0 );
+
              if( pOBList->nExpr==1
+
               && nArg==1
+
               && sqlite3ExprCompare(0,pOBList->a[0].pExpr,
+
                               pExpr->x.pList->a[0].pExpr,0)==0
+
              ){
+
                pItem->bOBPayload = 0;
+
                pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct);
+
              }else{
+
                pItem->bOBPayload = 1;
+
              }
+
            }else{
+
              pItem->iOBTab = -1;
+
            }
+
            if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){
              pItem->iDistinct = pParse->nTab++;
            }else{
              pItem->iDistinct = -1;
@@ -114634,14 +115393,19 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
    /* Verify that constraints are still satisfied */
    if( pNew->pCheck!=0
     || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
+
     || (pTab->tabFlags & TF_Strict)!=0
    ){
      sqlite3NestedParse(pParse,
        "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
        " THEN raise(ABORT,'CHECK constraint failed')"
+
        " WHEN quick_check GLOB 'non-* value in*'"
+
        " THEN raise(ABORT,'type mismatch on DEFAULT')"
        " ELSE raise(ABORT,'NOT NULL constraint failed')"
        " END"
        "  FROM pragma_quick_check(%Q,%Q)"
-
        " WHERE quick_check GLOB 'CHECK*' OR quick_check GLOB 'NULL*'",
+
        " WHERE quick_check GLOB 'CHECK*'"
+
        " OR quick_check GLOB 'NULL*'"
+
        " OR quick_check GLOB 'non-* value in*'",
        zTab, zDb
      );
    }
@@ -119620,19 +120384,14 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
    */
    if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);

-
    /* Code constant expressions that where factored out of inner loops.
-
    **
-
    ** The pConstExpr list might also contain expressions that we simply
-
    ** want to keep around until the Parse object is deleted.  Such
-
    ** expressions have iConstExprReg==0.  Do not generate code for
-
    ** those expressions, of course.
+
    /* Code constant expressions that were factored out of inner loops.
    */
    if( pParse->pConstExpr ){
      ExprList *pEL = pParse->pConstExpr;
      pParse->okConstFactor = 0;
      for(i=0; i<pEL->nExpr; i++){
-
        int iReg = pEL->a[i].u.iConstExprReg;
-
        sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg);
+
        assert( pEL->a[i].u.iConstExprReg>0 );
+
        sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
      }
    }

@@ -120787,19 +121546,12 @@ SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
#endif

/*
-
** Name of the special TEMP trigger used to implement RETURNING.  The
-
** name begins with "sqlite_" so that it is guaranteed not to collide
-
** with any application-generated triggers.
-
*/
-
#define RETURNING_TRIGGER_NAME  "sqlite_returning"
-

-
/*
** Clean up the data structures associated with the RETURNING clause.
*/
static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){
  Hash *pHash;
  pHash = &(db->aDb[1].pSchema->trigHash);
-
  sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, 0);
+
  sqlite3HashInsert(pHash, pRet->zName, 0);
  sqlite3ExprListDelete(db, pRet->pReturnEL);
  sqlite3DbFree(db, pRet);
}
@@ -120842,7 +121594,9 @@ SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){
     (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet);
  testcase( pParse->earlyCleanup );
  if( db->mallocFailed ) return;
-
  pRet->retTrig.zName = RETURNING_TRIGGER_NAME;
+
  sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
+
                   "sqlite_returning_%p", pParse);
+
  pRet->retTrig.zName = pRet->zName;
  pRet->retTrig.op = TK_RETURNING;
  pRet->retTrig.tr_tm = TRIGGER_AFTER;
  pRet->retTrig.bReturning = 1;
@@ -120853,9 +121607,9 @@ SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){
  pRet->retTStep.pTrig = &pRet->retTrig;
  pRet->retTStep.pExprList = pList;
  pHash = &(db->aDb[1].pSchema->trigHash);
-
  assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0
+
  assert( sqlite3HashFind(pHash, pRet->zName)==0
          || pParse->nErr  || pParse->ifNotExists );
-
  if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig)
+
  if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
          ==&pRet->retTrig ){
    sqlite3OomFault(db);
  }
@@ -122299,6 +123053,17 @@ SQLITE_PRIVATE void sqlite3EndTable(
    /* Reparse everything to update our internal data structures */
    sqlite3VdbeAddParseSchemaOp(v, iDb,
           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
+

+
    /* Test for cycles in generated columns and illegal expressions
+
    ** in CHECK constraints and in DEFAULT clauses. */
+
    if( p->tabFlags & TF_HasGenerated ){
+
      sqlite3VdbeAddOp4(v, OP_SqlExec, 1, 0, 0,
+
             sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
+
                   db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
+
    }
+
    sqlite3VdbeAddOp4(v, OP_SqlExec, 1, 0, 0,
+
           sqlite3MPrintf(db, "PRAGMA \"%w\".integrity_check(%Q)",
+
                 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
  }

  /* Add the table to the in-memory representation of the database.
@@ -127901,7 +128666,8 @@ static void hexFunc(
      *(z++) = hexdigits[c&0xf];
    }
    *z = 0;
-
    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
+
    sqlite3_result_text64(context, zHex, (u64)(z-zHex),
+
                          sqlite3_free, SQLITE_UTF8);
  }
}

@@ -128195,6 +128961,81 @@ static void trimFunc(
  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
}

+
/* The core implementation of the CONCAT(...) and CONCAT_WS(SEP,...)
+
** functions.
+
**
+
** Return a string value that is the concatenation of all non-null
+
** entries in argv[].  Use zSep as the separator.
+
*/
+
static void concatFuncCore(
+
  sqlite3_context *context,
+
  int argc,
+
  sqlite3_value **argv,
+
  int nSep,
+
  const char *zSep
+
){
+
  i64 j, k, n = 0;
+
  int i;
+
  char *z;
+
  for(i=0; i<argc; i++){
+
    n += sqlite3_value_bytes(argv[i]);
+
  }
+
  n += (argc-1)*nSep;
+
  z = sqlite3_malloc64(n+1);
+
  if( z==0 ){
+
    sqlite3_result_error_nomem(context);
+
    return;
+
  }
+
  j = 0;
+
  for(i=0; i<argc; i++){
+
    k = sqlite3_value_bytes(argv[i]);
+
    if( k>0 ){
+
      const char *v = (const char*)sqlite3_value_text(argv[i]);
+
      if( v!=0 ){
+
        if( j>0 && nSep>0 ){
+
          memcpy(&z[j], zSep, nSep);
+
          j += nSep;
+
        }
+
        memcpy(&z[j], v, k);
+
        j += k;
+
      }
+
    }
+
  }
+
  z[j] = 0;
+
  assert( j<=n );
+
  sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8);
+
}
+

+
/*
+
** The CONCAT(...) function.  Generate a string result that is the
+
** concatentation of all non-null arguments.
+
*/
+
static void concatFunc(
+
  sqlite3_context *context,
+
  int argc,
+
  sqlite3_value **argv
+
){
+
  concatFuncCore(context, argc, argv, 0, "");
+
}
+

+
/*
+
** The CONCAT_WS(separator, ...) function.
+
**
+
** Generate a string that is the concatenation of 2nd through the Nth
+
** argument.  Use the first argument (which must be non-NULL) as the
+
** separator.
+
*/
+
static void concatwsFunc(
+
  sqlite3_context *context,
+
  int argc,
+
  sqlite3_value **argv
+
){
+
  int nSep = sqlite3_value_bytes(argv[0]);
+
  const char *zSep = (const char*)sqlite3_value_text(argv[0]);
+
  if( zSep==0 ) return;
+
  concatFuncCore(context, argc-1, argv+1, nSep, zSep);
+
}
+


#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
/*
@@ -128461,8 +129302,10 @@ static void sumFinalize(sqlite3_context *context){
    if( p->approx ){
      if( p->ovrfl ){
        sqlite3_result_error(context,"integer overflow",-1);
-
      }else{
+
      }else if( !sqlite3IsNaN(p->rErr) ){
        sqlite3_result_double(context, p->rSum+p->rErr);
+
      }else{
+
        sqlite3_result_double(context, p->rSum);
      }
    }else{
      sqlite3_result_int64(context, p->iSum);
@@ -128475,7 +129318,8 @@ static void avgFinalize(sqlite3_context *context){
  if( p && p->cnt>0 ){
    double r;
    if( p->approx ){
-
      r = p->rSum+p->rErr;
+
      r = p->rSum;
+
      if( !sqlite3IsNaN(p->rErr) ) r += p->rErr;
    }else{
      r = (double)(p->iSum);
    }
@@ -128488,7 +129332,8 @@ static void totalFinalize(sqlite3_context *context){
  p = sqlite3_aggregate_context(context, 0);
  if( p ){
    if( p->approx ){
-
      r = p->rSum+p->rErr;
+
      r = p->rSum;
+
      if( !sqlite3IsNaN(p->rErr) ) r += p->rErr;
    }else{
      r = (double)(p->iSum);
    }
@@ -128612,6 +129457,7 @@ static void minMaxFinalize(sqlite3_context *context){

/*
** group_concat(EXPR, ?SEPARATOR?)
+
** string_agg(EXPR, SEPARATOR)
**
** The SEPARATOR goes before the EXPR string.  This is tragic.  The
** groupConcatInverse() implementation would have been easier if the
@@ -129202,6 +130048,11 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
    FUNCTION(hex,                1, 0, 0, hexFunc          ),
    FUNCTION(unhex,              1, 0, 0, unhexFunc        ),
    FUNCTION(unhex,              2, 0, 0, unhexFunc        ),
+
    FUNCTION(concat,            -1, 0, 0, concatFunc       ),
+
    FUNCTION(concat,             0, 0, 0, 0                ),
+
    FUNCTION(concat_ws,         -1, 0, 0, concatwsFunc     ),
+
    FUNCTION(concat_ws,          0, 0, 0, 0                ),
+
    FUNCTION(concat_ws,          1, 0, 0, 0                ),
    INLINE_FUNC(ifnull,          2, INLINEFUNC_coalesce, 0 ),
    VFUNCTION(random,            0, 0, 0, randomFunc       ),
    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
@@ -129231,6 +130082,8 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
    WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
+
    WAGGREGATE(string_agg,   2, 0, 0, groupConcatStep,
+
        groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),

    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
#ifdef SQLITE_CASE_SENSITIVE_LIKE
@@ -130173,6 +131026,7 @@ static int isSetNullAction(Parse *pParse, FKey *pFKey){
    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
    ){
+
      assert( (pTop->db->flags & SQLITE_FkNoAction)==0 );
      return 1;
    }
  }
@@ -130367,6 +131221,8 @@ SQLITE_PRIVATE void sqlite3FkCheck(
      }
      if( regOld!=0 ){
        int eAction = pFKey->aAction[aChange!=0];
+
        if( (db->flags & SQLITE_FkNoAction) ) eAction = OE_None;
+

        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
        ** action applies, then any foreign key violations caused by
@@ -130482,7 +131338,11 @@ SQLITE_PRIVATE int sqlite3FkRequired(
      /* Check if any parent key columns are being modified. */
      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
        if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
-
          if( p->aAction[1]!=OE_None ) return 2;
+
          if( (pParse->db->flags & SQLITE_FkNoAction)==0
+
           && p->aAction[1]!=OE_None
+
          ){
+
            return 2;
+
          }
          bHaveFK = 1;
        }
      }
@@ -130532,6 +131392,7 @@ static Trigger *fkActionTrigger(
  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */

  action = pFKey->aAction[iAction];
+
  if( (db->flags & SQLITE_FkNoAction) ) action = OE_None;
  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
    return 0;
  }
@@ -134487,6 +135348,9 @@ struct sqlite3_api_routines {
  int (*is_interrupted)(sqlite3*);
  /* Version 3.43.0 and later */
  int (*stmt_explain)(sqlite3_stmt*,int);
+
  /* Version 3.44.0 and later */
+
  void *(*get_clientdata)(sqlite3*,const char*);
+
  int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*));
};

/*
@@ -134817,6 +135681,9 @@ typedef int (*sqlite3_loadext_entry)(
#define sqlite3_is_interrupted         sqlite3_api->is_interrupted
/* Version 3.43.0 and later */
#define sqlite3_stmt_explain           sqlite3_api->stmt_explain
+
/* Version 3.44.0 and later */
+
#define sqlite3_get_clientdata         sqlite3_api->get_clientdata
+
#define sqlite3_set_clientdata         sqlite3_api->set_clientdata
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */

#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
@@ -135335,7 +136202,10 @@ static const sqlite3_api_routines sqlite3Apis = {
  /* Version 3.41.0 and later */
  sqlite3_is_interrupted,
  /* Version 3.43.0 and later */
-
  sqlite3_stmt_explain
+
  sqlite3_stmt_explain,
+
  /* Version 3.44.0 and later */
+
  sqlite3_get_clientdata,
+
  sqlite3_set_clientdata
};

/* True if x is the directory separator character
@@ -135551,6 +136421,9 @@ SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
** default so as not to open security holes in older applications.
*/
SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+
#endif
  sqlite3_mutex_enter(db->mutex);
  if( onoff ){
    db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
@@ -135600,6 +136473,9 @@ SQLITE_API int sqlite3_auto_extension(
  void (*xInit)(void)
){
  int rc = SQLITE_OK;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( xInit==0 ) return SQLITE_MISUSE_BKPT;
+
#endif
#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite3_initialize();
  if( rc ){
@@ -135652,6 +136528,9 @@ SQLITE_API int sqlite3_cancel_auto_extension(
  int i;
  int n = 0;
  wsdAutoextInit;
+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( xInit==0 ) return 0;
+
#endif
  sqlite3_mutex_enter(mutex);
  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
    if( wsdAutoext.aExt[i]==xInit ){
@@ -137521,7 +138400,11 @@ SQLITE_PRIVATE void sqlite3Pragma(
#endif

      if( sqlite3GetBoolean(zRight, 0) ){
-
        db->flags |= mask;
+
        if( (mask & SQLITE_WriteSchema)==0
+
         || (db->flags & SQLITE_Defensive)==0
+
        ){
+
          db->flags |= mask;
+
        }
      }else{
        db->flags &= ~mask;
        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
@@ -138154,8 +139037,31 @@ SQLITE_PRIVATE void sqlite3Pragma(
        int r2;                 /* Previous key for WITHOUT ROWID tables */
        int mxCol;              /* Maximum non-virtual column number */

-
        if( !IsOrdinaryTable(pTab) ) continue;
        if( pObjTab && pObjTab!=pTab ) continue;
+
        if( !IsOrdinaryTable(pTab) ){
+
#ifndef SQLITE_OMIT_VIRTUALTABLE
+
          sqlite3_vtab *pVTab;
+
          int a1;
+
          if( !IsVirtual(pTab) ) continue;
+
          if( pTab->nCol<=0 ){
+
            const char *zMod = pTab->u.vtab.azArg[0];
+
            if( sqlite3HashFind(&db->aModule, zMod)==0 ) continue;
+
          }
+
          sqlite3ViewGetColumnNames(pParse, pTab);
+
          if( pTab->u.vtab.p==0 ) continue;
+
          pVTab = pTab->u.vtab.p->pVtab;
+
          if( NEVER(pVTab==0) ) continue;
+
          if( NEVER(pVTab->pModule==0) ) continue;
+
          if( pVTab->pModule->iVersion<4 ) continue;
+
          if( pVTab->pModule->xIntegrity==0 ) continue;
+
          sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
+
          sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
+
          a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
+
          integrityCheckResultRow(v);
+
          sqlite3VdbeJumpHere(v, a1);
+
#endif
+
          continue;
+
        }
        if( isQuick || HasRowid(pTab) ){
          pPk = 0;
          r2 = 0;
@@ -139281,7 +140187,8 @@ static const sqlite3_module pragmaVtabModule = {
  0,                           /* xSavepoint */
  0,                           /* xRelease */
  0,                           /* xRollbackTo */
-
  0                            /* xShadowName */
+
  0,                           /* xShadowName */
+
  0                            /* xIntegrity */
};

/*
@@ -139905,8 +140812,6 @@ SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse *pParse){
  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;
}

/*
@@ -140844,6 +141749,7 @@ static void unsetJoinExpr(Expr *p, int iTable, int nullable){
    }
    if( p->op==TK_FUNCTION ){
      assert( ExprUseXList(p) );
+
      assert( p->pLeft==0 );
      if( p->x.pList ){
        int i;
        for(i=0; i<p->x.pList->nExpr; i++){
@@ -142708,7 +143614,8 @@ SQLITE_PRIVATE void sqlite3SubqueryColumnTypes(
  NameContext sNC;

  assert( pSelect!=0 );
-
  assert( (pSelect->selFlags & SF_Resolved)!=0 );
+
  testcase( (pSelect->selFlags & SF_Resolved)==0 );
+
  assert( (pSelect->selFlags & SF_Resolved)!=0 || IN_RENAME_OBJECT );
  assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
  assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
  if( db->mallocFailed || IN_RENAME_OBJECT ) return;
@@ -145691,12 +146598,12 @@ static int disableUnusedSubqueryResultColumns(SrcItem *pItem){
  assert( pItem->pSelect!=0 );
  pSub = pItem->pSelect;
  assert( pSub->pEList->nExpr==pTab->nCol );
-
  if( (pSub->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
-
    testcase( pSub->selFlags & SF_Distinct );
-
    testcase( pSub->selFlags & SF_Aggregate );
-
    return 0;
-
  }
  for(pX=pSub; pX; pX=pX->pPrior){
+
    if( (pX->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
+
      testcase( pX->selFlags & SF_Distinct );
+
      testcase( pX->selFlags & SF_Aggregate );
+
      return 0;
+
    }
    if( pX->pPrior && pX->op!=TK_ALL ){
      /* This optimization does not work for compound subqueries that
      ** use UNION, INTERSECT, or EXCEPT.  Only UNION ALL is allowed. */
@@ -146504,6 +147411,7 @@ static int selectExpander(Walker *pWalker, Select *p){
        char *zTName = 0;       /* text of name of TABLE */
        int iErrOfst;
        if( pE->op==TK_DOT ){
+
          assert( (selFlags & SF_NestedFrom)==0 );
          assert( pE->pLeft!=0 );
          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
          zTName = pE->pLeft->u.zToken;
@@ -146514,6 +147422,7 @@ static int selectExpander(Walker *pWalker, Select *p){
          iErrOfst = pE->w.iOfst;
        }
        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
+
          int nAdd;                    /* Number of cols including rowid */
          Table *pTab = pFrom->pTab;   /* Table for this data source */
          ExprList *pNestedFrom;       /* Result-set of a nested FROM clause */
          char *zTabName;              /* AS name for this data source */
@@ -146531,6 +147440,7 @@ static int selectExpander(Walker *pWalker, Select *p){
            pNestedFrom = pFrom->pSelect->pEList;
            assert( pNestedFrom!=0 );
            assert( pNestedFrom->nExpr==pTab->nCol );
+
            assert( VisibleRowid(pTab)==0 );
          }else{
            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
              continue;
@@ -146561,33 +147471,48 @@ static int selectExpander(Walker *pWalker, Select *p){
          }else{
            pUsing = 0;
          }
-
          for(j=0; j<pTab->nCol; j++){
-
            char *zName = pTab->aCol[j].zCnName;
+

+
          nAdd = pTab->nCol + (VisibleRowid(pTab) && (selFlags&SF_NestedFrom));
+
          for(j=0; j<nAdd; j++){
+
            const char *zName;
            struct ExprList_item *pX; /* Newly added ExprList term */

-
            assert( zName );
-
            if( zTName
-
             && pNestedFrom
-
             && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0)==0
-
            ){
-
              continue;
-
            }
+
            if( j==pTab->nCol ){
+
              zName = sqlite3RowidAlias(pTab);
+
              if( zName==0 ) continue;
+
            }else{
+
              zName = pTab->aCol[j].zCnName;

-
            /* If a column is marked as 'hidden', omit it from the expanded
-
            ** result-set list unless the SELECT has the SF_IncludeHidden
-
            ** bit set.
-
            */
-
            if( (p->selFlags & SF_IncludeHidden)==0
-
             && IsHiddenColumn(&pTab->aCol[j])
-
            ){
-
              continue;
-
            }
-
            if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
-
             && zTName==0
-
             && (selFlags & (SF_NestedFrom))==0
-
            ){
-
              continue;
+
              /* If pTab is actually an SF_NestedFrom sub-select, do not
+
              ** expand any ENAME_ROWID columns.  */
+
              if( pNestedFrom && pNestedFrom->a[j].fg.eEName==ENAME_ROWID ){
+
                continue;
+
              }
+

+
              if( zTName
+
               && pNestedFrom
+
               && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0, 0)==0
+
              ){
+
                continue;
+
              }
+

+
              /* If a column is marked as 'hidden', omit it from the expanded
+
              ** result-set list unless the SELECT has the SF_IncludeHidden
+
              ** bit set.
+
              */
+
              if( (p->selFlags & SF_IncludeHidden)==0
+
                && IsHiddenColumn(&pTab->aCol[j])
+
              ){
+
                continue;
+
              }
+
              if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
+
               && zTName==0
+
               && (selFlags & (SF_NestedFrom))==0
+
              ){
+
                continue;
+
              }
            }
+
            assert( zName );
            tableSeen = 1;

            if( i>0 && zTName==0 && (selFlags & SF_NestedFrom)==0 ){
@@ -146637,11 +147562,11 @@ static int selectExpander(Walker *pWalker, Select *p){
                                           zSchemaName, zTabName, zName);
                testcase( pX->zEName==0 );
              }
-
              pX->fg.eEName = ENAME_TAB;
+
              pX->fg.eEName = (j==pTab->nCol ? ENAME_ROWID : ENAME_TAB);
              if( (pFrom->fg.isUsing
                   && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
               || (pUsing && sqlite3IdListIndex(pUsing, zName)>=0)
-
               || (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
+
               || (j<pTab->nCol && (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND))
              ){
                pX->fg.bNoExpand = 1;
              }
@@ -146743,10 +147668,11 @@ static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  SrcList *pTabList;
  SrcItem *pFrom;

-
  assert( p->selFlags & SF_Resolved );
  if( p->selFlags & SF_HasTypeInfo ) return;
  p->selFlags |= SF_HasTypeInfo;
  pParse = pWalker->pParse;
+
  testcase( (p->selFlags & SF_Resolved)==0 );
+
  assert( (p->selFlags & SF_Resolved) || IN_RENAME_OBJECT );
  pTabList = p->pSrc;
  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
    Table *pTab = pFrom->pTab;
@@ -146862,8 +147788,14 @@ static void analyzeAggFuncArgs(
  pNC->ncFlags |= NC_InAggFunc;
  for(i=0; i<pAggInfo->nFunc; i++){
    Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
+
    assert( pExpr->op==TK_FUNCTION || pExpr->op==TK_AGG_FUNCTION );
    assert( ExprUseXList(pExpr) );
    sqlite3ExprAnalyzeAggList(pNC, pExpr->x.pList);
+
    if( pExpr->pLeft ){
+
      assert( pExpr->pLeft->op==TK_ORDER );
+
      assert( ExprUseXList(pExpr->pLeft) );
+
      sqlite3ExprAnalyzeAggList(pNC, pExpr->pLeft->x.pList);
+
    }
#ifndef SQLITE_OMIT_WINDOWFUNC
    assert( !IsWindowFunc(pExpr) );
    if( ExprHasProperty(pExpr, EP_WinFunc) ){
@@ -147018,6 +147950,32 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
                          pFunc->pFunc->zName));
      }
    }
+
    if( pFunc->iOBTab>=0 ){
+
      ExprList *pOBList;
+
      KeyInfo *pKeyInfo;
+
      int nExtra = 0;
+
      assert( pFunc->pFExpr->pLeft!=0 );
+
      assert( pFunc->pFExpr->pLeft->op==TK_ORDER );
+
      assert( ExprUseXList(pFunc->pFExpr->pLeft) );
+
      pOBList = pFunc->pFExpr->pLeft->x.pList;
+
      if( !pFunc->bOBUnique ){
+
        nExtra++;  /* One extra column for the OP_Sequence */
+
      }
+
      if( pFunc->bOBPayload ){
+
        /* extra columns for the function arguments */
+
        assert( ExprUseXList(pFunc->pFExpr) );
+
        nExtra += pFunc->pFExpr->x.pList->nExpr;
+
      }
+
      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOBList, 0, nExtra);
+
      if( !pFunc->bOBUnique && pParse->nErr==0 ){
+
        pKeyInfo->nKeyField++;
+
      }
+
      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
+
            pFunc->iOBTab, pOBList->nExpr+nExtra, 0,
+
            (char*)pKeyInfo, P4_KEYINFO);
+
      ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(ORDER BY)",
+
                          pFunc->pFunc->zName));
+
    }
  }
}

@@ -147033,13 +147991,46 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
    ExprList *pList;
    assert( ExprUseXList(pF->pFExpr) );
    pList = pF->pFExpr->x.pList;
+
    if( pF->iOBTab>=0 ){
+
      /* For an ORDER BY aggregate, calls to OP_AggStep where deferred and
+
      ** all content was stored in emphermal table pF->iOBTab.  Extract that
+
      ** content now (in ORDER BY order) and make all calls to OP_AggStep
+
      ** before doing the OP_AggFinal call. */
+
      int iTop;        /* Start of loop for extracting columns */
+
      int nArg;        /* Number of columns to extract */
+
      int nKey;        /* Key columns to be skipped */
+
      int regAgg;      /* Extract into this array */
+
      int j;           /* Loop counter */
+

+
      nArg = pList->nExpr;
+
      regAgg = sqlite3GetTempRange(pParse, nArg);
+

+
      if( pF->bOBPayload==0 ){
+
        nKey = 0;
+
      }else{
+
        assert( pF->pFExpr->pLeft!=0 );
+
        assert( ExprUseXList(pF->pFExpr->pLeft) );
+
        assert( pF->pFExpr->pLeft->x.pList!=0 );
+
        nKey = pF->pFExpr->pLeft->x.pList->nExpr;
+
        if( ALWAYS(!pF->bOBUnique) ) nKey++;
+
      }
+
      iTop = sqlite3VdbeAddOp1(v, OP_Rewind, pF->iOBTab); VdbeCoverage(v);
+
      for(j=nArg-1; j>=0; j--){
+
        sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, nKey+j, regAgg+j);
+
      }
+
      sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
+
      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
+
      sqlite3VdbeChangeP5(v, (u8)nArg);
+
      sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v);
+
      sqlite3VdbeJumpHere(v, iTop);
+
      sqlite3ReleaseTempRange(pParse, regAgg, nArg);
+
    }
    sqlite3VdbeAddOp2(v, OP_AggFinal, AggInfoFuncReg(pAggInfo,i),
                      pList ? pList->nExpr : 0);
    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  }
}

-

/*
** Generate code that will update the accumulator memory cells for an
** aggregate based on the current cursor position.
@@ -147048,6 +148039,13 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
** registers if register regAcc contains 0. The caller will take care
** of setting and clearing regAcc.
+
**
+
** For an ORDER BY aggregate, the actual accumulator memory cell update
+
** is deferred until after all input rows have been received, so that they
+
** can be run in the requested order.  In that case, instead of invoking
+
** OP_AggStep to update the accumulator, just add the arguments that would
+
** have been passed into OP_AggStep into the sorting ephemeral table
+
** (along with the appropriate sort key).
*/
static void updateAccumulator(
  Parse *pParse,
@@ -147069,6 +148067,8 @@ static void updateAccumulator(
    int nArg;
    int addrNext = 0;
    int regAgg;
+
    int regAggSz = 0;
+
    int regDistinct = 0;
    ExprList *pList;
    assert( ExprUseXList(pF->pFExpr) );
    assert( !IsWindowFunc(pF->pFExpr) );
@@ -147095,9 +148095,44 @@ static void updateAccumulator(
      addrNext = sqlite3VdbeMakeLabel(pParse);
      sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
    }
-
    if( pList ){
+
    if( pF->iOBTab>=0 ){
+
      /* Instead of invoking AggStep, we must push the arguments that would
+
      ** have been passed to AggStep onto the sorting table. */
+
      int jj;                /* Registered used so far in building the record */
+
      ExprList *pOBList;     /* The ORDER BY clause */
+
      assert( pList!=0 );
+
      nArg = pList->nExpr;
+
      assert( nArg>0 );
+
      assert( pF->pFExpr->pLeft!=0 );
+
      assert( pF->pFExpr->pLeft->op==TK_ORDER );
+
      assert( ExprUseXList(pF->pFExpr->pLeft) );
+
      pOBList = pF->pFExpr->pLeft->x.pList;
+
      assert( pOBList!=0 );
+
      assert( pOBList->nExpr>0 );
+
      regAggSz = pOBList->nExpr;
+
      if( !pF->bOBUnique ){
+
        regAggSz++;   /* One register for OP_Sequence */
+
      }
+
      if( pF->bOBPayload ){
+
        regAggSz += nArg;
+
      }
+
      regAggSz++;  /* One extra register to hold result of MakeRecord */
+
      regAgg = sqlite3GetTempRange(pParse, regAggSz);
+
      regDistinct = regAgg;
+
      sqlite3ExprCodeExprList(pParse, pOBList, regAgg, 0, SQLITE_ECEL_DUP);
+
      jj = pOBList->nExpr;
+
      if( !pF->bOBUnique ){
+
        sqlite3VdbeAddOp2(v, OP_Sequence, pF->iOBTab, regAgg+jj);
+
        jj++;
+
      }
+
      if( pF->bOBPayload ){
+
        regDistinct = regAgg+jj;
+
        sqlite3ExprCodeExprList(pParse, pList, regDistinct, 0, SQLITE_ECEL_DUP);
+
      }
+
    }else if( pList ){
      nArg = pList->nExpr;
      regAgg = sqlite3GetTempRange(pParse, nArg);
+
      regDistinct = regAgg;
      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
    }else{
      nArg = 0;
@@ -147108,26 +148143,37 @@ static void updateAccumulator(
        addrNext = sqlite3VdbeMakeLabel(pParse);
      }
      pF->iDistinct = codeDistinct(pParse, eDistinctType,
-
          pF->iDistinct, addrNext, pList, regAgg);
-
    }
-
    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
-
      CollSeq *pColl = 0;
-
      struct ExprList_item *pItem;
-
      int j;
-
      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
-
      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
-
        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
-
      }
-
      if( !pColl ){
-
        pColl = pParse->db->pDfltColl;
+
          pF->iDistinct, addrNext, pList, regDistinct);
+
    }
+
    if( pF->iOBTab>=0 ){
+
      /* Insert a new record into the ORDER BY table */
+
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regAgg, regAggSz-1,
+
                        regAgg+regAggSz-1);
+
      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pF->iOBTab, regAgg+regAggSz-1,
+
                           regAgg, regAggSz-1);
+
      sqlite3ReleaseTempRange(pParse, regAgg, regAggSz);
+
    }else{
+
      /* Invoke the AggStep function */
+
      if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
+
        CollSeq *pColl = 0;
+
        struct ExprList_item *pItem;
+
        int j;
+
        assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
+
        for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
+
          pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
+
        }
+
        if( !pColl ){
+
          pColl = pParse->db->pDfltColl;
+
        }
+
        if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
+
        sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0,
+
                         (char *)pColl, P4_COLLSEQ);
      }
-
      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
-
      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
+
      sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
+
      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
+
      sqlite3VdbeChangeP5(v, (u8)nArg);
+
      sqlite3ReleaseTempRange(pParse, regAgg, nArg);
    }
-
    sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
-
    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
-
    sqlite3VdbeChangeP5(v, (u8)nArg);
-
    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
    if( addrNext ){
      sqlite3VdbeResolveLabel(v, addrNext);
    }
@@ -147648,6 +148694,7 @@ SQLITE_PRIVATE int sqlite3Select(
          TREETRACE(0x1000,pParse,p,
                    ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
          pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
+
          unsetJoinExpr(p->pWhere, pItem->iCursor, 0);
        }
      }
      if( pItem->fg.jointype & JT_LTORJ ){
@@ -147662,17 +148709,15 @@ SQLITE_PRIVATE int sqlite3Select(
              TREETRACE(0x1000,pParse,p,
                        ("RIGHT-JOIN simplifies to JOIN on term %d\n",j));
              pI2->fg.jointype &= ~(JT_RIGHT|JT_OUTER);
+
              unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
            }
          }
        }
-
        for(j=pTabList->nSrc-1; j>=i; j--){
+
        for(j=pTabList->nSrc-1; j>=0; j--){
          pTabList->a[j].fg.jointype &= ~JT_LTORJ;
          if( pTabList->a[j].fg.jointype & JT_RIGHT ) break;
        }
      }
-
      assert( pItem->iCursor>=0 );
-
      unsetJoinExpr(p->pWhere, pItem->iCursor,
-
                    pTabList->a[0].fg.jointype & JT_LTORJ);
    }

    /* No further action if this term of the FROM clause is not a subquery */
@@ -149188,6 +150233,10 @@ SQLITE_PRIVATE void sqlite3BeginTrigger(
    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
    goto trigger_orphan_error;
  }
+
  if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
+
    sqlite3ErrorMsg(pParse, "cannot create triggers on shadow tables");
+
    goto trigger_orphan_error;
+
  }

  /* Check that the trigger name is not reserved and that no trigger of the
  ** specified name exists */
@@ -149971,10 +151020,17 @@ static void codeReturningTrigger(
  SrcList sFrom;

  assert( v!=0 );
-
  assert( pParse->bReturning );
+
  if( !pParse->bReturning ){
+
    /* This RETURNING trigger must be for a different statement as
+
    ** this statement lacks a RETURNING clause. */
+
    return;
+
  }
  assert( db->pParse==pParse );
  pReturning = pParse->u1.pReturning;
-
  assert( pTrigger == &(pReturning->retTrig) );
+
  if( pTrigger != &(pReturning->retTrig) ){
+
    /* This RETURNING trigger is for a different statement */
+
    return;
+
  }
  memset(&sSelect, 0, sizeof(sSelect));
  memset(&sFrom, 0, sizeof(sFrom));
  sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
@@ -153411,7 +154467,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  sqlite3_mutex_enter(db->mutex);
  pCtx = db->pVtabCtx;
  if( !pCtx || pCtx->bDeclared ){
-
    sqlite3Error(db, SQLITE_MISUSE);
+
    sqlite3Error(db, SQLITE_MISUSE_BKPT);
    sqlite3_mutex_leave(db->mutex);
    return SQLITE_MISUSE_BKPT;
  }
@@ -154602,7 +155658,7 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*);
#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 */
-
#define WHERE_VIEWSCAN     0x02000000  /* A full-scan of a VIEW or subquery */
+
                      /*   0x02000000  -- available for reuse */
#define WHERE_EXPRIDX      0x04000000  /* Uses an index-on-expressions */

#endif /* !defined(SQLITE_WHEREINT_H) */
@@ -160397,13 +161453,17 @@ static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
  WhereLoop *pLoop = pLevel->pWLoop;   /* The loop being coded */
  int iCur;                            /* Cursor for table getting the filter */
  IndexedExpr *saved_pIdxEpr;          /* saved copy of Parse.pIdxEpr */
+
  IndexedExpr *saved_pIdxPartExpr;     /* saved copy of Parse.pIdxPartExpr */

  saved_pIdxEpr = pParse->pIdxEpr;
+
  saved_pIdxPartExpr = pParse->pIdxPartExpr;
  pParse->pIdxEpr = 0;
+
  pParse->pIdxPartExpr = 0;

  assert( pLoop!=0 );
  assert( v!=0 );
  assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
+
  assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 );

  addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  do{
@@ -160493,6 +161553,7 @@ static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
  }while( iLevel < pWInfo->nLevel );
  sqlite3VdbeJumpHere(v, addrOnce);
  pParse->pIdxEpr = saved_pIdxEpr;
+
  pParse->pIdxPartExpr = saved_pIdxPartExpr;
}


@@ -162753,6 +163814,100 @@ static SQLITE_NOINLINE u32 whereIsCoveringIndex(
}

/*
+
** This is an sqlite3ParserAddCleanup() callback that is invoked to
+
** free the Parse->pIdxEpr list when the Parse object is destroyed.
+
*/
+
static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){
+
  IndexedExpr **pp = (IndexedExpr**)pObject;
+
  while( *pp!=0 ){
+
    IndexedExpr *p = *pp;
+
    *pp = p->pIENext;
+
    sqlite3ExprDelete(db, p->pExpr);
+
    sqlite3DbFreeNN(db, p);
+
  }
+
}
+

+
/*
+
** This function is called for a partial index - one with a WHERE clause - in
+
** two scenarios. In both cases, it determines whether or not the WHERE
+
** clause on the index implies that a column of the table may be safely
+
** replaced by a constant expression. For example, in the following
+
** SELECT:
+
**
+
**   CREATE INDEX i1 ON t1(b, c) WHERE a=<expr>;
+
**   SELECT a, b, c FROM t1 WHERE a=<expr> AND b=?;
+
**
+
** The "a" in the select-list may be replaced by <expr>, iff:
+
**
+
**    (a) <expr> is a constant expression, and
+
**    (b) The (a=<expr>) comparison uses the BINARY collation sequence, and
+
**    (c) Column "a" has an affinity other than NONE or BLOB.
+
**
+
** If argument pItem is NULL, then pMask must not be NULL. In this case this
+
** function is being called as part of determining whether or not pIdx
+
** is a covering index. This function clears any bits in (*pMask)
+
** corresponding to columns that may be replaced by constants as described
+
** above.
+
**
+
** Otherwise, if pItem is not NULL, then this function is being called
+
** as part of coding a loop that uses index pIdx. In this case, add entries
+
** to the Parse.pIdxPartExpr list for each column that can be replaced
+
** by a constant.
+
*/
+
static void wherePartIdxExpr(
+
  Parse *pParse,                  /* Parse context */
+
  Index *pIdx,                    /* Partial index being processed */
+
  Expr *pPart,                    /* WHERE clause being processed */
+
  Bitmask *pMask,                 /* Mask to clear bits in */
+
  int iIdxCur,                    /* Cursor number for index */
+
  SrcItem *pItem                  /* The FROM clause entry for the table */
+
){
+
  assert( pItem==0 || (pItem->fg.jointype & JT_RIGHT)==0 );
+
  assert( (pItem==0 || pMask==0) && (pMask!=0 || pItem!=0) );
+

+
  if( pPart->op==TK_AND ){
+
    wherePartIdxExpr(pParse, pIdx, pPart->pRight, pMask, iIdxCur, pItem);
+
    pPart = pPart->pLeft;
+
  }
+

+
  if( (pPart->op==TK_EQ || pPart->op==TK_IS) ){
+
    Expr *pLeft = pPart->pLeft;
+
    Expr *pRight = pPart->pRight;
+
    u8 aff;
+

+
    if( pLeft->op!=TK_COLUMN ) return;
+
    if( !sqlite3ExprIsConstant(pRight) ) return;
+
    if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pParse, pPart)) ) return;
+
    if( pLeft->iColumn<0 ) return;
+
    aff = pIdx->pTable->aCol[pLeft->iColumn].affinity;
+
    if( aff>=SQLITE_AFF_TEXT ){
+
      if( pItem ){
+
        sqlite3 *db = pParse->db;
+
        IndexedExpr *p = (IndexedExpr*)sqlite3DbMallocRaw(db, sizeof(*p));
+
        if( p ){
+
          int bNullRow = (pItem->fg.jointype&(JT_LEFT|JT_LTORJ))!=0;
+
          p->pExpr = sqlite3ExprDup(db, pRight, 0);
+
          p->iDataCur = pItem->iCursor;
+
          p->iIdxCur = iIdxCur;
+
          p->iIdxCol = pLeft->iColumn;
+
          p->bMaybeNullRow = bNullRow;
+
          p->pIENext = pParse->pIdxPartExpr;
+
          p->aff = aff;
+
          pParse->pIdxPartExpr = p;
+
          if( p->pIENext==0 ){
+
            void *pArg = (void*)&pParse->pIdxPartExpr;
+
            sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
+
          }
+
        }
+
      }else if( pLeft->iColumn<(BMS-1) ){
+
        *pMask &= ~((Bitmask)1 << pLeft->iColumn);
+
      }
+
    }
+
  }
+
}
+

+

+
/*
** Add all WhereLoop objects for a single table of the join where the table
** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
** a b-tree table, not a virtual table.
@@ -162955,9 +164110,6 @@ static int whereLoopAddBtree(
#else
      pNew->rRun = rSize + 16;
#endif
-
      if( IsView(pTab) || (pTab->tabFlags & TF_Ephemeral)!=0 ){
-
        pNew->wsFlags |= WHERE_VIEWSCAN;
-
      }
      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
      whereLoopOutputAdjust(pWC, pNew, rSize);
      rc = whereLoopInsert(pBuilder, pNew);
@@ -162970,6 +164122,11 @@ static int whereLoopAddBtree(
        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
      }else{
        m = pSrc->colUsed & pProbe->colNotIdxed;
+
        if( pProbe->pPartIdxWhere ){
+
          wherePartIdxExpr(
+
              pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0
+
          );
+
        }
        pNew->wsFlags = WHERE_INDEXED;
        if( m==TOPBIT || (pProbe->bHasExpr && !pProbe->bHasVCol && m!=0) ){
          u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
@@ -163352,7 +164509,7 @@ SQLITE_API int sqlite3_vtab_rhs_value(
  sqlite3_value *pVal = 0;
  int rc = SQLITE_OK;
  if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
-
    rc = SQLITE_MISUSE; /* EV: R-30545-25046 */
+
    rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */
  }else{
    if( pH->aRhs[iCons]==0 ){
      WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
@@ -164376,14 +165533,6 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
          rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */
        }

-
        /* TUNING:  A full-scan of a VIEW or subquery in the outer loop
-
        ** is not so bad. */
-
        if( iLoop==0 && (pWLoop->wsFlags & WHERE_VIEWSCAN)!=0 && nLoop>1 ){
-
          rCost += -10;
-
          nOut += -30;
-
          WHERETRACE(0x80,("VIEWSCAN cost reduction for %c\n",pWLoop->cId));
-
        }
-

        /* Check to see if pWLoop should be added to the set of
        ** mxChoice best-so-far paths.
        **
@@ -164934,20 +166083,6 @@ static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
}

/*
-
** This is an sqlite3ParserAddCleanup() callback that is invoked to
-
** free the Parse->pIdxEpr list when the Parse object is destroyed.
-
*/
-
static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){
-
  Parse *pParse = (Parse*)pObject;
-
  while( pParse->pIdxEpr!=0 ){
-
    IndexedExpr *p = pParse->pIdxEpr;
-
    pParse->pIdxEpr = p->pIENext;
-
    sqlite3ExprDelete(db, p->pExpr);
-
    sqlite3DbFreeNN(db, p);
-
  }
-
}
-

-
/*
** The index pIdx is used by a query and contains one or more expressions.
** In other words pIdx is an index on an expression.  iIdxCur is the cursor
** number for the index and iDataCur is the cursor number for the corresponding
@@ -164986,6 +166121,20 @@ static SQLITE_NOINLINE void whereAddIndexedExpr(
      continue;
    }
    if( sqlite3ExprIsConstant(pExpr) ) continue;
+
    if( pExpr->op==TK_FUNCTION ){
+
      /* Functions that might set a subtype should not be replaced by the
+
      ** value taken from an expression index since the index omits the
+
      ** subtype.  https://sqlite.org/forum/forumpost/68d284c86b082c3e */
+
      int n;
+
      FuncDef *pDef;
+
      sqlite3 *db = pParse->db;
+
      assert( ExprUseXList(pExpr) );
+
      n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
+
      pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
+
      if( pDef==0 || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
+
        continue;
+
      }
+
    }
    p = sqlite3DbMallocRaw(pParse->db,  sizeof(IndexedExpr));
    if( p==0 ) break;
    p->pIENext = pParse->pIdxEpr;
@@ -165008,7 +166157,8 @@ static SQLITE_NOINLINE void whereAddIndexedExpr(
#endif
    pParse->pIdxEpr = p;
    if( p->pIENext==0 ){
-
      sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pParse);
+
      void *pArg = (void*)&pParse->pIdxEpr;
+
      sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
    }
  }
}
@@ -165398,6 +166548,16 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
       if( db->mallocFailed ) goto whereBeginError;
    }
+

+
    /* TUNING:  Assume that a DISTINCT clause on a subquery reduces
+
    ** the output size by a factor of 8 (LogEst -30).
+
    */
+
    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
+
      WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n",
+
                         pWInfo->nRowOut, pWInfo->nRowOut-30));
+
      pWInfo->nRowOut -= 30;
+
    }
+

  }
  assert( pWInfo->pTabList!=0 );
  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
@@ -165610,6 +166770,11 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
        if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
          whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem);
        }
+
        if( pIx->pPartIdxWhere && (pTabItem->fg.jointype & JT_RIGHT)==0 ){
+
          wherePartIdxExpr(
+
              pParse, pIx, pIx->pPartIdxWhere, 0, iIndexCur, pTabItem
+
          );
+
        }
      }
      pLevel->iIdxCur = iIndexCur;
      assert( pIx!=0 );
@@ -167152,7 +168317,7 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
      assert( ExprUseXList(pWin->pOwner) );
      assert( pWin->pWFunc!=0 );
      pArgs = pWin->pOwner->x.pList;
-
      if( pWin->pWFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
+
      if( pWin->pWFunc->funcFlags & SQLITE_SUBTYPE ){
        selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
        pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
        pWin->bExprArgs = 1;
@@ -167426,8 +168591,9 @@ SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
  if( p ){
    assert( p->op==TK_FUNCTION );
    assert( pWin );
+
    assert( ExprIsFullSize(p) );
    p->y.pWin = pWin;
-
    ExprSetProperty(p, EP_WinFunc);
+
    ExprSetProperty(p, EP_WinFunc|EP_FullSize);
    pWin->pOwner = p;
    if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
      sqlite3ErrorMsg(pParse,
@@ -169729,18 +170895,18 @@ typedef union {
#define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
#define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
#define YYFALLBACK 1
-
#define YYNSTATE             575
-
#define YYNRULE              403
-
#define YYNRULE_WITH_ACTION  338
+
#define YYNSTATE             579
+
#define YYNRULE              405
+
#define YYNRULE_WITH_ACTION  340
#define YYNTOKEN             185
-
#define YY_MAX_SHIFT         574
-
#define YY_MIN_SHIFTREDUCE   833
-
#define YY_MAX_SHIFTREDUCE   1235
-
#define YY_ERROR_ACTION      1236
-
#define YY_ACCEPT_ACTION     1237
-
#define YY_NO_ACTION         1238
-
#define YY_MIN_REDUCE        1239
-
#define YY_MAX_REDUCE        1641
+
#define YY_MAX_SHIFT         578
+
#define YY_MIN_SHIFTREDUCE   838
+
#define YY_MAX_SHIFTREDUCE   1242
+
#define YY_ERROR_ACTION      1243
+
#define YY_ACCEPT_ACTION     1244
+
#define YY_NO_ACTION         1245
+
#define YY_MIN_REDUCE        1246
+
#define YY_MAX_REDUCE        1650
/************* End control #defines *******************************************/
#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))

@@ -169807,218 +170973,218 @@ typedef union {
**  yy_default[]       Default action for each state.
**
*********** Begin parsing tables **********************************************/
-
#define YY_ACTTAB_COUNT (2096)
+
#define YY_ACTTAB_COUNT (2100)
static const YYACTIONTYPE yy_action[] = {
-
 /*     0 */   568,  208,  568,  118,  115,  229,  568,  118,  115,  229,
-
 /*    10 */   568, 1310,  377, 1289,  408,  562,  562,  562,  568,  409,
-
 /*    20 */   378, 1310, 1272,   41,   41,   41,   41,  208, 1520,   71,
-
 /*    30 */    71,  969,  419,   41,   41,  491,  303,  279,  303,  970,
-
 /*    40 */   397,   71,   71,  125,  126,   80, 1210, 1210, 1047, 1050,
-
 /*    50 */  1037, 1037,  123,  123,  124,  124,  124,  124,  476,  409,
-
 /*    60 */  1237,    1,    1,  574,    2, 1241,  550,  118,  115,  229,
-
 /*    70 */   317,  480,  146,  480,  524,  118,  115,  229,  529, 1323,
-
 /*    80 */   417,  523,  142,  125,  126,   80, 1210, 1210, 1047, 1050,
-
 /*    90 */  1037, 1037,  123,  123,  124,  124,  124,  124,  118,  115,
-
 /*   100 */   229,  327,  122,  122,  122,  122,  121,  121,  120,  120,
-
 /*   110 */   120,  119,  116,  444,  284,  284,  284,  284,  442,  442,
-
 /*   120 */   442, 1559,  376, 1561, 1186,  375, 1157,  565, 1157,  565,
-
 /*   130 */   409, 1559,  537,  259,  226,  444,  101,  145,  449,  316,
-
 /*   140 */   559,  240,  122,  122,  122,  122,  121,  121,  120,  120,
-
 /*   150 */   120,  119,  116,  444,  125,  126,   80, 1210, 1210, 1047,
-
 /*   160 */  1050, 1037, 1037,  123,  123,  124,  124,  124,  124,  142,
-
 /*   170 */   294, 1186,  339,  448,  120,  120,  120,  119,  116,  444,
-
 /*   180 */   127, 1186, 1187, 1186,  148,  441,  440,  568,  119,  116,
-
 /*   190 */   444,  124,  124,  124,  124,  117,  122,  122,  122,  122,
-
 /*   200 */   121,  121,  120,  120,  120,  119,  116,  444,  454,  113,
-
 /*   210 */    13,   13,  546,  122,  122,  122,  122,  121,  121,  120,
-
 /*   220 */   120,  120,  119,  116,  444,  422,  316,  559, 1186, 1187,
-
 /*   230 */  1186,  149, 1218,  409, 1218,  124,  124,  124,  124,  122,
-
 /*   240 */   122,  122,  122,  121,  121,  120,  120,  120,  119,  116,
-
 /*   250 */   444,  465,  342, 1034, 1034, 1048, 1051,  125,  126,   80,
-
 /*   260 */  1210, 1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,
-
 /*   270 */   124,  124, 1275,  522,  222, 1186,  568,  409,  224,  514,
-
 /*   280 */   175,   82,   83,  122,  122,  122,  122,  121,  121,  120,
-
 /*   290 */   120,  120,  119,  116,  444, 1005,   16,   16, 1186,  133,
-
 /*   300 */   133,  125,  126,   80, 1210, 1210, 1047, 1050, 1037, 1037,
-
 /*   310 */   123,  123,  124,  124,  124,  124,  122,  122,  122,  122,
-
 /*   320 */   121,  121,  120,  120,  120,  119,  116,  444, 1038,  546,
-
 /*   330 */  1186,  373, 1186, 1187, 1186,  252, 1429,  399,  504,  501,
-
 /*   340 */   500,  111,  560,  566,    4,  924,  924,  433,  499,  340,
-
 /*   350 */   460,  328,  360,  394, 1231, 1186, 1187, 1186,  563,  568,
-
 /*   360 */   122,  122,  122,  122,  121,  121,  120,  120,  120,  119,
-
 /*   370 */   116,  444,  284,  284,  369, 1572, 1598,  441,  440,  154,
-
 /*   380 */   409,  445,   71,   71, 1282,  565, 1215, 1186, 1187, 1186,
-
 /*   390 */    85, 1217,  271,  557,  543,  515,  515,  568,   98, 1216,
-
 /*   400 */     6, 1274,  472,  142,  125,  126,   80, 1210, 1210, 1047,
-
 /*   410 */  1050, 1037, 1037,  123,  123,  124,  124,  124,  124,  550,
-
 /*   420 */    13,   13, 1024,  507, 1218, 1186, 1218,  549,  109,  109,
-
 /*   430 */   222,  568, 1232,  175,  568,  427,  110,  197,  445,  569,
-
 /*   440 */   445,  430, 1546, 1014,  325,  551, 1186,  270,  287,  368,
-
 /*   450 */   510,  363,  509,  257,   71,   71,  543,   71,   71,  359,
-
 /*   460 */   316,  559, 1604,  122,  122,  122,  122,  121,  121,  120,
-
 /*   470 */   120,  120,  119,  116,  444, 1014, 1014, 1016, 1017,   27,
-
 /*   480 */   284,  284, 1186, 1187, 1186, 1152,  568, 1603,  409,  899,
-
 /*   490 */   190,  550,  356,  565,  550,  935,  533,  517, 1152,  516,
-
 /*   500 */   413, 1152,  552, 1186, 1187, 1186,  568,  544,  544,   51,
-
 /*   510 */    51,  214,  125,  126,   80, 1210, 1210, 1047, 1050, 1037,
-
 /*   520 */  1037,  123,  123,  124,  124,  124,  124, 1186,  474,  135,
-
 /*   530 */   135,  409,  284,  284, 1484,  505,  121,  121,  120,  120,
-
 /*   540 */   120,  119,  116,  444, 1005,  565,  518,  217,  541,  541,
-
 /*   550 */   316,  559,  142,    6,  532,  125,  126,   80, 1210, 1210,
-
 /*   560 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
-
 /*   570 */  1548,  122,  122,  122,  122,  121,  121,  120,  120,  120,
-
 /*   580 */   119,  116,  444,  485, 1186, 1187, 1186,  482,  281, 1263,
-
 /*   590 */   955,  252, 1186,  373,  504,  501,  500, 1186,  340,  570,
-
 /*   600 */  1186,  570,  409,  292,  499,  955,  874,  191,  480,  316,
-
 /*   610 */   559,  384,  290,  380,  122,  122,  122,  122,  121,  121,
-
 /*   620 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1210,
-
 /*   630 */  1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
-
 /*   640 */   124,  409,  394, 1132, 1186,  867,  100,  284,  284, 1186,
-
 /*   650 */  1187, 1186,  373, 1089, 1186, 1187, 1186, 1186, 1187, 1186,
-
 /*   660 */   565,  455,   32,  373,  233,  125,  126,   80, 1210, 1210,
-
 /*   670 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
-
 /*   680 */  1428,  957,  568,  228,  956,  122,  122,  122,  122,  121,
-
 /*   690 */   121,  120,  120,  120,  119,  116,  444, 1152,  228, 1186,
-
 /*   700 */   157, 1186, 1187, 1186, 1547,   13,   13,  301,  955, 1226,
-
 /*   710 */  1152,  153,  409, 1152,  373, 1575, 1170,    5,  369, 1572,
-
 /*   720 */   429, 1232,    3,  955,  122,  122,  122,  122,  121,  121,
-
 /*   730 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1210,
-
 /*   740 */  1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
-
 /*   750 */   124,  409,  208,  567, 1186, 1025, 1186, 1187, 1186, 1186,
-
 /*   760 */   388,  850,  155, 1546,  286,  402, 1094, 1094,  488,  568,
-
 /*   770 */   465,  342, 1315, 1315, 1546,  125,  126,   80, 1210, 1210,
-
 /*   780 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
-
 /*   790 */   129,  568,   13,   13,  374,  122,  122,  122,  122,  121,
-
 /*   800 */   121,  120,  120,  120,  119,  116,  444,  302,  568,  453,
-
 /*   810 */   528, 1186, 1187, 1186,   13,   13, 1186, 1187, 1186, 1293,
-
 /*   820 */   463, 1263,  409, 1313, 1313, 1546, 1010,  453,  452,  200,
-
 /*   830 */   299,   71,   71, 1261,  122,  122,  122,  122,  121,  121,
-
 /*   840 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1210,
-
 /*   850 */  1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
-
 /*   860 */   124,  409,  227, 1069, 1152,  284,  284,  419,  312,  278,
-
 /*   870 */   278,  285,  285, 1415,  406,  405,  382, 1152,  565,  568,
-
 /*   880 */  1152, 1189,  565, 1592,  565,  125,  126,   80, 1210, 1210,
-
 /*   890 */  1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,  124,
-
 /*   900 */   453, 1476,   13,   13, 1530,  122,  122,  122,  122,  121,
-
 /*   910 */   121,  120,  120,  120,  119,  116,  444,  201,  568,  354,
-
 /*   920 */  1578,  574,    2, 1241,  838,  839,  840, 1554,  317, 1205,
-
 /*   930 */   146,    6,  409,  255,  254,  253,  206, 1323,    9, 1189,
-
 /*   940 */   262,   71,   71,  424,  122,  122,  122,  122,  121,  121,
-
 /*   950 */   120,  120,  120,  119,  116,  444,  125,  126,   80, 1210,
-
 /*   960 */  1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
-
 /*   970 */   124,  568,  284,  284,  568, 1206,  409,  573,  313, 1241,
-
 /*   980 */   349, 1292,  352,  419,  317,  565,  146,  491,  525, 1635,
-
 /*   990 */   395,  371,  491, 1323,   70,   70, 1291,   71,   71,  240,
-
 /*  1000 */  1321,  104,   80, 1210, 1210, 1047, 1050, 1037, 1037,  123,
-
 /*  1010 */   123,  124,  124,  124,  124,  122,  122,  122,  122,  121,
-
 /*  1020 */   121,  120,  120,  120,  119,  116,  444, 1110,  284,  284,
-
 /*  1030 */   428,  448, 1519, 1206,  439,  284,  284, 1483, 1348,  311,
-
 /*  1040 */   474,  565, 1111,  969,  491,  491,  217, 1259,  565, 1532,
-
 /*  1050 */   568,  970,  207,  568, 1024,  240,  383, 1112,  519,  122,
-
 /*  1060 */   122,  122,  122,  121,  121,  120,  120,  120,  119,  116,
-
 /*  1070 */   444, 1015,  107,   71,   71, 1014,   13,   13,  910,  568,
-
 /*  1080 */  1489,  568,  284,  284,   97,  526,  491,  448,  911, 1322,
-
 /*  1090 */  1318,  545,  409,  284,  284,  565,  151,  209, 1489, 1491,
-
 /*  1100 */   262,  450,   55,   55,   56,   56,  565, 1014, 1014, 1016,
-
 /*  1110 */   443,  332,  409,  527,   12,  295,  125,  126,   80, 1210,
-
 /*  1120 */  1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
-
 /*  1130 */   124,  347,  409,  862, 1528, 1206,  125,  126,   80, 1210,
-
 /*  1140 */  1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
-
 /*  1150 */   124, 1133, 1633,  474, 1633,  371,  125,  114,   80, 1210,
-
 /*  1160 */  1210, 1047, 1050, 1037, 1037,  123,  123,  124,  124,  124,
-
 /*  1170 */   124, 1489,  329,  474,  331,  122,  122,  122,  122,  121,
-
 /*  1180 */   121,  120,  120,  120,  119,  116,  444,  203, 1415,  568,
-
 /*  1190 */  1290,  862,  464, 1206,  436,  122,  122,  122,  122,  121,
-
 /*  1200 */   121,  120,  120,  120,  119,  116,  444,  553, 1133, 1634,
-
 /*  1210 */   539, 1634,   15,   15,  890,  122,  122,  122,  122,  121,
-
 /*  1220 */   121,  120,  120,  120,  119,  116,  444,  568,  298,  538,
-
 /*  1230 */  1131, 1415, 1552, 1553, 1327,  409,    6,    6, 1163, 1264,
-
 /*  1240 */   415,  320,  284,  284, 1415,  508,  565,  525,  300,  457,
-
 /*  1250 */    43,   43,  568,  891,   12,  565,  330,  478,  425,  407,
-
 /*  1260 */   126,   80, 1210, 1210, 1047, 1050, 1037, 1037,  123,  123,
-
 /*  1270 */   124,  124,  124,  124,  568,   57,   57,  288, 1186, 1415,
-
 /*  1280 */   496,  458,  392,  392,  391,  273,  389, 1131, 1551,  847,
-
 /*  1290 */  1163,  407,    6,  568,  321, 1152,  470,   44,   44, 1550,
-
 /*  1300 */  1110,  426,  234,    6,  323,  256,  540,  256, 1152,  431,
-
 /*  1310 */   568, 1152,  322,   17,  487, 1111,   58,   58,  122,  122,
-
 /*  1320 */   122,  122,  121,  121,  120,  120,  120,  119,  116,  444,
-
 /*  1330 */  1112,  216,  481,   59,   59, 1186, 1187, 1186,  111,  560,
-
 /*  1340 */   324,    4,  236,  456,  526,  568,  237,  456,  568,  437,
-
 /*  1350 */   168,  556,  420,  141,  479,  563,  568,  293,  568, 1091,
-
 /*  1360 */   568,  293,  568, 1091,  531,  568,  870,    8,   60,   60,
-
 /*  1370 */   235,   61,   61,  568,  414,  568,  414,  568,  445,   62,
-
 /*  1380 */    62,   45,   45,   46,   46,   47,   47,  199,   49,   49,
-
 /*  1390 */   557,  568,  359,  568,  100,  486,   50,   50,   63,   63,
-
 /*  1400 */    64,   64,  561,  415,  535,  410,  568, 1024,  568,  534,
-
 /*  1410 */   316,  559,  316,  559,   65,   65,   14,   14,  568, 1024,
-
 /*  1420 */   568,  512,  930,  870, 1015,  109,  109,  929, 1014,   66,
-
 /*  1430 */    66,  131,  131,  110,  451,  445,  569,  445,  416,  177,
-
 /*  1440 */  1014,  132,  132,   67,   67,  568,  467,  568,  930,  471,
-
 /*  1450 */  1360,  283,  226,  929,  315, 1359,  407,  568,  459,  407,
-
 /*  1460 */  1014, 1014, 1016,  239,  407,   86,  213, 1346,   52,   52,
-
 /*  1470 */    68,   68, 1014, 1014, 1016, 1017,   27, 1577, 1174,  447,
-
 /*  1480 */    69,   69,  288,   97,  108, 1535,  106,  392,  392,  391,
-
 /*  1490 */   273,  389,  568,  877,  847,  881,  568,  111,  560,  466,
-
 /*  1500 */     4,  568,  152,   30,   38,  568, 1128,  234,  396,  323,
-
 /*  1510 */   111,  560,  527,    4,  563,   53,   53,  322,  568,  163,
-
 /*  1520 */   163,  568,  337,  468,  164,  164,  333,  563,   76,   76,
-
 /*  1530 */   568,  289, 1508,  568,   31, 1507,  568,  445,  338,  483,
-
 /*  1540 */   100,   54,   54,  344,   72,   72,  296,  236, 1076,  557,
-
 /*  1550 */   445,  877, 1356,  134,  134,  168,   73,   73,  141,  161,
-
 /*  1560 */   161, 1566,  557,  535,  568,  319,  568,  348,  536, 1007,
-
 /*  1570 */   473,  261,  261,  889,  888,  235,  535,  568, 1024,  568,
-
 /*  1580 */   475,  534,  261,  367,  109,  109,  521,  136,  136,  130,
-
 /*  1590 */   130, 1024,  110,  366,  445,  569,  445,  109,  109, 1014,
-
 /*  1600 */   162,  162,  156,  156,  568,  110, 1076,  445,  569,  445,
-
 /*  1610 */   410,  351, 1014,  568,  353,  316,  559,  568,  343,  568,
-
 /*  1620 */   100,  497,  357,  258,  100,  896,  897,  140,  140,  355,
-
 /*  1630 */  1306, 1014, 1014, 1016, 1017,   27,  139,  139,  362,  451,
-
 /*  1640 */   137,  137,  138,  138, 1014, 1014, 1016, 1017,   27, 1174,
-
 /*  1650 */   447,  568,  372,  288,  111,  560, 1018,    4,  392,  392,
-
 /*  1660 */   391,  273,  389,  568, 1137,  847,  568, 1072,  568,  258,
-
 /*  1670 */   492,  563,  568,  211,   75,   75,  555,  960,  234,  261,
-
 /*  1680 */   323,  111,  560,  927,    4,  113,   77,   77,  322,   74,
-
 /*  1690 */    74,   42,   42, 1369,  445,   48,   48, 1414,  563,  972,
-
 /*  1700 */   973, 1088, 1087, 1088, 1087,  860,  557,  150,  928, 1342,
-
 /*  1710 */   113, 1354,  554, 1419, 1018, 1271, 1262, 1250,  236, 1249,
-
 /*  1720 */  1251,  445, 1585, 1339,  308,  276,  168,  309,   11,  141,
-
 /*  1730 */   393,  310,  232,  557, 1401, 1024,  335,  291, 1396,  219,
-
 /*  1740 */   336,  109,  109,  934,  297, 1406,  235,  341,  477,  110,
-
 /*  1750 */   502,  445,  569,  445, 1389, 1405, 1014,  400, 1289,  365,
-
 /*  1760 */   223, 1480, 1024, 1479, 1351, 1352, 1350, 1349,  109,  109,
-
 /*  1770 */   204, 1588, 1226,  558,  265,  218,  110,  205,  445,  569,
-
 /*  1780 */   445,  410,  387, 1014, 1527,  179,  316,  559, 1014, 1014,
-
 /*  1790 */  1016, 1017,   27,  230, 1525, 1223,   79,  560,   85,    4,
-
 /*  1800 */   418,  215,  548,   81,   84,  188, 1402,  173,  181,  461,
-
 /*  1810 */   451,   35,  462,  563,  183, 1014, 1014, 1016, 1017,   27,
-
 /*  1820 */   184, 1485,  185,  186,  495,  242,   98,  398, 1408,   36,
-
 /*  1830 */  1407,  484,   91,  469,  401, 1410,  445,  192, 1474,  246,
-
 /*  1840 */  1496,  490,  346,  277,  248,  196,  493,  511,  557,  350,
-
 /*  1850 */  1252,  249,  250,  403, 1309, 1308,  111,  560,  432,    4,
-
 /*  1860 */  1307, 1300,   93, 1602,  881, 1601,  224,  404,  434,  520,
-
 /*  1870 */   263,  435, 1571,  563, 1279, 1278,  364, 1024,  306, 1277,
-
 /*  1880 */   264, 1600, 1557,  109,  109,  370, 1299,  307, 1556,  438,
-
 /*  1890 */   128,  110, 1374,  445,  569,  445,  445,  546, 1014,   10,
-
 /*  1900 */  1461,  105,  381, 1373,   34,  571,   99, 1332,  557,  314,
-
 /*  1910 */  1180,  530,  272,  274,  379,  210, 1331,  547,  385,  386,
-
 /*  1920 */   275,  572, 1247, 1242,  411,  412, 1512,  165,  178, 1513,
-
 /*  1930 */  1014, 1014, 1016, 1017,   27, 1511, 1510, 1024,   78,  147,
-
 /*  1940 */   166,  220,  221,  109,  109,  834,  304,  167,  446,  212,
-
 /*  1950 */   318,  110,  231,  445,  569,  445,  144, 1086, 1014, 1084,
-
 /*  1960 */   326,  180,  169, 1205,  182,  334,  238,  913,  241, 1100,
-
 /*  1970 */   187,  170,  171,  421,   87,   88,  423,  189,   89,   90,
-
 /*  1980 */   172, 1103,  243, 1099,  244,  158,   18,  245,  345,  247,
-
 /*  1990 */  1014, 1014, 1016, 1017,   27,  261, 1092,  193, 1220,  489,
-
 /*  2000 */   194,   37,  366,  849,  494,  251,  195,  506,   92,   19,
-
 /*  2010 */   498,  358,   20,  503,  879,  361,   94,  892,  305,  159,
-
 /*  2020 */   513,   39,   95, 1168,  160, 1053,  964, 1139,   96,  174,
-
 /*  2030 */  1138,  225,  280,  282,  198,  958,  113, 1158, 1154,  260,
-
 /*  2040 */    21,   22,   23, 1156, 1162, 1161, 1143,   24,   33,   25,
-
 /*  2050 */   202,  542,   26,  100, 1067,  102, 1054,  103,    7, 1052,
-
 /*  2060 */  1056, 1109, 1057, 1108,  266,  267,   28,   40,  390, 1019,
-
 /*  2070 */   861,  112,   29,  564, 1176, 1175,  268,  176,  143,  923,
-
 /*  2080 */  1238, 1238, 1238, 1238, 1238, 1238, 1238, 1238, 1238, 1238,
-
 /*  2090 */  1238, 1238, 1238, 1238,  269, 1593,
+
 /*     0 */   572,  210,  572,  119,  116,  231,  572,  119,  116,  231,
+
 /*    10 */   572, 1317,  379, 1296,  410,  566,  566,  566,  572,  411,
+
 /*    20 */   380, 1317, 1279,   42,   42,   42,   42,  210, 1529,   72,
+
 /*    30 */    72,  974,  421,   42,   42,  495,  305,  281,  305,  975,
+
 /*    40 */   399,   72,   72,  126,  127,   81, 1217, 1217, 1054, 1057,
+
 /*    50 */  1044, 1044,  124,  124,  125,  125,  125,  125,  480,  411,
+
 /*    60 */  1244,    1,    1,  578,    2, 1248,  554,  119,  116,  231,
+
 /*    70 */   319,  484,  147,  484,  528,  119,  116,  231,  533, 1330,
+
 /*    80 */   419,  527,  143,  126,  127,   81, 1217, 1217, 1054, 1057,
+
 /*    90 */  1044, 1044,  124,  124,  125,  125,  125,  125,  119,  116,
+
 /*   100 */   231,  329,  123,  123,  123,  123,  122,  122,  121,  121,
+
 /*   110 */   121,  120,  117,  448,  286,  286,  286,  286,  446,  446,
+
 /*   120 */   446, 1568,  378, 1570, 1193,  377, 1164,  569, 1164,  569,
+
 /*   130 */   411, 1568,  541,  261,  228,  448,  102,  146,  453,  318,
+
 /*   140 */   563,  242,  123,  123,  123,  123,  122,  122,  121,  121,
+
 /*   150 */   121,  120,  117,  448,  126,  127,   81, 1217, 1217, 1054,
+
 /*   160 */  1057, 1044, 1044,  124,  124,  125,  125,  125,  125,  143,
+
 /*   170 */   296, 1193,  341,  452,  121,  121,  121,  120,  117,  448,
+
 /*   180 */   128, 1193, 1194, 1193,  149,  445,  444,  572,  120,  117,
+
 /*   190 */   448,  125,  125,  125,  125,  118,  123,  123,  123,  123,
+
 /*   200 */   122,  122,  121,  121,  121,  120,  117,  448,  458,  114,
+
 /*   210 */    13,   13,  550,  123,  123,  123,  123,  122,  122,  121,
+
 /*   220 */   121,  121,  120,  117,  448,  424,  318,  563, 1193, 1194,
+
 /*   230 */  1193,  150, 1225,  411, 1225,  125,  125,  125,  125,  123,
+
 /*   240 */   123,  123,  123,  122,  122,  121,  121,  121,  120,  117,
+
 /*   250 */   448,  469,  344, 1041, 1041, 1055, 1058,  126,  127,   81,
+
 /*   260 */  1217, 1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,
+
 /*   270 */   125,  125, 1282,  526,  224, 1193,  572,  411,  226,  519,
+
 /*   280 */   177,   83,   84,  123,  123,  123,  123,  122,  122,  121,
+
 /*   290 */   121,  121,  120,  117,  448, 1010,   16,   16, 1193,  134,
+
 /*   300 */   134,  126,  127,   81, 1217, 1217, 1054, 1057, 1044, 1044,
+
 /*   310 */   124,  124,  125,  125,  125,  125,  123,  123,  123,  123,
+
 /*   320 */   122,  122,  121,  121,  121,  120,  117,  448, 1045,  550,
+
 /*   330 */  1193,  375, 1193, 1194, 1193,  254, 1438,  401,  508,  505,
+
 /*   340 */   504,  112,  564,  570,    4,  929,  929,  435,  503,  342,
+
 /*   350 */   464,  330,  362,  396, 1238, 1193, 1194, 1193,  567,  572,
+
 /*   360 */   123,  123,  123,  123,  122,  122,  121,  121,  121,  120,
+
 /*   370 */   117,  448,  286,  286,  371, 1581, 1607,  445,  444,  155,
+
 /*   380 */   411,  449,   72,   72, 1289,  569, 1222, 1193, 1194, 1193,
+
 /*   390 */    86, 1224,  273,  561,  547,  520,  520,  572,   99, 1223,
+
 /*   400 */     6, 1281,  476,  143,  126,  127,   81, 1217, 1217, 1054,
+
 /*   410 */  1057, 1044, 1044,  124,  124,  125,  125,  125,  125,  554,
+
 /*   420 */    13,   13, 1031,  511, 1225, 1193, 1225,  553,  110,  110,
+
 /*   430 */   224,  572, 1239,  177,  572,  429,  111,  199,  449,  573,
+
 /*   440 */   449,  432, 1555, 1019,  327,  555, 1193,  272,  289,  370,
+
 /*   450 */   514,  365,  513,  259,   72,   72,  547,   72,   72,  361,
+
 /*   460 */   318,  563, 1613,  123,  123,  123,  123,  122,  122,  121,
+
 /*   470 */   121,  121,  120,  117,  448, 1019, 1019, 1021, 1022,   28,
+
 /*   480 */   286,  286, 1193, 1194, 1193, 1159,  572, 1612,  411,  904,
+
 /*   490 */   192,  554,  358,  569,  554,  940,  537,  521, 1159,  437,
+
 /*   500 */   415, 1159,  556, 1193, 1194, 1193,  572,  548,  548,   52,
+
 /*   510 */    52,  216,  126,  127,   81, 1217, 1217, 1054, 1057, 1044,
+
 /*   520 */  1044,  124,  124,  125,  125,  125,  125, 1193,  478,  136,
+
 /*   530 */   136,  411,  286,  286, 1493,  509,  122,  122,  121,  121,
+
 /*   540 */   121,  120,  117,  448, 1010,  569,  522,  219,  545,  545,
+
 /*   550 */   318,  563,  143,    6,  536,  126,  127,   81, 1217, 1217,
+
 /*   560 */  1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,  125,
+
 /*   570 */  1557,  123,  123,  123,  123,  122,  122,  121,  121,  121,
+
 /*   580 */   120,  117,  448,  489, 1193, 1194, 1193,  486,  283, 1270,
+
 /*   590 */   960,  254, 1193,  375,  508,  505,  504, 1193,  342,  574,
+
 /*   600 */  1193,  574,  411,  294,  503,  960,  879,  193,  484,  318,
+
 /*   610 */   563,  386,  292,  382,  123,  123,  123,  123,  122,  122,
+
 /*   620 */   121,  121,  121,  120,  117,  448,  126,  127,   81, 1217,
+
 /*   630 */  1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,
+
 /*   640 */   125,  411,  396, 1139, 1193,  872,  101,  286,  286, 1193,
+
 /*   650 */  1194, 1193,  375, 1096, 1193, 1194, 1193, 1193, 1194, 1193,
+
 /*   660 */   569,  459,   33,  375,  235,  126,  127,   81, 1217, 1217,
+
 /*   670 */  1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,  125,
+
 /*   680 */  1437,  962,  572,  230,  961,  123,  123,  123,  123,  122,
+
 /*   690 */   122,  121,  121,  121,  120,  117,  448, 1159,  230, 1193,
+
 /*   700 */   158, 1193, 1194, 1193, 1556,   13,   13,  303,  960, 1233,
+
 /*   710 */  1159,  154,  411, 1159,  375, 1584, 1177,    5,  371, 1581,
+
 /*   720 */   431, 1239,    3,  960,  123,  123,  123,  123,  122,  122,
+
 /*   730 */   121,  121,  121,  120,  117,  448,  126,  127,   81, 1217,
+
 /*   740 */  1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,
+
 /*   750 */   125,  411,  210,  571, 1193, 1032, 1193, 1194, 1193, 1193,
+
 /*   760 */   390,  855,  156, 1555,  376,  404, 1101, 1101,  492,  572,
+
 /*   770 */   469,  344, 1322, 1322, 1555,  126,  127,   81, 1217, 1217,
+
 /*   780 */  1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,  125,
+
 /*   790 */   130,  572,   13,   13,  532,  123,  123,  123,  123,  122,
+
 /*   800 */   122,  121,  121,  121,  120,  117,  448,  304,  572,  457,
+
 /*   810 */   229, 1193, 1194, 1193,   13,   13, 1193, 1194, 1193, 1300,
+
 /*   820 */   467, 1270,  411, 1320, 1320, 1555, 1015,  457,  456,  436,
+
 /*   830 */   301,   72,   72, 1268,  123,  123,  123,  123,  122,  122,
+
 /*   840 */   121,  121,  121,  120,  117,  448,  126,  127,   81, 1217,
+
 /*   850 */  1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,
+
 /*   860 */   125,  411,  384, 1076, 1159,  286,  286,  421,  314,  280,
+
 /*   870 */   280,  287,  287,  461,  408,  407, 1539, 1159,  569,  572,
+
 /*   880 */  1159, 1196,  569,  409,  569,  126,  127,   81, 1217, 1217,
+
 /*   890 */  1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,  125,
+
 /*   900 */   457, 1485,   13,   13, 1541,  123,  123,  123,  123,  122,
+
 /*   910 */   122,  121,  121,  121,  120,  117,  448,  202,  572,  462,
+
 /*   920 */  1587,  578,    2, 1248,  843,  844,  845, 1563,  319,  409,
+
 /*   930 */   147,    6,  411,  257,  256,  255,  208, 1330,    9, 1196,
+
 /*   940 */   264,   72,   72, 1436,  123,  123,  123,  123,  122,  122,
+
 /*   950 */   121,  121,  121,  120,  117,  448,  126,  127,   81, 1217,
+
 /*   960 */  1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,
+
 /*   970 */   125,  572,  286,  286,  572, 1213,  411,  577,  315, 1248,
+
 /*   980 */   421,  371, 1581,  356,  319,  569,  147,  495,  529, 1644,
+
 /*   990 */   397,  935,  495, 1330,   71,   71,  934,   72,   72,  242,
+
 /*  1000 */  1328,  105,   81, 1217, 1217, 1054, 1057, 1044, 1044,  124,
+
 /*  1010 */   124,  125,  125,  125,  125,  123,  123,  123,  123,  122,
+
 /*  1020 */   122,  121,  121,  121,  120,  117,  448, 1117,  286,  286,
+
 /*  1030 */  1422,  452, 1528, 1213,  443,  286,  286, 1492, 1355,  313,
+
 /*  1040 */   478,  569, 1118,  454,  351,  495,  354, 1266,  569,  209,
+
 /*  1050 */   572,  418,  179,  572, 1031,  242,  385, 1119,  523,  123,
+
 /*  1060 */   123,  123,  123,  122,  122,  121,  121,  121,  120,  117,
+
 /*  1070 */   448, 1020,  108,   72,   72, 1019,   13,   13,  915,  572,
+
 /*  1080 */  1498,  572,  286,  286,   98,  530, 1537,  452,  916, 1334,
+
 /*  1090 */  1329,  203,  411,  286,  286,  569,  152,  211, 1498, 1500,
+
 /*  1100 */   426,  569,   56,   56,   57,   57,  569, 1019, 1019, 1021,
+
 /*  1110 */   447,  572,  411,  531,   12,  297,  126,  127,   81, 1217,
+
 /*  1120 */  1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,
+
 /*  1130 */   125,  572,  411,  867,   15,   15,  126,  127,   81, 1217,
+
 /*  1140 */  1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,
+
 /*  1150 */   125,  373,  529,  264,   44,   44,  126,  115,   81, 1217,
+
 /*  1160 */  1217, 1054, 1057, 1044, 1044,  124,  124,  125,  125,  125,
+
 /*  1170 */   125, 1498,  478, 1271,  417,  123,  123,  123,  123,  122,
+
 /*  1180 */   122,  121,  121,  121,  120,  117,  448,  205, 1213,  495,
+
 /*  1190 */   430,  867,  468,  322,  495,  123,  123,  123,  123,  122,
+
 /*  1200 */   122,  121,  121,  121,  120,  117,  448,  572,  557, 1140,
+
 /*  1210 */  1642, 1422, 1642,  543,  572,  123,  123,  123,  123,  122,
+
 /*  1220 */   122,  121,  121,  121,  120,  117,  448,  572, 1422,  572,
+
 /*  1230 */    13,   13,  542,  323, 1325,  411,  334,   58,   58,  349,
+
 /*  1240 */  1422, 1170,  326,  286,  286,  549, 1213,  300,  895,  530,
+
 /*  1250 */    45,   45,   59,   59, 1140, 1643,  569, 1643,  565,  417,
+
 /*  1260 */   127,   81, 1217, 1217, 1054, 1057, 1044, 1044,  124,  124,
+
 /*  1270 */   125,  125,  125,  125, 1367,  373,  500,  290, 1193,  512,
+
 /*  1280 */  1366,  427,  394,  394,  393,  275,  391,  896, 1138,  852,
+
 /*  1290 */   478,  258, 1422, 1170,  463, 1159,   12,  331,  428,  333,
+
 /*  1300 */  1117,  460,  236,  258,  325,  460,  544, 1544, 1159, 1098,
+
 /*  1310 */   491, 1159,  324, 1098,  440, 1118,  335,  516,  123,  123,
+
 /*  1320 */   123,  123,  122,  122,  121,  121,  121,  120,  117,  448,
+
 /*  1330 */  1119,  318,  563, 1138,  572, 1193, 1194, 1193,  112,  564,
+
 /*  1340 */   201,    4,  238,  433,  935,  490,  285,  228, 1517,  934,
+
 /*  1350 */   170,  560,  572,  142, 1516,  567,  572,   60,   60,  572,
+
 /*  1360 */   416,  572,  441,  572,  535,  302,  875,    8,  487,  572,
+
 /*  1370 */   237,  572,  416,  572,  485,   61,   61,  572,  449,   62,
+
 /*  1380 */    62,  332,   63,   63,   46,   46,   47,   47,  361,  572,
+
 /*  1390 */   561,  572,   48,   48,   50,   50,   51,   51,  572,  295,
+
 /*  1400 */    64,   64,  482,  295,  539,  412,  471, 1031,  572,  538,
+
 /*  1410 */   318,  563,   65,   65,   66,   66,  409,  475,  572, 1031,
+
 /*  1420 */   572,   14,   14,  875, 1020,  110,  110,  409, 1019,  572,
+
 /*  1430 */   474,   67,   67,  111,  455,  449,  573,  449,   98,  317,
+
 /*  1440 */  1019,  132,  132,  133,  133,  572, 1561,  572,  974,  409,
+
 /*  1450 */     6, 1562,   68,   68, 1560,    6,  975,  572,    6, 1559,
+
 /*  1460 */  1019, 1019, 1021,    6,  346,  218,  101,  531,   53,   53,
+
 /*  1470 */    69,   69, 1019, 1019, 1021, 1022,   28, 1586, 1181,  451,
+
 /*  1480 */    70,   70,  290,   87,  215,   31, 1363,  394,  394,  393,
+
 /*  1490 */   275,  391,  350,  109,  852,  107,  572,  112,  564,  483,
+
 /*  1500 */     4, 1212,  572,  239,  153,  572,   39,  236, 1299,  325,
+
 /*  1510 */   112,  564, 1298,    4,  567,  572,   32,  324,  572,   54,
+
 /*  1520 */    54,  572, 1135,  353,  398,  165,  165,  567,  166,  166,
+
 /*  1530 */   572,  291,  355,  572,   17,  357,  572,  449,   77,   77,
+
 /*  1540 */  1313,   55,   55, 1297,   73,   73,  572,  238,  470,  561,
+
 /*  1550 */   449,  472,  364,  135,  135,  170,   74,   74,  142,  163,
+
 /*  1560 */   163,  374,  561,  539,  572,  321,  572,  886,  540,  137,
+
 /*  1570 */   137,  339, 1353,  422,  298,  237,  539,  572, 1031,  572,
+
 /*  1580 */   340,  538,  101,  369,  110,  110,  162,  131,  131,  164,
+
 /*  1590 */   164, 1031,  111,  368,  449,  573,  449,  110,  110, 1019,
+
 /*  1600 */   157,  157,  141,  141,  572,  111,  572,  449,  573,  449,
+
 /*  1610 */   412,  288, 1019,  572,  882,  318,  563,  572,  219,  572,
+
 /*  1620 */   241, 1012,  477,  263,  263,  894,  893,  140,  140,  138,
+
 /*  1630 */   138, 1019, 1019, 1021, 1022,   28,  139,  139,  525,  455,
+
 /*  1640 */    76,   76,   78,   78, 1019, 1019, 1021, 1022,   28, 1181,
+
 /*  1650 */   451,  572, 1083,  290,  112,  564, 1575,    4,  394,  394,
+
 /*  1660 */   393,  275,  391,  572, 1023,  852,  572,  479,  345,  263,
+
 /*  1670 */   101,  567,  882, 1376,   75,   75, 1421,  501,  236,  260,
+
 /*  1680 */   325,  112,  564,  359,    4,  101,   43,   43,  324,   49,
+
 /*  1690 */    49,  901,  902,  161,  449,  101,  977,  978,  567, 1079,
+
 /*  1700 */  1349,  260,  965,  932,  263,  114,  561, 1095,  517, 1095,
+
 /*  1710 */  1083, 1094,  865, 1094,  151,  933, 1144,  114,  238, 1361,
+
 /*  1720 */   558,  449, 1023,  559, 1426, 1278,  170, 1269, 1257,  142,
+
 /*  1730 */  1601, 1256, 1258,  561, 1594, 1031,  496,  278,  213, 1346,
+
 /*  1740 */   310,  110,  110,  939,  311,  312,  237,   11,  234,  111,
+
 /*  1750 */   221,  449,  573,  449,  293,  395, 1019, 1408,  337, 1403,
+
 /*  1760 */  1396,  338, 1031,  299,  343, 1413, 1412,  481,  110,  110,
+
 /*  1770 */   506,  402,  225, 1296,  206,  367,  111, 1358,  449,  573,
+
 /*  1780 */   449,  412, 1359, 1019, 1489, 1488,  318,  563, 1019, 1019,
+
 /*  1790 */  1021, 1022,   28,  562,  207,  220,   80,  564,  389,    4,
+
 /*  1800 */  1597, 1357,  552, 1356, 1233,  181,  267,  232, 1536, 1534,
+
 /*  1810 */   455, 1230,  420,  567,   82, 1019, 1019, 1021, 1022,   28,
+
 /*  1820 */    86,  217,   85, 1494,  190,  175,  183,  465,  185,  466,
+
 /*  1830 */    36, 1409,  186,  187,  188,  499,  449,  244,   37,   99,
+
 /*  1840 */   400, 1415, 1414,  488, 1417,  194,  473,  403,  561, 1483,
+
 /*  1850 */   248,   92, 1505,  494,  198,  279,  112,  564,  250,    4,
+
 /*  1860 */   348,  497,  405,  352, 1259,  251,  252,  515, 1316,  434,
+
 /*  1870 */  1315, 1314,   94,  567, 1307,  886, 1306, 1031,  226,  406,
+
 /*  1880 */  1611, 1610,  438,  110,  110, 1580, 1286,  524,  439,  308,
+
 /*  1890 */   266,  111, 1285,  449,  573,  449,  449,  309, 1019,  366,
+
 /*  1900 */  1284, 1609,  265, 1566, 1565,  442,  372, 1381,  561,  129,
+
 /*  1910 */   550, 1380,   10, 1470,  383,  106,  316,  551,  100,   35,
+
 /*  1920 */   534,  575,  212, 1339,  381,  387, 1187, 1338,  274,  276,
+
 /*  1930 */  1019, 1019, 1021, 1022,   28,  277,  413, 1031,  576, 1254,
+
 /*  1940 */   388, 1521, 1249,  110,  110,  167, 1522,  168,  148, 1520,
+
 /*  1950 */  1519,  111,  306,  449,  573,  449,  222,  223, 1019,  839,
+
 /*  1960 */   169,   79,  450,  214,  414,  233,  320,  145, 1093, 1091,
+
 /*  1970 */   328,  182,  171, 1212,  918,  184,  240,  336,  243, 1107,
+
 /*  1980 */   189,  172,  173,  423,  425,   88,  180,  191,   89,   90,
+
 /*  1990 */  1019, 1019, 1021, 1022,   28,   91,  174, 1110,  245, 1106,
+
 /*  2000 */   246,  159,   18,  247,  347, 1099,  263,  195, 1227,  493,
+
 /*  2010 */   249,  196,   38,  854,  498,  368,  253,  360,  897,  197,
+
 /*  2020 */   502,   93,   19,   20,  507,  884,  363,  510,   95,  307,
+
 /*  2030 */   160,   96,  518,   97, 1175, 1060, 1146,   40,   21,  227,
+
 /*  2040 */   176, 1145,  282,  284,  969,  200,  963,  114,  262, 1165,
+
 /*  2050 */    22,   23,   24, 1161, 1169,   25, 1163, 1150,   34,   26,
+
 /*  2060 */  1168,  546,   27,  204,  101,  103,  104, 1074,    7, 1061,
+
 /*  2070 */  1059, 1063, 1116, 1064, 1115,  268,  269,   29,   41,  270,
+
 /*  2080 */  1024,  866,  113,   30,  568,  392, 1183,  144,  178, 1182,
+
 /*  2090 */   271,  928, 1245, 1245, 1245, 1245, 1245, 1245, 1245, 1602,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */   193,  193,  193,  274,  275,  276,  193,  274,  275,  276,
@@ -170097,7 +171263,7 @@ static const YYCODETYPE yy_lookahead[] = {
 /*   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,  193,  193,   59,   23,  116,  117,  118,   59,
-
 /*   760 */   201,   21,  241,  304,   22,  206,  127,  128,  129,  193,
+
 /*   760 */   201,   21,  241,  304,  193,  206,  127,  128,  129,  193,
 /*   770 */   128,  129,  235,  236,  304,   43,   44,   45,   46,   47,
 /*   780 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
 /*   790 */    22,  193,  216,  217,  193,  102,  103,  104,  105,  106,
@@ -170108,129 +171274,129 @@ static const YYCODETYPE yy_lookahead[] = {
 /*   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,  123,   76,  239,  240,  193,  253,  239,
-
 /*   870 */   240,  239,  240,  193,  106,  107,  193,   89,  252,  193,
-
 /*   880 */    92,   59,  252,  141,  252,   43,   44,   45,   46,   47,
+
 /*   870 */   240,  239,  240,  244,  106,  107,  193,   89,  252,  193,
+
 /*   880 */    92,   59,  252,  254,  252,   43,   44,   45,   46,   47,
 /*   890 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
 /*   900 */   284,  161,  216,  217,  193,  102,  103,  104,  105,  106,
-
 /*   910 */   107,  108,  109,  110,  111,  112,  113,  231,  193,   16,
-
 /*   920 */   187,  188,  189,  190,    7,    8,    9,  309,  195,   25,
+
 /*   910 */   107,  108,  109,  110,  111,  112,  113,  231,  193,  244,
+
 /*   920 */   187,  188,  189,  190,    7,    8,    9,  309,  195,  254,
 /*   930 */   197,  313,   19,  127,  128,  129,  262,  204,   22,  117,
-
 /*   940 */    24,  216,  217,  263,  102,  103,  104,  105,  106,  107,
+
 /*   940 */    24,  216,  217,  273,  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,  193,  239,  240,  193,   59,   19,  188,  253,  190,
-
 /*   980 */    77,  226,   79,  193,  195,  252,  197,  193,   19,  301,
-
 /*   990 */   302,  193,  193,  204,  216,  217,  226,  216,  217,  266,
+
 /*   980 */   193,  311,  312,   16,  195,  252,  197,  193,   19,  301,
+
 /*   990 */   302,  135,  193,  204,  216,  217,  140,  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 */   232,  298,  238,  117,  253,  239,  240,  238,  259,  260,
-
 /*  1040 */   193,  252,   27,   31,  193,  193,  142,  204,  252,  193,
-
 /*  1050 */   193,   39,  262,  193,  100,  266,  278,   42,  204,  102,
+
 /*  1030 */   193,  298,  238,  117,  253,  239,  240,  238,  259,  260,
+
 /*  1040 */   193,  252,   27,  193,   77,  193,   79,  204,  252,  262,
+
 /*  1050 */   193,  299,  300,  193,  100,  266,  278,   42,  204,  102,
 /*  1060 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  112,
 /*  1070 */   113,  117,  159,  216,  217,  121,  216,  217,   63,  193,
-
 /*  1080 */   193,  193,  239,  240,  115,  116,  193,  298,   73,  238,
+
 /*  1080 */   193,  193,  239,  240,  115,  116,  193,  298,   73,  240,
 /*  1090 */   238,  231,   19,  239,  240,  252,   22,   24,  211,  212,
-
 /*  1100 */    24,  193,  216,  217,  216,  217,  252,  153,  154,  155,
-
 /*  1110 */   253,   16,   19,  144,  213,  268,   43,   44,   45,   46,
+
 /*  1100 */   263,  252,  216,  217,  216,  217,  252,  153,  154,  155,
+
 /*  1110 */   253,  193,   19,  144,  213,  268,   43,   44,   45,   46,
 /*  1120 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
-
 /*  1130 */    57,  238,   19,   59,  193,   59,   43,   44,   45,   46,
+
 /*  1130 */    57,  193,   19,   59,  216,  217,   43,   44,   45,   46,
 /*  1140 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
-
 /*  1150 */    57,   22,   23,  193,   25,  193,   43,   44,   45,   46,
+
 /*  1150 */    57,  193,   19,   24,  216,  217,   43,   44,   45,   46,
 /*  1160 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
-
 /*  1170 */    57,  284,   77,  193,   79,  102,  103,  104,  105,  106,
-
 /*  1180 */   107,  108,  109,  110,  111,  112,  113,  286,  193,  193,
-
 /*  1190 */   193,  117,  291,  117,  232,  102,  103,  104,  105,  106,
-
 /*  1200 */   107,  108,  109,  110,  111,  112,  113,  204,   22,   23,
-
 /*  1210 */    66,   25,  216,  217,   35,  102,  103,  104,  105,  106,
-
 /*  1220 */   107,  108,  109,  110,  111,  112,  113,  193,  268,   85,
-
 /*  1230 */   101,  193,  309,  309,  240,   19,  313,  313,   94,  208,
-
 /*  1240 */   209,  193,  239,  240,  193,   66,  252,   19,  268,  244,
-
 /*  1250 */   216,  217,  193,   74,  213,  252,  161,   19,  263,  254,
+
 /*  1170 */    57,  284,  193,  208,  209,  102,  103,  104,  105,  106,
+
 /*  1180 */   107,  108,  109,  110,  111,  112,  113,  286,   59,  193,
+
 /*  1190 */   232,  117,  291,  193,  193,  102,  103,  104,  105,  106,
+
 /*  1200 */   107,  108,  109,  110,  111,  112,  113,  193,  204,   22,
+
 /*  1210 */    23,  193,   25,   66,  193,  102,  103,  104,  105,  106,
+
 /*  1220 */   107,  108,  109,  110,  111,  112,  113,  193,  193,  193,
+
 /*  1230 */   216,  217,   85,  193,  238,   19,   16,  216,  217,  238,
+
 /*  1240 */   193,   94,  193,  239,  240,  231,  117,  268,   35,  116,
+
 /*  1250 */   216,  217,  216,  217,   22,   23,  252,   25,  208,  209,
 /*  1260 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
-
 /*  1270 */    54,   55,   56,   57,  193,  216,  217,    5,   59,  193,
-
 /*  1280 */    19,  244,   10,   11,   12,   13,   14,  101,  309,   17,
-
 /*  1290 */   146,  254,  313,  193,  193,   76,  115,  216,  217,  309,
-
 /*  1300 */    12,  263,   30,  313,   32,   46,   87,   46,   89,  130,
-
 /*  1310 */   193,   92,   40,   22,  263,   27,  216,  217,  102,  103,
+
 /*  1270 */    54,   55,   56,   57,  193,  193,   19,    5,   59,   66,
+
 /*  1280 */   193,  263,   10,   11,   12,   13,   14,   74,  101,   17,
+
 /*  1290 */   193,   46,  193,  146,  193,   76,  213,   77,  263,   79,
+
 /*  1300 */    12,  260,   30,   46,   32,  264,   87,  193,   89,   29,
+
 /*  1310 */   263,   92,   40,   33,  232,   27,  193,  108,  102,  103,
 /*  1320 */   104,  105,  106,  107,  108,  109,  110,  111,  112,  113,
-
 /*  1330 */    42,  150,  291,  216,  217,  116,  117,  118,   19,   20,
-
 /*  1340 */   193,   22,   70,  260,  116,  193,   24,  264,  193,  263,
-
 /*  1350 */    78,   63,   61,   81,  116,   36,  193,  260,  193,   29,
-
 /*  1360 */   193,  264,  193,   33,  145,  193,   59,   48,  216,  217,
-
 /*  1370 */    98,  216,  217,  193,  115,  193,  115,  193,   59,  216,
-
 /*  1380 */   217,  216,  217,  216,  217,  216,  217,  255,  216,  217,
-
 /*  1390 */    71,  193,  131,  193,   25,   65,  216,  217,  216,  217,
-
 /*  1400 */   216,  217,  208,  209,   85,  133,  193,  100,  193,   90,
-
 /*  1410 */   138,  139,  138,  139,  216,  217,  216,  217,  193,  100,
-
 /*  1420 */   193,  108,  135,  116,  117,  106,  107,  140,  121,  216,
-
 /*  1430 */   217,  216,  217,  114,  162,  116,  117,  118,  299,  300,
-
 /*  1440 */   121,  216,  217,  216,  217,  193,  244,  193,  135,  244,
-
 /*  1450 */   193,  256,  257,  140,  244,  193,  254,  193,  193,  254,
-
 /*  1460 */   153,  154,  155,  141,  254,  149,  150,  258,  216,  217,
+
 /*  1330 */    42,  138,  139,  101,  193,  116,  117,  118,   19,   20,
+
 /*  1340 */   255,   22,   70,  130,  135,   65,  256,  257,  193,  140,
+
 /*  1350 */    78,   63,  193,   81,  193,   36,  193,  216,  217,  193,
+
 /*  1360 */   115,  193,  263,  193,  145,  268,   59,   48,  193,  193,
+
 /*  1370 */    98,  193,  115,  193,  291,  216,  217,  193,   59,  216,
+
 /*  1380 */   217,  161,  216,  217,  216,  217,  216,  217,  131,  193,
+
 /*  1390 */    71,  193,  216,  217,  216,  217,  216,  217,  193,  260,
+
 /*  1400 */   216,  217,   19,  264,   85,  133,  244,  100,  193,   90,
+
 /*  1410 */   138,  139,  216,  217,  216,  217,  254,  244,  193,  100,
+
 /*  1420 */   193,  216,  217,  116,  117,  106,  107,  254,  121,  193,
+
 /*  1430 */   115,  216,  217,  114,  162,  116,  117,  118,  115,  244,
+
 /*  1440 */   121,  216,  217,  216,  217,  193,  309,  193,   31,  254,
+
 /*  1450 */   313,  309,  216,  217,  309,  313,   39,  193,  313,  309,
+
 /*  1460 */   153,  154,  155,  313,  193,  150,   25,  144,  216,  217,
 /*  1470 */   216,  217,  153,  154,  155,  156,  157,    0,    1,    2,
-
 /*  1480 */   216,  217,    5,  115,  158,  193,  160,   10,   11,   12,
-
 /*  1490 */    13,   14,  193,   59,   17,  126,  193,   19,   20,  129,
-
 /*  1500 */    22,  193,   22,   22,   24,  193,   23,   30,   25,   32,
-
 /*  1510 */    19,   20,  144,   22,   36,  216,  217,   40,  193,  216,
-
 /*  1520 */   217,  193,  152,  129,  216,  217,  193,   36,  216,  217,
-
 /*  1530 */   193,   99,  193,  193,   53,  193,  193,   59,   23,  193,
-
 /*  1540 */    25,  216,  217,  193,  216,  217,  152,   70,   59,   71,
-
 /*  1550 */    59,  117,  193,  216,  217,   78,  216,  217,   81,  216,
-
 /*  1560 */   217,  318,   71,   85,  193,  133,  193,  193,   90,   23,
-
 /*  1570 */    23,   25,   25,  120,  121,   98,   85,  193,  100,  193,
-
 /*  1580 */    23,   90,   25,  121,  106,  107,   19,  216,  217,  216,
+
 /*  1480 */   216,  217,    5,  149,  150,   22,  193,   10,   11,   12,
+
 /*  1490 */    13,   14,  193,  158,   17,  160,  193,   19,   20,  116,
+
 /*  1500 */    22,   25,  193,   24,   22,  193,   24,   30,  226,   32,
+
 /*  1510 */    19,   20,  226,   22,   36,  193,   53,   40,  193,  216,
+
 /*  1520 */   217,  193,   23,  193,   25,  216,  217,   36,  216,  217,
+
 /*  1530 */   193,   99,  193,  193,   22,  193,  193,   59,  216,  217,
+
 /*  1540 */   193,  216,  217,  193,  216,  217,  193,   70,  129,   71,
+
 /*  1550 */    59,  129,  193,  216,  217,   78,  216,  217,   81,  216,
+
 /*  1560 */   217,  193,   71,   85,  193,  133,  193,  126,   90,  216,
+
 /*  1570 */   217,  152,  258,   61,  152,   98,   85,  193,  100,  193,
+
 /*  1580 */    23,   90,   25,  121,  106,  107,   23,  216,  217,  216,
 /*  1590 */   217,  100,  114,  131,  116,  117,  118,  106,  107,  121,
-
 /*  1600 */   216,  217,  216,  217,  193,  114,  117,  116,  117,  118,
-
 /*  1610 */   133,  193,  121,  193,  193,  138,  139,  193,   23,  193,
-
 /*  1620 */    25,   23,   23,   25,   25,    7,    8,  216,  217,  193,
-
 /*  1630 */   193,  153,  154,  155,  156,  157,  216,  217,  193,  162,
+
 /*  1600 */   216,  217,  216,  217,  193,  114,  193,  116,  117,  118,
+
 /*  1610 */   133,   22,  121,  193,   59,  138,  139,  193,  142,  193,
+
 /*  1620 */   141,   23,   23,   25,   25,  120,  121,  216,  217,  216,
+
 /*  1630 */   217,  153,  154,  155,  156,  157,  216,  217,   19,  162,
 /*  1640 */   216,  217,  216,  217,  153,  154,  155,  156,  157,    1,
-
 /*  1650 */     2,  193,  193,    5,   19,   20,   59,   22,   10,   11,
-
 /*  1660 */    12,   13,   14,  193,   97,   17,  193,   23,  193,   25,
-
 /*  1670 */   288,   36,  193,  242,  216,  217,  236,   23,   30,   25,
+
 /*  1650 */     2,  193,   59,    5,   19,   20,  318,   22,   10,   11,
+
 /*  1660 */    12,   13,   14,  193,   59,   17,  193,   23,   23,   25,
+
 /*  1670 */    25,   36,  117,  193,  216,  217,  193,   23,   30,   25,
 /*  1680 */    32,   19,   20,   23,   22,   25,  216,  217,   40,  216,
-
 /*  1690 */   217,  216,  217,  193,   59,  216,  217,  193,   36,   83,
-
 /*  1700 */    84,  153,  153,  155,  155,   23,   71,   25,   23,  193,
-
 /*  1710 */    25,  193,  193,  193,  117,  193,  193,  193,   70,  193,
-
 /*  1720 */   193,   59,  193,  255,  255,  287,   78,  255,  243,   81,
-
 /*  1730 */   191,  255,  297,   71,  271,  100,  293,  245,  267,  214,
-
 /*  1740 */   246,  106,  107,  108,  246,  271,   98,  245,  293,  114,
-
 /*  1750 */   220,  116,  117,  118,  267,  271,  121,  271,  225,  219,
-
 /*  1760 */   229,  219,  100,  219,  259,  259,  259,  259,  106,  107,
-
 /*  1770 */   249,  196,   60,  280,  141,  243,  114,  249,  116,  117,
-
 /*  1780 */   118,  133,  245,  121,  200,  297,  138,  139,  153,  154,
-
 /*  1790 */   155,  156,  157,  297,  200,   38,   19,   20,  151,   22,
-
 /*  1800 */   200,  150,  140,  294,  294,   22,  272,   43,  234,   18,
-
 /*  1810 */   162,  270,  200,   36,  237,  153,  154,  155,  156,  157,
-
 /*  1820 */   237,  283,  237,  237,   18,  199,  149,  246,  272,  270,
-
 /*  1830 */   272,  200,  158,  246,  246,  234,   59,  234,  246,  199,
-
 /*  1840 */   290,   62,  289,  200,  199,   22,  221,  115,   71,  200,
-
 /*  1850 */   200,  199,  199,  221,  218,  218,   19,   20,   64,   22,
-
 /*  1860 */   218,  227,   22,  224,  126,  224,  165,  221,   24,  305,
-
 /*  1870 */   200,  113,  312,   36,  218,  220,  218,  100,  282,  218,
-
 /*  1880 */    91,  218,  317,  106,  107,  221,  227,  282,  317,   82,
-
 /*  1890 */   148,  114,  265,  116,  117,  118,   59,  145,  121,   22,
-
 /*  1900 */   277,  158,  200,  265,   25,  202,  147,  250,   71,  279,
-
 /*  1910 */    13,  146,  194,  194,  249,  248,  250,  140,  247,  246,
-
 /*  1920 */     6,  192,  192,  192,  303,  303,  213,  207,  300,  213,
-
 /*  1930 */   153,  154,  155,  156,  157,  213,  213,  100,  213,  222,
-
 /*  1940 */   207,  214,  214,  106,  107,    4,  222,  207,    3,   22,
-
 /*  1950 */   163,  114,   15,  116,  117,  118,   16,   23,  121,   23,
-
 /*  1960 */   139,  151,  130,   25,  142,   16,   24,   20,  144,    1,
-
 /*  1970 */   142,  130,  130,   61,   53,   53,   37,  151,   53,   53,
-
 /*  1980 */   130,  116,   34,    1,  141,    5,   22,  115,  161,  141,
-
 /*  1990 */   153,  154,  155,  156,  157,   25,   68,   68,   75,   41,
-
 /*  2000 */   115,   24,  131,   20,   19,  125,   22,   96,   22,   22,
-
 /*  2010 */    67,   23,   22,   67,   59,   24,   22,   28,   67,   23,
-
 /*  2020 */    22,   22,  149,   23,   23,   23,  116,   23,   25,   37,
-
 /*  2030 */    97,  141,   23,   23,   22,  143,   25,   75,   88,   34,
-
 /*  2040 */    34,   34,   34,   86,   75,   93,   23,   34,   22,   34,
-
 /*  2050 */    25,   24,   34,   25,   23,  142,   23,  142,   44,   23,
-
 /*  2060 */    23,   23,   11,   23,   25,   22,   22,   22,   15,   23,
-
 /*  2070 */    23,   22,   22,   25,    1,    1,  141,   25,   23,  135,
-
 /*  2080 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
-
 /*  2090 */   319,  319,  319,  319,  141,  141,  319,  319,  319,  319,
+
 /*  1690 */   217,    7,    8,   23,   59,   25,   83,   84,   36,   23,
+
 /*  1700 */   193,   25,   23,   23,   25,   25,   71,  153,  145,  155,
+
 /*  1710 */   117,  153,   23,  155,   25,   23,   97,   25,   70,  193,
+
 /*  1720 */   193,   59,  117,  236,  193,  193,   78,  193,  193,   81,
+
 /*  1730 */   141,  193,  193,   71,  193,  100,  288,  287,  242,  255,
+
 /*  1740 */   255,  106,  107,  108,  255,  255,   98,  243,  297,  114,
+
 /*  1750 */   214,  116,  117,  118,  245,  191,  121,  271,  293,  267,
+
 /*  1760 */   267,  246,  100,  246,  245,  271,  271,  293,  106,  107,
+
 /*  1770 */   220,  271,  229,  225,  249,  219,  114,  259,  116,  117,
+
 /*  1780 */   118,  133,  259,  121,  219,  219,  138,  139,  153,  154,
+
 /*  1790 */   155,  156,  157,  280,  249,  243,   19,   20,  245,   22,
+
 /*  1800 */   196,  259,  140,  259,   60,  297,  141,  297,  200,  200,
+
 /*  1810 */   162,   38,  200,   36,  294,  153,  154,  155,  156,  157,
+
 /*  1820 */   151,  150,  294,  283,   22,   43,  234,   18,  237,  200,
+
 /*  1830 */   270,  272,  237,  237,  237,   18,   59,  199,  270,  149,
+
 /*  1840 */   246,  272,  272,  200,  234,  234,  246,  246,   71,  246,
+
 /*  1850 */   199,  158,  290,   62,   22,  200,   19,   20,  199,   22,
+
 /*  1860 */   289,  221,  221,  200,  200,  199,  199,  115,  218,   64,
+
 /*  1870 */   218,  218,   22,   36,  227,  126,  227,  100,  165,  221,
+
 /*  1880 */   224,  224,   24,  106,  107,  312,  218,  305,  113,  282,
+
 /*  1890 */    91,  114,  220,  116,  117,  118,   59,  282,  121,  218,
+
 /*  1900 */   218,  218,  200,  317,  317,   82,  221,  265,   71,  148,
+
 /*  1910 */   145,  265,   22,  277,  200,  158,  279,  140,  147,   25,
+
 /*  1920 */   146,  202,  248,  250,  249,  247,   13,  250,  194,  194,
+
 /*  1930 */   153,  154,  155,  156,  157,    6,  303,  100,  192,  192,
+
 /*  1940 */   246,  213,  192,  106,  107,  207,  213,  207,  222,  213,
+
 /*  1950 */   213,  114,  222,  116,  117,  118,  214,  214,  121,    4,
+
 /*  1960 */   207,  213,    3,   22,  303,   15,  163,   16,   23,   23,
+
 /*  1970 */   139,  151,  130,   25,   20,  142,   24,   16,  144,    1,
+
 /*  1980 */   142,  130,  130,   61,   37,   53,  300,  151,   53,   53,
+
 /*  1990 */   153,  154,  155,  156,  157,   53,  130,  116,   34,    1,
+
 /*  2000 */   141,    5,   22,  115,  161,   68,   25,   68,   75,   41,
+
 /*  2010 */   141,  115,   24,   20,   19,  131,  125,   23,   28,   22,
+
 /*  2020 */    67,   22,   22,   22,   67,   59,   24,   96,   22,   67,
+
 /*  2030 */    23,  149,   22,   25,   23,   23,   23,   22,   34,  141,
+
 /*  2040 */    37,   97,   23,   23,  116,   22,  143,   25,   34,   75,
+
 /*  2050 */    34,   34,   34,   88,   75,   34,   86,   23,   22,   34,
+
 /*  2060 */    93,   24,   34,   25,   25,  142,  142,   23,   44,   23,
+
 /*  2070 */    23,   23,   23,   11,   23,   25,   22,   22,   22,  141,
+
 /*  2080 */    23,   23,   22,   22,   25,   15,    1,   23,   25,    1,
+
 /*  2090 */   141,  135,  319,  319,  319,  319,  319,  319,  319,  141,
 /*  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,
@@ -170249,176 +171415,177 @@ static const YYCODETYPE yy_lookahead[] = {
 /*  2250 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2260 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
 /*  2270 */   319,  319,  319,  319,  319,  319,  319,  319,  319,  319,
-
 /*  2280 */   319,
+
 /*  2280 */   319,  319,  319,  319,  319,
};
-
#define YY_SHIFT_COUNT    (574)
+
#define YY_SHIFT_COUNT    (578)
#define YY_SHIFT_MIN      (0)
-
#define YY_SHIFT_MAX      (2074)
+
#define YY_SHIFT_MAX      (2088)
static const unsigned short int yy_shift_ofst[] = {
 /*     0 */  1648, 1477, 1272,  322,  322,    1, 1319, 1478, 1491, 1837,
 /*    10 */  1837, 1837,  471,    0,    0,  214, 1093, 1837, 1837, 1837,
 /*    20 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
-
 /*    30 */   271,  271, 1219, 1219,  216,   88,    1,    1,    1,    1,
-
 /*    40 */     1,   40,  111,  258,  361,  469,  512,  583,  622,  693,
-
 /*    50 */   732,  803,  842,  913, 1073, 1093, 1093, 1093, 1093, 1093,
+
 /*    30 */  1837,  271,  271, 1219, 1219,  216,   88,    1,    1,    1,
+
 /*    40 */     1,    1,   40,  111,  258,  361,  469,  512,  583,  622,
+
 /*    50 */   693,  732,  803,  842,  913, 1073, 1093, 1093, 1093, 1093,
 /*    60 */  1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093, 1093,
-
 /*    70 */  1093, 1093, 1093, 1113, 1093, 1216,  957,  957, 1635, 1662,
-
 /*    80 */  1777, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
+
 /*    70 */  1093, 1093, 1093, 1093, 1113, 1093, 1216,  957,  957, 1635,
+
 /*    80 */  1662, 1777, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*    90 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   100 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   110 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
 /*   120 */  1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837, 1837,
-
 /*   130 */   137,  181,  181,  181,  181,  181,  181,  181,   94,  430,
-
 /*   140 */    66,   65,  112,  366,  533,  533,  740, 1261,  533,  533,
-
 /*   150 */    79,   79,  533,  412,  412,  412,   77,  412,  123,  113,
-
 /*   160 */   113,   22,   22, 2096, 2096,  328,  328,  328,  239,  468,
-
 /*   170 */   468,  468,  468, 1015, 1015,  409,  366, 1129, 1186,  533,
-
 /*   180 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  533,
-
 /*   190 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  969,
-
 /*   200 */   621,  621,  533,  642,  788,  788, 1228, 1228,  822,  822,
-
 /*   210 */    67, 1274, 2096, 2096, 2096, 2096, 2096, 2096, 2096, 1307,
-
 /*   220 */   954,  954,  585,  472,  640,  387,  695,  538,  541,  700,
-
 /*   230 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  533,
-
 /*   240 */   222,  533,  533,  533,  533,  533,  533,  533,  533,  533,
-
 /*   250 */   533,  533,  533, 1179, 1179, 1179,  533,  533,  533,  565,
-
 /*   260 */   533,  533,  533,  916, 1144,  533,  533, 1288,  533,  533,
-
 /*   270 */   533,  533,  533,  533,  533,  533,  639, 1330,  209, 1076,
-
 /*   280 */  1076, 1076, 1076,  580,  209,  209, 1313,  768,  917,  649,
-
 /*   290 */  1181, 1316,  405, 1316, 1238,  249, 1181, 1181,  249, 1181,
-
 /*   300 */   405, 1238, 1369,  464, 1259, 1012, 1012, 1012, 1368, 1368,
-
 /*   310 */  1368, 1368,  184,  184, 1326,  904, 1287, 1480, 1712, 1712,
-
 /*   320 */  1633, 1633, 1757, 1757, 1633, 1647, 1651, 1783, 1764, 1791,
-
 /*   330 */  1791, 1791, 1791, 1633, 1806, 1677, 1651, 1651, 1677, 1783,
-
 /*   340 */  1764, 1677, 1764, 1677, 1633, 1806, 1674, 1779, 1633, 1806,
-
 /*   350 */  1823, 1633, 1806, 1633, 1806, 1823, 1732, 1732, 1732, 1794,
-
 /*   360 */  1840, 1840, 1823, 1732, 1738, 1732, 1794, 1732, 1732, 1701,
-
 /*   370 */  1844, 1758, 1758, 1823, 1633, 1789, 1789, 1807, 1807, 1742,
-
 /*   380 */  1752, 1877, 1633, 1743, 1742, 1759, 1765, 1677, 1879, 1897,
-
 /*   390 */  1897, 1914, 1914, 1914, 2096, 2096, 2096, 2096, 2096, 2096,
-
 /*   400 */  2096, 2096, 2096, 2096, 2096, 2096, 2096, 2096, 2096,  207,
-
 /*   410 */  1095,  331,  620,  903,  806, 1074, 1483, 1432, 1481, 1322,
-
 /*   420 */  1370, 1394, 1515, 1291, 1546, 1547, 1557, 1595, 1598, 1599,
-
 /*   430 */  1434, 1453, 1618, 1462, 1567, 1489, 1644, 1654, 1616, 1660,
-
 /*   440 */  1548, 1549, 1682, 1685, 1597,  742, 1941, 1945, 1927, 1787,
-
 /*   450 */  1937, 1940, 1934, 1936, 1821, 1810, 1832, 1938, 1938, 1942,
-
 /*   460 */  1822, 1947, 1824, 1949, 1968, 1828, 1841, 1938, 1842, 1912,
-
 /*   470 */  1939, 1938, 1826, 1921, 1922, 1925, 1926, 1850, 1865, 1948,
-
 /*   480 */  1843, 1982, 1980, 1964, 1872, 1827, 1928, 1970, 1929, 1923,
-
 /*   490 */  1958, 1848, 1885, 1977, 1983, 1985, 1871, 1880, 1984, 1943,
-
 /*   500 */  1986, 1987, 1988, 1990, 1946, 1955, 1991, 1911, 1989, 1994,
-
 /*   510 */  1951, 1992, 1996, 1873, 1998, 2000, 2001, 2002, 2003, 2004,
-
 /*   520 */  1999, 1933, 1890, 2009, 2010, 1910, 2005, 2012, 1892, 2011,
-
 /*   530 */  2006, 2007, 2008, 2013, 1950, 1962, 1957, 2014, 1969, 1952,
-
 /*   540 */  2015, 2023, 2026, 2027, 2025, 2028, 2018, 1913, 1915, 2031,
-
 /*   550 */  2011, 2033, 2036, 2037, 2038, 2039, 2040, 2043, 2051, 2044,
-
 /*   560 */  2045, 2046, 2047, 2049, 2050, 2048, 1944, 1935, 1953, 1954,
-
 /*   570 */  2052, 2055, 2053, 2073, 2074,
+
 /*   130 */  1837,  137,  181,  181,  181,  181,  181,  181,  181,   94,
+
 /*   140 */   430,   66,   65,  112,  366,  533,  533,  740, 1257,  533,
+
 /*   150 */   533,   79,   79,  533,  412,  412,  412,   77,  412,  123,
+
 /*   160 */   113,  113,  113,   22,   22, 2100, 2100,  328,  328,  328,
+
 /*   170 */   239,  468,  468,  468,  468, 1015, 1015,  409,  366, 1187,
+
 /*   180 */  1232,  533,  533,  533,  533,  533,  533,  533,  533,  533,
+
 /*   190 */   533,  533,  533,  533,  533,  533,  533,  533,  533,  533,
+
 /*   200 */   533,  969,  621,  621,  533,  642,  788,  788, 1133, 1133,
+
 /*   210 */   822,  822,   67, 1193, 2100, 2100, 2100, 2100, 2100, 2100,
+
 /*   220 */  2100, 1307,  954,  954,  585,  472,  640,  387,  695,  538,
+
 /*   230 */   541,  700,  533,  533,  533,  533,  533,  533,  533,  533,
+
 /*   240 */   533,  533,  222,  533,  533,  533,  533,  533,  533,  533,
+
 /*   250 */   533,  533,  533,  533,  533, 1213, 1213, 1213,  533,  533,
+
 /*   260 */   533,  565,  533,  533,  533,  916, 1147,  533,  533, 1288,
+
 /*   270 */   533,  533,  533,  533,  533,  533,  533,  533,  639, 1280,
+
 /*   280 */   209, 1129, 1129, 1129, 1129,  580,  209,  209, 1209,  768,
+
 /*   290 */   917,  649, 1315, 1334,  405, 1334, 1383,  249, 1315, 1315,
+
 /*   300 */   249, 1315,  405, 1383, 1441,  464, 1245, 1417, 1417, 1417,
+
 /*   310 */  1323, 1323, 1323, 1323,  184,  184, 1335, 1476,  856, 1482,
+
 /*   320 */  1744, 1744, 1665, 1665, 1773, 1773, 1665, 1669, 1671, 1802,
+
 /*   330 */  1782, 1809, 1809, 1809, 1809, 1665, 1817, 1690, 1671, 1671,
+
 /*   340 */  1690, 1802, 1782, 1690, 1782, 1690, 1665, 1817, 1693, 1791,
+
 /*   350 */  1665, 1817, 1832, 1665, 1817, 1665, 1817, 1832, 1752, 1752,
+
 /*   360 */  1752, 1805, 1850, 1850, 1832, 1752, 1749, 1752, 1805, 1752,
+
 /*   370 */  1752, 1713, 1858, 1775, 1775, 1832, 1665, 1799, 1799, 1823,
+
 /*   380 */  1823, 1761, 1765, 1890, 1665, 1757, 1761, 1771, 1774, 1690,
+
 /*   390 */  1894, 1913, 1913, 1929, 1929, 1929, 2100, 2100, 2100, 2100,
+
 /*   400 */  2100, 2100, 2100, 2100, 2100, 2100, 2100, 2100, 2100, 2100,
+
 /*   410 */  2100,  207, 1220,  331,  620,  967,  806, 1074, 1499, 1432,
+
 /*   420 */  1463, 1479, 1419, 1422, 1557, 1512, 1598, 1599, 1644, 1645,
+
 /*   430 */  1654, 1660, 1555, 1505, 1684, 1462, 1670, 1563, 1619, 1593,
+
 /*   440 */  1676, 1679, 1613, 1680, 1554, 1558, 1689, 1692, 1605, 1589,
+
 /*   450 */  1955, 1959, 1941, 1803, 1950, 1951, 1945, 1946, 1831, 1820,
+
 /*   460 */  1842, 1948, 1948, 1952, 1833, 1954, 1834, 1961, 1978, 1838,
+
 /*   470 */  1851, 1948, 1852, 1922, 1947, 1948, 1836, 1932, 1935, 1936,
+
 /*   480 */  1942, 1866, 1881, 1964, 1859, 1998, 1996, 1980, 1888, 1843,
+
 /*   490 */  1937, 1981, 1939, 1933, 1968, 1869, 1896, 1988, 1993, 1995,
+
 /*   500 */  1884, 1891, 1997, 1953, 1999, 2000, 1994, 2001, 1957, 1966,
+
 /*   510 */  2002, 1931, 1990, 2006, 1962, 2003, 2007, 2004, 1882, 2010,
+
 /*   520 */  2011, 2012, 2008, 2013, 2015, 1944, 1898, 2019, 2020, 1928,
+
 /*   530 */  2014, 2023, 1903, 2022, 2016, 2017, 2018, 2021, 1965, 1974,
+
 /*   540 */  1970, 2024, 1979, 1967, 2025, 2034, 2036, 2037, 2038, 2039,
+
 /*   550 */  2028, 1923, 1924, 2044, 2022, 2046, 2047, 2048, 2049, 2050,
+
 /*   560 */  2051, 2054, 2062, 2055, 2056, 2057, 2058, 2060, 2061, 2059,
+
 /*   570 */  1956, 1938, 1949, 1958, 2063, 2064, 2070, 2085, 2088,
};
-
#define YY_REDUCE_COUNT (408)
+
#define YY_REDUCE_COUNT (410)
#define YY_REDUCE_MIN   (-271)
-
#define YY_REDUCE_MAX   (1740)
+
#define YY_REDUCE_MAX   (1753)
static const short yy_reduce_ofst[] = {
 /*     0 */  -125,  733,  789,  241,  293, -123, -193, -191, -183, -187,
 /*    10 */   166,  238,  133, -207, -199, -267, -176,   -6,  204,  489,
-
 /*    20 */   576, -175,  598,  686,  615,  725,  860,  778,  781,  857,
-
 /*    30 */   616,  887,   87,  240, -192,  408,  626,  796,  843,  854,
-
 /*    40 */  1003, -271, -271, -271, -271, -271, -271, -271, -271, -271,
+
 /*    20 */   576,  598, -175,  686,  860,  615,  725, 1014,  778,  781,
+
 /*    30 */   857,  616,  887,   87,  240, -192,  408,  626,  796,  843,
+
 /*    40 */   854, 1004, -271, -271, -271, -271, -271, -271, -271, -271,
 /*    50 */  -271, -271, -271, -271, -271, -271, -271, -271, -271, -271,
 /*    60 */  -271, -271, -271, -271, -271, -271, -271, -271, -271, -271,
-
 /*    70 */  -271, -271, -271, -271, -271, -271, -271, -271,   80,   83,
-
 /*    80 */   313,  886,  888,  996, 1034, 1059, 1081, 1100, 1117, 1152,
-
 /*    90 */  1155, 1163, 1165, 1167, 1169, 1172, 1180, 1182, 1184, 1198,
-
 /*   100 */  1200, 1213, 1215, 1225, 1227, 1252, 1254, 1264, 1299, 1303,
-
 /*   110 */  1308, 1312, 1325, 1328, 1337, 1340, 1343, 1371, 1373, 1384,
-
 /*   120 */  1386, 1411, 1420, 1424, 1426, 1458, 1470, 1473, 1475, 1479,
-
 /*   130 */  -271, -271, -271, -271, -271, -271, -271, -271, -271, -271,
-
 /*   140 */  -271,  138,  459,  396, -158,  470,  302, -212,  521,  201,
-
 /*   150 */  -195,  -92,  559,  630,  632,  630, -271,  632,  901,   63,
-
 /*   160 */   407, -271, -271, -271, -271,  161,  161,  161,  251,  335,
-
 /*   170 */   847,  960,  980,  537,  588,  618,  628,  688,  688, -166,
-
 /*   180 */  -161,  674,  790,  794,  799,  851,  852, -122,  680, -120,
-
 /*   190 */   995, 1038,  415, 1051,  893,  798,  962,  400, 1086,  779,
-
 /*   200 */   923,  924,  263, 1041,  979,  990, 1083, 1097, 1031, 1194,
-
 /*   210 */   362,  994, 1139, 1005, 1037, 1202, 1205, 1195, 1210, -194,
-
 /*   220 */    56,  185, -135,  232,  522,  560,  601,  617,  669,  683,
-
 /*   230 */   711,  856,  908,  941, 1048, 1101, 1147, 1257, 1262, 1265,
-
 /*   240 */   392, 1292, 1333, 1339, 1342, 1346, 1350, 1359, 1374, 1418,
-
 /*   250 */  1421, 1436, 1437,  593,  755,  770,  997, 1445, 1459, 1209,
-
 /*   260 */  1500, 1504, 1516, 1132, 1243, 1518, 1519, 1440, 1520,  560,
-
 /*   270 */  1522, 1523, 1524, 1526, 1527, 1529, 1382, 1438, 1431, 1468,
-
 /*   280 */  1469, 1472, 1476, 1209, 1431, 1431, 1485, 1525, 1539, 1435,
-
 /*   290 */  1463, 1471, 1492, 1487, 1443, 1494, 1474, 1484, 1498, 1486,
-
 /*   300 */  1502, 1455, 1530, 1531, 1533, 1540, 1542, 1544, 1505, 1506,
-
 /*   310 */  1507, 1508, 1521, 1528, 1493, 1537, 1532, 1575, 1488, 1496,
-
 /*   320 */  1584, 1594, 1509, 1510, 1600, 1538, 1534, 1541, 1574, 1577,
-
 /*   330 */  1583, 1585, 1586, 1612, 1626, 1581, 1556, 1558, 1587, 1559,
-
 /*   340 */  1601, 1588, 1603, 1592, 1631, 1640, 1550, 1553, 1643, 1645,
-
 /*   350 */  1625, 1649, 1652, 1650, 1653, 1632, 1636, 1637, 1642, 1634,
-
 /*   360 */  1639, 1641, 1646, 1656, 1655, 1658, 1659, 1661, 1663, 1560,
-
 /*   370 */  1564, 1596, 1605, 1664, 1670, 1565, 1571, 1627, 1638, 1657,
-
 /*   380 */  1665, 1623, 1702, 1630, 1666, 1667, 1671, 1673, 1703, 1718,
-
 /*   390 */  1719, 1729, 1730, 1731, 1621, 1622, 1628, 1720, 1713, 1716,
-
 /*   400 */  1722, 1723, 1733, 1717, 1724, 1727, 1728, 1725, 1740,
+
 /*    70 */  -271, -271, -271, -271, -271, -271, -271, -271, -271,   80,
+
 /*    80 */    83,  313,  886,  888,  918,  938, 1021, 1034, 1036, 1141,
+
 /*    90 */  1159, 1163, 1166, 1168, 1170, 1176, 1178, 1180, 1184, 1196,
+
 /*   100 */  1198, 1205, 1215, 1225, 1227, 1236, 1252, 1254, 1264, 1303,
+
 /*   110 */  1309, 1312, 1322, 1325, 1328, 1337, 1340, 1343, 1353, 1371,
+
 /*   120 */  1373, 1384, 1386, 1411, 1413, 1420, 1424, 1426, 1458, 1470,
+
 /*   130 */  1473, -271, -271, -271, -271, -271, -271, -271, -271, -271,
+
 /*   140 */  -271, -271,  138,  459,  396, -158,  470,  302, -212,  521,
+
 /*   150 */   201, -195,  -92,  559,  630,  632,  630, -271,  632,  901,
+
 /*   160 */    63,  407,  670, -271, -271, -271, -271,  161,  161,  161,
+
 /*   170 */   251,  335,  847,  979, 1097,  537,  588,  618,  628,  688,
+
 /*   180 */   688, -166, -161,  674,  787,  794,  799,  852,  996, -122,
+
 /*   190 */   837, -120, 1018, 1035,  415, 1047, 1001,  958, 1082,  400,
+
 /*   200 */  1099,  779, 1137, 1142,  263, 1083, 1145, 1150, 1041, 1139,
+
 /*   210 */   965, 1050,  362,  849,  752,  629,  675, 1162, 1173, 1090,
+
 /*   220 */  1195, -194,   56,  185, -135,  232,  522,  560,  571,  601,
+
 /*   230 */   617,  669,  683,  711,  850,  893, 1000, 1040, 1049, 1081,
+
 /*   240 */  1087, 1101,  392, 1114, 1123, 1155, 1161, 1175, 1271, 1293,
+
 /*   250 */  1299, 1330, 1339, 1342, 1347,  593, 1282, 1286, 1350, 1359,
+
 /*   260 */  1368, 1314, 1480, 1483, 1507, 1085, 1338, 1526, 1527, 1487,
+
 /*   270 */  1531,  560, 1532, 1534, 1535, 1538, 1539, 1541, 1448, 1450,
+
 /*   280 */  1496, 1484, 1485, 1489, 1490, 1314, 1496, 1496, 1504, 1536,
+
 /*   290 */  1564, 1451, 1486, 1492, 1509, 1493, 1465, 1515, 1494, 1495,
+
 /*   300 */  1517, 1500, 1519, 1474, 1550, 1543, 1548, 1556, 1565, 1566,
+
 /*   310 */  1518, 1523, 1542, 1544, 1525, 1545, 1513, 1553, 1552, 1604,
+
 /*   320 */  1508, 1510, 1608, 1609, 1520, 1528, 1612, 1540, 1559, 1560,
+
 /*   330 */  1592, 1591, 1595, 1596, 1597, 1629, 1638, 1594, 1569, 1570,
+
 /*   340 */  1600, 1568, 1610, 1601, 1611, 1603, 1643, 1651, 1562, 1571,
+
 /*   350 */  1655, 1659, 1640, 1663, 1666, 1664, 1667, 1641, 1650, 1652,
+
 /*   360 */  1653, 1647, 1656, 1657, 1658, 1668, 1672, 1681, 1649, 1682,
+
 /*   370 */  1683, 1573, 1582, 1607, 1615, 1685, 1702, 1586, 1587, 1642,
+
 /*   380 */  1646, 1673, 1675, 1636, 1714, 1637, 1677, 1674, 1678, 1694,
+
 /*   390 */  1719, 1734, 1735, 1746, 1747, 1750, 1633, 1661, 1686, 1738,
+
 /*   400 */  1728, 1733, 1736, 1737, 1740, 1726, 1730, 1742, 1743, 1748,
+
 /*   410 */  1753,
};
static const YYACTIONTYPE yy_default[] = {
-
 /*     0 */  1639, 1639, 1639, 1469, 1236, 1347, 1236, 1236, 1236, 1469,
-
 /*    10 */  1469, 1469, 1236, 1377, 1377, 1522, 1269, 1236, 1236, 1236,
-
 /*    20 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1468, 1236, 1236,
-
 /*    30 */  1236, 1236, 1555, 1555, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*    40 */  1236, 1236, 1386, 1236, 1393, 1236, 1236, 1236, 1236, 1236,
-
 /*    50 */  1470, 1471, 1236, 1236, 1236, 1521, 1523, 1486, 1400, 1399,
-
 /*    60 */  1398, 1397, 1504, 1365, 1391, 1384, 1388, 1465, 1466, 1464,
-
 /*    70 */  1617, 1471, 1470, 1236, 1387, 1433, 1449, 1432, 1236, 1236,
-
 /*    80 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*    90 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   100 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   110 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   120 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   130 */  1441, 1448, 1447, 1446, 1455, 1445, 1442, 1435, 1434, 1436,
-
 /*   140 */  1437, 1236, 1236, 1260, 1236, 1236, 1257, 1311, 1236, 1236,
-
 /*   150 */  1236, 1236, 1236, 1541, 1540, 1236, 1438, 1236, 1269, 1427,
-
 /*   160 */  1426, 1452, 1439, 1451, 1450, 1529, 1591, 1590, 1487, 1236,
-
 /*   170 */  1236, 1236, 1236, 1236, 1236, 1555, 1236, 1236, 1236, 1236,
-
 /*   180 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   190 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1367,
-
 /*   200 */  1555, 1555, 1236, 1269, 1555, 1555, 1368, 1368, 1265, 1265,
-
 /*   210 */  1371, 1236, 1536, 1338, 1338, 1338, 1338, 1347, 1338, 1236,
-
 /*   220 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   230 */  1236, 1236, 1236, 1236, 1526, 1524, 1236, 1236, 1236, 1236,
-
 /*   240 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   250 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   260 */  1236, 1236, 1236, 1343, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   270 */  1236, 1236, 1236, 1236, 1236, 1584, 1236, 1499, 1325, 1343,
-
 /*   280 */  1343, 1343, 1343, 1345, 1326, 1324, 1337, 1270, 1243, 1631,
-
 /*   290 */  1403, 1392, 1344, 1392, 1628, 1390, 1403, 1403, 1390, 1403,
-
 /*   300 */  1344, 1628, 1286, 1606, 1281, 1377, 1377, 1377, 1367, 1367,
-
 /*   310 */  1367, 1367, 1371, 1371, 1467, 1344, 1337, 1236, 1631, 1631,
-
 /*   320 */  1353, 1353, 1630, 1630, 1353, 1487, 1614, 1412, 1314, 1320,
-
 /*   330 */  1320, 1320, 1320, 1353, 1254, 1390, 1614, 1614, 1390, 1412,
-
 /*   340 */  1314, 1390, 1314, 1390, 1353, 1254, 1503, 1625, 1353, 1254,
-
 /*   350 */  1477, 1353, 1254, 1353, 1254, 1477, 1312, 1312, 1312, 1301,
-
 /*   360 */  1236, 1236, 1477, 1312, 1286, 1312, 1301, 1312, 1312, 1573,
-
 /*   370 */  1236, 1481, 1481, 1477, 1353, 1565, 1565, 1380, 1380, 1385,
-
 /*   380 */  1371, 1472, 1353, 1236, 1385, 1383, 1381, 1390, 1304, 1587,
-
 /*   390 */  1587, 1583, 1583, 1583, 1636, 1636, 1536, 1599, 1269, 1269,
-
 /*   400 */  1269, 1269, 1599, 1288, 1288, 1270, 1270, 1269, 1599, 1236,
-
 /*   410 */  1236, 1236, 1236, 1236, 1236, 1594, 1236, 1531, 1488, 1357,
-
 /*   420 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   430 */  1236, 1236, 1236, 1236, 1542, 1236, 1236, 1236, 1236, 1236,
-
 /*   440 */  1236, 1236, 1236, 1236, 1236, 1417, 1236, 1239, 1533, 1236,
-
 /*   450 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1394, 1395, 1358,
-
 /*   460 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1409, 1236, 1236,
-
 /*   470 */  1236, 1404, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   480 */  1627, 1236, 1236, 1236, 1236, 1236, 1236, 1502, 1501, 1236,
-
 /*   490 */  1236, 1355, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   500 */  1236, 1236, 1236, 1236, 1236, 1284, 1236, 1236, 1236, 1236,
-
 /*   510 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   520 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1382,
-
 /*   530 */  1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   540 */  1236, 1236, 1236, 1236, 1570, 1372, 1236, 1236, 1236, 1236,
-
 /*   550 */  1618, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236,
-
 /*   560 */  1236, 1236, 1236, 1236, 1236, 1610, 1328, 1418, 1236, 1421,
-
 /*   570 */  1258, 1236, 1248, 1236, 1236,
+
 /*     0 */  1648, 1648, 1648, 1478, 1243, 1354, 1243, 1243, 1243, 1478,
+
 /*    10 */  1478, 1478, 1243, 1384, 1384, 1531, 1276, 1243, 1243, 1243,
+
 /*    20 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1477, 1243,
+
 /*    30 */  1243, 1243, 1243, 1564, 1564, 1243, 1243, 1243, 1243, 1243,
+
 /*    40 */  1243, 1243, 1243, 1393, 1243, 1400, 1243, 1243, 1243, 1243,
+
 /*    50 */  1243, 1479, 1480, 1243, 1243, 1243, 1530, 1532, 1495, 1407,
+
 /*    60 */  1406, 1405, 1404, 1513, 1372, 1398, 1391, 1395, 1474, 1475,
+
 /*    70 */  1473, 1626, 1480, 1479, 1243, 1394, 1442, 1458, 1441, 1243,
+
 /*    80 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*    90 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   100 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   110 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   120 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   130 */  1243, 1450, 1457, 1456, 1455, 1464, 1454, 1451, 1444, 1443,
+
 /*   140 */  1445, 1446, 1243, 1243, 1267, 1243, 1243, 1264, 1318, 1243,
+
 /*   150 */  1243, 1243, 1243, 1243, 1550, 1549, 1243, 1447, 1243, 1276,
+
 /*   160 */  1435, 1434, 1433, 1461, 1448, 1460, 1459, 1538, 1600, 1599,
+
 /*   170 */  1496, 1243, 1243, 1243, 1243, 1243, 1243, 1564, 1243, 1243,
+
 /*   180 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   190 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   200 */  1243, 1374, 1564, 1564, 1243, 1276, 1564, 1564, 1375, 1375,
+
 /*   210 */  1272, 1272, 1378, 1243, 1545, 1345, 1345, 1345, 1345, 1354,
+
 /*   220 */  1345, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   230 */  1243, 1243, 1243, 1243, 1243, 1243, 1535, 1533, 1243, 1243,
+
 /*   240 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   250 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   260 */  1243, 1243, 1243, 1243, 1243, 1350, 1243, 1243, 1243, 1243,
+
 /*   270 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1593, 1243, 1508,
+
 /*   280 */  1332, 1350, 1350, 1350, 1350, 1352, 1333, 1331, 1344, 1277,
+
 /*   290 */  1250, 1640, 1410, 1399, 1351, 1399, 1637, 1397, 1410, 1410,
+
 /*   300 */  1397, 1410, 1351, 1637, 1293, 1615, 1288, 1384, 1384, 1384,
+
 /*   310 */  1374, 1374, 1374, 1374, 1378, 1378, 1476, 1351, 1344, 1243,
+
 /*   320 */  1640, 1640, 1360, 1360, 1639, 1639, 1360, 1496, 1623, 1419,
+
 /*   330 */  1321, 1327, 1327, 1327, 1327, 1360, 1261, 1397, 1623, 1623,
+
 /*   340 */  1397, 1419, 1321, 1397, 1321, 1397, 1360, 1261, 1512, 1634,
+
 /*   350 */  1360, 1261, 1486, 1360, 1261, 1360, 1261, 1486, 1319, 1319,
+
 /*   360 */  1319, 1308, 1243, 1243, 1486, 1319, 1293, 1319, 1308, 1319,
+
 /*   370 */  1319, 1582, 1243, 1490, 1490, 1486, 1360, 1574, 1574, 1387,
+
 /*   380 */  1387, 1392, 1378, 1481, 1360, 1243, 1392, 1390, 1388, 1397,
+
 /*   390 */  1311, 1596, 1596, 1592, 1592, 1592, 1645, 1645, 1545, 1608,
+
 /*   400 */  1276, 1276, 1276, 1276, 1608, 1295, 1295, 1277, 1277, 1276,
+
 /*   410 */  1608, 1243, 1243, 1243, 1243, 1243, 1243, 1603, 1243, 1540,
+
 /*   420 */  1497, 1364, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   430 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1551, 1243,
+
 /*   440 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1424,
+
 /*   450 */  1243, 1246, 1542, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   460 */  1243, 1401, 1402, 1365, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   470 */  1243, 1416, 1243, 1243, 1243, 1411, 1243, 1243, 1243, 1243,
+
 /*   480 */  1243, 1243, 1243, 1243, 1636, 1243, 1243, 1243, 1243, 1243,
+
 /*   490 */  1243, 1511, 1510, 1243, 1243, 1362, 1243, 1243, 1243, 1243,
+
 /*   500 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1291,
+
 /*   510 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   520 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   530 */  1243, 1243, 1243, 1389, 1243, 1243, 1243, 1243, 1243, 1243,
+
 /*   540 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1579, 1379,
+
 /*   550 */  1243, 1243, 1243, 1243, 1627, 1243, 1243, 1243, 1243, 1243,
+
 /*   560 */  1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1243, 1619,
+
 /*   570 */  1335, 1425, 1243, 1428, 1265, 1243, 1255, 1243, 1243,
};
/********** End of lemon-generated parsing tables *****************************/

@@ -171225,221 +172392,223 @@ static const char *const yyRuleName[] = {
 /* 185 */ "expr ::= expr COLLATE ID|STRING",
 /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
 /* 187 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP",
-
 /* 188 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP",
-
 /* 189 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over",
-
 /* 190 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over",
-
 /* 191 */ "term ::= CTIME_KW",
-
 /* 192 */ "expr ::= LP nexprlist COMMA expr RP",
-
 /* 193 */ "expr ::= expr AND expr",
-
 /* 194 */ "expr ::= expr OR expr",
-
 /* 195 */ "expr ::= expr LT|GT|GE|LE expr",
-
 /* 196 */ "expr ::= expr EQ|NE expr",
-
 /* 197 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
-
 /* 198 */ "expr ::= expr PLUS|MINUS expr",
-
 /* 199 */ "expr ::= expr STAR|SLASH|REM expr",
-
 /* 200 */ "expr ::= expr CONCAT expr",
-
 /* 201 */ "likeop ::= NOT LIKE_KW|MATCH",
-
 /* 202 */ "expr ::= expr likeop expr",
-
 /* 203 */ "expr ::= expr likeop expr ESCAPE expr",
-
 /* 204 */ "expr ::= expr ISNULL|NOTNULL",
-
 /* 205 */ "expr ::= expr NOT NULL",
-
 /* 206 */ "expr ::= expr IS expr",
-
 /* 207 */ "expr ::= expr IS NOT expr",
-
 /* 208 */ "expr ::= expr IS NOT DISTINCT FROM expr",
-
 /* 209 */ "expr ::= expr IS DISTINCT FROM expr",
-
 /* 210 */ "expr ::= NOT expr",
-
 /* 211 */ "expr ::= BITNOT expr",
-
 /* 212 */ "expr ::= PLUS|MINUS expr",
-
 /* 213 */ "expr ::= expr PTR expr",
-
 /* 214 */ "between_op ::= BETWEEN",
-
 /* 215 */ "between_op ::= NOT BETWEEN",
-
 /* 216 */ "expr ::= expr between_op expr AND expr",
-
 /* 217 */ "in_op ::= IN",
-
 /* 218 */ "in_op ::= NOT IN",
-
 /* 219 */ "expr ::= expr in_op LP exprlist RP",
-
 /* 220 */ "expr ::= LP select RP",
-
 /* 221 */ "expr ::= expr in_op LP select RP",
-
 /* 222 */ "expr ::= expr in_op nm dbnm paren_exprlist",
-
 /* 223 */ "expr ::= EXISTS LP select RP",
-
 /* 224 */ "expr ::= CASE case_operand case_exprlist case_else END",
-
 /* 225 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
-
 /* 226 */ "case_exprlist ::= WHEN expr THEN expr",
-
 /* 227 */ "case_else ::= ELSE expr",
-
 /* 228 */ "case_else ::=",
-
 /* 229 */ "case_operand ::=",
-
 /* 230 */ "exprlist ::=",
-
 /* 231 */ "nexprlist ::= nexprlist COMMA expr",
-
 /* 232 */ "nexprlist ::= expr",
-
 /* 233 */ "paren_exprlist ::=",
-
 /* 234 */ "paren_exprlist ::= LP exprlist RP",
-
 /* 235 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
-
 /* 236 */ "uniqueflag ::= UNIQUE",
-
 /* 237 */ "uniqueflag ::=",
-
 /* 238 */ "eidlist_opt ::=",
-
 /* 239 */ "eidlist_opt ::= LP eidlist RP",
-
 /* 240 */ "eidlist ::= eidlist COMMA nm collate sortorder",
-
 /* 241 */ "eidlist ::= nm collate sortorder",
-
 /* 242 */ "collate ::=",
-
 /* 243 */ "collate ::= COLLATE ID|STRING",
-
 /* 244 */ "cmd ::= DROP INDEX ifexists fullname",
-
 /* 245 */ "cmd ::= VACUUM vinto",
-
 /* 246 */ "cmd ::= VACUUM nm vinto",
-
 /* 247 */ "vinto ::= INTO expr",
-
 /* 248 */ "vinto ::=",
-
 /* 249 */ "cmd ::= PRAGMA nm dbnm",
-
 /* 250 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
-
 /* 251 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
-
 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
-
 /* 253 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
-
 /* 254 */ "plus_num ::= PLUS INTEGER|FLOAT",
-
 /* 255 */ "minus_num ::= MINUS INTEGER|FLOAT",
-
 /* 256 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
-
 /* 257 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
-
 /* 258 */ "trigger_time ::= BEFORE|AFTER",
-
 /* 259 */ "trigger_time ::= INSTEAD OF",
-
 /* 260 */ "trigger_time ::=",
-
 /* 261 */ "trigger_event ::= DELETE|INSERT",
-
 /* 262 */ "trigger_event ::= UPDATE",
-
 /* 263 */ "trigger_event ::= UPDATE OF idlist",
-
 /* 264 */ "when_clause ::=",
-
 /* 265 */ "when_clause ::= WHEN expr",
-
 /* 266 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
-
 /* 267 */ "trigger_cmd_list ::= trigger_cmd SEMI",
-
 /* 268 */ "trnm ::= nm DOT nm",
-
 /* 269 */ "tridxby ::= INDEXED BY nm",
-
 /* 270 */ "tridxby ::= NOT INDEXED",
-
 /* 271 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
-
 /* 272 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
-
 /* 273 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
-
 /* 274 */ "trigger_cmd ::= scanpt select scanpt",
-
 /* 275 */ "expr ::= RAISE LP IGNORE RP",
-
 /* 276 */ "expr ::= RAISE LP raisetype COMMA nm RP",
-
 /* 277 */ "raisetype ::= ROLLBACK",
-
 /* 278 */ "raisetype ::= ABORT",
-
 /* 279 */ "raisetype ::= FAIL",
-
 /* 280 */ "cmd ::= DROP TRIGGER ifexists fullname",
-
 /* 281 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
-
 /* 282 */ "cmd ::= DETACH database_kw_opt expr",
-
 /* 283 */ "key_opt ::=",
-
 /* 284 */ "key_opt ::= KEY expr",
-
 /* 285 */ "cmd ::= REINDEX",
-
 /* 286 */ "cmd ::= REINDEX nm dbnm",
-
 /* 287 */ "cmd ::= ANALYZE",
-
 /* 288 */ "cmd ::= ANALYZE nm dbnm",
-
 /* 289 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
-
 /* 290 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
-
 /* 291 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm",
-
 /* 292 */ "add_column_fullname ::= fullname",
-
 /* 293 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
-
 /* 294 */ "cmd ::= create_vtab",
-
 /* 295 */ "cmd ::= create_vtab LP vtabarglist RP",
-
 /* 296 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
-
 /* 297 */ "vtabarg ::=",
-
 /* 298 */ "vtabargtoken ::= ANY",
-
 /* 299 */ "vtabargtoken ::= lp anylist RP",
-
 /* 300 */ "lp ::= LP",
-
 /* 301 */ "with ::= WITH wqlist",
-
 /* 302 */ "with ::= WITH RECURSIVE wqlist",
-
 /* 303 */ "wqas ::= AS",
-
 /* 304 */ "wqas ::= AS MATERIALIZED",
-
 /* 305 */ "wqas ::= AS NOT MATERIALIZED",
-
 /* 306 */ "wqitem ::= nm eidlist_opt wqas LP select RP",
-
 /* 307 */ "wqlist ::= wqitem",
-
 /* 308 */ "wqlist ::= wqlist COMMA wqitem",
-
 /* 309 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
-
 /* 310 */ "windowdefn ::= nm AS LP window RP",
-
 /* 311 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
-
 /* 312 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
-
 /* 313 */ "window ::= ORDER BY sortlist frame_opt",
-
 /* 314 */ "window ::= nm ORDER BY sortlist frame_opt",
-
 /* 315 */ "window ::= nm frame_opt",
-
 /* 316 */ "frame_opt ::=",
-
 /* 317 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
-
 /* 318 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
-
 /* 319 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
-
 /* 320 */ "frame_bound_s ::= frame_bound",
-
 /* 321 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
-
 /* 322 */ "frame_bound_e ::= frame_bound",
-
 /* 323 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
-
 /* 324 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
-
 /* 325 */ "frame_bound ::= CURRENT ROW",
-
 /* 326 */ "frame_exclude_opt ::=",
-
 /* 327 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
-
 /* 328 */ "frame_exclude ::= NO OTHERS",
-
 /* 329 */ "frame_exclude ::= CURRENT ROW",
-
 /* 330 */ "frame_exclude ::= GROUP|TIES",
-
 /* 331 */ "window_clause ::= WINDOW windowdefn_list",
-
 /* 332 */ "filter_over ::= filter_clause over_clause",
-
 /* 333 */ "filter_over ::= over_clause",
-
 /* 334 */ "filter_over ::= filter_clause",
-
 /* 335 */ "over_clause ::= OVER LP window RP",
-
 /* 336 */ "over_clause ::= OVER nm",
-
 /* 337 */ "filter_clause ::= FILTER LP WHERE expr RP",
-
 /* 338 */ "input ::= cmdlist",
-
 /* 339 */ "cmdlist ::= cmdlist ecmd",
-
 /* 340 */ "cmdlist ::= ecmd",
-
 /* 341 */ "ecmd ::= SEMI",
-
 /* 342 */ "ecmd ::= cmdx SEMI",
-
 /* 343 */ "ecmd ::= explain cmdx SEMI",
-
 /* 344 */ "trans_opt ::=",
-
 /* 345 */ "trans_opt ::= TRANSACTION",
-
 /* 346 */ "trans_opt ::= TRANSACTION nm",
-
 /* 347 */ "savepoint_opt ::= SAVEPOINT",
-
 /* 348 */ "savepoint_opt ::=",
-
 /* 349 */ "cmd ::= create_table create_table_args",
-
 /* 350 */ "table_option_set ::= table_option",
-
 /* 351 */ "columnlist ::= columnlist COMMA columnname carglist",
-
 /* 352 */ "columnlist ::= columnname carglist",
-
 /* 353 */ "nm ::= ID|INDEXED|JOIN_KW",
-
 /* 354 */ "nm ::= STRING",
-
 /* 355 */ "typetoken ::= typename",
-
 /* 356 */ "typename ::= ID|STRING",
-
 /* 357 */ "signed ::= plus_num",
-
 /* 358 */ "signed ::= minus_num",
-
 /* 359 */ "carglist ::= carglist ccons",
-
 /* 360 */ "carglist ::=",
-
 /* 361 */ "ccons ::= NULL onconf",
-
 /* 362 */ "ccons ::= GENERATED ALWAYS AS generated",
-
 /* 363 */ "ccons ::= AS generated",
-
 /* 364 */ "conslist_opt ::= COMMA conslist",
-
 /* 365 */ "conslist ::= conslist tconscomma tcons",
-
 /* 366 */ "conslist ::= tcons",
-
 /* 367 */ "tconscomma ::=",
-
 /* 368 */ "defer_subclause_opt ::= defer_subclause",
-
 /* 369 */ "resolvetype ::= raisetype",
-
 /* 370 */ "selectnowith ::= oneselect",
-
 /* 371 */ "oneselect ::= values",
-
 /* 372 */ "sclp ::= selcollist COMMA",
-
 /* 373 */ "as ::= ID|STRING",
-
 /* 374 */ "indexed_opt ::= indexed_by",
-
 /* 375 */ "returning ::=",
-
 /* 376 */ "expr ::= term",
-
 /* 377 */ "likeop ::= LIKE_KW|MATCH",
-
 /* 378 */ "case_operand ::= expr",
-
 /* 379 */ "exprlist ::= nexprlist",
-
 /* 380 */ "nmnum ::= plus_num",
-
 /* 381 */ "nmnum ::= nm",
-
 /* 382 */ "nmnum ::= ON",
-
 /* 383 */ "nmnum ::= DELETE",
-
 /* 384 */ "nmnum ::= DEFAULT",
-
 /* 385 */ "plus_num ::= INTEGER|FLOAT",
-
 /* 386 */ "foreach_clause ::=",
-
 /* 387 */ "foreach_clause ::= FOR EACH ROW",
-
 /* 388 */ "trnm ::= nm",
-
 /* 389 */ "tridxby ::=",
-
 /* 390 */ "database_kw_opt ::= DATABASE",
-
 /* 391 */ "database_kw_opt ::=",
-
 /* 392 */ "kwcolumn_opt ::=",
-
 /* 393 */ "kwcolumn_opt ::= COLUMNKW",
-
 /* 394 */ "vtabarglist ::= vtabarg",
-
 /* 395 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
-
 /* 396 */ "vtabarg ::= vtabarg vtabargtoken",
-
 /* 397 */ "anylist ::=",
-
 /* 398 */ "anylist ::= anylist LP anylist RP",
-
 /* 399 */ "anylist ::= anylist ANY",
-
 /* 400 */ "with ::=",
-
 /* 401 */ "windowdefn_list ::= windowdefn",
-
 /* 402 */ "window ::= frame_opt",
+
 /* 188 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP",
+
 /* 189 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP",
+
 /* 190 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over",
+
 /* 191 */ "expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over",
+
 /* 192 */ "expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over",
+
 /* 193 */ "term ::= CTIME_KW",
+
 /* 194 */ "expr ::= LP nexprlist COMMA expr RP",
+
 /* 195 */ "expr ::= expr AND expr",
+
 /* 196 */ "expr ::= expr OR expr",
+
 /* 197 */ "expr ::= expr LT|GT|GE|LE expr",
+
 /* 198 */ "expr ::= expr EQ|NE expr",
+
 /* 199 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
+
 /* 200 */ "expr ::= expr PLUS|MINUS expr",
+
 /* 201 */ "expr ::= expr STAR|SLASH|REM expr",
+
 /* 202 */ "expr ::= expr CONCAT expr",
+
 /* 203 */ "likeop ::= NOT LIKE_KW|MATCH",
+
 /* 204 */ "expr ::= expr likeop expr",
+
 /* 205 */ "expr ::= expr likeop expr ESCAPE expr",
+
 /* 206 */ "expr ::= expr ISNULL|NOTNULL",
+
 /* 207 */ "expr ::= expr NOT NULL",
+
 /* 208 */ "expr ::= expr IS expr",
+
 /* 209 */ "expr ::= expr IS NOT expr",
+
 /* 210 */ "expr ::= expr IS NOT DISTINCT FROM expr",
+
 /* 211 */ "expr ::= expr IS DISTINCT FROM expr",
+
 /* 212 */ "expr ::= NOT expr",
+
 /* 213 */ "expr ::= BITNOT expr",
+
 /* 214 */ "expr ::= PLUS|MINUS expr",
+
 /* 215 */ "expr ::= expr PTR expr",
+
 /* 216 */ "between_op ::= BETWEEN",
+
 /* 217 */ "between_op ::= NOT BETWEEN",
+
 /* 218 */ "expr ::= expr between_op expr AND expr",
+
 /* 219 */ "in_op ::= IN",
+
 /* 220 */ "in_op ::= NOT IN",
+
 /* 221 */ "expr ::= expr in_op LP exprlist RP",
+
 /* 222 */ "expr ::= LP select RP",
+
 /* 223 */ "expr ::= expr in_op LP select RP",
+
 /* 224 */ "expr ::= expr in_op nm dbnm paren_exprlist",
+
 /* 225 */ "expr ::= EXISTS LP select RP",
+
 /* 226 */ "expr ::= CASE case_operand case_exprlist case_else END",
+
 /* 227 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
+
 /* 228 */ "case_exprlist ::= WHEN expr THEN expr",
+
 /* 229 */ "case_else ::= ELSE expr",
+
 /* 230 */ "case_else ::=",
+
 /* 231 */ "case_operand ::=",
+
 /* 232 */ "exprlist ::=",
+
 /* 233 */ "nexprlist ::= nexprlist COMMA expr",
+
 /* 234 */ "nexprlist ::= expr",
+
 /* 235 */ "paren_exprlist ::=",
+
 /* 236 */ "paren_exprlist ::= LP exprlist RP",
+
 /* 237 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
+
 /* 238 */ "uniqueflag ::= UNIQUE",
+
 /* 239 */ "uniqueflag ::=",
+
 /* 240 */ "eidlist_opt ::=",
+
 /* 241 */ "eidlist_opt ::= LP eidlist RP",
+
 /* 242 */ "eidlist ::= eidlist COMMA nm collate sortorder",
+
 /* 243 */ "eidlist ::= nm collate sortorder",
+
 /* 244 */ "collate ::=",
+
 /* 245 */ "collate ::= COLLATE ID|STRING",
+
 /* 246 */ "cmd ::= DROP INDEX ifexists fullname",
+
 /* 247 */ "cmd ::= VACUUM vinto",
+
 /* 248 */ "cmd ::= VACUUM nm vinto",
+
 /* 249 */ "vinto ::= INTO expr",
+
 /* 250 */ "vinto ::=",
+
 /* 251 */ "cmd ::= PRAGMA nm dbnm",
+
 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
+
 /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
+
 /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
+
 /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
+
 /* 256 */ "plus_num ::= PLUS INTEGER|FLOAT",
+
 /* 257 */ "minus_num ::= MINUS INTEGER|FLOAT",
+
 /* 258 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
+
 /* 259 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
+
 /* 260 */ "trigger_time ::= BEFORE|AFTER",
+
 /* 261 */ "trigger_time ::= INSTEAD OF",
+
 /* 262 */ "trigger_time ::=",
+
 /* 263 */ "trigger_event ::= DELETE|INSERT",
+
 /* 264 */ "trigger_event ::= UPDATE",
+
 /* 265 */ "trigger_event ::= UPDATE OF idlist",
+
 /* 266 */ "when_clause ::=",
+
 /* 267 */ "when_clause ::= WHEN expr",
+
 /* 268 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
+
 /* 269 */ "trigger_cmd_list ::= trigger_cmd SEMI",
+
 /* 270 */ "trnm ::= nm DOT nm",
+
 /* 271 */ "tridxby ::= INDEXED BY nm",
+
 /* 272 */ "tridxby ::= NOT INDEXED",
+
 /* 273 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
+
 /* 274 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
+
 /* 275 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
+
 /* 276 */ "trigger_cmd ::= scanpt select scanpt",
+
 /* 277 */ "expr ::= RAISE LP IGNORE RP",
+
 /* 278 */ "expr ::= RAISE LP raisetype COMMA nm RP",
+
 /* 279 */ "raisetype ::= ROLLBACK",
+
 /* 280 */ "raisetype ::= ABORT",
+
 /* 281 */ "raisetype ::= FAIL",
+
 /* 282 */ "cmd ::= DROP TRIGGER ifexists fullname",
+
 /* 283 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
+
 /* 284 */ "cmd ::= DETACH database_kw_opt expr",
+
 /* 285 */ "key_opt ::=",
+
 /* 286 */ "key_opt ::= KEY expr",
+
 /* 287 */ "cmd ::= REINDEX",
+
 /* 288 */ "cmd ::= REINDEX nm dbnm",
+
 /* 289 */ "cmd ::= ANALYZE",
+
 /* 290 */ "cmd ::= ANALYZE nm dbnm",
+
 /* 291 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
+
 /* 292 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
+
 /* 293 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm",
+
 /* 294 */ "add_column_fullname ::= fullname",
+
 /* 295 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
+
 /* 296 */ "cmd ::= create_vtab",
+
 /* 297 */ "cmd ::= create_vtab LP vtabarglist RP",
+
 /* 298 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
+
 /* 299 */ "vtabarg ::=",
+
 /* 300 */ "vtabargtoken ::= ANY",
+
 /* 301 */ "vtabargtoken ::= lp anylist RP",
+
 /* 302 */ "lp ::= LP",
+
 /* 303 */ "with ::= WITH wqlist",
+
 /* 304 */ "with ::= WITH RECURSIVE wqlist",
+
 /* 305 */ "wqas ::= AS",
+
 /* 306 */ "wqas ::= AS MATERIALIZED",
+
 /* 307 */ "wqas ::= AS NOT MATERIALIZED",
+
 /* 308 */ "wqitem ::= nm eidlist_opt wqas LP select RP",
+
 /* 309 */ "wqlist ::= wqitem",
+
 /* 310 */ "wqlist ::= wqlist COMMA wqitem",
+
 /* 311 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
+
 /* 312 */ "windowdefn ::= nm AS LP window RP",
+
 /* 313 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
+
 /* 314 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
+
 /* 315 */ "window ::= ORDER BY sortlist frame_opt",
+
 /* 316 */ "window ::= nm ORDER BY sortlist frame_opt",
+
 /* 317 */ "window ::= nm frame_opt",
+
 /* 318 */ "frame_opt ::=",
+
 /* 319 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
+
 /* 320 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
+
 /* 321 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
+
 /* 322 */ "frame_bound_s ::= frame_bound",
+
 /* 323 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
+
 /* 324 */ "frame_bound_e ::= frame_bound",
+
 /* 325 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
+
 /* 326 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
+
 /* 327 */ "frame_bound ::= CURRENT ROW",
+
 /* 328 */ "frame_exclude_opt ::=",
+
 /* 329 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
+
 /* 330 */ "frame_exclude ::= NO OTHERS",
+
 /* 331 */ "frame_exclude ::= CURRENT ROW",
+
 /* 332 */ "frame_exclude ::= GROUP|TIES",
+
 /* 333 */ "window_clause ::= WINDOW windowdefn_list",
+
 /* 334 */ "filter_over ::= filter_clause over_clause",
+
 /* 335 */ "filter_over ::= over_clause",
+
 /* 336 */ "filter_over ::= filter_clause",
+
 /* 337 */ "over_clause ::= OVER LP window RP",
+
 /* 338 */ "over_clause ::= OVER nm",
+
 /* 339 */ "filter_clause ::= FILTER LP WHERE expr RP",
+
 /* 340 */ "input ::= cmdlist",
+
 /* 341 */ "cmdlist ::= cmdlist ecmd",
+
 /* 342 */ "cmdlist ::= ecmd",
+
 /* 343 */ "ecmd ::= SEMI",
+
 /* 344 */ "ecmd ::= cmdx SEMI",
+
 /* 345 */ "ecmd ::= explain cmdx SEMI",
+
 /* 346 */ "trans_opt ::=",
+
 /* 347 */ "trans_opt ::= TRANSACTION",
+
 /* 348 */ "trans_opt ::= TRANSACTION nm",
+
 /* 349 */ "savepoint_opt ::= SAVEPOINT",
+
 /* 350 */ "savepoint_opt ::=",
+
 /* 351 */ "cmd ::= create_table create_table_args",
+
 /* 352 */ "table_option_set ::= table_option",
+
 /* 353 */ "columnlist ::= columnlist COMMA columnname carglist",
+
 /* 354 */ "columnlist ::= columnname carglist",
+
 /* 355 */ "nm ::= ID|INDEXED|JOIN_KW",
+
 /* 356 */ "nm ::= STRING",
+
 /* 357 */ "typetoken ::= typename",
+
 /* 358 */ "typename ::= ID|STRING",
+
 /* 359 */ "signed ::= plus_num",
+
 /* 360 */ "signed ::= minus_num",
+
 /* 361 */ "carglist ::= carglist ccons",
+
 /* 362 */ "carglist ::=",
+
 /* 363 */ "ccons ::= NULL onconf",
+
 /* 364 */ "ccons ::= GENERATED ALWAYS AS generated",
+
 /* 365 */ "ccons ::= AS generated",
+
 /* 366 */ "conslist_opt ::= COMMA conslist",
+
 /* 367 */ "conslist ::= conslist tconscomma tcons",
+
 /* 368 */ "conslist ::= tcons",
+
 /* 369 */ "tconscomma ::=",
+
 /* 370 */ "defer_subclause_opt ::= defer_subclause",
+
 /* 371 */ "resolvetype ::= raisetype",
+
 /* 372 */ "selectnowith ::= oneselect",
+
 /* 373 */ "oneselect ::= values",
+
 /* 374 */ "sclp ::= selcollist COMMA",
+
 /* 375 */ "as ::= ID|STRING",
+
 /* 376 */ "indexed_opt ::= indexed_by",
+
 /* 377 */ "returning ::=",
+
 /* 378 */ "expr ::= term",
+
 /* 379 */ "likeop ::= LIKE_KW|MATCH",
+
 /* 380 */ "case_operand ::= expr",
+
 /* 381 */ "exprlist ::= nexprlist",
+
 /* 382 */ "nmnum ::= plus_num",
+
 /* 383 */ "nmnum ::= nm",
+
 /* 384 */ "nmnum ::= ON",
+
 /* 385 */ "nmnum ::= DELETE",
+
 /* 386 */ "nmnum ::= DEFAULT",
+
 /* 387 */ "plus_num ::= INTEGER|FLOAT",
+
 /* 388 */ "foreach_clause ::=",
+
 /* 389 */ "foreach_clause ::= FOR EACH ROW",
+
 /* 390 */ "trnm ::= nm",
+
 /* 391 */ "tridxby ::=",
+
 /* 392 */ "database_kw_opt ::= DATABASE",
+
 /* 393 */ "database_kw_opt ::=",
+
 /* 394 */ "kwcolumn_opt ::=",
+
 /* 395 */ "kwcolumn_opt ::= COLUMNKW",
+
 /* 396 */ "vtabarglist ::= vtabarg",
+
 /* 397 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
+
 /* 398 */ "vtabarg ::= vtabarg vtabargtoken",
+
 /* 399 */ "anylist ::=",
+
 /* 400 */ "anylist ::= anylist LP anylist RP",
+
 /* 401 */ "anylist ::= anylist ANY",
+
 /* 402 */ "with ::=",
+
 /* 403 */ "windowdefn_list ::= windowdefn",
+
 /* 404 */ "window ::= frame_opt",
};
#endif /* NDEBUG */

@@ -172134,221 +173303,223 @@ static const YYCODETYPE yyRuleInfoLhs[] = {
   217,  /* (185) expr ::= expr COLLATE ID|STRING */
   217,  /* (186) expr ::= CAST LP expr AS typetoken RP */
   217,  /* (187) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
-
   217,  /* (188) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
-
   217,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
-
   217,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
-
   216,  /* (191) term ::= CTIME_KW */
-
   217,  /* (192) expr ::= LP nexprlist COMMA expr RP */
-
   217,  /* (193) expr ::= expr AND expr */
-
   217,  /* (194) expr ::= expr OR expr */
-
   217,  /* (195) expr ::= expr LT|GT|GE|LE expr */
-
   217,  /* (196) expr ::= expr EQ|NE expr */
-
   217,  /* (197) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
-
   217,  /* (198) expr ::= expr PLUS|MINUS expr */
-
   217,  /* (199) expr ::= expr STAR|SLASH|REM expr */
-
   217,  /* (200) expr ::= expr CONCAT expr */
-
   274,  /* (201) likeop ::= NOT LIKE_KW|MATCH */
-
   217,  /* (202) expr ::= expr likeop expr */
-
   217,  /* (203) expr ::= expr likeop expr ESCAPE expr */
-
   217,  /* (204) expr ::= expr ISNULL|NOTNULL */
-
   217,  /* (205) expr ::= expr NOT NULL */
-
   217,  /* (206) expr ::= expr IS expr */
-
   217,  /* (207) expr ::= expr IS NOT expr */
-
   217,  /* (208) expr ::= expr IS NOT DISTINCT FROM expr */
-
   217,  /* (209) expr ::= expr IS DISTINCT FROM expr */
-
   217,  /* (210) expr ::= NOT expr */
-
   217,  /* (211) expr ::= BITNOT expr */
-
   217,  /* (212) expr ::= PLUS|MINUS expr */
-
   217,  /* (213) expr ::= expr PTR expr */
-
   275,  /* (214) between_op ::= BETWEEN */
-
   275,  /* (215) between_op ::= NOT BETWEEN */
-
   217,  /* (216) expr ::= expr between_op expr AND expr */
-
   276,  /* (217) in_op ::= IN */
-
   276,  /* (218) in_op ::= NOT IN */
-
   217,  /* (219) expr ::= expr in_op LP exprlist RP */
-
   217,  /* (220) expr ::= LP select RP */
-
   217,  /* (221) expr ::= expr in_op LP select RP */
-
   217,  /* (222) expr ::= expr in_op nm dbnm paren_exprlist */
-
   217,  /* (223) expr ::= EXISTS LP select RP */
-
   217,  /* (224) expr ::= CASE case_operand case_exprlist case_else END */
-
   279,  /* (225) case_exprlist ::= case_exprlist WHEN expr THEN expr */
-
   279,  /* (226) case_exprlist ::= WHEN expr THEN expr */
-
   280,  /* (227) case_else ::= ELSE expr */
-
   280,  /* (228) case_else ::= */
-
   278,  /* (229) case_operand ::= */
-
   261,  /* (230) exprlist ::= */
-
   253,  /* (231) nexprlist ::= nexprlist COMMA expr */
-
   253,  /* (232) nexprlist ::= expr */
-
   277,  /* (233) paren_exprlist ::= */
-
   277,  /* (234) paren_exprlist ::= LP exprlist RP */
-
   190,  /* (235) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
-
   281,  /* (236) uniqueflag ::= UNIQUE */
-
   281,  /* (237) uniqueflag ::= */
-
   221,  /* (238) eidlist_opt ::= */
-
   221,  /* (239) eidlist_opt ::= LP eidlist RP */
-
   232,  /* (240) eidlist ::= eidlist COMMA nm collate sortorder */
-
   232,  /* (241) eidlist ::= nm collate sortorder */
-
   282,  /* (242) collate ::= */
-
   282,  /* (243) collate ::= COLLATE ID|STRING */
-
   190,  /* (244) cmd ::= DROP INDEX ifexists fullname */
-
   190,  /* (245) cmd ::= VACUUM vinto */
-
   190,  /* (246) cmd ::= VACUUM nm vinto */
-
   283,  /* (247) vinto ::= INTO expr */
-
   283,  /* (248) vinto ::= */
-
   190,  /* (249) cmd ::= PRAGMA nm dbnm */
-
   190,  /* (250) cmd ::= PRAGMA nm dbnm EQ nmnum */
-
   190,  /* (251) cmd ::= PRAGMA nm dbnm LP nmnum RP */
-
   190,  /* (252) cmd ::= PRAGMA nm dbnm EQ minus_num */
-
   190,  /* (253) cmd ::= PRAGMA nm dbnm LP minus_num RP */
-
   211,  /* (254) plus_num ::= PLUS INTEGER|FLOAT */
-
   212,  /* (255) minus_num ::= MINUS INTEGER|FLOAT */
-
   190,  /* (256) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
-
   285,  /* (257) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
-
   287,  /* (258) trigger_time ::= BEFORE|AFTER */
-
   287,  /* (259) trigger_time ::= INSTEAD OF */
-
   287,  /* (260) trigger_time ::= */
-
   288,  /* (261) trigger_event ::= DELETE|INSERT */
-
   288,  /* (262) trigger_event ::= UPDATE */
-
   288,  /* (263) trigger_event ::= UPDATE OF idlist */
-
   290,  /* (264) when_clause ::= */
-
   290,  /* (265) when_clause ::= WHEN expr */
-
   286,  /* (266) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
-
   286,  /* (267) trigger_cmd_list ::= trigger_cmd SEMI */
-
   292,  /* (268) trnm ::= nm DOT nm */
-
   293,  /* (269) tridxby ::= INDEXED BY nm */
-
   293,  /* (270) tridxby ::= NOT INDEXED */
-
   291,  /* (271) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
-
   291,  /* (272) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
-
   291,  /* (273) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-
   291,  /* (274) trigger_cmd ::= scanpt select scanpt */
-
   217,  /* (275) expr ::= RAISE LP IGNORE RP */
-
   217,  /* (276) expr ::= RAISE LP raisetype COMMA nm RP */
-
   236,  /* (277) raisetype ::= ROLLBACK */
-
   236,  /* (278) raisetype ::= ABORT */
-
   236,  /* (279) raisetype ::= FAIL */
-
   190,  /* (280) cmd ::= DROP TRIGGER ifexists fullname */
-
   190,  /* (281) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
-
   190,  /* (282) cmd ::= DETACH database_kw_opt expr */
-
   295,  /* (283) key_opt ::= */
-
   295,  /* (284) key_opt ::= KEY expr */
-
   190,  /* (285) cmd ::= REINDEX */
-
   190,  /* (286) cmd ::= REINDEX nm dbnm */
-
   190,  /* (287) cmd ::= ANALYZE */
-
   190,  /* (288) cmd ::= ANALYZE nm dbnm */
-
   190,  /* (289) cmd ::= ALTER TABLE fullname RENAME TO nm */
-
   190,  /* (290) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
-
   190,  /* (291) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
-
   296,  /* (292) add_column_fullname ::= fullname */
-
   190,  /* (293) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
-
   190,  /* (294) cmd ::= create_vtab */
-
   190,  /* (295) cmd ::= create_vtab LP vtabarglist RP */
-
   298,  /* (296) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
-
   300,  /* (297) vtabarg ::= */
-
   301,  /* (298) vtabargtoken ::= ANY */
-
   301,  /* (299) vtabargtoken ::= lp anylist RP */
-
   302,  /* (300) lp ::= LP */
-
   266,  /* (301) with ::= WITH wqlist */
-
   266,  /* (302) with ::= WITH RECURSIVE wqlist */
-
   305,  /* (303) wqas ::= AS */
-
   305,  /* (304) wqas ::= AS MATERIALIZED */
-
   305,  /* (305) wqas ::= AS NOT MATERIALIZED */
-
   304,  /* (306) wqitem ::= nm eidlist_opt wqas LP select RP */
-
   241,  /* (307) wqlist ::= wqitem */
-
   241,  /* (308) wqlist ::= wqlist COMMA wqitem */
-
   306,  /* (309) windowdefn_list ::= windowdefn_list COMMA windowdefn */
-
   307,  /* (310) windowdefn ::= nm AS LP window RP */
-
   308,  /* (311) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
-
   308,  /* (312) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
-
   308,  /* (313) window ::= ORDER BY sortlist frame_opt */
-
   308,  /* (314) window ::= nm ORDER BY sortlist frame_opt */
-
   308,  /* (315) window ::= nm frame_opt */
-
   309,  /* (316) frame_opt ::= */
-
   309,  /* (317) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
-
   309,  /* (318) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
-
   313,  /* (319) range_or_rows ::= RANGE|ROWS|GROUPS */
-
   315,  /* (320) frame_bound_s ::= frame_bound */
-
   315,  /* (321) frame_bound_s ::= UNBOUNDED PRECEDING */
-
   316,  /* (322) frame_bound_e ::= frame_bound */
-
   316,  /* (323) frame_bound_e ::= UNBOUNDED FOLLOWING */
-
   314,  /* (324) frame_bound ::= expr PRECEDING|FOLLOWING */
-
   314,  /* (325) frame_bound ::= CURRENT ROW */
-
   317,  /* (326) frame_exclude_opt ::= */
-
   317,  /* (327) frame_exclude_opt ::= EXCLUDE frame_exclude */
-
   318,  /* (328) frame_exclude ::= NO OTHERS */
-
   318,  /* (329) frame_exclude ::= CURRENT ROW */
-
   318,  /* (330) frame_exclude ::= GROUP|TIES */
-
   251,  /* (331) window_clause ::= WINDOW windowdefn_list */
-
   273,  /* (332) filter_over ::= filter_clause over_clause */
-
   273,  /* (333) filter_over ::= over_clause */
-
   273,  /* (334) filter_over ::= filter_clause */
-
   312,  /* (335) over_clause ::= OVER LP window RP */
-
   312,  /* (336) over_clause ::= OVER nm */
-
   311,  /* (337) filter_clause ::= FILTER LP WHERE expr RP */
-
   185,  /* (338) input ::= cmdlist */
-
   186,  /* (339) cmdlist ::= cmdlist ecmd */
-
   186,  /* (340) cmdlist ::= ecmd */
-
   187,  /* (341) ecmd ::= SEMI */
-
   187,  /* (342) ecmd ::= cmdx SEMI */
-
   187,  /* (343) ecmd ::= explain cmdx SEMI */
-
   192,  /* (344) trans_opt ::= */
-
   192,  /* (345) trans_opt ::= TRANSACTION */
-
   192,  /* (346) trans_opt ::= TRANSACTION nm */
-
   194,  /* (347) savepoint_opt ::= SAVEPOINT */
-
   194,  /* (348) savepoint_opt ::= */
-
   190,  /* (349) cmd ::= create_table create_table_args */
-
   203,  /* (350) table_option_set ::= table_option */
-
   201,  /* (351) columnlist ::= columnlist COMMA columnname carglist */
-
   201,  /* (352) columnlist ::= columnname carglist */
-
   193,  /* (353) nm ::= ID|INDEXED|JOIN_KW */
-
   193,  /* (354) nm ::= STRING */
-
   208,  /* (355) typetoken ::= typename */
-
   209,  /* (356) typename ::= ID|STRING */
-
   210,  /* (357) signed ::= plus_num */
-
   210,  /* (358) signed ::= minus_num */
-
   207,  /* (359) carglist ::= carglist ccons */
-
   207,  /* (360) carglist ::= */
-
   215,  /* (361) ccons ::= NULL onconf */
-
   215,  /* (362) ccons ::= GENERATED ALWAYS AS generated */
-
   215,  /* (363) ccons ::= AS generated */
-
   202,  /* (364) conslist_opt ::= COMMA conslist */
-
   228,  /* (365) conslist ::= conslist tconscomma tcons */
-
   228,  /* (366) conslist ::= tcons */
-
   229,  /* (367) tconscomma ::= */
-
   233,  /* (368) defer_subclause_opt ::= defer_subclause */
-
   235,  /* (369) resolvetype ::= raisetype */
-
   239,  /* (370) selectnowith ::= oneselect */
-
   240,  /* (371) oneselect ::= values */
-
   254,  /* (372) sclp ::= selcollist COMMA */
-
   255,  /* (373) as ::= ID|STRING */
-
   264,  /* (374) indexed_opt ::= indexed_by */
-
   272,  /* (375) returning ::= */
-
   217,  /* (376) expr ::= term */
-
   274,  /* (377) likeop ::= LIKE_KW|MATCH */
-
   278,  /* (378) case_operand ::= expr */
-
   261,  /* (379) exprlist ::= nexprlist */
-
   284,  /* (380) nmnum ::= plus_num */
-
   284,  /* (381) nmnum ::= nm */
-
   284,  /* (382) nmnum ::= ON */
-
   284,  /* (383) nmnum ::= DELETE */
-
   284,  /* (384) nmnum ::= DEFAULT */
-
   211,  /* (385) plus_num ::= INTEGER|FLOAT */
-
   289,  /* (386) foreach_clause ::= */
-
   289,  /* (387) foreach_clause ::= FOR EACH ROW */
-
   292,  /* (388) trnm ::= nm */
-
   293,  /* (389) tridxby ::= */
-
   294,  /* (390) database_kw_opt ::= DATABASE */
-
   294,  /* (391) database_kw_opt ::= */
-
   297,  /* (392) kwcolumn_opt ::= */
-
   297,  /* (393) kwcolumn_opt ::= COLUMNKW */
-
   299,  /* (394) vtabarglist ::= vtabarg */
-
   299,  /* (395) vtabarglist ::= vtabarglist COMMA vtabarg */
-
   300,  /* (396) vtabarg ::= vtabarg vtabargtoken */
-
   303,  /* (397) anylist ::= */
-
   303,  /* (398) anylist ::= anylist LP anylist RP */
-
   303,  /* (399) anylist ::= anylist ANY */
-
   266,  /* (400) with ::= */
-
   306,  /* (401) windowdefn_list ::= windowdefn */
-
   308,  /* (402) window ::= frame_opt */
+
   217,  /* (188) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */
+
   217,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
+
   217,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
+
   217,  /* (191) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */
+
   217,  /* (192) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
+
   216,  /* (193) term ::= CTIME_KW */
+
   217,  /* (194) expr ::= LP nexprlist COMMA expr RP */
+
   217,  /* (195) expr ::= expr AND expr */
+
   217,  /* (196) expr ::= expr OR expr */
+
   217,  /* (197) expr ::= expr LT|GT|GE|LE expr */
+
   217,  /* (198) expr ::= expr EQ|NE expr */
+
   217,  /* (199) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+
   217,  /* (200) expr ::= expr PLUS|MINUS expr */
+
   217,  /* (201) expr ::= expr STAR|SLASH|REM expr */
+
   217,  /* (202) expr ::= expr CONCAT expr */
+
   274,  /* (203) likeop ::= NOT LIKE_KW|MATCH */
+
   217,  /* (204) expr ::= expr likeop expr */
+
   217,  /* (205) expr ::= expr likeop expr ESCAPE expr */
+
   217,  /* (206) expr ::= expr ISNULL|NOTNULL */
+
   217,  /* (207) expr ::= expr NOT NULL */
+
   217,  /* (208) expr ::= expr IS expr */
+
   217,  /* (209) expr ::= expr IS NOT expr */
+
   217,  /* (210) expr ::= expr IS NOT DISTINCT FROM expr */
+
   217,  /* (211) expr ::= expr IS DISTINCT FROM expr */
+
   217,  /* (212) expr ::= NOT expr */
+
   217,  /* (213) expr ::= BITNOT expr */
+
   217,  /* (214) expr ::= PLUS|MINUS expr */
+
   217,  /* (215) expr ::= expr PTR expr */
+
   275,  /* (216) between_op ::= BETWEEN */
+
   275,  /* (217) between_op ::= NOT BETWEEN */
+
   217,  /* (218) expr ::= expr between_op expr AND expr */
+
   276,  /* (219) in_op ::= IN */
+
   276,  /* (220) in_op ::= NOT IN */
+
   217,  /* (221) expr ::= expr in_op LP exprlist RP */
+
   217,  /* (222) expr ::= LP select RP */
+
   217,  /* (223) expr ::= expr in_op LP select RP */
+
   217,  /* (224) expr ::= expr in_op nm dbnm paren_exprlist */
+
   217,  /* (225) expr ::= EXISTS LP select RP */
+
   217,  /* (226) expr ::= CASE case_operand case_exprlist case_else END */
+
   279,  /* (227) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+
   279,  /* (228) case_exprlist ::= WHEN expr THEN expr */
+
   280,  /* (229) case_else ::= ELSE expr */
+
   280,  /* (230) case_else ::= */
+
   278,  /* (231) case_operand ::= */
+
   261,  /* (232) exprlist ::= */
+
   253,  /* (233) nexprlist ::= nexprlist COMMA expr */
+
   253,  /* (234) nexprlist ::= expr */
+
   277,  /* (235) paren_exprlist ::= */
+
   277,  /* (236) paren_exprlist ::= LP exprlist RP */
+
   190,  /* (237) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+
   281,  /* (238) uniqueflag ::= UNIQUE */
+
   281,  /* (239) uniqueflag ::= */
+
   221,  /* (240) eidlist_opt ::= */
+
   221,  /* (241) eidlist_opt ::= LP eidlist RP */
+
   232,  /* (242) eidlist ::= eidlist COMMA nm collate sortorder */
+
   232,  /* (243) eidlist ::= nm collate sortorder */
+
   282,  /* (244) collate ::= */
+
   282,  /* (245) collate ::= COLLATE ID|STRING */
+
   190,  /* (246) cmd ::= DROP INDEX ifexists fullname */
+
   190,  /* (247) cmd ::= VACUUM vinto */
+
   190,  /* (248) cmd ::= VACUUM nm vinto */
+
   283,  /* (249) vinto ::= INTO expr */
+
   283,  /* (250) vinto ::= */
+
   190,  /* (251) cmd ::= PRAGMA nm dbnm */
+
   190,  /* (252) cmd ::= PRAGMA nm dbnm EQ nmnum */
+
   190,  /* (253) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+
   190,  /* (254) cmd ::= PRAGMA nm dbnm EQ minus_num */
+
   190,  /* (255) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+
   211,  /* (256) plus_num ::= PLUS INTEGER|FLOAT */
+
   212,  /* (257) minus_num ::= MINUS INTEGER|FLOAT */
+
   190,  /* (258) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+
   285,  /* (259) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+
   287,  /* (260) trigger_time ::= BEFORE|AFTER */
+
   287,  /* (261) trigger_time ::= INSTEAD OF */
+
   287,  /* (262) trigger_time ::= */
+
   288,  /* (263) trigger_event ::= DELETE|INSERT */
+
   288,  /* (264) trigger_event ::= UPDATE */
+
   288,  /* (265) trigger_event ::= UPDATE OF idlist */
+
   290,  /* (266) when_clause ::= */
+
   290,  /* (267) when_clause ::= WHEN expr */
+
   286,  /* (268) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+
   286,  /* (269) trigger_cmd_list ::= trigger_cmd SEMI */
+
   292,  /* (270) trnm ::= nm DOT nm */
+
   293,  /* (271) tridxby ::= INDEXED BY nm */
+
   293,  /* (272) tridxby ::= NOT INDEXED */
+
   291,  /* (273) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+
   291,  /* (274) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+
   291,  /* (275) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+
   291,  /* (276) trigger_cmd ::= scanpt select scanpt */
+
   217,  /* (277) expr ::= RAISE LP IGNORE RP */
+
   217,  /* (278) expr ::= RAISE LP raisetype COMMA nm RP */
+
   236,  /* (279) raisetype ::= ROLLBACK */
+
   236,  /* (280) raisetype ::= ABORT */
+
   236,  /* (281) raisetype ::= FAIL */
+
   190,  /* (282) cmd ::= DROP TRIGGER ifexists fullname */
+
   190,  /* (283) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+
   190,  /* (284) cmd ::= DETACH database_kw_opt expr */
+
   295,  /* (285) key_opt ::= */
+
   295,  /* (286) key_opt ::= KEY expr */
+
   190,  /* (287) cmd ::= REINDEX */
+
   190,  /* (288) cmd ::= REINDEX nm dbnm */
+
   190,  /* (289) cmd ::= ANALYZE */
+
   190,  /* (290) cmd ::= ANALYZE nm dbnm */
+
   190,  /* (291) cmd ::= ALTER TABLE fullname RENAME TO nm */
+
   190,  /* (292) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+
   190,  /* (293) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
+
   296,  /* (294) add_column_fullname ::= fullname */
+
   190,  /* (295) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+
   190,  /* (296) cmd ::= create_vtab */
+
   190,  /* (297) cmd ::= create_vtab LP vtabarglist RP */
+
   298,  /* (298) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+
   300,  /* (299) vtabarg ::= */
+
   301,  /* (300) vtabargtoken ::= ANY */
+
   301,  /* (301) vtabargtoken ::= lp anylist RP */
+
   302,  /* (302) lp ::= LP */
+
   266,  /* (303) with ::= WITH wqlist */
+
   266,  /* (304) with ::= WITH RECURSIVE wqlist */
+
   305,  /* (305) wqas ::= AS */
+
   305,  /* (306) wqas ::= AS MATERIALIZED */
+
   305,  /* (307) wqas ::= AS NOT MATERIALIZED */
+
   304,  /* (308) wqitem ::= nm eidlist_opt wqas LP select RP */
+
   241,  /* (309) wqlist ::= wqitem */
+
   241,  /* (310) wqlist ::= wqlist COMMA wqitem */
+
   306,  /* (311) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+
   307,  /* (312) windowdefn ::= nm AS LP window RP */
+
   308,  /* (313) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+
   308,  /* (314) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+
   308,  /* (315) window ::= ORDER BY sortlist frame_opt */
+
   308,  /* (316) window ::= nm ORDER BY sortlist frame_opt */
+
   308,  /* (317) window ::= nm frame_opt */
+
   309,  /* (318) frame_opt ::= */
+
   309,  /* (319) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+
   309,  /* (320) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+
   313,  /* (321) range_or_rows ::= RANGE|ROWS|GROUPS */
+
   315,  /* (322) frame_bound_s ::= frame_bound */
+
   315,  /* (323) frame_bound_s ::= UNBOUNDED PRECEDING */
+
   316,  /* (324) frame_bound_e ::= frame_bound */
+
   316,  /* (325) frame_bound_e ::= UNBOUNDED FOLLOWING */
+
   314,  /* (326) frame_bound ::= expr PRECEDING|FOLLOWING */
+
   314,  /* (327) frame_bound ::= CURRENT ROW */
+
   317,  /* (328) frame_exclude_opt ::= */
+
   317,  /* (329) frame_exclude_opt ::= EXCLUDE frame_exclude */
+
   318,  /* (330) frame_exclude ::= NO OTHERS */
+
   318,  /* (331) frame_exclude ::= CURRENT ROW */
+
   318,  /* (332) frame_exclude ::= GROUP|TIES */
+
   251,  /* (333) window_clause ::= WINDOW windowdefn_list */
+
   273,  /* (334) filter_over ::= filter_clause over_clause */
+
   273,  /* (335) filter_over ::= over_clause */
+
   273,  /* (336) filter_over ::= filter_clause */
+
   312,  /* (337) over_clause ::= OVER LP window RP */
+
   312,  /* (338) over_clause ::= OVER nm */
+
   311,  /* (339) filter_clause ::= FILTER LP WHERE expr RP */
+
   185,  /* (340) input ::= cmdlist */
+
   186,  /* (341) cmdlist ::= cmdlist ecmd */
+
   186,  /* (342) cmdlist ::= ecmd */
+
   187,  /* (343) ecmd ::= SEMI */
+
   187,  /* (344) ecmd ::= cmdx SEMI */
+
   187,  /* (345) ecmd ::= explain cmdx SEMI */
+
   192,  /* (346) trans_opt ::= */
+
   192,  /* (347) trans_opt ::= TRANSACTION */
+
   192,  /* (348) trans_opt ::= TRANSACTION nm */
+
   194,  /* (349) savepoint_opt ::= SAVEPOINT */
+
   194,  /* (350) savepoint_opt ::= */
+
   190,  /* (351) cmd ::= create_table create_table_args */
+
   203,  /* (352) table_option_set ::= table_option */
+
   201,  /* (353) columnlist ::= columnlist COMMA columnname carglist */
+
   201,  /* (354) columnlist ::= columnname carglist */
+
   193,  /* (355) nm ::= ID|INDEXED|JOIN_KW */
+
   193,  /* (356) nm ::= STRING */
+
   208,  /* (357) typetoken ::= typename */
+
   209,  /* (358) typename ::= ID|STRING */
+
   210,  /* (359) signed ::= plus_num */
+
   210,  /* (360) signed ::= minus_num */
+
   207,  /* (361) carglist ::= carglist ccons */
+
   207,  /* (362) carglist ::= */
+
   215,  /* (363) ccons ::= NULL onconf */
+
   215,  /* (364) ccons ::= GENERATED ALWAYS AS generated */
+
   215,  /* (365) ccons ::= AS generated */
+
   202,  /* (366) conslist_opt ::= COMMA conslist */
+
   228,  /* (367) conslist ::= conslist tconscomma tcons */
+
   228,  /* (368) conslist ::= tcons */
+
   229,  /* (369) tconscomma ::= */
+
   233,  /* (370) defer_subclause_opt ::= defer_subclause */
+
   235,  /* (371) resolvetype ::= raisetype */
+
   239,  /* (372) selectnowith ::= oneselect */
+
   240,  /* (373) oneselect ::= values */
+
   254,  /* (374) sclp ::= selcollist COMMA */
+
   255,  /* (375) as ::= ID|STRING */
+
   264,  /* (376) indexed_opt ::= indexed_by */
+
   272,  /* (377) returning ::= */
+
   217,  /* (378) expr ::= term */
+
   274,  /* (379) likeop ::= LIKE_KW|MATCH */
+
   278,  /* (380) case_operand ::= expr */
+
   261,  /* (381) exprlist ::= nexprlist */
+
   284,  /* (382) nmnum ::= plus_num */
+
   284,  /* (383) nmnum ::= nm */
+
   284,  /* (384) nmnum ::= ON */
+
   284,  /* (385) nmnum ::= DELETE */
+
   284,  /* (386) nmnum ::= DEFAULT */
+
   211,  /* (387) plus_num ::= INTEGER|FLOAT */
+
   289,  /* (388) foreach_clause ::= */
+
   289,  /* (389) foreach_clause ::= FOR EACH ROW */
+
   292,  /* (390) trnm ::= nm */
+
   293,  /* (391) tridxby ::= */
+
   294,  /* (392) database_kw_opt ::= DATABASE */
+
   294,  /* (393) database_kw_opt ::= */
+
   297,  /* (394) kwcolumn_opt ::= */
+
   297,  /* (395) kwcolumn_opt ::= COLUMNKW */
+
   299,  /* (396) vtabarglist ::= vtabarg */
+
   299,  /* (397) vtabarglist ::= vtabarglist COMMA vtabarg */
+
   300,  /* (398) vtabarg ::= vtabarg vtabargtoken */
+
   303,  /* (399) anylist ::= */
+
   303,  /* (400) anylist ::= anylist LP anylist RP */
+
   303,  /* (401) anylist ::= anylist ANY */
+
   266,  /* (402) with ::= */
+
   306,  /* (403) windowdefn_list ::= windowdefn */
+
   308,  /* (404) window ::= frame_opt */
};

/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
@@ -172542,221 +173713,223 @@ static const signed char yyRuleInfoNRhs[] = {
   -3,  /* (185) expr ::= expr COLLATE ID|STRING */
   -6,  /* (186) expr ::= CAST LP expr AS typetoken RP */
   -5,  /* (187) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */
-
   -4,  /* (188) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
-
   -6,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
-
   -5,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
-
   -1,  /* (191) term ::= CTIME_KW */
-
   -5,  /* (192) expr ::= LP nexprlist COMMA expr RP */
-
   -3,  /* (193) expr ::= expr AND expr */
-
   -3,  /* (194) expr ::= expr OR expr */
-
   -3,  /* (195) expr ::= expr LT|GT|GE|LE expr */
-
   -3,  /* (196) expr ::= expr EQ|NE expr */
-
   -3,  /* (197) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
-
   -3,  /* (198) expr ::= expr PLUS|MINUS expr */
-
   -3,  /* (199) expr ::= expr STAR|SLASH|REM expr */
-
   -3,  /* (200) expr ::= expr CONCAT expr */
-
   -2,  /* (201) likeop ::= NOT LIKE_KW|MATCH */
-
   -3,  /* (202) expr ::= expr likeop expr */
-
   -5,  /* (203) expr ::= expr likeop expr ESCAPE expr */
-
   -2,  /* (204) expr ::= expr ISNULL|NOTNULL */
-
   -3,  /* (205) expr ::= expr NOT NULL */
-
   -3,  /* (206) expr ::= expr IS expr */
-
   -4,  /* (207) expr ::= expr IS NOT expr */
-
   -6,  /* (208) expr ::= expr IS NOT DISTINCT FROM expr */
-
   -5,  /* (209) expr ::= expr IS DISTINCT FROM expr */
-
   -2,  /* (210) expr ::= NOT expr */
-
   -2,  /* (211) expr ::= BITNOT expr */
-
   -2,  /* (212) expr ::= PLUS|MINUS expr */
-
   -3,  /* (213) expr ::= expr PTR expr */
-
   -1,  /* (214) between_op ::= BETWEEN */
-
   -2,  /* (215) between_op ::= NOT BETWEEN */
-
   -5,  /* (216) expr ::= expr between_op expr AND expr */
-
   -1,  /* (217) in_op ::= IN */
-
   -2,  /* (218) in_op ::= NOT IN */
-
   -5,  /* (219) expr ::= expr in_op LP exprlist RP */
-
   -3,  /* (220) expr ::= LP select RP */
-
   -5,  /* (221) expr ::= expr in_op LP select RP */
-
   -5,  /* (222) expr ::= expr in_op nm dbnm paren_exprlist */
-
   -4,  /* (223) expr ::= EXISTS LP select RP */
-
   -5,  /* (224) expr ::= CASE case_operand case_exprlist case_else END */
-
   -5,  /* (225) case_exprlist ::= case_exprlist WHEN expr THEN expr */
-
   -4,  /* (226) case_exprlist ::= WHEN expr THEN expr */
-
   -2,  /* (227) case_else ::= ELSE expr */
-
    0,  /* (228) case_else ::= */
-
    0,  /* (229) case_operand ::= */
-
    0,  /* (230) exprlist ::= */
-
   -3,  /* (231) nexprlist ::= nexprlist COMMA expr */
-
   -1,  /* (232) nexprlist ::= expr */
-
    0,  /* (233) paren_exprlist ::= */
-
   -3,  /* (234) paren_exprlist ::= LP exprlist RP */
-
  -12,  /* (235) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
-
   -1,  /* (236) uniqueflag ::= UNIQUE */
-
    0,  /* (237) uniqueflag ::= */
-
    0,  /* (238) eidlist_opt ::= */
-
   -3,  /* (239) eidlist_opt ::= LP eidlist RP */
-
   -5,  /* (240) eidlist ::= eidlist COMMA nm collate sortorder */
-
   -3,  /* (241) eidlist ::= nm collate sortorder */
-
    0,  /* (242) collate ::= */
-
   -2,  /* (243) collate ::= COLLATE ID|STRING */
-
   -4,  /* (244) cmd ::= DROP INDEX ifexists fullname */
-
   -2,  /* (245) cmd ::= VACUUM vinto */
-
   -3,  /* (246) cmd ::= VACUUM nm vinto */
-
   -2,  /* (247) vinto ::= INTO expr */
-
    0,  /* (248) vinto ::= */
-
   -3,  /* (249) cmd ::= PRAGMA nm dbnm */
-
   -5,  /* (250) cmd ::= PRAGMA nm dbnm EQ nmnum */
-
   -6,  /* (251) cmd ::= PRAGMA nm dbnm LP nmnum RP */
-
   -5,  /* (252) cmd ::= PRAGMA nm dbnm EQ minus_num */
-
   -6,  /* (253) cmd ::= PRAGMA nm dbnm LP minus_num RP */
-
   -2,  /* (254) plus_num ::= PLUS INTEGER|FLOAT */
-
   -2,  /* (255) minus_num ::= MINUS INTEGER|FLOAT */
-
   -5,  /* (256) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
-
  -11,  /* (257) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
-
   -1,  /* (258) trigger_time ::= BEFORE|AFTER */
-
   -2,  /* (259) trigger_time ::= INSTEAD OF */
-
    0,  /* (260) trigger_time ::= */
-
   -1,  /* (261) trigger_event ::= DELETE|INSERT */
-
   -1,  /* (262) trigger_event ::= UPDATE */
-
   -3,  /* (263) trigger_event ::= UPDATE OF idlist */
-
    0,  /* (264) when_clause ::= */
-
   -2,  /* (265) when_clause ::= WHEN expr */
-
   -3,  /* (266) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
-
   -2,  /* (267) trigger_cmd_list ::= trigger_cmd SEMI */
-
   -3,  /* (268) trnm ::= nm DOT nm */
-
   -3,  /* (269) tridxby ::= INDEXED BY nm */
-
   -2,  /* (270) tridxby ::= NOT INDEXED */
-
   -9,  /* (271) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
-
   -8,  /* (272) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
-
   -6,  /* (273) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-
   -3,  /* (274) trigger_cmd ::= scanpt select scanpt */
-
   -4,  /* (275) expr ::= RAISE LP IGNORE RP */
-
   -6,  /* (276) expr ::= RAISE LP raisetype COMMA nm RP */
-
   -1,  /* (277) raisetype ::= ROLLBACK */
-
   -1,  /* (278) raisetype ::= ABORT */
-
   -1,  /* (279) raisetype ::= FAIL */
-
   -4,  /* (280) cmd ::= DROP TRIGGER ifexists fullname */
-
   -6,  /* (281) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
-
   -3,  /* (282) cmd ::= DETACH database_kw_opt expr */
-
    0,  /* (283) key_opt ::= */
-
   -2,  /* (284) key_opt ::= KEY expr */
-
   -1,  /* (285) cmd ::= REINDEX */
-
   -3,  /* (286) cmd ::= REINDEX nm dbnm */
-
   -1,  /* (287) cmd ::= ANALYZE */
-
   -3,  /* (288) cmd ::= ANALYZE nm dbnm */
-
   -6,  /* (289) cmd ::= ALTER TABLE fullname RENAME TO nm */
-
   -7,  /* (290) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
-
   -6,  /* (291) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
-
   -1,  /* (292) add_column_fullname ::= fullname */
-
   -8,  /* (293) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
-
   -1,  /* (294) cmd ::= create_vtab */
-
   -4,  /* (295) cmd ::= create_vtab LP vtabarglist RP */
-
   -8,  /* (296) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
-
    0,  /* (297) vtabarg ::= */
-
   -1,  /* (298) vtabargtoken ::= ANY */
-
   -3,  /* (299) vtabargtoken ::= lp anylist RP */
-
   -1,  /* (300) lp ::= LP */
-
   -2,  /* (301) with ::= WITH wqlist */
-
   -3,  /* (302) with ::= WITH RECURSIVE wqlist */
-
   -1,  /* (303) wqas ::= AS */
-
   -2,  /* (304) wqas ::= AS MATERIALIZED */
-
   -3,  /* (305) wqas ::= AS NOT MATERIALIZED */
-
   -6,  /* (306) wqitem ::= nm eidlist_opt wqas LP select RP */
-
   -1,  /* (307) wqlist ::= wqitem */
-
   -3,  /* (308) wqlist ::= wqlist COMMA wqitem */
-
   -3,  /* (309) windowdefn_list ::= windowdefn_list COMMA windowdefn */
-
   -5,  /* (310) windowdefn ::= nm AS LP window RP */
-
   -5,  /* (311) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
-
   -6,  /* (312) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
-
   -4,  /* (313) window ::= ORDER BY sortlist frame_opt */
-
   -5,  /* (314) window ::= nm ORDER BY sortlist frame_opt */
-
   -2,  /* (315) window ::= nm frame_opt */
-
    0,  /* (316) frame_opt ::= */
-
   -3,  /* (317) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
-
   -6,  /* (318) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
-
   -1,  /* (319) range_or_rows ::= RANGE|ROWS|GROUPS */
-
   -1,  /* (320) frame_bound_s ::= frame_bound */
-
   -2,  /* (321) frame_bound_s ::= UNBOUNDED PRECEDING */
-
   -1,  /* (322) frame_bound_e ::= frame_bound */
-
   -2,  /* (323) frame_bound_e ::= UNBOUNDED FOLLOWING */
-
   -2,  /* (324) frame_bound ::= expr PRECEDING|FOLLOWING */
-
   -2,  /* (325) frame_bound ::= CURRENT ROW */
-
    0,  /* (326) frame_exclude_opt ::= */
-
   -2,  /* (327) frame_exclude_opt ::= EXCLUDE frame_exclude */
-
   -2,  /* (328) frame_exclude ::= NO OTHERS */
-
   -2,  /* (329) frame_exclude ::= CURRENT ROW */
-
   -1,  /* (330) frame_exclude ::= GROUP|TIES */
-
   -2,  /* (331) window_clause ::= WINDOW windowdefn_list */
-
   -2,  /* (332) filter_over ::= filter_clause over_clause */
-
   -1,  /* (333) filter_over ::= over_clause */
-
   -1,  /* (334) filter_over ::= filter_clause */
-
   -4,  /* (335) over_clause ::= OVER LP window RP */
-
   -2,  /* (336) over_clause ::= OVER nm */
-
   -5,  /* (337) filter_clause ::= FILTER LP WHERE expr RP */
-
   -1,  /* (338) input ::= cmdlist */
-
   -2,  /* (339) cmdlist ::= cmdlist ecmd */
-
   -1,  /* (340) cmdlist ::= ecmd */
-
   -1,  /* (341) ecmd ::= SEMI */
-
   -2,  /* (342) ecmd ::= cmdx SEMI */
-
   -3,  /* (343) ecmd ::= explain cmdx SEMI */
-
    0,  /* (344) trans_opt ::= */
-
   -1,  /* (345) trans_opt ::= TRANSACTION */
-
   -2,  /* (346) trans_opt ::= TRANSACTION nm */
-
   -1,  /* (347) savepoint_opt ::= SAVEPOINT */
-
    0,  /* (348) savepoint_opt ::= */
-
   -2,  /* (349) cmd ::= create_table create_table_args */
-
   -1,  /* (350) table_option_set ::= table_option */
-
   -4,  /* (351) columnlist ::= columnlist COMMA columnname carglist */
-
   -2,  /* (352) columnlist ::= columnname carglist */
-
   -1,  /* (353) nm ::= ID|INDEXED|JOIN_KW */
-
   -1,  /* (354) nm ::= STRING */
-
   -1,  /* (355) typetoken ::= typename */
-
   -1,  /* (356) typename ::= ID|STRING */
-
   -1,  /* (357) signed ::= plus_num */
-
   -1,  /* (358) signed ::= minus_num */
-
   -2,  /* (359) carglist ::= carglist ccons */
-
    0,  /* (360) carglist ::= */
-
   -2,  /* (361) ccons ::= NULL onconf */
-
   -4,  /* (362) ccons ::= GENERATED ALWAYS AS generated */
-
   -2,  /* (363) ccons ::= AS generated */
-
   -2,  /* (364) conslist_opt ::= COMMA conslist */
-
   -3,  /* (365) conslist ::= conslist tconscomma tcons */
-
   -1,  /* (366) conslist ::= tcons */
-
    0,  /* (367) tconscomma ::= */
-
   -1,  /* (368) defer_subclause_opt ::= defer_subclause */
-
   -1,  /* (369) resolvetype ::= raisetype */
-
   -1,  /* (370) selectnowith ::= oneselect */
-
   -1,  /* (371) oneselect ::= values */
-
   -2,  /* (372) sclp ::= selcollist COMMA */
-
   -1,  /* (373) as ::= ID|STRING */
-
   -1,  /* (374) indexed_opt ::= indexed_by */
-
    0,  /* (375) returning ::= */
-
   -1,  /* (376) expr ::= term */
-
   -1,  /* (377) likeop ::= LIKE_KW|MATCH */
-
   -1,  /* (378) case_operand ::= expr */
-
   -1,  /* (379) exprlist ::= nexprlist */
-
   -1,  /* (380) nmnum ::= plus_num */
-
   -1,  /* (381) nmnum ::= nm */
-
   -1,  /* (382) nmnum ::= ON */
-
   -1,  /* (383) nmnum ::= DELETE */
-
   -1,  /* (384) nmnum ::= DEFAULT */
-
   -1,  /* (385) plus_num ::= INTEGER|FLOAT */
-
    0,  /* (386) foreach_clause ::= */
-
   -3,  /* (387) foreach_clause ::= FOR EACH ROW */
-
   -1,  /* (388) trnm ::= nm */
-
    0,  /* (389) tridxby ::= */
-
   -1,  /* (390) database_kw_opt ::= DATABASE */
-
    0,  /* (391) database_kw_opt ::= */
-
    0,  /* (392) kwcolumn_opt ::= */
-
   -1,  /* (393) kwcolumn_opt ::= COLUMNKW */
-
   -1,  /* (394) vtabarglist ::= vtabarg */
-
   -3,  /* (395) vtabarglist ::= vtabarglist COMMA vtabarg */
-
   -2,  /* (396) vtabarg ::= vtabarg vtabargtoken */
-
    0,  /* (397) anylist ::= */
-
   -4,  /* (398) anylist ::= anylist LP anylist RP */
-
   -2,  /* (399) anylist ::= anylist ANY */
-
    0,  /* (400) with ::= */
-
   -1,  /* (401) windowdefn_list ::= windowdefn */
-
   -1,  /* (402) window ::= frame_opt */
+
   -8,  /* (188) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */
+
   -4,  /* (189) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
+
   -6,  /* (190) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
+
   -9,  /* (191) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */
+
   -5,  /* (192) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
+
   -1,  /* (193) term ::= CTIME_KW */
+
   -5,  /* (194) expr ::= LP nexprlist COMMA expr RP */
+
   -3,  /* (195) expr ::= expr AND expr */
+
   -3,  /* (196) expr ::= expr OR expr */
+
   -3,  /* (197) expr ::= expr LT|GT|GE|LE expr */
+
   -3,  /* (198) expr ::= expr EQ|NE expr */
+
   -3,  /* (199) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+
   -3,  /* (200) expr ::= expr PLUS|MINUS expr */
+
   -3,  /* (201) expr ::= expr STAR|SLASH|REM expr */
+
   -3,  /* (202) expr ::= expr CONCAT expr */
+
   -2,  /* (203) likeop ::= NOT LIKE_KW|MATCH */
+
   -3,  /* (204) expr ::= expr likeop expr */
+
   -5,  /* (205) expr ::= expr likeop expr ESCAPE expr */
+
   -2,  /* (206) expr ::= expr ISNULL|NOTNULL */
+
   -3,  /* (207) expr ::= expr NOT NULL */
+
   -3,  /* (208) expr ::= expr IS expr */
+
   -4,  /* (209) expr ::= expr IS NOT expr */
+
   -6,  /* (210) expr ::= expr IS NOT DISTINCT FROM expr */
+
   -5,  /* (211) expr ::= expr IS DISTINCT FROM expr */
+
   -2,  /* (212) expr ::= NOT expr */
+
   -2,  /* (213) expr ::= BITNOT expr */
+
   -2,  /* (214) expr ::= PLUS|MINUS expr */
+
   -3,  /* (215) expr ::= expr PTR expr */
+
   -1,  /* (216) between_op ::= BETWEEN */
+
   -2,  /* (217) between_op ::= NOT BETWEEN */
+
   -5,  /* (218) expr ::= expr between_op expr AND expr */
+
   -1,  /* (219) in_op ::= IN */
+
   -2,  /* (220) in_op ::= NOT IN */
+
   -5,  /* (221) expr ::= expr in_op LP exprlist RP */
+
   -3,  /* (222) expr ::= LP select RP */
+
   -5,  /* (223) expr ::= expr in_op LP select RP */
+
   -5,  /* (224) expr ::= expr in_op nm dbnm paren_exprlist */
+
   -4,  /* (225) expr ::= EXISTS LP select RP */
+
   -5,  /* (226) expr ::= CASE case_operand case_exprlist case_else END */
+
   -5,  /* (227) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+
   -4,  /* (228) case_exprlist ::= WHEN expr THEN expr */
+
   -2,  /* (229) case_else ::= ELSE expr */
+
    0,  /* (230) case_else ::= */
+
    0,  /* (231) case_operand ::= */
+
    0,  /* (232) exprlist ::= */
+
   -3,  /* (233) nexprlist ::= nexprlist COMMA expr */
+
   -1,  /* (234) nexprlist ::= expr */
+
    0,  /* (235) paren_exprlist ::= */
+
   -3,  /* (236) paren_exprlist ::= LP exprlist RP */
+
  -12,  /* (237) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+
   -1,  /* (238) uniqueflag ::= UNIQUE */
+
    0,  /* (239) uniqueflag ::= */
+
    0,  /* (240) eidlist_opt ::= */
+
   -3,  /* (241) eidlist_opt ::= LP eidlist RP */
+
   -5,  /* (242) eidlist ::= eidlist COMMA nm collate sortorder */
+
   -3,  /* (243) eidlist ::= nm collate sortorder */
+
    0,  /* (244) collate ::= */
+
   -2,  /* (245) collate ::= COLLATE ID|STRING */
+
   -4,  /* (246) cmd ::= DROP INDEX ifexists fullname */
+
   -2,  /* (247) cmd ::= VACUUM vinto */
+
   -3,  /* (248) cmd ::= VACUUM nm vinto */
+
   -2,  /* (249) vinto ::= INTO expr */
+
    0,  /* (250) vinto ::= */
+
   -3,  /* (251) cmd ::= PRAGMA nm dbnm */
+
   -5,  /* (252) cmd ::= PRAGMA nm dbnm EQ nmnum */
+
   -6,  /* (253) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+
   -5,  /* (254) cmd ::= PRAGMA nm dbnm EQ minus_num */
+
   -6,  /* (255) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+
   -2,  /* (256) plus_num ::= PLUS INTEGER|FLOAT */
+
   -2,  /* (257) minus_num ::= MINUS INTEGER|FLOAT */
+
   -5,  /* (258) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+
  -11,  /* (259) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+
   -1,  /* (260) trigger_time ::= BEFORE|AFTER */
+
   -2,  /* (261) trigger_time ::= INSTEAD OF */
+
    0,  /* (262) trigger_time ::= */
+
   -1,  /* (263) trigger_event ::= DELETE|INSERT */
+
   -1,  /* (264) trigger_event ::= UPDATE */
+
   -3,  /* (265) trigger_event ::= UPDATE OF idlist */
+
    0,  /* (266) when_clause ::= */
+
   -2,  /* (267) when_clause ::= WHEN expr */
+
   -3,  /* (268) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+
   -2,  /* (269) trigger_cmd_list ::= trigger_cmd SEMI */
+
   -3,  /* (270) trnm ::= nm DOT nm */
+
   -3,  /* (271) tridxby ::= INDEXED BY nm */
+
   -2,  /* (272) tridxby ::= NOT INDEXED */
+
   -9,  /* (273) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+
   -8,  /* (274) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+
   -6,  /* (275) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+
   -3,  /* (276) trigger_cmd ::= scanpt select scanpt */
+
   -4,  /* (277) expr ::= RAISE LP IGNORE RP */
+
   -6,  /* (278) expr ::= RAISE LP raisetype COMMA nm RP */
+
   -1,  /* (279) raisetype ::= ROLLBACK */
+
   -1,  /* (280) raisetype ::= ABORT */
+
   -1,  /* (281) raisetype ::= FAIL */
+
   -4,  /* (282) cmd ::= DROP TRIGGER ifexists fullname */
+
   -6,  /* (283) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+
   -3,  /* (284) cmd ::= DETACH database_kw_opt expr */
+
    0,  /* (285) key_opt ::= */
+
   -2,  /* (286) key_opt ::= KEY expr */
+
   -1,  /* (287) cmd ::= REINDEX */
+
   -3,  /* (288) cmd ::= REINDEX nm dbnm */
+
   -1,  /* (289) cmd ::= ANALYZE */
+
   -3,  /* (290) cmd ::= ANALYZE nm dbnm */
+
   -6,  /* (291) cmd ::= ALTER TABLE fullname RENAME TO nm */
+
   -7,  /* (292) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+
   -6,  /* (293) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
+
   -1,  /* (294) add_column_fullname ::= fullname */
+
   -8,  /* (295) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+
   -1,  /* (296) cmd ::= create_vtab */
+
   -4,  /* (297) cmd ::= create_vtab LP vtabarglist RP */
+
   -8,  /* (298) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+
    0,  /* (299) vtabarg ::= */
+
   -1,  /* (300) vtabargtoken ::= ANY */
+
   -3,  /* (301) vtabargtoken ::= lp anylist RP */
+
   -1,  /* (302) lp ::= LP */
+
   -2,  /* (303) with ::= WITH wqlist */
+
   -3,  /* (304) with ::= WITH RECURSIVE wqlist */
+
   -1,  /* (305) wqas ::= AS */
+
   -2,  /* (306) wqas ::= AS MATERIALIZED */
+
   -3,  /* (307) wqas ::= AS NOT MATERIALIZED */
+
   -6,  /* (308) wqitem ::= nm eidlist_opt wqas LP select RP */
+
   -1,  /* (309) wqlist ::= wqitem */
+
   -3,  /* (310) wqlist ::= wqlist COMMA wqitem */
+
   -3,  /* (311) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+
   -5,  /* (312) windowdefn ::= nm AS LP window RP */
+
   -5,  /* (313) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+
   -6,  /* (314) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+
   -4,  /* (315) window ::= ORDER BY sortlist frame_opt */
+
   -5,  /* (316) window ::= nm ORDER BY sortlist frame_opt */
+
   -2,  /* (317) window ::= nm frame_opt */
+
    0,  /* (318) frame_opt ::= */
+
   -3,  /* (319) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+
   -6,  /* (320) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+
   -1,  /* (321) range_or_rows ::= RANGE|ROWS|GROUPS */
+
   -1,  /* (322) frame_bound_s ::= frame_bound */
+
   -2,  /* (323) frame_bound_s ::= UNBOUNDED PRECEDING */
+
   -1,  /* (324) frame_bound_e ::= frame_bound */
+
   -2,  /* (325) frame_bound_e ::= UNBOUNDED FOLLOWING */
+
   -2,  /* (326) frame_bound ::= expr PRECEDING|FOLLOWING */
+
   -2,  /* (327) frame_bound ::= CURRENT ROW */
+
    0,  /* (328) frame_exclude_opt ::= */
+
   -2,  /* (329) frame_exclude_opt ::= EXCLUDE frame_exclude */
+
   -2,  /* (330) frame_exclude ::= NO OTHERS */
+
   -2,  /* (331) frame_exclude ::= CURRENT ROW */
+
   -1,  /* (332) frame_exclude ::= GROUP|TIES */
+
   -2,  /* (333) window_clause ::= WINDOW windowdefn_list */
+
   -2,  /* (334) filter_over ::= filter_clause over_clause */
+
   -1,  /* (335) filter_over ::= over_clause */
+
   -1,  /* (336) filter_over ::= filter_clause */
+
   -4,  /* (337) over_clause ::= OVER LP window RP */
+
   -2,  /* (338) over_clause ::= OVER nm */
+
   -5,  /* (339) filter_clause ::= FILTER LP WHERE expr RP */
+
   -1,  /* (340) input ::= cmdlist */
+
   -2,  /* (341) cmdlist ::= cmdlist ecmd */
+
   -1,  /* (342) cmdlist ::= ecmd */
+
   -1,  /* (343) ecmd ::= SEMI */
+
   -2,  /* (344) ecmd ::= cmdx SEMI */
+
   -3,  /* (345) ecmd ::= explain cmdx SEMI */
+
    0,  /* (346) trans_opt ::= */
+
   -1,  /* (347) trans_opt ::= TRANSACTION */
+
   -2,  /* (348) trans_opt ::= TRANSACTION nm */
+
   -1,  /* (349) savepoint_opt ::= SAVEPOINT */
+
    0,  /* (350) savepoint_opt ::= */
+
   -2,  /* (351) cmd ::= create_table create_table_args */
+
   -1,  /* (352) table_option_set ::= table_option */
+
   -4,  /* (353) columnlist ::= columnlist COMMA columnname carglist */
+
   -2,  /* (354) columnlist ::= columnname carglist */
+
   -1,  /* (355) nm ::= ID|INDEXED|JOIN_KW */
+
   -1,  /* (356) nm ::= STRING */
+
   -1,  /* (357) typetoken ::= typename */
+
   -1,  /* (358) typename ::= ID|STRING */
+
   -1,  /* (359) signed ::= plus_num */
+
   -1,  /* (360) signed ::= minus_num */
+
   -2,  /* (361) carglist ::= carglist ccons */
+
    0,  /* (362) carglist ::= */
+
   -2,  /* (363) ccons ::= NULL onconf */
+
   -4,  /* (364) ccons ::= GENERATED ALWAYS AS generated */
+
   -2,  /* (365) ccons ::= AS generated */
+
   -2,  /* (366) conslist_opt ::= COMMA conslist */
+
   -3,  /* (367) conslist ::= conslist tconscomma tcons */
+
   -1,  /* (368) conslist ::= tcons */
+
    0,  /* (369) tconscomma ::= */
+
   -1,  /* (370) defer_subclause_opt ::= defer_subclause */
+
   -1,  /* (371) resolvetype ::= raisetype */
+
   -1,  /* (372) selectnowith ::= oneselect */
+
   -1,  /* (373) oneselect ::= values */
+
   -2,  /* (374) sclp ::= selcollist COMMA */
+
   -1,  /* (375) as ::= ID|STRING */
+
   -1,  /* (376) indexed_opt ::= indexed_by */
+
    0,  /* (377) returning ::= */
+
   -1,  /* (378) expr ::= term */
+
   -1,  /* (379) likeop ::= LIKE_KW|MATCH */
+
   -1,  /* (380) case_operand ::= expr */
+
   -1,  /* (381) exprlist ::= nexprlist */
+
   -1,  /* (382) nmnum ::= plus_num */
+
   -1,  /* (383) nmnum ::= nm */
+
   -1,  /* (384) nmnum ::= ON */
+
   -1,  /* (385) nmnum ::= DELETE */
+
   -1,  /* (386) nmnum ::= DEFAULT */
+
   -1,  /* (387) plus_num ::= INTEGER|FLOAT */
+
    0,  /* (388) foreach_clause ::= */
+
   -3,  /* (389) foreach_clause ::= FOR EACH ROW */
+
   -1,  /* (390) trnm ::= nm */
+
    0,  /* (391) tridxby ::= */
+
   -1,  /* (392) database_kw_opt ::= DATABASE */
+
    0,  /* (393) database_kw_opt ::= */
+
    0,  /* (394) kwcolumn_opt ::= */
+
   -1,  /* (395) kwcolumn_opt ::= COLUMNKW */
+
   -1,  /* (396) vtabarglist ::= vtabarg */
+
   -3,  /* (397) vtabarglist ::= vtabarglist COMMA vtabarg */
+
   -2,  /* (398) vtabarg ::= vtabarg vtabargtoken */
+
    0,  /* (399) anylist ::= */
+
   -4,  /* (400) anylist ::= anylist LP anylist RP */
+
   -2,  /* (401) anylist ::= anylist ANY */
+
    0,  /* (402) with ::= */
+
   -1,  /* (403) windowdefn_list ::= windowdefn */
+
   -1,  /* (404) window ::= frame_opt */
};

static void yy_accept(yyParser*);  /* Forward Declaration */
@@ -172816,7 +173989,7 @@ static YYACTIONTYPE yy_reduce(
      case 5: /* transtype ::= DEFERRED */
      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
-
      case 319: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==319);
+
      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 */
@@ -172853,7 +174026,7 @@ static YYACTIONTYPE yy_reduce(
      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);
+
      case 244: /* collate ::= */ yytestcase(yyruleno==244);
{yymsp[1].minor.yy394 = 0;}
        break;
      case 16: /* ifnotexists ::= IF NOT EXISTS */
@@ -173037,9 +174210,9 @@ static YYACTIONTYPE yy_reduce(
        break;
      case 63: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
      case 80: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==80);
-
      case 215: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==215);
-
      case 218: /* in_op ::= NOT IN */ yytestcase(yyruleno==218);
-
      case 243: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==243);
+
      case 217: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==217);
+
      case 220: /* in_op ::= NOT IN */ yytestcase(yyruleno==220);
+
      case 245: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==245);
{yymsp[-1].minor.yy394 = 1;}
        break;
      case 64: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
@@ -173188,9 +174361,9 @@ static YYACTIONTYPE yy_reduce(
      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);
+
      case 232: /* exprlist ::= */ yytestcase(yyruleno==232);
+
      case 235: /* paren_exprlist ::= */ yytestcase(yyruleno==235);
+
      case 240: /* eidlist_opt ::= */ yytestcase(yyruleno==240);
{yymsp[1].minor.yy322 = 0;}
        break;
      case 100: /* selcollist ::= sclp scanpt expr scanpt as */
@@ -173219,8 +174392,8 @@ static YYACTIONTYPE yy_reduce(
        break;
      case 103: /* as ::= AS nm */
      case 115: /* dbnm ::= DOT nm */ yytestcase(yyruleno==115);
-
      case 254: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==254);
-
      case 255: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==255);
+
      case 256: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==256);
+
      case 257: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==257);
{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
        break;
      case 105: /* from ::= */
@@ -173392,16 +174565,16 @@ static YYACTIONTYPE yy_reduce(
      case 146: /* limit_opt ::= */ yytestcase(yyruleno==146);
      case 151: /* where_opt ::= */ yytestcase(yyruleno==151);
      case 153: /* where_opt_ret ::= */ yytestcase(yyruleno==153);
-
      case 228: /* case_else ::= */ yytestcase(yyruleno==228);
-
      case 229: /* case_operand ::= */ yytestcase(yyruleno==229);
-
      case 248: /* vinto ::= */ yytestcase(yyruleno==248);
+
      case 230: /* case_else ::= */ yytestcase(yyruleno==230);
+
      case 231: /* case_operand ::= */ yytestcase(yyruleno==231);
+
      case 250: /* vinto ::= */ yytestcase(yyruleno==250);
{yymsp[1].minor.yy528 = 0;}
        break;
      case 145: /* having_opt ::= HAVING expr */
      case 152: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==152);
      case 154: /* where_opt_ret ::= WHERE expr */ yytestcase(yyruleno==154);
-
      case 227: /* case_else ::= ELSE expr */ yytestcase(yyruleno==227);
-
      case 247: /* vinto ::= INTO expr */ yytestcase(yyruleno==247);
+
      case 229: /* case_else ::= ELSE expr */ yytestcase(yyruleno==229);
+
      case 249: /* vinto ::= INTO expr */ yytestcase(yyruleno==249);
{yymsp[-1].minor.yy528 = yymsp[0].minor.yy528;}
        break;
      case 147: /* limit_opt ::= LIMIT expr */
@@ -173587,33 +174760,48 @@ static YYACTIONTYPE yy_reduce(
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
-
      case 188: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
+
      case 188: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */
+
{
+
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-4].minor.yy322, &yymsp[-7].minor.yy0, yymsp[-5].minor.yy394);
+
  sqlite3ExprAddFunctionOrderBy(pParse, yylhsminor.yy528, yymsp[-1].minor.yy322);
+
}
+
  yymsp[-7].minor.yy528 = yylhsminor.yy528;
+
        break;
+
      case 189: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
}
  yymsp[-3].minor.yy528 = yylhsminor.yy528;
        break;
-
      case 189: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
+
      case 190: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy322, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy394);
  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
}
  yymsp[-5].minor.yy528 = yylhsminor.yy528;
        break;
-
      case 190: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
+
      case 191: /* expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */
+
{
+
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-5].minor.yy322, &yymsp[-8].minor.yy0, yymsp[-6].minor.yy394);
+
  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
+
  sqlite3ExprAddFunctionOrderBy(pParse, yylhsminor.yy528, yymsp[-2].minor.yy322);
+
}
+
  yymsp[-8].minor.yy528 = yylhsminor.yy528;
+
        break;
+
      case 192: /* expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
  sqlite3WindowAttach(pParse, yylhsminor.yy528, yymsp[0].minor.yy41);
}
  yymsp[-4].minor.yy528 = yylhsminor.yy528;
        break;
-
      case 191: /* term ::= CTIME_KW */
+
      case 193: /* term ::= CTIME_KW */
{
  yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
}
  yymsp[0].minor.yy528 = yylhsminor.yy528;
        break;
-
      case 192: /* expr ::= LP nexprlist COMMA expr RP */
+
      case 194: /* expr ::= LP nexprlist COMMA expr RP */
{
  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528);
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
@@ -173627,22 +174815,22 @@ static YYACTIONTYPE yy_reduce(
  }
}
        break;
-
      case 193: /* expr ::= expr AND expr */
+
      case 195: /* expr ::= expr AND expr */
{yymsp[-2].minor.yy528=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
        break;
-
      case 194: /* expr ::= expr OR expr */
-
      case 195: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==195);
-
      case 196: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==196);
-
      case 197: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==197);
-
      case 198: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==198);
-
      case 199: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==199);
-
      case 200: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==200);
+
      case 196: /* expr ::= expr OR expr */
+
      case 197: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==197);
+
      case 198: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==198);
+
      case 199: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==199);
+
      case 200: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==200);
+
      case 201: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==201);
+
      case 202: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==202);
{yymsp[-2].minor.yy528=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
        break;
-
      case 201: /* likeop ::= NOT LIKE_KW|MATCH */
+
      case 203: /* likeop ::= NOT LIKE_KW|MATCH */
{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
        break;
-
      case 202: /* expr ::= expr likeop expr */
+
      case 204: /* expr ::= expr likeop expr */
{
  ExprList *pList;
  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
@@ -173654,7 +174842,7 @@ static YYACTIONTYPE yy_reduce(
  if( yymsp[-2].minor.yy528 ) yymsp[-2].minor.yy528->flags |= EP_InfixFunc;
}
        break;
-
      case 203: /* expr ::= expr likeop expr ESCAPE expr */
+
      case 205: /* expr ::= expr likeop expr ESCAPE expr */
{
  ExprList *pList;
  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
@@ -173667,47 +174855,47 @@ static YYACTIONTYPE yy_reduce(
  if( yymsp[-4].minor.yy528 ) yymsp[-4].minor.yy528->flags |= EP_InfixFunc;
}
        break;
-
      case 204: /* expr ::= expr ISNULL|NOTNULL */
+
      case 206: /* expr ::= expr ISNULL|NOTNULL */
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy528,0);}
        break;
-
      case 205: /* expr ::= expr NOT NULL */
+
      case 207: /* expr ::= expr NOT NULL */
{yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy528,0);}
        break;
-
      case 206: /* expr ::= expr IS expr */
+
      case 208: /* expr ::= expr IS expr */
{
  yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-2].minor.yy528, TK_ISNULL);
}
        break;
-
      case 207: /* expr ::= expr IS NOT expr */
+
      case 209: /* expr ::= expr IS NOT expr */
{
  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-3].minor.yy528, TK_NOTNULL);
}
        break;
-
      case 208: /* expr ::= expr IS NOT DISTINCT FROM expr */
+
      case 210: /* expr ::= expr IS NOT DISTINCT FROM expr */
{
  yymsp[-5].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-5].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-5].minor.yy528, TK_ISNULL);
}
        break;
-
      case 209: /* expr ::= expr IS DISTINCT FROM expr */
+
      case 211: /* expr ::= expr IS DISTINCT FROM expr */
{
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-4].minor.yy528,yymsp[0].minor.yy528);
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-4].minor.yy528, TK_NOTNULL);
}
        break;
-
      case 210: /* expr ::= NOT expr */
-
      case 211: /* expr ::= BITNOT expr */ yytestcase(yyruleno==211);
+
      case 212: /* expr ::= NOT expr */
+
      case 213: /* expr ::= BITNOT expr */ yytestcase(yyruleno==213);
{yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy528, 0);/*A-overwrites-B*/}
        break;
-
      case 212: /* expr ::= PLUS|MINUS expr */
+
      case 214: /* expr ::= PLUS|MINUS expr */
{
  yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy528, 0);
  /*A-overwrites-B*/
}
        break;
-
      case 213: /* expr ::= expr PTR expr */
+
      case 215: /* expr ::= expr PTR expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy528);
@@ -173715,11 +174903,11 @@ static YYACTIONTYPE yy_reduce(
}
  yymsp[-2].minor.yy528 = yylhsminor.yy528;
        break;
-
      case 214: /* between_op ::= BETWEEN */
-
      case 217: /* in_op ::= IN */ yytestcase(yyruleno==217);
+
      case 216: /* between_op ::= BETWEEN */
+
      case 219: /* in_op ::= IN */ yytestcase(yyruleno==219);
{yymsp[0].minor.yy394 = 0;}
        break;
-
      case 216: /* expr ::= expr between_op expr AND expr */
+
      case 218: /* expr ::= expr between_op expr AND expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy528);
@@ -173732,7 +174920,7 @@ static YYACTIONTYPE yy_reduce(
  if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
}
        break;
-
      case 219: /* expr ::= expr in_op LP exprlist RP */
+
      case 221: /* expr ::= expr in_op LP exprlist RP */
{
    if( yymsp[-1].minor.yy322==0 ){
      /* Expressions of the form
@@ -173778,20 +174966,20 @@ static YYACTIONTYPE yy_reduce(
    }
  }
        break;
-
      case 220: /* expr ::= LP select RP */
+
      case 222: /* expr ::= LP select RP */
{
    yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy528, yymsp[-1].minor.yy47);
  }
        break;
-
      case 221: /* expr ::= expr in_op LP select RP */
+
      case 223: /* expr ::= expr in_op LP select RP */
{
    yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, yymsp[-1].minor.yy47);
    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  }
        break;
-
      case 222: /* expr ::= expr in_op nm dbnm paren_exprlist */
+
      case 224: /* 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);
@@ -173801,14 +174989,14 @@ static YYACTIONTYPE yy_reduce(
    if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
  }
        break;
-
      case 223: /* expr ::= EXISTS LP select RP */
+
      case 225: /* expr ::= EXISTS LP select RP */
{
    Expr *p;
    p = yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy47);
  }
        break;
-
      case 224: /* expr ::= CASE case_operand case_exprlist case_else END */
+
      case 226: /* expr ::= CASE case_operand case_exprlist case_else END */
{
  yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy528, 0);
  if( yymsp[-4].minor.yy528 ){
@@ -173820,29 +175008,29 @@ static YYACTIONTYPE yy_reduce(
  }
}
        break;
-
      case 225: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
+
      case 227: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
{
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
  yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[0].minor.yy528);
}
        break;
-
      case 226: /* case_exprlist ::= WHEN expr THEN expr */
+
      case 228: /* case_exprlist ::= WHEN expr THEN expr */
{
  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
  yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, yymsp[0].minor.yy528);
}
        break;
-
      case 231: /* nexprlist ::= nexprlist COMMA expr */
+
      case 233: /* nexprlist ::= nexprlist COMMA expr */
{yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy528);}
        break;
-
      case 232: /* nexprlist ::= expr */
+
      case 234: /* nexprlist ::= expr */
{yymsp[0].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy528); /*A-overwrites-Y*/}
        break;
-
      case 234: /* paren_exprlist ::= LP exprlist RP */
-
      case 239: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==239);
+
      case 236: /* paren_exprlist ::= LP exprlist RP */
+
      case 241: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==241);
{yymsp[-2].minor.yy322 = yymsp[-1].minor.yy322;}
        break;
-
      case 235: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+
      case 237: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
{
  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy394,
@@ -173852,48 +175040,48 @@ static YYACTIONTYPE yy_reduce(
  }
}
        break;
-
      case 236: /* uniqueflag ::= UNIQUE */
-
      case 278: /* raisetype ::= ABORT */ yytestcase(yyruleno==278);
+
      case 238: /* uniqueflag ::= UNIQUE */
+
      case 280: /* raisetype ::= ABORT */ yytestcase(yyruleno==280);
{yymsp[0].minor.yy394 = OE_Abort;}
        break;
-
      case 237: /* uniqueflag ::= */
+
      case 239: /* uniqueflag ::= */
{yymsp[1].minor.yy394 = OE_None;}
        break;
-
      case 240: /* eidlist ::= eidlist COMMA nm collate sortorder */
+
      case 242: /* eidlist ::= eidlist COMMA nm collate sortorder */
{
  yymsp[-4].minor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394);
}
        break;
-
      case 241: /* eidlist ::= nm collate sortorder */
+
      case 243: /* eidlist ::= nm collate sortorder */
{
  yymsp[-2].minor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy394, yymsp[0].minor.yy394); /*A-overwrites-Y*/
}
        break;
-
      case 244: /* cmd ::= DROP INDEX ifexists fullname */
+
      case 246: /* cmd ::= DROP INDEX ifexists fullname */
{sqlite3DropIndex(pParse, yymsp[0].minor.yy131, yymsp[-1].minor.yy394);}
        break;
-
      case 245: /* cmd ::= VACUUM vinto */
+
      case 247: /* cmd ::= VACUUM vinto */
{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy528);}
        break;
-
      case 246: /* cmd ::= VACUUM nm vinto */
+
      case 248: /* cmd ::= VACUUM nm vinto */
{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy528);}
        break;
-
      case 249: /* cmd ::= PRAGMA nm dbnm */
+
      case 251: /* cmd ::= PRAGMA nm dbnm */
{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
        break;
-
      case 250: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
+
      case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
        break;
-
      case 251: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
+
      case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
        break;
-
      case 252: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
+
      case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
        break;
-
      case 253: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
+
      case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
        break;
-
      case 256: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+
      case 258: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
{
  Token all;
  all.z = yymsp[-3].minor.yy0.z;
@@ -173901,50 +175089,50 @@ static YYACTIONTYPE yy_reduce(
  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy33, &all);
}
        break;
-
      case 257: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+
      case 259: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
{
  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy394, yymsp[-4].minor.yy180.a, yymsp[-4].minor.yy180.b, yymsp[-2].minor.yy131, yymsp[0].minor.yy528, yymsp[-10].minor.yy394, yymsp[-8].minor.yy394);
  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
}
        break;
-
      case 258: /* trigger_time ::= BEFORE|AFTER */
+
      case 260: /* trigger_time ::= BEFORE|AFTER */
{ yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/ }
        break;
-
      case 259: /* trigger_time ::= INSTEAD OF */
+
      case 261: /* trigger_time ::= INSTEAD OF */
{ yymsp[-1].minor.yy394 = TK_INSTEAD;}
        break;
-
      case 260: /* trigger_time ::= */
+
      case 262: /* trigger_time ::= */
{ yymsp[1].minor.yy394 = TK_BEFORE; }
        break;
-
      case 261: /* trigger_event ::= DELETE|INSERT */
-
      case 262: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==262);
+
      case 263: /* trigger_event ::= DELETE|INSERT */
+
      case 264: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==264);
{yymsp[0].minor.yy180.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy180.b = 0;}
        break;
-
      case 263: /* trigger_event ::= UPDATE OF idlist */
+
      case 265: /* trigger_event ::= UPDATE OF idlist */
{yymsp[-2].minor.yy180.a = TK_UPDATE; yymsp[-2].minor.yy180.b = yymsp[0].minor.yy254;}
        break;
-
      case 264: /* when_clause ::= */
-
      case 283: /* key_opt ::= */ yytestcase(yyruleno==283);
+
      case 266: /* when_clause ::= */
+
      case 285: /* key_opt ::= */ yytestcase(yyruleno==285);
{ yymsp[1].minor.yy528 = 0; }
        break;
-
      case 265: /* when_clause ::= WHEN expr */
-
      case 284: /* key_opt ::= KEY expr */ yytestcase(yyruleno==284);
+
      case 267: /* when_clause ::= WHEN expr */
+
      case 286: /* key_opt ::= KEY expr */ yytestcase(yyruleno==286);
{ yymsp[-1].minor.yy528 = yymsp[0].minor.yy528; }
        break;
-
      case 266: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+
      case 268: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
{
  assert( yymsp[-2].minor.yy33!=0 );
  yymsp[-2].minor.yy33->pLast->pNext = yymsp[-1].minor.yy33;
  yymsp[-2].minor.yy33->pLast = yymsp[-1].minor.yy33;
}
        break;
-
      case 267: /* trigger_cmd_list ::= trigger_cmd SEMI */
+
      case 269: /* trigger_cmd_list ::= trigger_cmd SEMI */
{
  assert( yymsp[-1].minor.yy33!=0 );
  yymsp[-1].minor.yy33->pLast = yymsp[-1].minor.yy33;
}
        break;
-
      case 268: /* trnm ::= nm DOT nm */
+
      case 270: /* trnm ::= nm DOT nm */
{
  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  sqlite3ErrorMsg(pParse,
@@ -173952,39 +175140,39 @@ static YYACTIONTYPE yy_reduce(
        "statements within triggers");
}
        break;
-
      case 269: /* tridxby ::= INDEXED BY nm */
+
      case 271: /* tridxby ::= INDEXED BY nm */
{
  sqlite3ErrorMsg(pParse,
        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}
        break;
-
      case 270: /* tridxby ::= NOT INDEXED */
+
      case 272: /* tridxby ::= NOT INDEXED */
{
  sqlite3ErrorMsg(pParse,
        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
        "within triggers");
}
        break;
-
      case 271: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+
      case 273: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
{yylhsminor.yy33 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy131, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528, yymsp[-7].minor.yy394, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy522);}
  yymsp[-8].minor.yy33 = yylhsminor.yy33;
        break;
-
      case 272: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+
      case 274: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
{
   yylhsminor.yy33 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy254,yymsp[-2].minor.yy47,yymsp[-6].minor.yy394,yymsp[-1].minor.yy444,yymsp[-7].minor.yy522,yymsp[0].minor.yy522);/*yylhsminor.yy33-overwrites-yymsp[-6].minor.yy394*/
}
  yymsp[-7].minor.yy33 = yylhsminor.yy33;
        break;
-
      case 273: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+
      case 275: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
{yylhsminor.yy33 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy528, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy522);}
  yymsp[-5].minor.yy33 = yylhsminor.yy33;
        break;
-
      case 274: /* trigger_cmd ::= scanpt select scanpt */
+
      case 276: /* trigger_cmd ::= scanpt select scanpt */
{yylhsminor.yy33 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy47, yymsp[-2].minor.yy522, yymsp[0].minor.yy522); /*yylhsminor.yy33-overwrites-yymsp[-1].minor.yy47*/}
  yymsp[-2].minor.yy33 = yylhsminor.yy33;
        break;
-
      case 275: /* expr ::= RAISE LP IGNORE RP */
+
      case 277: /* expr ::= RAISE LP IGNORE RP */
{
  yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  if( yymsp[-3].minor.yy528 ){
@@ -173992,7 +175180,7 @@ static YYACTIONTYPE yy_reduce(
  }
}
        break;
-
      case 276: /* expr ::= RAISE LP raisetype COMMA nm RP */
+
      case 278: /* expr ::= RAISE LP raisetype COMMA nm RP */
{
  yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  if( yymsp[-5].minor.yy528 ) {
@@ -174000,114 +175188,114 @@ static YYACTIONTYPE yy_reduce(
  }
}
        break;
-
      case 277: /* raisetype ::= ROLLBACK */
+
      case 279: /* raisetype ::= ROLLBACK */
{yymsp[0].minor.yy394 = OE_Rollback;}
        break;
-
      case 279: /* raisetype ::= FAIL */
+
      case 281: /* raisetype ::= FAIL */
{yymsp[0].minor.yy394 = OE_Fail;}
        break;
-
      case 280: /* cmd ::= DROP TRIGGER ifexists fullname */
+
      case 282: /* cmd ::= DROP TRIGGER ifexists fullname */
{
  sqlite3DropTrigger(pParse,yymsp[0].minor.yy131,yymsp[-1].minor.yy394);
}
        break;
-
      case 281: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+
      case 283: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
{
  sqlite3Attach(pParse, yymsp[-3].minor.yy528, yymsp[-1].minor.yy528, yymsp[0].minor.yy528);
}
        break;
-
      case 282: /* cmd ::= DETACH database_kw_opt expr */
+
      case 284: /* cmd ::= DETACH database_kw_opt expr */
{
  sqlite3Detach(pParse, yymsp[0].minor.yy528);
}
        break;
-
      case 285: /* cmd ::= REINDEX */
+
      case 287: /* cmd ::= REINDEX */
{sqlite3Reindex(pParse, 0, 0);}
        break;
-
      case 286: /* cmd ::= REINDEX nm dbnm */
+
      case 288: /* cmd ::= REINDEX nm dbnm */
{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
        break;
-
      case 287: /* cmd ::= ANALYZE */
+
      case 289: /* cmd ::= ANALYZE */
{sqlite3Analyze(pParse, 0, 0);}
        break;
-
      case 288: /* cmd ::= ANALYZE nm dbnm */
+
      case 290: /* cmd ::= ANALYZE nm dbnm */
{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
        break;
-
      case 289: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
+
      case 291: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
{
  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy131,&yymsp[0].minor.yy0);
}
        break;
-
      case 290: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+
      case 292: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
{
  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
}
        break;
-
      case 291: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
+
      case 293: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
{
  sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy131, &yymsp[0].minor.yy0);
}
        break;
-
      case 292: /* add_column_fullname ::= fullname */
+
      case 294: /* add_column_fullname ::= fullname */
{
  disableLookaside(pParse);
  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy131);
}
        break;
-
      case 293: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+
      case 295: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
{
  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy131, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
}
        break;
-
      case 294: /* cmd ::= create_vtab */
+
      case 296: /* cmd ::= create_vtab */
{sqlite3VtabFinishParse(pParse,0);}
        break;
-
      case 295: /* cmd ::= create_vtab LP vtabarglist RP */
+
      case 297: /* cmd ::= create_vtab LP vtabarglist RP */
{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
        break;
-
      case 296: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+
      case 298: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
{
    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy394);
}
        break;
-
      case 297: /* vtabarg ::= */
+
      case 299: /* vtabarg ::= */
{sqlite3VtabArgInit(pParse);}
        break;
-
      case 298: /* vtabargtoken ::= ANY */
-
      case 299: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==299);
-
      case 300: /* lp ::= LP */ yytestcase(yyruleno==300);
+
      case 300: /* vtabargtoken ::= ANY */
+
      case 301: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==301);
+
      case 302: /* lp ::= LP */ yytestcase(yyruleno==302);
{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
        break;
-
      case 301: /* with ::= WITH wqlist */
-
      case 302: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==302);
+
      case 303: /* with ::= WITH wqlist */
+
      case 304: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==304);
{ sqlite3WithPush(pParse, yymsp[0].minor.yy521, 1); }
        break;
-
      case 303: /* wqas ::= AS */
+
      case 305: /* wqas ::= AS */
{yymsp[0].minor.yy516 = M10d_Any;}
        break;
-
      case 304: /* wqas ::= AS MATERIALIZED */
+
      case 306: /* wqas ::= AS MATERIALIZED */
{yymsp[-1].minor.yy516 = M10d_Yes;}
        break;
-
      case 305: /* wqas ::= AS NOT MATERIALIZED */
+
      case 307: /* wqas ::= AS NOT MATERIALIZED */
{yymsp[-2].minor.yy516 = M10d_No;}
        break;
-
      case 306: /* wqitem ::= nm eidlist_opt wqas LP select RP */
+
      case 308: /* wqitem ::= nm eidlist_opt wqas LP select RP */
{
  yymsp[-5].minor.yy385 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy47, yymsp[-3].minor.yy516); /*A-overwrites-X*/
}
        break;
-
      case 307: /* wqlist ::= wqitem */
+
      case 309: /* wqlist ::= wqitem */
{
  yymsp[0].minor.yy521 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy385); /*A-overwrites-X*/
}
        break;
-
      case 308: /* wqlist ::= wqlist COMMA wqitem */
+
      case 310: /* wqlist ::= wqlist COMMA wqitem */
{
  yymsp[-2].minor.yy521 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy521, yymsp[0].minor.yy385);
}
        break;
-
      case 309: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
+
      case 311: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
{
  assert( yymsp[0].minor.yy41!=0 );
  sqlite3WindowChain(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy41);
@@ -174116,7 +175304,7 @@ static YYACTIONTYPE yy_reduce(
}
  yymsp[-2].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 310: /* windowdefn ::= nm AS LP window RP */
+
      case 312: /* windowdefn ::= nm AS LP window RP */
{
  if( ALWAYS(yymsp[-1].minor.yy41) ){
    yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
@@ -174125,83 +175313,83 @@ static YYACTIONTYPE yy_reduce(
}
  yymsp[-4].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 311: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+
      case 313: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
{
  yymsp[-4].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, 0);
}
        break;
-
      case 312: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+
      case 314: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, &yymsp[-5].minor.yy0);
}
  yymsp[-5].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 313: /* window ::= ORDER BY sortlist frame_opt */
+
      case 315: /* window ::= ORDER BY sortlist frame_opt */
{
  yymsp[-3].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, 0);
}
        break;
-
      case 314: /* window ::= nm ORDER BY sortlist frame_opt */
+
      case 316: /* window ::= nm ORDER BY sortlist frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
}
  yymsp[-4].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 315: /* window ::= nm frame_opt */
+
      case 317: /* window ::= nm frame_opt */
{
  yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, 0, &yymsp[-1].minor.yy0);
}
  yymsp[-1].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 316: /* frame_opt ::= */
+
      case 318: /* frame_opt ::= */
{
  yymsp[1].minor.yy41 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
}
        break;
-
      case 317: /* 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.yy41 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy394, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy516);
}
  yymsp[-2].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 318: /* 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.yy41 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy394, yymsp[-3].minor.yy595.eType, yymsp[-3].minor.yy595.pExpr, yymsp[-1].minor.yy595.eType, yymsp[-1].minor.yy595.pExpr, yymsp[0].minor.yy516);
}
  yymsp[-5].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 320: /* frame_bound_s ::= frame_bound */
-
      case 322: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==322);
+
      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 321: /* frame_bound_s ::= UNBOUNDED PRECEDING */
-
      case 323: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==323);
-
      case 325: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==325);
+
      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 324: /* frame_bound ::= expr PRECEDING|FOLLOWING */
+
      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 326: /* frame_exclude_opt ::= */
+
      case 328: /* frame_exclude_opt ::= */
{yymsp[1].minor.yy516 = 0;}
        break;
-
      case 327: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
+
      case 329: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
{yymsp[-1].minor.yy516 = yymsp[0].minor.yy516;}
        break;
-
      case 328: /* frame_exclude ::= NO OTHERS */
-
      case 329: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==329);
+
      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 330: /* frame_exclude ::= GROUP|TIES */
+
      case 332: /* frame_exclude ::= GROUP|TIES */
{yymsp[0].minor.yy516 = yymsp[0].major; /*A-overwrites-X*/}
        break;
-
      case 331: /* window_clause ::= WINDOW windowdefn_list */
+
      case 333: /* window_clause ::= WINDOW windowdefn_list */
{ yymsp[-1].minor.yy41 = yymsp[0].minor.yy41; }
        break;
-
      case 332: /* filter_over ::= filter_clause over_clause */
+
      case 334: /* filter_over ::= filter_clause over_clause */
{
  if( yymsp[0].minor.yy41 ){
    yymsp[0].minor.yy41->pFilter = yymsp[-1].minor.yy528;
@@ -174212,13 +175400,13 @@ static YYACTIONTYPE yy_reduce(
}
  yymsp[-1].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 333: /* filter_over ::= over_clause */
+
      case 335: /* filter_over ::= over_clause */
{
  yylhsminor.yy41 = yymsp[0].minor.yy41;
}
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 334: /* filter_over ::= filter_clause */
+
      case 336: /* filter_over ::= filter_clause */
{
  yylhsminor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  if( yylhsminor.yy41 ){
@@ -174230,13 +175418,13 @@ static YYACTIONTYPE yy_reduce(
}
  yymsp[0].minor.yy41 = yylhsminor.yy41;
        break;
-
      case 335: /* over_clause ::= OVER LP window RP */
+
      case 337: /* over_clause ::= OVER LP window RP */
{
  yymsp[-3].minor.yy41 = yymsp[-1].minor.yy41;
  assert( yymsp[-3].minor.yy41!=0 );
}
        break;
-
      case 336: /* over_clause ::= OVER nm */
+
      case 338: /* over_clause ::= OVER nm */
{
  yymsp[-1].minor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  if( yymsp[-1].minor.yy41 ){
@@ -174244,75 +175432,75 @@ static YYACTIONTYPE yy_reduce(
  }
}
        break;
-
      case 337: /* filter_clause ::= FILTER LP WHERE expr RP */
+
      case 339: /* filter_clause ::= FILTER LP WHERE expr RP */
{ yymsp[-4].minor.yy528 = yymsp[-1].minor.yy528; }
        break;
      default:
-
      /* (338) input ::= cmdlist */ yytestcase(yyruleno==338);
-
      /* (339) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==339);
-
      /* (340) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=340);
-
      /* (341) ecmd ::= SEMI */ yytestcase(yyruleno==341);
-
      /* (342) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==342);
-
      /* (343) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=343);
-
      /* (344) trans_opt ::= */ yytestcase(yyruleno==344);
-
      /* (345) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==345);
-
      /* (346) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==346);
-
      /* (347) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==347);
-
      /* (348) savepoint_opt ::= */ yytestcase(yyruleno==348);
-
      /* (349) cmd ::= create_table create_table_args */ yytestcase(yyruleno==349);
-
      /* (350) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=350);
-
      /* (351) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==351);
-
      /* (352) columnlist ::= columnname carglist */ yytestcase(yyruleno==352);
-
      /* (353) nm ::= ID|INDEXED|JOIN_KW */ yytestcase(yyruleno==353);
-
      /* (354) nm ::= STRING */ yytestcase(yyruleno==354);
-
      /* (355) typetoken ::= typename */ yytestcase(yyruleno==355);
-
      /* (356) typename ::= ID|STRING */ yytestcase(yyruleno==356);
-
      /* (357) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=357);
-
      /* (358) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=358);
-
      /* (359) carglist ::= carglist ccons */ yytestcase(yyruleno==359);
-
      /* (360) carglist ::= */ yytestcase(yyruleno==360);
-
      /* (361) ccons ::= NULL onconf */ yytestcase(yyruleno==361);
-
      /* (362) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==362);
-
      /* (363) ccons ::= AS generated */ yytestcase(yyruleno==363);
-
      /* (364) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==364);
-
      /* (365) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==365);
-
      /* (366) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=366);
-
      /* (367) tconscomma ::= */ yytestcase(yyruleno==367);
-
      /* (368) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=368);
-
      /* (369) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=369);
-
      /* (370) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=370);
-
      /* (371) oneselect ::= values */ yytestcase(yyruleno==371);
-
      /* (372) sclp ::= selcollist COMMA */ yytestcase(yyruleno==372);
-
      /* (373) as ::= ID|STRING */ yytestcase(yyruleno==373);
-
      /* (374) indexed_opt ::= indexed_by (OPTIMIZED OUT) */ assert(yyruleno!=374);
-
      /* (375) returning ::= */ yytestcase(yyruleno==375);
-
      /* (376) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=376);
-
      /* (377) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==377);
-
      /* (378) case_operand ::= expr */ yytestcase(yyruleno==378);
-
      /* (379) exprlist ::= nexprlist */ yytestcase(yyruleno==379);
-
      /* (380) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=380);
-
      /* (381) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=381);
-
      /* (382) nmnum ::= ON */ yytestcase(yyruleno==382);
-
      /* (383) nmnum ::= DELETE */ yytestcase(yyruleno==383);
-
      /* (384) nmnum ::= DEFAULT */ yytestcase(yyruleno==384);
-
      /* (385) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==385);
-
      /* (386) foreach_clause ::= */ yytestcase(yyruleno==386);
-
      /* (387) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==387);
-
      /* (388) trnm ::= nm */ yytestcase(yyruleno==388);
-
      /* (389) tridxby ::= */ yytestcase(yyruleno==389);
-
      /* (390) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==390);
-
      /* (391) database_kw_opt ::= */ yytestcase(yyruleno==391);
-
      /* (392) kwcolumn_opt ::= */ yytestcase(yyruleno==392);
-
      /* (393) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==393);
-
      /* (394) vtabarglist ::= vtabarg */ yytestcase(yyruleno==394);
-
      /* (395) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==395);
-
      /* (396) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==396);
-
      /* (397) anylist ::= */ yytestcase(yyruleno==397);
-
      /* (398) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==398);
-
      /* (399) anylist ::= anylist ANY */ yytestcase(yyruleno==399);
-
      /* (400) with ::= */ yytestcase(yyruleno==400);
-
      /* (401) windowdefn_list ::= windowdefn (OPTIMIZED OUT) */ assert(yyruleno!=401);
-
      /* (402) window ::= frame_opt (OPTIMIZED OUT) */ assert(yyruleno!=402);
+
      /* (340) input ::= cmdlist */ yytestcase(yyruleno==340);
+
      /* (341) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==341);
+
      /* (342) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=342);
+
      /* (343) ecmd ::= SEMI */ yytestcase(yyruleno==343);
+
      /* (344) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==344);
+
      /* (345) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=345);
+
      /* (346) trans_opt ::= */ yytestcase(yyruleno==346);
+
      /* (347) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==347);
+
      /* (348) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==348);
+
      /* (349) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==349);
+
      /* (350) savepoint_opt ::= */ yytestcase(yyruleno==350);
+
      /* (351) cmd ::= create_table create_table_args */ yytestcase(yyruleno==351);
+
      /* (352) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=352);
+
      /* (353) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==353);
+
      /* (354) columnlist ::= columnname carglist */ yytestcase(yyruleno==354);
+
      /* (355) nm ::= ID|INDEXED|JOIN_KW */ yytestcase(yyruleno==355);
+
      /* (356) nm ::= STRING */ yytestcase(yyruleno==356);
+
      /* (357) typetoken ::= typename */ yytestcase(yyruleno==357);
+
      /* (358) typename ::= ID|STRING */ yytestcase(yyruleno==358);
+
      /* (359) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=359);
+
      /* (360) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=360);
+
      /* (361) carglist ::= carglist ccons */ yytestcase(yyruleno==361);
+
      /* (362) carglist ::= */ yytestcase(yyruleno==362);
+
      /* (363) ccons ::= NULL onconf */ yytestcase(yyruleno==363);
+
      /* (364) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==364);
+
      /* (365) ccons ::= AS generated */ yytestcase(yyruleno==365);
+
      /* (366) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==366);
+
      /* (367) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==367);
+
      /* (368) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=368);
+
      /* (369) tconscomma ::= */ yytestcase(yyruleno==369);
+
      /* (370) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=370);
+
      /* (371) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=371);
+
      /* (372) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=372);
+
      /* (373) oneselect ::= values */ yytestcase(yyruleno==373);
+
      /* (374) sclp ::= selcollist COMMA */ yytestcase(yyruleno==374);
+
      /* (375) as ::= ID|STRING */ yytestcase(yyruleno==375);
+
      /* (376) indexed_opt ::= indexed_by (OPTIMIZED OUT) */ assert(yyruleno!=376);
+
      /* (377) returning ::= */ yytestcase(yyruleno==377);
+
      /* (378) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=378);
+
      /* (379) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==379);
+
      /* (380) case_operand ::= expr */ yytestcase(yyruleno==380);
+
      /* (381) exprlist ::= nexprlist */ yytestcase(yyruleno==381);
+
      /* (382) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=382);
+
      /* (383) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=383);
+
      /* (384) nmnum ::= ON */ yytestcase(yyruleno==384);
+
      /* (385) nmnum ::= DELETE */ yytestcase(yyruleno==385);
+
      /* (386) nmnum ::= DEFAULT */ yytestcase(yyruleno==386);
+
      /* (387) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==387);
+
      /* (388) foreach_clause ::= */ yytestcase(yyruleno==388);
+
      /* (389) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==389);
+
      /* (390) trnm ::= nm */ yytestcase(yyruleno==390);
+
      /* (391) tridxby ::= */ yytestcase(yyruleno==391);
+
      /* (392) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==392);
+
      /* (393) database_kw_opt ::= */ yytestcase(yyruleno==393);
+
      /* (394) kwcolumn_opt ::= */ yytestcase(yyruleno==394);
+
      /* (395) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==395);
+
      /* (396) vtabarglist ::= vtabarg */ yytestcase(yyruleno==396);
+
      /* (397) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==397);
+
      /* (398) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==398);
+
      /* (399) anylist ::= */ yytestcase(yyruleno==399);
+
      /* (400) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==400);
+
      /* (401) anylist ::= anylist ANY */ yytestcase(yyruleno==401);
+
      /* (402) with ::= */ yytestcase(yyruleno==402);
+
      /* (403) windowdefn_list ::= windowdefn (OPTIMIZED OUT) */ assert(yyruleno!=403);
+
      /* (404) window ::= frame_opt (OPTIMIZED OUT) */ assert(yyruleno!=404);
        break;
/********** End reduce actions ************************************************/
  };
@@ -176436,7 +177624,9 @@ SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
#ifdef SQLITE_ENABLE_STMTVTAB
SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
#endif
-

+
#ifdef SQLITE_EXTRA_AUTOEXT
+
int SQLITE_EXTRA_AUTOEXT(sqlite3*);
+
#endif
/*
** An array of pointers to extension initializer functions for
** built-in extensions.
@@ -176470,6 +177660,9 @@ static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
#ifdef SQLITE_ENABLE_BYTECODE_VTAB
  sqlite3VdbeBytecodeVtabInit,
#endif
+
#ifdef SQLITE_EXTRA_AUTOEXT
+
  SQLITE_EXTRA_AUTOEXT,
+
#endif
};

#ifndef SQLITE_AMALGAMATION
@@ -176544,6 +177737,32 @@ SQLITE_API char *sqlite3_temp_directory = 0;
SQLITE_API char *sqlite3_data_directory = 0;

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

+

+
/*
** Initialize SQLite.
**
** This routine must be called to initialize the memory allocation,
@@ -176738,6 +177957,12 @@ SQLITE_API int sqlite3_initialize(void){
  }
#endif

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

  return rc;
}

@@ -177308,6 +178533,10 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  va_list ap;
  int rc;
+

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+
#endif
  sqlite3_mutex_enter(db->mutex);
  va_start(ap, op);
  switch( op ){
@@ -177637,6 +178866,14 @@ static int sqlite3Close(sqlite3 *db, int forceZombie){
  }
#endif

+
  while( db->pDbData ){
+
    DbClientData *p = db->pDbData;
+
    db->pDbData = p->pNext;
+
    assert( p->pData!=0 );
+
    if( p->xDestructor ) p->xDestructor(p->pData);
+
    sqlite3_free(p);
+
  }
+

  /* Convert the connection into a zombie and then close it.
  */
  db->eOpenState = SQLITE_STATE_ZOMBIE;
@@ -178254,7 +179491,7 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
  extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
-
                       SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
+
                       SQLITE_SUBTYPE|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE);
  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);

  /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE.  But
@@ -178711,6 +179948,12 @@ SQLITE_API void *sqlite3_preupdate_hook(
  void *pArg                /* First callback argument */
){
  void *pRet;
+

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( db==0 ){
+
    return 0;
+
  }
+
#endif
  sqlite3_mutex_enter(db->mutex);
  pRet = db->pPreUpdateArg;
  db->xPreUpdateCallback = xCallback;
@@ -178857,7 +180100,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2(
  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
    ** mode: */
-
    return SQLITE_MISUSE;
+
    return SQLITE_MISUSE_BKPT;
  }

  sqlite3_mutex_enter(db->mutex);
@@ -180094,6 +181337,69 @@ SQLITE_API int sqlite3_collation_needed16(
}
#endif /* SQLITE_OMIT_UTF16 */

+
/*
+
** Find existing client data.
+
*/
+
SQLITE_API void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){
+
  DbClientData *p;
+
  sqlite3_mutex_enter(db->mutex);
+
  for(p=db->pDbData; p; p=p->pNext){
+
    if( strcmp(p->zName, zName)==0 ){
+
      void *pResult = p->pData;
+
      sqlite3_mutex_leave(db->mutex);
+
      return pResult;
+
    }
+
  }
+
  sqlite3_mutex_leave(db->mutex);
+
  return 0;
+
}
+

+
/*
+
** Add new client data to a database connection.
+
*/
+
SQLITE_API int sqlite3_set_clientdata(
+
  sqlite3 *db,                   /* Attach client data to this connection */
+
  const char *zName,             /* Name of the client data */
+
  void *pData,                   /* The client data itself */
+
  void (*xDestructor)(void*)     /* Destructor */
+
){
+
  DbClientData *p, **pp;
+
  sqlite3_mutex_enter(db->mutex);
+
  pp = &db->pDbData;
+
  for(p=db->pDbData; p && strcmp(p->zName,zName); p=p->pNext){
+
    pp = &p->pNext;
+
  }
+
  if( p ){
+
    assert( p->pData!=0 );
+
    if( p->xDestructor ) p->xDestructor(p->pData);
+
    if( pData==0 ){
+
      *pp = p->pNext;
+
      sqlite3_free(p);
+
      sqlite3_mutex_leave(db->mutex);
+
      return SQLITE_OK;
+
    }
+
  }else if( pData==0 ){
+
    sqlite3_mutex_leave(db->mutex);
+
    return SQLITE_OK;
+
  }else{
+
    size_t n = strlen(zName);
+
    p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );
+
    if( p==0 ){
+
      if( xDestructor ) xDestructor(pData);
+
      sqlite3_mutex_leave(db->mutex);
+
      return SQLITE_NOMEM;
+
    }
+
    memcpy(p->zName, zName, n+1);
+
    p->pNext = db->pDbData;
+
    db->pDbData = p;
+
  }
+
  p->pData = pData;
+
  p->xDestructor = xDestructor;
+
  sqlite3_mutex_leave(db->mutex);
+
  return SQLITE_OK;
+
}
+

+

#ifndef SQLITE_OMIT_DEPRECATED
/*
** This function is now an anachronism. It used to be used to recover from a
@@ -180443,6 +181749,28 @@ SQLITE_API int sqlite3_test_control(int op, ...){
    }
#endif

+
    /*  sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
+
    **
+
    ** If b is true, then activate the SQLITE_FkNoAction setting.  If b is
+
    ** false then clearn that setting.  If the SQLITE_FkNoAction setting is
+
    ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
+
    ** they were NO ACTION, regardless of how they are defined.
+
    **
+
    ** NB:  One must usually run "PRAGMA writable_schema=RESET" after
+
    ** using this test-control, before it will take full effect.  failing
+
    ** to reset the schema can result in some unexpected behavior.
+
    */
+
    case SQLITE_TESTCTRL_FK_NO_ACTION: {
+
      sqlite3 *db = va_arg(ap, sqlite3*);
+
      int b = va_arg(ap, int);
+
      if( b ){
+
        db->flags |= SQLITE_FkNoAction;
+
      }else{
+
        db->flags &= ~SQLITE_FkNoAction;
+
      }
+
      break;
+
    }
+

    /*
    **  sqlite3_test_control(BITVEC_TEST, size, program)
    **
@@ -180867,11 +182195,11 @@ SQLITE_API int sqlite3_test_control(int op, ...){
    **   X<0     Make no changes to the bUseLongDouble.  Just report value.
    **   X==0    Disable bUseLongDouble
    **   X==1    Enable bUseLongDouble
-
    **   X==2    Set bUseLongDouble to its default value for this platform
+
    **   X>=2    Set bUseLongDouble to its default value for this platform
    */
    case SQLITE_TESTCTRL_USELONGDOUBLE: {
      int b = va_arg(ap, int);
-
      if( b==2 ) b = sizeof(LONGDOUBLE_TYPE)>8;
+
      if( b>=2 ) b = hasHighPrecisionDouble(b);
      if( b>=0 ) sqlite3Config.bUseLongDouble = b>0;
      rc = sqlite3Config.bUseLongDouble!=0;
      break;
@@ -181285,7 +182613,7 @@ SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  int nOpt;
  const char **azCompileOpt;

-
#if SQLITE_ENABLE_API_ARMOR
+
#ifdef SQLITE_ENABLE_API_ARMOR
  if( zOptName==0 ){
    (void)SQLITE_MISUSE_BKPT;
    return 0;
@@ -181480,6 +182808,9 @@ SQLITE_API int sqlite3_unlock_notify(
){
  int rc = SQLITE_OK;

+
#ifdef SQLITE_ENABLE_API_ARMOR
+
  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
+
#endif
  sqlite3_mutex_enter(db->mutex);
  enterMutex();

@@ -182501,6 +183832,7 @@ struct Fts3Table {
  int nPgsz;                      /* Page size for host database */
  char *zSegmentsTbl;             /* Name of %_segments table */
  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
+
  int iSavepoint;

  /*
  ** The following array of hash tables is used to buffer pending index
@@ -183244,6 +184576,7 @@ static void fts3DeclareVtab(int *pRc, Fts3Table *p){

    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
+
    sqlite3_vtab_config(p->db, SQLITE_VTAB_INNOCUOUS);

    /* Create a list of user columns for the virtual table */
    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
@@ -186493,6 +187826,8 @@ static int fts3RenameMethod(
    rc = sqlite3Fts3PendingTermsFlush(p);
  }

+
  p->bIgnoreSavepoint = 1;
+

  if( p->zContentTbl==0 ){
    fts3DbExec(&rc, db,
      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
@@ -186520,6 +187855,8 @@ static int fts3RenameMethod(
    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
    p->zDb, p->zName, zName
  );
+

+
  p->bIgnoreSavepoint = 0;
  return rc;
}

@@ -186530,12 +187867,28 @@ static int fts3RenameMethod(
*/
static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  int rc = SQLITE_OK;
-
  UNUSED_PARAMETER(iSavepoint);
-
  assert( ((Fts3Table *)pVtab)->inTransaction );
-
  assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
-
  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
-
  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
-
    rc = fts3SyncMethod(pVtab);
+
  Fts3Table *pTab = (Fts3Table*)pVtab;
+
  assert( pTab->inTransaction );
+
  assert( pTab->mxSavepoint<=iSavepoint );
+
  TESTONLY( pTab->mxSavepoint = iSavepoint );
+

+
  if( pTab->bIgnoreSavepoint==0 ){
+
    if( fts3HashCount(&pTab->aIndex[0].hPending)>0 ){
+
      char *zSql = sqlite3_mprintf("INSERT INTO %Q.%Q(%Q) VALUES('flush')",
+
          pTab->zDb, pTab->zName, pTab->zName
+
          );
+
      if( zSql ){
+
        pTab->bIgnoreSavepoint = 1;
+
        rc = sqlite3_exec(pTab->db, zSql, 0, 0, 0);
+
        pTab->bIgnoreSavepoint = 0;
+
        sqlite3_free(zSql);
+
      }else{
+
        rc = SQLITE_NOMEM;
+
      }
+
    }
+
    if( rc==SQLITE_OK ){
+
      pTab->iSavepoint = iSavepoint+1;
+
    }
  }
  return rc;
}
@@ -186546,12 +187899,11 @@ static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
** This is a no-op.
*/
static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
-
  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
-
  UNUSED_PARAMETER(iSavepoint);
-
  UNUSED_PARAMETER(pVtab);
-
  assert( p->inTransaction );
-
  assert( p->mxSavepoint >= iSavepoint );
-
  TESTONLY( p->mxSavepoint = iSavepoint-1 );
+
  Fts3Table *pTab = (Fts3Table*)pVtab;
+
  assert( pTab->inTransaction );
+
  assert( pTab->mxSavepoint >= iSavepoint );
+
  TESTONLY( pTab->mxSavepoint = iSavepoint-1 );
+
  pTab->iSavepoint = iSavepoint;
  return SQLITE_OK;
}

@@ -186561,11 +187913,13 @@ static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
** Discard the contents of the pending terms table.
*/
static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
-
  Fts3Table *p = (Fts3Table*)pVtab;
+
  Fts3Table *pTab = (Fts3Table*)pVtab;
  UNUSED_PARAMETER(iSavepoint);
-
  assert( p->inTransaction );
-
  TESTONLY( p->mxSavepoint = iSavepoint );
-
  sqlite3Fts3PendingTermsClear(p);
+
  assert( pTab->inTransaction );
+
  TESTONLY( pTab->mxSavepoint = iSavepoint );
+
  if( (iSavepoint+1)<=pTab->iSavepoint ){
+
    sqlite3Fts3PendingTermsClear(pTab);
+
  }
  return SQLITE_OK;
}

@@ -186584,8 +187938,49 @@ static int fts3ShadowName(const char *zName){
  return 0;
}

+
/*
+
** Implementation of the xIntegrity() method on the FTS3/FTS4 virtual
+
** table.
+
*/
+
static int fts3Integrity(
+
  sqlite3_vtab *pVtab,      /* The virtual table to be checked */
+
  const char *zSchema,      /* Name of schema in which pVtab lives */
+
  const char *zTabname,     /* Name of the pVTab table */
+
  int isQuick,              /* True if this is a quick_check */
+
  char **pzErr              /* Write error message here */
+
){
+
  Fts3Table *p = (Fts3Table*)pVtab;
+
  char *zSql;
+
  int rc;
+
  char *zErr = 0;
+

+
  assert( pzErr!=0 );
+
  assert( *pzErr==0 );
+
  UNUSED_PARAMETER(isQuick);
+
  zSql = sqlite3_mprintf(
+
            "INSERT INTO \"%w\".\"%w\"(\"%w\") VALUES('integrity-check');",
+
            zSchema, zTabname, zTabname);
+
  if( zSql==0 ){
+
    return SQLITE_NOMEM;
+
  }
+
  rc = sqlite3_exec(p->db, zSql, 0, 0, &zErr);
+
  sqlite3_free(zSql);
+
  if( (rc&0xff)==SQLITE_CORRUPT ){
+
    *pzErr = sqlite3_mprintf("malformed inverted index for FTS%d table %s.%s",
+
                p->bFts4 ? 4 : 3, zSchema, zTabname);
+
  }else if( rc!=SQLITE_OK ){
+
    *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
+
                             " FTS%d table %s.%s: %s",
+
                p->bFts4 ? 4 : 3, zSchema, zTabname, zErr);
+
  }
+
  sqlite3_free(zErr);
+
  return SQLITE_OK;
+
}
+

+

+

static const sqlite3_module fts3Module = {
-
  /* iVersion      */ 3,
+
  /* iVersion      */ 4,
  /* xCreate       */ fts3CreateMethod,
  /* xConnect      */ fts3ConnectMethod,
  /* xBestIndex    */ fts3BestIndexMethod,
@@ -186609,6 +188004,7 @@ static const sqlite3_module fts3Module = {
  /* xRelease      */ fts3ReleaseMethod,
  /* xRollbackTo   */ fts3RollbackToMethod,
  /* xShadowName   */ fts3ShadowName,
+
  /* xIntegrity    */ fts3Integrity,
};

/*
@@ -189284,7 +190680,8 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
     0,                           /* xSavepoint    */
     0,                           /* xRelease      */
     0,                           /* xRollbackTo   */
-
     0                            /* xShadowName   */
+
     0,                           /* xShadowName   */
+
     0                            /* xIntegrity    */
  };
  int rc;                         /* Return code */

@@ -192850,7 +194247,8 @@ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash, void(*xDestr
     0,                           /* xSavepoint    */
     0,                           /* xRelease      */
     0,                           /* xRollbackTo   */
-
     0                            /* xShadowName   */
+
     0,                           /* xShadowName   */
+
     0                            /* xIntegrity    */
  };
  int rc;                         /* Return code */

@@ -196191,7 +197589,6 @@ SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  }
-
  sqlite3Fts3PendingTermsClear(p);

  /* Determine the auto-incr-merge setting if unknown.  If enabled,
  ** estimate the number of leaf blocks of content to be written
@@ -196213,6 +197610,10 @@ SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
      rc = sqlite3_reset(pStmt);
    }
  }
+

+
  if( rc==SQLITE_OK ){
+
    sqlite3Fts3PendingTermsClear(p);
+
  }
  return rc;
}

@@ -196844,6 +198245,8 @@ static int fts3AppendToNode(

  blobGrowBuffer(pPrev, nTerm, &rc);
  if( rc!=SQLITE_OK ) return rc;
+
  assert( pPrev!=0 );
+
  assert( pPrev->a!=0 );

  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  nSuffix = nTerm - nPrefix;
@@ -196900,9 +198303,13 @@ static int fts3IncrmergeAppend(
  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;

  /* If the current block is not empty, and if adding this term/doclist
-
  ** to the current block would make it larger than Fts3Table.nNodeSize
-
  ** bytes, write this block out to the database. */
-
  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
+
  ** to the current block would make it larger than Fts3Table.nNodeSize bytes,
+
  ** and if there is still room for another leaf page, write this block out to
+
  ** the database. */
+
  if( pLeaf->block.n>0
+
   && (pLeaf->block.n + nSpace)>p->nNodeSize
+
   && pLeaf->iBlock < (pWriter->iStart + pWriter->nLeafEst)
+
  ){
    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
    pWriter->nWork++;

@@ -197234,7 +198641,7 @@ static int fts3IncrmergeLoad(
              rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock,0);
              blobGrowBuffer(&pNode->block,
                  MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
-
                  );
+
              );
              if( rc==SQLITE_OK ){
                memcpy(pNode->block.a, aBlock, nBlock);
                pNode->block.n = nBlock;
@@ -198084,7 +199491,7 @@ static u64 fts3ChecksumIndex(
  int rc;
  u64 cksum = 0;

-
  assert( *pRc==SQLITE_OK );
+
  if( *pRc ) return 0;

  memset(&filter, 0, sizeof(filter));
  memset(&csr, 0, sizeof(csr));
@@ -198299,8 +199706,11 @@ static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
    rc = fts3DoIncrmerge(p, &zVal[6]);
  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
    rc = fts3DoAutoincrmerge(p, &zVal[10]);
+
  }else if( nVal==5 && 0==sqlite3_strnicmp(zVal, "flush", 5) ){
+
    rc = sqlite3Fts3PendingTermsFlush(p);
+
  }
#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
-
  }else{
+
  else{
    int v;
    if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
      v = atoi(&zVal[9]);
@@ -198318,8 +199728,8 @@ static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
      if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;
      rc = SQLITE_OK;
    }
-
#endif
  }
+
#endif
  return rc;
}

@@ -201662,13 +203072,19 @@ static void jsonAppendNormalizedString(JsonString *p, const char *zIn, u32 N){
  zIn++;
  N -= 2;
  while( N>0 ){
-
    for(i=0; i<N && zIn[i]!='\\'; i++){}
+
    for(i=0; i<N && zIn[i]!='\\' && zIn[i]!='"'; i++){}
    if( i>0 ){
      jsonAppendRawNZ(p, zIn, i);
      zIn += i;
      N -= i;
      if( N==0 ) break;
    }
+
    if( zIn[0]=='"' ){
+
      jsonAppendRawNZ(p, "\\\"", 2);
+
      zIn++;
+
      N--;
+
      continue;
+
    }
    assert( zIn[0]=='\\' );
    switch( (u8)zIn[1] ){
      case '\'':
@@ -201832,7 +203248,7 @@ static void jsonResult(JsonString *p){
    }else if( jsonForceRCStr(p) ){
      sqlite3RCStrRef(p->zBuf);
      sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
-
                            (void(*)(void*))sqlite3RCStrUnref,
+
                            sqlite3RCStrUnref,
                            SQLITE_UTF8);
    }
  }
@@ -202063,7 +203479,8 @@ static void jsonReturnJson(
  JsonParse *pParse,          /* The complete JSON */
  JsonNode *pNode,            /* Node to return */
  sqlite3_context *pCtx,      /* Return value for this function */
-
  int bGenerateAlt            /* Also store the rendered text in zAlt */
+
  int bGenerateAlt,           /* Also store the rendered text in zAlt */
+
  int omitSubtype             /* Do not call sqlite3_result_subtype() */
){
  JsonString s;
  if( pParse->oom ){
@@ -202078,7 +203495,7 @@ static void jsonReturnJson(
      pParse->nAlt = s.nUsed;
    }
    jsonResult(&s);
-
    sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
+
    if( !omitSubtype ) sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  }
}

@@ -202119,7 +203536,8 @@ static u32 jsonHexToInt4(const char *z){
static void jsonReturn(
  JsonParse *pParse,          /* Complete JSON parse tree */
  JsonNode *pNode,            /* Node to return */
-
  sqlite3_context *pCtx       /* Return value for this function */
+
  sqlite3_context *pCtx,      /* Return value for this function */
+
  int omitSubtype             /* Do not call sqlite3_result_subtype() */
){
  switch( pNode->eType ){
    default: {
@@ -202265,7 +203683,7 @@ static void jsonReturn(
    }
    case JSON_ARRAY:
    case JSON_OBJECT: {
-
      jsonReturnJson(pParse, pNode, pCtx, 0);
+
      jsonReturnJson(pParse, pNode, pCtx, 0, omitSubtype);
      break;
    }
  }
@@ -203172,7 +204590,7 @@ static JsonParse *jsonParseCached(
  /* The input JSON was not found anywhere in the cache.  We will need
  ** to parse it ourselves and generate a new JsonParse object.
  */
-
  bJsonRCStr = sqlite3ValueIsOfClass(pJson,(void(*)(void*))sqlite3RCStrUnref);
+
  bJsonRCStr = sqlite3ValueIsOfClass(pJson,sqlite3RCStrUnref);
  p = sqlite3_malloc64( sizeof(*p) + (bJsonRCStr ? 0 : nJson+1) );
  if( p==0 ){
    sqlite3_result_error_nomem(pCtx);
@@ -203386,6 +204804,7 @@ static JsonNode *jsonLookupStep(
        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 || pParse->useMod==0 ) i--;
        j += jsonNodeSize(&pRoot[j]);
      }
+
      if( i==0 && j<=pRoot->n ) break;
      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
      if( pParse->useMod==0 ) break;
      assert( pRoot->eU==2 );
@@ -203616,7 +205035,7 @@ static void jsonParseFunc(
  printf("iSubst    = %u\n", p->iSubst);
  printf("iHold     = %u\n", p->iHold);
  jsonDebugPrintNodeEntries(p->aNode, p->nNode);
-
  jsonReturnJson(p, p->aNode, ctx, 1);
+
  jsonReturnJson(p, p->aNode, ctx, 1, 0);
}

/*
@@ -203714,7 +205133,9 @@ static void jsonArrayLengthFunc(
  }
  if( pNode->eType==JSON_ARRAY ){
    while( 1 /*exit-by-break*/ ){
-
      for(i=1; i<=pNode->n; n++){
+
      i = 1;
+
      while( i<=pNode->n ){
+
        if( (pNode[i].jnFlags & JNODE_REMOVE)==0 ) n++;
        i += jsonNodeSize(&pNode[i]);
      }
      if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
@@ -203800,15 +205221,14 @@ static void jsonExtractFunc(
      }
      if( pNode ){
        if( flags & JSON_JSON ){
-
          jsonReturnJson(p, pNode, ctx, 0);
+
          jsonReturnJson(p, pNode, ctx, 0, 0);
        }else{
-
          jsonReturn(p, pNode, ctx);
-
          sqlite3_result_subtype(ctx, 0);
+
          jsonReturn(p, pNode, ctx, 1);
        }
      }
    }else{
      pNode = jsonLookup(p, zPath, 0, ctx);
-
      if( p->nErr==0 && pNode ) jsonReturn(p, pNode, ctx);
+
      if( p->nErr==0 && pNode ) jsonReturn(p, pNode, ctx, 0);
    }
  }else{
    /* Two or more PATH arguments results in a JSON array with each
@@ -203934,7 +205354,7 @@ static void jsonPatchFunc(
  if( pResult && pX->oom==0 ){
    jsonDebugPrintParse(pX);
    jsonDebugPrintNode(pResult);
-
    jsonReturnJson(pX, pResult, ctx, 0);
+
    jsonReturnJson(pX, pResult, ctx, 0, 0);
  }else{
    sqlite3_result_error_nomem(ctx);
  }
@@ -204013,7 +205433,7 @@ static void jsonRemoveFunc(
    }
  }
  if( (pParse->aNode[0].jnFlags & JNODE_REMOVE)==0 ){
-
    jsonReturnJson(pParse, pParse->aNode, ctx, 1);
+
    jsonReturnJson(pParse, pParse->aNode, ctx, 1, 0);
  }
remove_done:
  jsonDebugPrintParse(p);
@@ -204071,11 +205491,13 @@ static void jsonReplaceNode(
         break;
      }
      if( sqlite3_value_subtype(pValue)!=JSON_SUBTYPE ){
-
        char *zCopy = sqlite3DbStrDup(0, z);
+
        char *zCopy = sqlite3_malloc64( n+1 );
        int k;
        if( zCopy ){
+
          memcpy(zCopy, z, n);
+
          zCopy[n] = 0;
          jsonParseAddCleanup(p, sqlite3_free, zCopy);
-
       }else{
+
        }else{
          p->oom = 1;
          sqlite3_result_error_nomem(pCtx);
        }
@@ -204130,6 +205552,7 @@ static void jsonReplaceFunc(
  }
  pParse = jsonParseCached(ctx, argv[0], ctx, argc>1);
  if( pParse==0 ) return;
+
  pParse->nJPRef++;
  for(i=1; i<(u32)argc; i+=2){
    zPath = (const char*)sqlite3_value_text(argv[i]);
    pParse->useMod = 1;
@@ -204139,9 +205562,10 @@ static void jsonReplaceFunc(
      jsonReplaceNode(ctx, pParse, (u32)(pNode - pParse->aNode), argv[i+1]);
    }
  }
-
  jsonReturnJson(pParse, pParse->aNode, ctx, 1);
+
  jsonReturnJson(pParse, pParse->aNode, ctx, 1, 0);
replace_err:
  jsonDebugPrintParse(pParse);
+
  jsonParseFree(pParse);
}


@@ -204176,6 +205600,7 @@ static void jsonSetFunc(
  }
  pParse = jsonParseCached(ctx, argv[0], ctx, argc>1);
  if( pParse==0 ) return;
+
  pParse->nJPRef++;
  for(i=1; i<(u32)argc; i+=2){
    zPath = (const char*)sqlite3_value_text(argv[i]);
    bApnd = 0;
@@ -204191,10 +205616,9 @@ static void jsonSetFunc(
    }
  }
  jsonDebugPrintParse(pParse);
-
  jsonReturnJson(pParse, pParse->aNode, ctx, 1);
-

+
  jsonReturnJson(pParse, pParse->aNode, ctx, 1, 0);
jsonSetDone:
-
  /* no cleanup required */;
+
  jsonParseFree(pParse);
}

/*
@@ -204350,7 +205774,7 @@ static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
    }else if( isFinal ){
      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
                          pStr->bStatic ? SQLITE_TRANSIENT :
-
                              (void(*)(void*))sqlite3RCStrUnref);
+
                              sqlite3RCStrUnref);
      pStr->bStatic = 1;
    }else{
      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
@@ -204459,7 +205883,7 @@ static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
    }else if( isFinal ){
      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
                          pStr->bStatic ? SQLITE_TRANSIENT :
-
                          (void(*)(void*))sqlite3RCStrUnref);
+
                          sqlite3RCStrUnref);
      pStr->bStatic = 1;
    }else{
      sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
@@ -204707,7 +206131,7 @@ static int jsonEachColumn(
    case JEACH_KEY: {
      if( p->i==0 ) break;
      if( p->eType==JSON_OBJECT ){
-
        jsonReturn(&p->sParse, pThis, ctx);
+
        jsonReturn(&p->sParse, pThis, ctx, 0);
      }else if( p->eType==JSON_ARRAY ){
        u32 iKey;
        if( p->bRecursive ){
@@ -204723,7 +206147,7 @@ static int jsonEachColumn(
    }
    case JEACH_VALUE: {
      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
-
      jsonReturn(&p->sParse, pThis, ctx);
+
      jsonReturn(&p->sParse, pThis, ctx, 0);
      break;
    }
    case JEACH_TYPE: {
@@ -204734,7 +206158,7 @@ static int jsonEachColumn(
    case JEACH_ATOM: {
      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
      if( pThis->eType>=JSON_ARRAY ) break;
-
      jsonReturn(&p->sParse, pThis, ctx);
+
      jsonReturn(&p->sParse, pThis, ctx, 0);
      break;
    }
    case JEACH_ID: {
@@ -204891,7 +206315,7 @@ static int jsonEachFilter(
  if( z==0 ) return SQLITE_OK;
  memset(&p->sParse, 0, sizeof(p->sParse));
  p->sParse.nJPRef = 1;
-
  if( sqlite3ValueIsOfClass(argv[0], (void(*)(void*))sqlite3RCStrUnref) ){
+
  if( sqlite3ValueIsOfClass(argv[0], sqlite3RCStrUnref) ){
    p->sParse.zJson = sqlite3RCStrRef((char*)z);
  }else{
    n = sqlite3_value_bytes(argv[0]);
@@ -204986,7 +206410,8 @@ static sqlite3_module jsonEachModule = {
  0,                         /* xSavepoint */
  0,                         /* xRelease */
  0,                         /* xRollbackTo */
-
  0                          /* xShadowName */
+
  0,                         /* xShadowName */
+
  0                          /* xIntegrity */
};

/* The methods of the json_tree virtual table. */
@@ -205014,7 +206439,8 @@ static sqlite3_module jsonTreeModule = {
  0,                         /* xSavepoint */
  0,                         /* xRelease */
  0,                         /* xRollbackTo */
-
  0                          /* xShadowName */
+
  0,                         /* xShadowName */
+
  0                          /* xIntegrity */
};
#endif /* SQLITE_OMIT_VIRTUALTABLE */
#endif /* !defined(SQLITE_OMIT_JSON) */
@@ -205025,34 +206451,43 @@ static sqlite3_module jsonTreeModule = {
SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){
#ifndef SQLITE_OMIT_JSON
  static FuncDef aJsonFunc[] = {
-
    JFUNCTION(json,               1, 0,  jsonRemoveFunc),
-
    JFUNCTION(json_array,        -1, 0,  jsonArrayFunc),
-
    JFUNCTION(json_array_length,  1, 0,  jsonArrayLengthFunc),
-
    JFUNCTION(json_array_length,  2, 0,  jsonArrayLengthFunc),
-
    JFUNCTION(json_error_position,1, 0,  jsonErrorFunc),
-
    JFUNCTION(json_extract,      -1, 0,  jsonExtractFunc),
-
    JFUNCTION(->,                 2, JSON_JSON, jsonExtractFunc),
-
    JFUNCTION(->>,                2, JSON_SQL, jsonExtractFunc),
-
    JFUNCTION(json_insert,       -1, 0,  jsonSetFunc),
-
    JFUNCTION(json_object,       -1, 0,  jsonObjectFunc),
-
    JFUNCTION(json_patch,         2, 0,  jsonPatchFunc),
-
    JFUNCTION(json_quote,         1, 0,  jsonQuoteFunc),
-
    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
-
    JFUNCTION(json_parse,         1, 0,  jsonParseFunc),
-
    JFUNCTION(json_test1,         1, 0,  jsonTest1Func),
+
    /*                     calls sqlite3_result_subtype()                    */
+
    /*                                  |                                    */
+
    /*              Uses cache ______   |   __ calls sqlite3_value_subtype() */
+
    /*                               |  |  |                                 */
+
    /*          Num args _________   |  |  |   ___ Flags                     */
+
    /*                            |  |  |  |  |                              */
+
    /*                            |  |  |  |  |                              */
+
    JFUNCTION(json,               1, 1, 1, 0, 0,          jsonRemoveFunc),
+
    JFUNCTION(json_array,        -1, 0, 1, 1, 0,          jsonArrayFunc),
+
    JFUNCTION(json_array_length,  1, 1, 0, 0, 0,          jsonArrayLengthFunc),
+
    JFUNCTION(json_array_length,  2, 1, 0, 0, 0,          jsonArrayLengthFunc),
+
    JFUNCTION(json_error_position,1, 1, 0, 0, 0,          jsonErrorFunc),
+
    JFUNCTION(json_extract,      -1, 1, 1, 0, 0,          jsonExtractFunc),
+
    JFUNCTION(->,                 2, 1, 1, 0, JSON_JSON,  jsonExtractFunc),
+
    JFUNCTION(->>,                2, 1, 0, 0, JSON_SQL,   jsonExtractFunc),
+
    JFUNCTION(json_insert,       -1, 1, 1, 1, 0,          jsonSetFunc),
+
    JFUNCTION(json_object,       -1, 0, 1, 1, 0,          jsonObjectFunc),
+
    JFUNCTION(json_patch,         2, 1, 1, 0, 0,          jsonPatchFunc),
+
    JFUNCTION(json_quote,         1, 0, 1, 1, 0,          jsonQuoteFunc),
+
    JFUNCTION(json_remove,       -1, 1, 1, 0, 0,          jsonRemoveFunc),
+
    JFUNCTION(json_replace,      -1, 1, 1, 1, 0,          jsonReplaceFunc),
+
    JFUNCTION(json_set,          -1, 1, 1, 1, JSON_ISSET, jsonSetFunc),
+
    JFUNCTION(json_type,          1, 1, 0, 0, 0,          jsonTypeFunc),
+
    JFUNCTION(json_type,          2, 1, 0, 0, 0,          jsonTypeFunc),
+
    JFUNCTION(json_valid,         1, 1, 0, 0, 0,          jsonValidFunc),
+
#ifdef SQLITE_DEBUG
+
    JFUNCTION(json_parse,         1, 1, 1, 0, 0,          jsonParseFunc),
+
    JFUNCTION(json_test1,         1, 1, 0, 1, 0,          jsonTest1Func),
#endif
    WAGGREGATE(json_group_array,  1, 0, 0,
       jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse,
-
       SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC),
+
       SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|
+
       SQLITE_DETERMINISTIC),
    WAGGREGATE(json_group_object, 2, 0, 0,
       jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse,
-
       SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC)
+
       SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|
+
       SQLITE_DETERMINISTIC)
  };
  sqlite3InsertBuiltinFuncs(aJsonFunc, ArraySize(aJsonFunc));
#endif
@@ -205249,6 +206684,7 @@ struct Rtree {
  int iDepth;                 /* Current depth of the r-tree structure */
  char *zDb;                  /* Name of database containing r-tree table */
  char *zName;                /* Name of r-tree table */
+
  char *zNodeName;            /* Name of the %_node table */
  u32 nBusy;                  /* Current number of users of this structure */
  i64 nRowEst;                /* Estimated number of rows in this table */
  u32 nCursor;                /* Number of open cursors */
@@ -205261,7 +206697,6 @@ struct Rtree {
  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  */
  RtreeNode *pDeleted;
-
  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */

  /* Blob I/O on xxx_node */
  sqlite3_blob *pNodeBlob;
@@ -205558,15 +206993,20 @@ struct RtreeMatchArg {
** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
** at run-time.
*/
-
#ifndef SQLITE_BYTEORDER
-
# if defined(i386)      || defined(__i386__)      || defined(_M_IX86) ||    \
+
#ifndef SQLITE_BYTEORDER /* Replicate changes at tag-20230904a */
+
# if defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__
+
#   define SQLITE_BYTEORDER 4321
+
# elif defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
+
#   define SQLITE_BYTEORDER 1234
+
# elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1
+
#   define SQLITE_BYTEORDER 4321
+
# elif defined(i386)    || defined(__i386__)      || defined(_M_IX86) ||    \
     defined(__x86_64)  || defined(__x86_64__)    || defined(_M_X64)  ||    \
     defined(_M_AMD64)  || defined(_M_ARM)        || defined(__x86)   ||    \
     defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
-
#   define SQLITE_BYTEORDER    1234
-
# elif defined(sparc)     || defined(__ppc__) || \
-
       defined(__ARMEB__) || defined(__AARCH64EB__)
-
#   define SQLITE_BYTEORDER    4321
+
#   define SQLITE_BYTEORDER 1234
+
# elif defined(sparc)   || defined(__ARMEB__)     || defined(__AARCH64EB__)
+
#   define SQLITE_BYTEORDER 4321
# else
#   define SQLITE_BYTEORDER 0
# endif
@@ -205815,11 +207255,9 @@ static int nodeAcquire(
    }
  }
  if( pRtree->pNodeBlob==0 ){
-
    char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
-
    if( zTab==0 ) return SQLITE_NOMEM;
-
    rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
+
    rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, pRtree->zNodeName,
+
                           "data", iNode, 0,
                           &pRtree->pNodeBlob);
-
    sqlite3_free(zTab);
  }
  if( rc ){
    nodeBlobReset(pRtree);
@@ -207160,8 +208598,12 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){

  pIdxInfo->idxNum = 2;
  pIdxInfo->needToFreeIdxStr = 1;
-
  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
-
    return SQLITE_NOMEM;
+
  if( iIdx>0 ){
+
    pIdxInfo->idxStr = sqlite3_malloc( iIdx+1 );
+
    if( pIdxInfo->idxStr==0 ){
+
      return SQLITE_NOMEM;
+
    }
+
    memcpy(pIdxInfo->idxStr, zIdxStr, iIdx+1);
  }

  nRow = pRtree->nRowEst >> (iIdx/2);
@@ -207240,31 +208682,22 @@ static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
*/
static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  int ii;
-
  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
-
  for(ii=0; ii<pRtree->nDim2; ii+=2){
-
    RtreeCoord *a1 = &p1->aCoord[ii];
-
    RtreeCoord *a2 = &p2->aCoord[ii];
-
    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
-
     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
-
    ){
-
      return 0;
+
  if( pRtree->eCoordType==RTREE_COORD_INT32 ){
+
    for(ii=0; ii<pRtree->nDim2; ii+=2){
+
      RtreeCoord *a1 = &p1->aCoord[ii];
+
      RtreeCoord *a2 = &p2->aCoord[ii];
+
      if( a2[0].i<a1[0].i || a2[1].i>a1[1].i ) return 0;
+
    }
+
  }else{
+
    for(ii=0; ii<pRtree->nDim2; ii+=2){
+
      RtreeCoord *a1 = &p1->aCoord[ii];
+
      RtreeCoord *a2 = &p2->aCoord[ii];
+
      if( a2[0].f<a1[0].f || a2[1].f>a1[1].f ) return 0;
    }
  }
  return 1;
}

-
/*
-
** Return the amount cell p would grow by if it were unioned with pCell.
-
*/
-
static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
-
  RtreeDValue area;
-
  RtreeCell cell;
-
  memcpy(&cell, p, sizeof(RtreeCell));
-
  area = cellArea(pRtree, &cell);
-
  cellUnion(pRtree, &cell, pCell);
-
  return (cellArea(pRtree, &cell)-area);
-
}
-

static RtreeDValue cellOverlap(
  Rtree *pRtree,
  RtreeCell *p,
@@ -207311,38 +208744,52 @@ static int ChooseLeaf(
  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
    int iCell;
    sqlite3_int64 iBest = 0;
-

+
    int bFound = 0;
    RtreeDValue fMinGrowth = RTREE_ZERO;
    RtreeDValue fMinArea = RTREE_ZERO;
-

    int nCell = NCELL(pNode);
-
    RtreeCell cell;
    RtreeNode *pChild = 0;

-
    RtreeCell *aCell = 0;
-

-
    /* Select the child node which will be enlarged the least if pCell
-
    ** is inserted into it. Resolve ties by choosing the entry with
-
    ** the smallest area.
+
    /* First check to see if there is are any cells in pNode that completely
+
    ** contains pCell.  If two or more cells in pNode completely contain pCell
+
    ** then pick the smallest.
    */
    for(iCell=0; iCell<nCell; iCell++){
-
      int bBest = 0;
-
      RtreeDValue growth;
-
      RtreeDValue area;
+
      RtreeCell cell;
      nodeGetCell(pRtree, pNode, iCell, &cell);
-
      growth = cellGrowth(pRtree, &cell, pCell);
-
      area = cellArea(pRtree, &cell);
-
      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
-
        bBest = 1;
+
      if( cellContains(pRtree, &cell, pCell) ){
+
        RtreeDValue area = cellArea(pRtree, &cell);
+
        if( bFound==0 || area<fMinArea ){
+
          iBest = cell.iRowid;
+
          fMinArea = area;
+
          bFound = 1;
+
        }
      }
-
      if( bBest ){
-
        fMinGrowth = growth;
-
        fMinArea = area;
-
        iBest = cell.iRowid;
+
    }
+
    if( !bFound ){
+
      /* No cells of pNode will completely contain pCell.  So pick the
+
      ** cell of pNode that grows by the least amount when pCell is added.
+
      ** Break ties by selecting the smaller cell.
+
      */
+
      for(iCell=0; iCell<nCell; iCell++){
+
        RtreeCell cell;
+
        RtreeDValue growth;
+
        RtreeDValue area;
+
        nodeGetCell(pRtree, pNode, iCell, &cell);
+
        area = cellArea(pRtree, &cell);
+
        cellUnion(pRtree, &cell, pCell);
+
        growth = cellArea(pRtree, &cell)-area;
+
        if( iCell==0
+
         || growth<fMinGrowth
+
         || (growth==fMinGrowth && area<fMinArea)
+
        ){
+
          fMinGrowth = growth;
+
          fMinArea = area;
+
          iBest = cell.iRowid;
+
        }
      }
    }

-
    sqlite3_free(aCell);
    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
    nodeRelease(pRtree, pNode);
    pNode = pChild;
@@ -207415,77 +208862,6 @@ static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);


-
/*
-
** Arguments aIdx, aDistance and aSpare all point to arrays of size
-
** nIdx. The aIdx array contains the set of integers from 0 to
-
** (nIdx-1) in no particular order. This function sorts the values
-
** in aIdx according to the indexed values in aDistance. For
-
** example, assuming the inputs:
-
**
-
**   aIdx      = { 0,   1,   2,   3 }
-
**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
-
**
-
** this function sets the aIdx array to contain:
-
**
-
**   aIdx      = { 0,   1,   2,   3 }
-
**
-
** The aSpare array is used as temporary working space by the
-
** sorting algorithm.
-
*/
-
static void SortByDistance(
-
  int *aIdx,
-
  int nIdx,
-
  RtreeDValue *aDistance,
-
  int *aSpare
-
){
-
  if( nIdx>1 ){
-
    int iLeft = 0;
-
    int iRight = 0;
-

-
    int nLeft = nIdx/2;
-
    int nRight = nIdx-nLeft;
-
    int *aLeft = aIdx;
-
    int *aRight = &aIdx[nLeft];
-

-
    SortByDistance(aLeft, nLeft, aDistance, aSpare);
-
    SortByDistance(aRight, nRight, aDistance, aSpare);
-

-
    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
-
    aLeft = aSpare;
-

-
    while( iLeft<nLeft || iRight<nRight ){
-
      if( iLeft==nLeft ){
-
        aIdx[iLeft+iRight] = aRight[iRight];
-
        iRight++;
-
      }else if( iRight==nRight ){
-
        aIdx[iLeft+iRight] = aLeft[iLeft];
-
        iLeft++;
-
      }else{
-
        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
-
        RtreeDValue fRight = aDistance[aRight[iRight]];
-
        if( fLeft<fRight ){
-
          aIdx[iLeft+iRight] = aLeft[iLeft];
-
          iLeft++;
-
        }else{
-
          aIdx[iLeft+iRight] = aRight[iRight];
-
          iRight++;
-
        }
-
      }
-
    }
-

-
#if 0
-
    /* Check that the sort worked */
-
    {
-
      int jj;
-
      for(jj=1; jj<nIdx; jj++){
-
        RtreeDValue left = aDistance[aIdx[jj-1]];
-
        RtreeDValue right = aDistance[aIdx[jj]];
-
        assert( left<=right );
-
      }
-
    }
-
#endif
-
  }
-
}

/*
** Arguments aIdx, aCell and aSpare all point to arrays of size
@@ -207970,107 +209346,6 @@ static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  return rc;
}

-
static int Reinsert(
-
  Rtree *pRtree,
-
  RtreeNode *pNode,
-
  RtreeCell *pCell,
-
  int iHeight
-
){
-
  int *aOrder;
-
  int *aSpare;
-
  RtreeCell *aCell;
-
  RtreeDValue *aDistance;
-
  int nCell;
-
  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
-
  int iDim;
-
  int ii;
-
  int rc = SQLITE_OK;
-
  int n;
-

-
  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
-

-
  nCell = NCELL(pNode)+1;
-
  n = (nCell+1)&(~1);
-

-
  /* Allocate the buffers used by this operation. The allocation is
-
  ** relinquished before this function returns.
-
  */
-
  aCell = (RtreeCell *)sqlite3_malloc64(n * (
-
    sizeof(RtreeCell)     +         /* aCell array */
-
    sizeof(int)           +         /* aOrder array */
-
    sizeof(int)           +         /* aSpare array */
-
    sizeof(RtreeDValue)             /* aDistance array */
-
  ));
-
  if( !aCell ){
-
    return SQLITE_NOMEM;
-
  }
-
  aOrder    = (int *)&aCell[n];
-
  aSpare    = (int *)&aOrder[n];
-
  aDistance = (RtreeDValue *)&aSpare[n];
-

-
  for(ii=0; ii<nCell; ii++){
-
    if( ii==(nCell-1) ){
-
      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
-
    }else{
-
      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
-
    }
-
    aOrder[ii] = ii;
-
    for(iDim=0; iDim<pRtree->nDim; iDim++){
-
      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
-
      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
-
    }
-
  }
-
  for(iDim=0; iDim<pRtree->nDim; iDim++){
-
    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
-
  }
-

-
  for(ii=0; ii<nCell; ii++){
-
    aDistance[ii] = RTREE_ZERO;
-
    for(iDim=0; iDim<pRtree->nDim; iDim++){
-
      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
-
                               DCOORD(aCell[ii].aCoord[iDim*2]));
-
      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
-
    }
-
  }
-

-
  SortByDistance(aOrder, nCell, aDistance, aSpare);
-
  nodeZero(pRtree, pNode);
-

-
  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
-
    RtreeCell *p = &aCell[aOrder[ii]];
-
    nodeInsertCell(pRtree, pNode, p);
-
    if( p->iRowid==pCell->iRowid ){
-
      if( iHeight==0 ){
-
        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
-
      }else{
-
        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
-
      }
-
    }
-
  }
-
  if( rc==SQLITE_OK ){
-
    rc = fixBoundingBox(pRtree, pNode);
-
  }
-
  for(; rc==SQLITE_OK && ii<nCell; ii++){
-
    /* Find a node to store this cell in. pNode->iNode currently contains
-
    ** the height of the sub-tree headed by the cell.
-
    */
-
    RtreeNode *pInsert;
-
    RtreeCell *p = &aCell[aOrder[ii]];
-
    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
-
    if( rc==SQLITE_OK ){
-
      int rc2;
-
      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
-
      rc2 = nodeRelease(pRtree, pInsert);
-
      if( rc==SQLITE_OK ){
-
        rc = rc2;
-
      }
-
    }
-
  }
-

-
  sqlite3_free(aCell);
-
  return rc;
-
}
-

/*
** Insert cell pCell into node pNode. Node pNode is the head of a
** subtree iHeight high (leaf nodes have iHeight==0).
@@ -208091,12 +209366,7 @@ static int rtreeInsertCell(
    }
  }
  if( nodeInsertCell(pRtree, pNode, pCell) ){
-
    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
-
      rc = SplitNode(pRtree, pNode, pCell, iHeight);
-
    }else{
-
      pRtree->iReinsertHeight = iHeight;
-
      rc = Reinsert(pRtree, pNode, pCell, iHeight);
-
    }
+
    rc = SplitNode(pRtree, pNode, pCell, iHeight);
  }else{
    rc = AdjustTree(pRtree, pNode, pCell);
    if( ALWAYS(rc==SQLITE_OK) ){
@@ -208439,7 +209709,6 @@ static int rtreeUpdate(
    }
    if( rc==SQLITE_OK ){
      int rc2;
-
      pRtree->iReinsertHeight = -1;
      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
      rc2 = nodeRelease(pRtree, pLeaf);
      if( rc==SQLITE_OK ){
@@ -208580,8 +209849,11 @@ static int rtreeShadowName(const char *zName){
  return 0;
}

+
/* Forward declaration */
+
static int rtreeIntegrity(sqlite3_vtab*, const char*, const char*, int, char**);
+

static sqlite3_module rtreeModule = {
-
  3,                          /* iVersion */
+
  4,                          /* iVersion */
  rtreeCreate,                /* xCreate - create a table */
  rtreeConnect,               /* xConnect - connect to an existing table */
  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
@@ -208604,7 +209876,8 @@ static sqlite3_module rtreeModule = {
  rtreeSavepoint,             /* xSavepoint */
  0,                          /* xRelease */
  0,                          /* xRollbackTo */
-
  rtreeShadowName             /* xShadowName */
+
  rtreeShadowName,            /* xShadowName */
+
  rtreeIntegrity              /* xIntegrity */
};

static int rtreeSqlInit(
@@ -208860,22 +210133,27 @@ static int rtreeInit(
  }

  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
+
  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
+


  /* Allocate the sqlite3_vtab structure */
  nDb = (int)strlen(argv[1]);
  nName = (int)strlen(argv[2]);
-
  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
+
  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName*2+8);
  if( !pRtree ){
    return SQLITE_NOMEM;
  }
-
  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
+
  memset(pRtree, 0, sizeof(Rtree)+nDb+nName*2+8);
  pRtree->nBusy = 1;
  pRtree->base.pModule = &rtreeModule;
  pRtree->zDb = (char *)&pRtree[1];
  pRtree->zName = &pRtree->zDb[nDb+1];
+
  pRtree->zNodeName = &pRtree->zName[nName+1];
  pRtree->eCoordType = (u8)eCoordType;
  memcpy(pRtree->zDb, argv[1], nDb);
  memcpy(pRtree->zName, argv[2], nName);
+
  memcpy(pRtree->zNodeName, argv[2], nName);
+
  memcpy(&pRtree->zNodeName[nName], "_node", 6);


  /* Create/Connect to the underlying relational database schema. If
@@ -209372,7 +210650,6 @@ static int rtreeCheckTable(
){
  RtreeCheck check;               /* Common context for various routines */
  sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */
-
  int bEnd = 0;                   /* True if transaction should be closed */
  int nAux = 0;                   /* Number of extra columns. */

  /* Initialize the context object */
@@ -209381,14 +210658,6 @@ static int rtreeCheckTable(
  check.zDb = zDb;
  check.zTab = zTab;

-
  /* If there is not already an open transaction, open one now. This is
-
  ** to ensure that the queries run as part of this integrity-check operate
-
  ** on a consistent snapshot.  */
-
  if( sqlite3_get_autocommit(db) ){
-
    check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
-
    bEnd = 1;
-
  }
-

  /* Find the number of auxiliary columns */
  if( check.rc==SQLITE_OK ){
    pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
@@ -209429,16 +210698,35 @@ static int rtreeCheckTable(
  sqlite3_finalize(check.aCheckMapping[0]);
  sqlite3_finalize(check.aCheckMapping[1]);

-
  /* If one was opened, close the transaction */
-
  if( bEnd ){
-
    int rc = sqlite3_exec(db, "END", 0, 0, 0);
-
    if( check.rc==SQLITE_OK ) check.rc = rc;
-
  }
  *pzReport = check.zReport;
  return check.rc;
}

/*
+
** Implementation of the xIntegrity method for Rtree.
+
*/
+
static int rtreeIntegrity(
+
  sqlite3_vtab *pVtab,   /* The virtual table to check */
+
  const char *zSchema,   /* Schema in which the virtual table lives */
+
  const char *zName,     /* Name of the virtual table */
+
  int isQuick,           /* True for a quick_check */
+
  char **pzErr           /* Write results here */
+
){
+
  Rtree *pRtree = (Rtree*)pVtab;
+
  int rc;
+
  assert( pzErr!=0 && *pzErr==0 );
+
  UNUSED_PARAMETER(zSchema);
+
  UNUSED_PARAMETER(zName);
+
  UNUSED_PARAMETER(isQuick);
+
  rc = rtreeCheckTable(pRtree->db, pRtree->zDb, pRtree->zName, pzErr);
+
  if( rc==SQLITE_OK && *pzErr ){
+
    *pzErr = sqlite3_mprintf("In RTree %s.%s:\n%z",
+
                 pRtree->zDb, pRtree->zName, *pzErr);
+
  }
+
  return rc;
+
}
+

+
/*
** Usage:
**
**   rtreecheck(<rtree-table>);
@@ -210759,24 +212047,28 @@ static int geopolyInit(
  (void)pAux;

  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
+
  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);

  /* Allocate the sqlite3_vtab structure */
  nDb = strlen(argv[1]);
  nName = strlen(argv[2]);
-
  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
+
  pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName*2+8);
  if( !pRtree ){
    return SQLITE_NOMEM;
  }
-
  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
+
  memset(pRtree, 0, sizeof(Rtree)+nDb+nName*2+8);
  pRtree->nBusy = 1;
  pRtree->base.pModule = &rtreeModule;
  pRtree->zDb = (char *)&pRtree[1];
  pRtree->zName = &pRtree->zDb[nDb+1];
+
  pRtree->zNodeName = &pRtree->zName[nName+1];
  pRtree->eCoordType = RTREE_COORD_REAL32;
  pRtree->nDim = 2;
  pRtree->nDim2 = 4;
  memcpy(pRtree->zDb, argv[1], nDb);
  memcpy(pRtree->zName, argv[2], nName);
+
  memcpy(pRtree->zNodeName, argv[2], nName);
+
  memcpy(&pRtree->zNodeName[nName], "_node", 6);


  /* Create/Connect to the underlying relational database schema. If
@@ -211190,7 +212482,6 @@ static int geopolyUpdate(
    }
    if( rc==SQLITE_OK ){
      int rc2;
-
      pRtree->iReinsertHeight = -1;
      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
      rc2 = nodeRelease(pRtree, pLeaf);
      if( rc==SQLITE_OK ){
@@ -211287,7 +212578,8 @@ static sqlite3_module geopolyModule = {
  rtreeSavepoint,             /* xSavepoint */
  0,                          /* xRelease */
  0,                          /* xRollbackTo */
-
  rtreeShadowName             /* xShadowName */
+
  rtreeShadowName,            /* xShadowName */
+
  rtreeIntegrity              /* xIntegrity */
};

static int sqlite3_geopoly_init(sqlite3 *db){
@@ -219301,7 +220593,8 @@ SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
    0,                            /* xSavepoint */
    0,                            /* xRelease */
    0,                            /* xRollbackTo */
-
    0                             /* xShadowName */
+
    0,                            /* xShadowName */
+
    0                             /* xIntegrity */
  };
  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
}
@@ -219738,7 +221031,8 @@ SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
    0,                            /* xSavepoint */
    0,                            /* xRelease */
    0,                            /* xRollbackTo */
-
    0                             /* xShadowName */
+
    0,                            /* xShadowName */
+
    0                             /* xIntegrity */
  };
  return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
}
@@ -219869,6 +221163,18 @@ struct sqlite3_changeset_iter {
** The data associated with each hash-table entry is a structure containing
** a subset of the initial values that the modified row contained at the
** start of the session. Or no initial values if the row was inserted.
+
**
+
** pDfltStmt:
+
**   This is only used by the sqlite3changegroup_xxx() APIs, not by
+
**   regular sqlite3_session objects. It is a SELECT statement that
+
**   selects the default value for each table column. For example,
+
**   if the table is
+
**
+
**      CREATE TABLE xx(a DEFAULT 1, b, c DEFAULT 'abc')
+
**
+
**   then this variable is the compiled version of:
+
**
+
**      SELECT 1, NULL, 'abc'
*/
struct SessionTable {
  SessionTable *pNext;
@@ -219877,10 +221183,12 @@ struct SessionTable {
  int bStat1;                     /* True if this is sqlite_stat1 */
  int bRowid;                     /* True if this table uses rowid for PK */
  const char **azCol;             /* Column names */
+
  const char **azDflt;            /* Default value expressions */
  u8 *abPK;                       /* Array of primary key flags */
  int nEntry;                     /* Total number of entries in hash table */
  int nChange;                    /* Size of apChange[] array */
  SessionChange **apChange;       /* Hash table buckets */
+
  sqlite3_stmt *pDfltStmt;
};

/*
@@ -220049,6 +221357,7 @@ struct SessionTable {
struct SessionChange {
  u8 op;                          /* One of UPDATE, DELETE, INSERT */
  u8 bIndirect;                   /* True if this change is "indirect" */
+
  u16 nRecordField;               /* Number of fields in aRecord[] */
  int nMaxSize;                   /* Max size of eventual changeset record */
  int nRecord;                    /* Number of bytes in buffer aRecord[] */
  u8 *aRecord;                    /* Buffer containing old.* record */
@@ -220074,7 +221383,7 @@ static int sessionVarintLen(int iVal){
** Read a varint value from aBuf[] into *piVal. Return the number of
** bytes read.
*/
-
static int sessionVarintGet(u8 *aBuf, int *piVal){
+
static int sessionVarintGet(const u8 *aBuf, int *piVal){
  return getVarint32(aBuf, *piVal);
}

@@ -220337,9 +221646,11 @@ static int sessionPreupdateHash(
** Return the number of bytes of space occupied by the value (including
** the type byte).
*/
-
static int sessionSerialLen(u8 *a){
-
  int e = *a;
+
static int sessionSerialLen(const u8 *a){
+
  int e;
  int n;
+
  assert( a!=0 );
+
  e = *a;
  if( e==0 || e==0xFF ) return 1;
  if( e==SQLITE_NULL ) return 1;
  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
@@ -220744,13 +222055,14 @@ static int sessionGrowHash(
**
** For example, if the table is declared as:
**
-
**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
+
**     CREATE TABLE tbl1(w, x DEFAULT 'abc', y, z, PRIMARY KEY(w, z));
**
-
** Then the four output variables are populated as follows:
+
** Then the five output variables are populated as follows:
**
**     *pnCol  = 4
**     *pzTab  = "tbl1"
**     *pazCol = {"w", "x", "y", "z"}
+
**     *pazDflt = {NULL, 'abc', NULL, NULL}
**     *pabPK  = {1, 0, 0, 1}
**
** All returned buffers are part of the same single allocation, which must
@@ -220764,6 +222076,7 @@ static int sessionTableInfo(
  int *pnCol,                     /* OUT: number of columns */
  const char **pzTab,             /* OUT: Copy of zThis */
  const char ***pazCol,           /* OUT: Array of column names for table */
+
  const char ***pazDflt,          /* OUT: Array of default value expressions */
  u8 **pabPK,                     /* OUT: Array of booleans - true for PK col */
  int *pbRowid                    /* OUT: True if only PK is a rowid */
){
@@ -220776,11 +222089,18 @@ static int sessionTableInfo(
  int i;
  u8 *pAlloc = 0;
  char **azCol = 0;
+
  char **azDflt = 0;
  u8 *abPK = 0;
  int bRowid = 0;                 /* Set to true to use rowid as PK */

  assert( pazCol && pabPK );

+
  *pazCol = 0;
+
  *pabPK = 0;
+
  *pnCol = 0;
+
  if( pzTab ) *pzTab = 0;
+
  if( pazDflt ) *pazDflt = 0;
+

  nThis = sqlite3Strlen30(zThis);
  if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
    rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
@@ -220794,39 +222114,28 @@ 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 ){
-
    *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 ){
-
    *pazCol = 0;
-
    *pabPK = 0;
-
    *pnCol = 0;
-
    if( pzTab ) *pzTab = 0;
    return rc;
  }

  nByte = nThis + 1;
  bRowid = (pbRowid!=0);
  while( SQLITE_ROW==sqlite3_step(pStmt) ){
-
    nByte += sqlite3_column_bytes(pStmt, 1);
+
    nByte += sqlite3_column_bytes(pStmt, 1);          /* name */
+
    nByte += sqlite3_column_bytes(pStmt, 4);          /* dflt_value */
    nDbCol++;
-
    if( sqlite3_column_int(pStmt, 5) ) bRowid = 0;
+
    if( sqlite3_column_int(pStmt, 5) ) bRowid = 0;    /* pk */
  }
  if( nDbCol==0 ) bRowid = 0;
  nDbCol += bRowid;
@@ -220834,15 +222143,18 @@ static int sessionTableInfo(
  rc = sqlite3_reset(pStmt);

  if( rc==SQLITE_OK ){
-
    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
+
    nByte += nDbCol * (sizeof(const char *)*2 + sizeof(u8) + 1 + 1);
    pAlloc = sessionMalloc64(pSession, nByte);
    if( pAlloc==0 ){
      rc = SQLITE_NOMEM;
+
    }else{
+
      memset(pAlloc, 0, nByte);
    }
  }
  if( rc==SQLITE_OK ){
    azCol = (char **)pAlloc;
-
    pAlloc = (u8 *)&azCol[nDbCol];
+
    azDflt = (char**)&azCol[nDbCol];
+
    pAlloc = (u8 *)&azDflt[nDbCol];
    abPK = (u8 *)pAlloc;
    pAlloc = &abPK[nDbCol];
    if( pzTab ){
@@ -220862,11 +222174,21 @@ static int sessionTableInfo(
    }
    while( SQLITE_ROW==sqlite3_step(pStmt) ){
      int nName = sqlite3_column_bytes(pStmt, 1);
+
      int nDflt = sqlite3_column_bytes(pStmt, 4);
      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
+
      const unsigned char *zDflt = sqlite3_column_text(pStmt, 4);
+

      if( zName==0 ) break;
      memcpy(pAlloc, zName, nName+1);
      azCol[i] = (char *)pAlloc;
      pAlloc += nName+1;
+
      if( zDflt ){
+
        memcpy(pAlloc, zDflt, nDflt+1);
+
        azDflt[i] = (char *)pAlloc;
+
        pAlloc += nDflt+1;
+
      }else{
+
        azDflt[i] = 0;
+
      }
      abPK[i] = sqlite3_column_int(pStmt, 5);
      i++;
    }
@@ -220877,14 +222199,11 @@ static int sessionTableInfo(
  ** free any allocation made. An error code will be returned in this case.
  */
  if( rc==SQLITE_OK ){
-
    *pazCol = (const char **)azCol;
+
    *pazCol = (const char**)azCol;
+
    if( pazDflt ) *pazDflt = (const char**)azDflt;
    *pabPK = abPK;
    *pnCol = nDbCol;
  }else{
-
    *pazCol = 0;
-
    *pabPK = 0;
-
    *pnCol = 0;
-
    if( pzTab ) *pzTab = 0;
    sessionFree(pSession, azCol);
  }
  if( pbRowid ) *pbRowid = bRowid;
@@ -220893,10 +222212,9 @@ static int sessionTableInfo(
}

/*
-
** This function is only called from within a pre-update handler for a
-
** write to table pTab, part of session pSession. If this is the first
-
** write to this table, initalize the SessionTable.nCol, azCol[] and
-
** abPK[] arrays accordingly.
+
** This function is called to initialize the SessionTable.nCol, azCol[]
+
** abPK[] and azDflt[] members of SessionTable object pTab. If these
+
** fields are already initilialized, this function is a no-op.
**
** If an error occurs, an error code is stored in sqlite3_session.rc and
** non-zero returned. Or, if no error occurs but the table has no primary
@@ -220904,15 +222222,22 @@ static int sessionTableInfo(
** indicate that updates on this table should be ignored. SessionTable.abPK
** is set to NULL in this case.
*/
-
static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
+
static int sessionInitTable(
+
  sqlite3_session *pSession,      /* Optional session handle */
+
  SessionTable *pTab,             /* Table object to initialize */
+
  sqlite3 *db,                    /* Database handle to read schema from */
+
  const char *zDb                 /* Name of db - "main", "temp" etc. */
+
){
+
  int rc = SQLITE_OK;
+

  if( pTab->nCol==0 ){
    u8 *abPK;
    assert( pTab->azCol==0 || pTab->abPK==0 );
-
    pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb,
-
        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK,
-
        (pSession->bImplicitPK ? &pTab->bRowid : 0)
+
    rc = sessionTableInfo(pSession, db, zDb,
+
        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &pTab->azDflt, &abPK,
+
        ((pSession==0 || pSession->bImplicitPK) ? &pTab->bRowid : 0)
    );
-
    if( pSession->rc==SQLITE_OK ){
+
    if( rc==SQLITE_OK ){
      int i;
      for(i=0; i<pTab->nCol; i++){
        if( abPK[i] ){
@@ -220924,14 +222249,321 @@ static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
        pTab->bStat1 = 1;
      }

-
      if( pSession->bEnableSize ){
+
      if( pSession && pSession->bEnableSize ){
        pSession->nMaxChangesetSize += (
          1 + sessionVarintLen(pTab->nCol) + pTab->nCol + strlen(pTab->zName)+1
        );
      }
    }
  }
-
  return (pSession->rc || pTab->abPK==0);
+

+
  if( pSession ){
+
    pSession->rc = rc;
+
    return (rc || pTab->abPK==0);
+
  }
+
  return rc;
+
}
+

+
/*
+
** Re-initialize table object pTab.
+
*/
+
static int sessionReinitTable(sqlite3_session *pSession, SessionTable *pTab){
+
  int nCol = 0;
+
  const char **azCol = 0;
+
  const char **azDflt = 0;
+
  u8 *abPK = 0;
+
  int bRowid = 0;
+

+
  assert( pSession->rc==SQLITE_OK );
+

+
  pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb,
+
      pTab->zName, &nCol, 0, &azCol, &azDflt, &abPK,
+
      (pSession->bImplicitPK ? &bRowid : 0)
+
  );
+
  if( pSession->rc==SQLITE_OK ){
+
    if( pTab->nCol>nCol || pTab->bRowid!=bRowid ){
+
      pSession->rc = SQLITE_SCHEMA;
+
    }else{
+
      int ii;
+
      int nOldCol = pTab->nCol;
+
      for(ii=0; ii<nCol; ii++){
+
        if( ii<pTab->nCol ){
+
          if( pTab->abPK[ii]!=abPK[ii] ){
+
            pSession->rc = SQLITE_SCHEMA;
+
          }
+
        }else if( abPK[ii] ){
+
          pSession->rc = SQLITE_SCHEMA;
+
        }
+
      }
+

+
      if( pSession->rc==SQLITE_OK ){
+
        const char **a = pTab->azCol;
+
        pTab->azCol = azCol;
+
        pTab->nCol = nCol;
+
        pTab->azDflt = azDflt;
+
        pTab->abPK = abPK;
+
        azCol = a;
+
      }
+
      if( pSession->bEnableSize ){
+
        pSession->nMaxChangesetSize += (nCol - nOldCol);
+
        pSession->nMaxChangesetSize += sessionVarintLen(nCol);
+
        pSession->nMaxChangesetSize -= sessionVarintLen(nOldCol);
+
      }
+
    }
+
  }
+

+
  sqlite3_free((char*)azCol);
+
  return pSession->rc;
+
}
+

+
/*
+
** Session-change object (*pp) contains an old.* record with fewer than
+
** nCol fields. This function updates it with the default values for
+
** the missing fields.
+
*/
+
static void sessionUpdateOneChange(
+
  sqlite3_session *pSession,      /* For memory accounting */
+
  int *pRc,                       /* IN/OUT: Error code */
+
  SessionChange **pp,             /* IN/OUT: Change object to update */
+
  int nCol,                       /* Number of columns now in table */
+
  sqlite3_stmt *pDflt             /* SELECT <default-values...> */
+
){
+
  SessionChange *pOld = *pp;
+

+
  while( pOld->nRecordField<nCol ){
+
    SessionChange *pNew = 0;
+
    int nByte = 0;
+
    int nIncr = 0;
+
    int iField = pOld->nRecordField;
+
    int eType = sqlite3_column_type(pDflt, iField);
+
    switch( eType ){
+
      case SQLITE_NULL:
+
        nIncr = 1;
+
        break;
+
      case SQLITE_INTEGER:
+
      case SQLITE_FLOAT:
+
        nIncr = 9;
+
        break;
+
      default: {
+
        int n = sqlite3_column_bytes(pDflt, iField);
+
        nIncr = 1 + sessionVarintLen(n) + n;
+
        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
+
        break;
+
      }
+
    }
+

+
    nByte = nIncr + (sizeof(SessionChange) + pOld->nRecord);
+
    pNew = sessionMalloc64(pSession, nByte);
+
    if( pNew==0 ){
+
      *pRc = SQLITE_NOMEM;
+
      return;
+
    }else{
+
      memcpy(pNew, pOld, sizeof(SessionChange));
+
      pNew->aRecord = (u8*)&pNew[1];
+
      memcpy(pNew->aRecord, pOld->aRecord, pOld->nRecord);
+
      pNew->aRecord[pNew->nRecord++] = (u8)eType;
+
      switch( eType ){
+
        case SQLITE_INTEGER: {
+
          i64 iVal = sqlite3_column_int64(pDflt, iField);
+
          sessionPutI64(&pNew->aRecord[pNew->nRecord], iVal);
+
          pNew->nRecord += 8;
+
          break;
+
        }
+

+
        case SQLITE_FLOAT: {
+
          double rVal = sqlite3_column_double(pDflt, iField);
+
          i64 iVal = 0;
+
          memcpy(&iVal, &rVal, sizeof(rVal));
+
          sessionPutI64(&pNew->aRecord[pNew->nRecord], iVal);
+
          pNew->nRecord += 8;
+
          break;
+
        }
+

+
        case SQLITE_TEXT: {
+
          int n = sqlite3_column_bytes(pDflt, iField);
+
          const char *z = (const char*)sqlite3_column_text(pDflt, iField);
+
          pNew->nRecord += sessionVarintPut(&pNew->aRecord[pNew->nRecord], n);
+
          memcpy(&pNew->aRecord[pNew->nRecord], z, n);
+
          pNew->nRecord += n;
+
          break;
+
        }
+

+
        case SQLITE_BLOB: {
+
          int n = sqlite3_column_bytes(pDflt, iField);
+
          const u8 *z = (const u8*)sqlite3_column_blob(pDflt, iField);
+
          pNew->nRecord += sessionVarintPut(&pNew->aRecord[pNew->nRecord], n);
+
          memcpy(&pNew->aRecord[pNew->nRecord], z, n);
+
          pNew->nRecord += n;
+
          break;
+
        }
+

+
        default:
+
          assert( eType==SQLITE_NULL );
+
          break;
+
      }
+

+
      sessionFree(pSession, pOld);
+
      *pp = pOld = pNew;
+
      pNew->nRecordField++;
+
      pNew->nMaxSize += nIncr;
+
      if( pSession ){
+
        pSession->nMaxChangesetSize += nIncr;
+
      }
+
    }
+
  }
+
}
+

+
/*
+
** Ensure that there is room in the buffer to append nByte bytes of data.
+
** If not, use sqlite3_realloc() to grow the buffer so that there is.
+
**
+
** 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, 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( 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 ){
+
      *pRc = SQLITE_NOMEM;
+
    }else{
+
      p->aBuf = aNew;
+
      p->nAlloc = nNew;
+
    }
+
  }
+
  return (*pRc!=SQLITE_OK);
+
}
+

+

+
/*
+
** This function is a no-op if *pRc is other than SQLITE_OK when it is
+
** called. Otherwise, append a string to the buffer. All bytes in the string
+
** up to (but not including) the nul-terminator are written to the buffer.
+
**
+
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
+
** returning.
+
*/
+
static void sessionAppendStr(
+
  SessionBuffer *p,
+
  const char *zStr,
+
  int *pRc
+
){
+
  int nStr = sqlite3Strlen30(zStr);
+
  if( 0==sessionBufferGrow(p, nStr+1, pRc) ){
+
    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
+
    p->nBuf += nStr;
+
    p->aBuf[p->nBuf] = 0x00;
+
  }
+
}
+

+
/*
+
** Format a string using printf() style formatting and then append it to the
+
** buffer using sessionAppendString().
+
*/
+
static void sessionAppendPrintf(
+
  SessionBuffer *p,               /* Buffer to append to */
+
  int *pRc,
+
  const char *zFmt,
+
  ...
+
){
+
  if( *pRc==SQLITE_OK ){
+
    char *zApp = 0;
+
    va_list ap;
+
    va_start(ap, zFmt);
+
    zApp = sqlite3_vmprintf(zFmt, ap);
+
    if( zApp==0 ){
+
      *pRc = SQLITE_NOMEM;
+
    }else{
+
      sessionAppendStr(p, zApp, pRc);
+
    }
+
    va_end(ap);
+
    sqlite3_free(zApp);
+
  }
+
}
+

+
/*
+
** Prepare a statement against database handle db that SELECTs a single
+
** row containing the default values for each column in table pTab. For
+
** example, if pTab is declared as:
+
**
+
**   CREATE TABLE pTab(a PRIMARY KEY, b DEFAULT 123, c DEFAULT 'abcd');
+
**
+
** Then this function prepares and returns the SQL statement:
+
**
+
**   SELECT NULL, 123, 'abcd';
+
*/
+
static int sessionPrepareDfltStmt(
+
  sqlite3 *db,                    /* Database handle */
+
  SessionTable *pTab,             /* Table to prepare statement for */
+
  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
+
){
+
  SessionBuffer sql = {0,0,0};
+
  int rc = SQLITE_OK;
+
  const char *zSep = " ";
+
  int ii = 0;
+

+
  *ppStmt = 0;
+
  sessionAppendPrintf(&sql, &rc, "SELECT");
+
  for(ii=0; ii<pTab->nCol; ii++){
+
    const char *zDflt = pTab->azDflt[ii] ? pTab->azDflt[ii] : "NULL";
+
    sessionAppendPrintf(&sql, &rc, "%s%s", zSep, zDflt);
+
    zSep = ", ";
+
  }
+
  if( rc==SQLITE_OK ){
+
    rc = sqlite3_prepare_v2(db, (const char*)sql.aBuf, -1, ppStmt, 0);
+
  }
+
  sqlite3_free(sql.aBuf);
+

+
  return rc;
+
}
+

+
/*
+
** Table pTab has one or more existing change-records with old.* records
+
** with fewer than pTab->nCol columns. This function updates all such
+
** change-records with the default values for the missing columns.
+
*/
+
static int sessionUpdateChanges(sqlite3_session *pSession, SessionTable *pTab){
+
  sqlite3_stmt *pStmt = 0;
+
  int rc = pSession->rc;
+

+
  rc = sessionPrepareDfltStmt(pSession->db, pTab, &pStmt);
+
  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
+
    int ii = 0;
+
    SessionChange **pp = 0;
+
    for(ii=0; ii<pTab->nChange; ii++){
+
      for(pp=&pTab->apChange[ii]; *pp; pp=&((*pp)->pNext)){
+
        if( (*pp)->nRecordField!=pTab->nCol ){
+
          sessionUpdateOneChange(pSession, &rc, pp, pTab->nCol, pStmt);
+
        }
+
      }
+
    }
+
  }
+

+
  pSession->rc = rc;
+
  rc = sqlite3_finalize(pStmt);
+
  if( pSession->rc==SQLITE_OK ) pSession->rc = rc;
+
  return pSession->rc;
}

/*
@@ -221094,16 +222726,22 @@ static void sessionPreupdateOneChange(
  int iHash;
  int bNull = 0;
  int rc = SQLITE_OK;
+
  int nExpect = 0;
  SessionStat1Ctx stat1 = {{0,0,0,0,0},0};

  if( pSession->rc ) return;

  /* Load table details if required */
-
  if( sessionInitTable(pSession, pTab) ) return;
+
  if( sessionInitTable(pSession, pTab, pSession->db, pSession->zDb) ) return;

  /* Check the number of columns in this xPreUpdate call matches the
  ** number of columns in the table.  */
-
  if( (pTab->nCol-pTab->bRowid)!=pSession->hook.xCount(pSession->hook.pCtx) ){
+
  nExpect = pSession->hook.xCount(pSession->hook.pCtx);
+
  if( (pTab->nCol-pTab->bRowid)<nExpect ){
+
    if( sessionReinitTable(pSession, pTab) ) return;
+
    if( sessionUpdateChanges(pSession, pTab) ) return;
+
  }
+
  if( (pTab->nCol-pTab->bRowid)!=nExpect ){
    pSession->rc = SQLITE_SCHEMA;
    return;
  }
@@ -221180,7 +222818,7 @@ static void sessionPreupdateOneChange(
      }

      /* Allocate the change object */
-
      pC = (SessionChange *)sessionMalloc64(pSession, nByte);
+
      pC = (SessionChange*)sessionMalloc64(pSession, nByte);
      if( !pC ){
        rc = SQLITE_NOMEM;
        goto error_out;
@@ -221213,6 +222851,7 @@ static void sessionPreupdateOneChange(
      if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
        pC->bIndirect = 1;
      }
+
      pC->nRecordField = pTab->nCol;
      pC->nRecord = nByte;
      pC->op = op;
      pC->pNext = pTab->apChange[iHash];
@@ -221592,7 +223231,7 @@ SQLITE_API int sqlite3session_diff(
    /* Locate and if necessary initialize the target table object */
    rc = sessionFindTable(pSession, zTbl, &pTo);
    if( pTo==0 ) goto diff_out;
-
    if( sessionInitTable(pSession, pTo) ){
+
    if( sessionInitTable(pSession, pTo, pSession->db, pSession->zDb) ){
      rc = pSession->rc;
      goto diff_out;
    }
@@ -221605,7 +223244,7 @@ SQLITE_API int sqlite3session_diff(
      int bRowid = 0;
      u8 *abPK;
      const char **azCol = 0;
-
      rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, &abPK,
+
      rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, 0, &abPK,
          pSession->bImplicitPK ? &bRowid : 0
      );
      if( rc==SQLITE_OK ){
@@ -221720,6 +223359,7 @@ static void sessionDeleteTable(sqlite3_session *pSession, SessionTable *pList){
        sessionFree(pSession, p);
      }
    }
+
    sqlite3_finalize(pTab->pDfltStmt);
    sessionFree(pSession, (char*)pTab->azCol);  /* cast works around VC++ bug */
    sessionFree(pSession, pTab->apChange);
    sessionFree(pSession, pTab);
@@ -221754,7 +223394,7 @@ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){

  /* Assert that all allocations have been freed and then free the
  ** session object itself. */
-
  assert( pSession->nMalloc==0 );
+
  // assert( pSession->nMalloc==0 );
  sqlite3_free(pSession);
}

@@ -221826,48 +223466,6 @@ SQLITE_API int sqlite3session_attach(
}

/*
-
** Ensure that there is room in the buffer to append nByte bytes of data.
-
** If not, use sqlite3_realloc() to grow the buffer so that there is.
-
**
-
** 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, 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( 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 ){
-
      *pRc = SQLITE_NOMEM;
-
    }else{
-
      p->aBuf = aNew;
-
      p->nAlloc = nNew;
-
    }
-
  }
-
  return (*pRc!=SQLITE_OK);
-
}
-

-
/*
** Append the value passed as the second argument to the buffer passed
** as the first.
**
@@ -221937,27 +223535,6 @@ static void sessionAppendBlob(

/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
-
** called. Otherwise, append a string to the buffer. All bytes in the string
-
** up to (but not including) the nul-terminator are written to the buffer.
-
**
-
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
-
** returning.
-
*/
-
static void sessionAppendStr(
-
  SessionBuffer *p,
-
  const char *zStr,
-
  int *pRc
-
){
-
  int nStr = sqlite3Strlen30(zStr);
-
  if( 0==sessionBufferGrow(p, nStr+1, pRc) ){
-
    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
-
    p->nBuf += nStr;
-
    p->aBuf[p->nBuf] = 0x00;
-
  }
-
}
-

-
/*
-
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string representation of integer iVal
** to the buffer. No nul-terminator is written.
**
@@ -221974,27 +223551,6 @@ static void sessionAppendInteger(
  sessionAppendStr(p, aBuf, pRc);
}

-
static void sessionAppendPrintf(
-
  SessionBuffer *p,               /* Buffer to append to */
-
  int *pRc,
-
  const char *zFmt,
-
  ...
-
){
-
  if( *pRc==SQLITE_OK ){
-
    char *zApp = 0;
-
    va_list ap;
-
    va_start(ap, zFmt);
-
    zApp = sqlite3_vmprintf(zFmt, ap);
-
    if( zApp==0 ){
-
      *pRc = SQLITE_NOMEM;
-
    }else{
-
      sessionAppendStr(p, zApp, pRc);
-
    }
-
    va_end(ap);
-
    sqlite3_free(zApp);
-
  }
-
}
-

/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string zStr enclosed in quotes (") and
@@ -222485,26 +224041,16 @@ static int sessionGenerateChangeset(
  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
    if( pTab->nEntry ){
      const char *zName = pTab->zName;
-
      int nCol = 0;               /* Number of columns in table */
-
      u8 *abPK = 0;               /* Primary key array */
-
      const char **azCol = 0;     /* Table columns */
      int i;                      /* Used to iterate through hash buckets */
      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
      int nRewind = buf.nBuf;     /* Initial size of write buffer */
      int nNoop;                  /* Size of buffer after writing tbl header */
-
      int bRowid = 0;
+
      int nOldCol = pTab->nCol;

      /* Check the table schema is still Ok. */
-
      rc = sessionTableInfo(
-
          0, db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK,
-
          (pSession->bImplicitPK ? &bRowid : 0)
-
      );
-
      if( rc==SQLITE_OK && (
-
          pTab->nCol!=nCol
-
       || pTab->bRowid!=bRowid
-
       || memcmp(abPK, pTab->abPK, nCol)
-
      )){
-
        rc = SQLITE_SCHEMA;
+
      rc = sessionReinitTable(pSession, pTab);
+
      if( rc==SQLITE_OK && pTab->nCol!=nOldCol ){
+
        rc = sessionUpdateChanges(pSession, pTab);
      }

      /* Write a table header */
@@ -222512,8 +224058,8 @@ static int sessionGenerateChangeset(

      /* Build and compile a statement to execute: */
      if( rc==SQLITE_OK ){
-
        rc = sessionSelectStmt(
-
            db, 0, pSession->zDb, zName, bRowid, nCol, azCol, abPK, &pSel
+
        rc = sessionSelectStmt(db, 0, pSession->zDb,
+
            zName, pTab->bRowid, pTab->nCol, pTab->azCol, pTab->abPK, &pSel
        );
      }

@@ -222522,22 +224068,22 @@ static int sessionGenerateChangeset(
        SessionChange *p;         /* Used to iterate through changes */

        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
-
          rc = sessionSelectBind(pSel, nCol, abPK, p);
+
          rc = sessionSelectBind(pSel, pTab->nCol, pTab->abPK, p);
          if( rc!=SQLITE_OK ) continue;
          if( sqlite3_step(pSel)==SQLITE_ROW ){
            if( p->op==SQLITE_INSERT ){
              int iCol;
              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
              sessionAppendByte(&buf, p->bIndirect, &rc);
-
              for(iCol=0; iCol<nCol; iCol++){
+
              for(iCol=0; iCol<pTab->nCol; iCol++){
                sessionAppendCol(&buf, pSel, iCol, &rc);
              }
            }else{
-
              assert( abPK!=0 );  /* Because sessionSelectStmt() returned ok */
-
              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
+
              assert( pTab->abPK!=0 );
+
              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, pTab->abPK);
            }
          }else if( p->op!=SQLITE_INSERT ){
-
            rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
+
            rc = sessionAppendDelete(&buf, bPatchset, p, pTab->nCol,pTab->abPK);
          }
          if( rc==SQLITE_OK ){
            rc = sqlite3_reset(pSel);
@@ -222562,7 +224108,6 @@ static int sessionGenerateChangeset(
      if( buf.nBuf==nNoop ){
        buf.nBuf = nRewind;
      }
-
      sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
    }
  }

@@ -222986,15 +224531,19 @@ static int sessionReadRecord(
        }
      }
      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
-
        sqlite3_int64 v = sessionGetI64(aVal);
-
        if( eType==SQLITE_INTEGER ){
-
          sqlite3VdbeMemSetInt64(apOut[i], v);
+
        if( (pIn->nData-pIn->iNext)<8 ){
+
          rc = SQLITE_CORRUPT_BKPT;
        }else{
-
          double d;
-
          memcpy(&d, &v, 8);
-
          sqlite3VdbeMemSetDouble(apOut[i], d);
+
          sqlite3_int64 v = sessionGetI64(aVal);
+
          if( eType==SQLITE_INTEGER ){
+
            sqlite3VdbeMemSetInt64(apOut[i], v);
+
          }else{
+
            double d;
+
            memcpy(&d, &v, 8);
+
            sqlite3VdbeMemSetDouble(apOut[i], d);
+
          }
+
          pIn->iNext += 8;
        }
-
        pIn->iNext += 8;
      }
    }
  }
@@ -224687,7 +226236,7 @@ static int sessionChangesetApply(

        sqlite3changeset_pk(pIter, &abPK, 0);
        rc = sessionTableInfo(0, db, "main", zNew,
-
            &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK, &sApply.bRowid
+
            &sApply.nCol, &zTab, &sApply.azCol, 0, &sApply.abPK, &sApply.bRowid
        );
        if( rc!=SQLITE_OK ) break;
        for(i=0; i<sApply.nCol; i++){
@@ -224819,11 +226368,24 @@ SQLITE_API int sqlite3changeset_apply_v2(
  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
  int bInv = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset, bInv, 1);
+
  u64 savedFlag = db->flags & SQLITE_FkNoAction;
+

+
  if( flags & SQLITE_CHANGESETAPPLY_FKNOACTION ){
+
    db->flags |= ((u64)SQLITE_FkNoAction);
+
    db->aDb[0].pSchema->schema_cookie -= 32;
+
  }
+

  if( rc==SQLITE_OK ){
    rc = sessionChangesetApply(
        db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
    );
  }
+

+
  if( (flags & SQLITE_CHANGESETAPPLY_FKNOACTION) && savedFlag==0 ){
+
    assert( db->flags & SQLITE_FkNoAction );
+
    db->flags &= ~((u64)SQLITE_FkNoAction);
+
    db->aDb[0].pSchema->schema_cookie -= 32;
+
  }
  return rc;
}

@@ -224911,6 +226473,9 @@ struct sqlite3_changegroup {
  int rc;                         /* Error code */
  int bPatch;                     /* True to accumulate patchsets */
  SessionTable *pList;            /* List of tables in current patch */
+

+
  sqlite3 *db;                    /* Configured by changegroup_schema() */
+
  char *zDb;                      /* Configured by changegroup_schema() */
};

/*
@@ -224931,6 +226496,7 @@ static int sessionChangeMerge(
){
  SessionChange *pNew = 0;
  int rc = SQLITE_OK;
+
  assert( aRec!=0 );

  if( !pExist ){
    pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
@@ -225097,6 +226663,114 @@ static int sessionChangeMerge(
}

/*
+
** Check if a changeset entry with nCol columns and the PK array passed
+
** as the final argument to this function is compatible with SessionTable
+
** pTab. If so, return 1. Otherwise, if they are incompatible in some way,
+
** return 0.
+
*/
+
static int sessionChangesetCheckCompat(
+
  SessionTable *pTab,
+
  int nCol,
+
  u8 *abPK
+
){
+
  if( pTab->azCol && nCol<pTab->nCol ){
+
    int ii;
+
    for(ii=0; ii<pTab->nCol; ii++){
+
      u8 bPK = (ii < nCol) ? abPK[ii] : 0;
+
      if( pTab->abPK[ii]!=bPK ) return 0;
+
    }
+
    return 1;
+
  }
+
  return (pTab->nCol==nCol && 0==memcmp(abPK, pTab->abPK, nCol));
+
}
+

+
static int sessionChangesetExtendRecord(
+
  sqlite3_changegroup *pGrp,
+
  SessionTable *pTab,
+
  int nCol,
+
  int op,
+
  const u8 *aRec,
+
  int nRec,
+
  SessionBuffer *pOut
+
){
+
  int rc = SQLITE_OK;
+
  int ii = 0;
+

+
  assert( pTab->azCol );
+
  assert( nCol<pTab->nCol );
+

+
  pOut->nBuf = 0;
+
  if( op==SQLITE_INSERT || (op==SQLITE_DELETE && pGrp->bPatch==0) ){
+
    /* Append the missing default column values to the record. */
+
    sessionAppendBlob(pOut, aRec, nRec, &rc);
+
    if( rc==SQLITE_OK && pTab->pDfltStmt==0 ){
+
      rc = sessionPrepareDfltStmt(pGrp->db, pTab, &pTab->pDfltStmt);
+
    }
+
    for(ii=nCol; rc==SQLITE_OK && ii<pTab->nCol; ii++){
+
      int eType = sqlite3_column_type(pTab->pDfltStmt, ii);
+
      sessionAppendByte(pOut, eType, &rc);
+
      switch( eType ){
+
        case SQLITE_FLOAT:
+
        case SQLITE_INTEGER: {
+
          i64 iVal;
+
          if( eType==SQLITE_INTEGER ){
+
            iVal = sqlite3_column_int64(pTab->pDfltStmt, ii);
+
          }else{
+
            double rVal = sqlite3_column_int64(pTab->pDfltStmt, ii);
+
            memcpy(&iVal, &rVal, sizeof(i64));
+
          }
+
          if( SQLITE_OK==sessionBufferGrow(pOut, 8, &rc) ){
+
            sessionPutI64(&pOut->aBuf[pOut->nBuf], iVal);
+
          }
+
          break;
+
        }
+

+
        case SQLITE_BLOB:
+
        case SQLITE_TEXT: {
+
          int n = sqlite3_column_bytes(pTab->pDfltStmt, ii);
+
          sessionAppendVarint(pOut, n, &rc);
+
          if( eType==SQLITE_TEXT ){
+
            const u8 *z = (const u8*)sqlite3_column_text(pTab->pDfltStmt, ii);
+
            sessionAppendBlob(pOut, z, n, &rc);
+
          }else{
+
            const u8 *z = (const u8*)sqlite3_column_blob(pTab->pDfltStmt, ii);
+
            sessionAppendBlob(pOut, z, n, &rc);
+
          }
+
          break;
+
        }
+

+
        default:
+
          assert( eType==SQLITE_NULL );
+
          break;
+
      }
+
    }
+
  }else if( op==SQLITE_UPDATE ){
+
    /* Append missing "undefined" entries to the old.* record. And, if this
+
    ** is an UPDATE, to the new.* record as well.  */
+
    int iOff = 0;
+
    if( pGrp->bPatch==0 ){
+
      for(ii=0; ii<nCol; ii++){
+
        iOff += sessionSerialLen(&aRec[iOff]);
+
      }
+
      sessionAppendBlob(pOut, aRec, iOff, &rc);
+
      for(ii=0; ii<(pTab->nCol-nCol); ii++){
+
        sessionAppendByte(pOut, 0x00, &rc);
+
      }
+
    }
+

+
    sessionAppendBlob(pOut, &aRec[iOff], nRec-iOff, &rc);
+
    for(ii=0; ii<(pTab->nCol-nCol); ii++){
+
      sessionAppendByte(pOut, 0x00, &rc);
+
    }
+
  }else{
+
    assert( op==SQLITE_DELETE && pGrp->bPatch );
+
    sessionAppendBlob(pOut, aRec, nRec, &rc);
+
  }
+

+
  return rc;
+
}
+

+
/*
** Add all changes in the changeset traversed by the iterator passed as
** the first argument to the changegroup hash tables.
*/
@@ -225109,6 +226783,7 @@ static int sessionChangesetToHash(
  int nRec;
  int rc = SQLITE_OK;
  SessionTable *pTab = 0;
+
  SessionBuffer rec = {0, 0, 0};

  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
    const char *zNew;
@@ -225120,6 +226795,9 @@ static int sessionChangesetToHash(
    SessionChange *pExist = 0;
    SessionChange **pp;

+
    /* Ensure that only changesets, or only patchsets, but not a mixture
+
    ** of both, are being combined. It is an error to try to combine a
+
    ** changeset and a patchset.  */
    if( pGrp->pList==0 ){
      pGrp->bPatch = pIter->bPatchset;
    }else if( pIter->bPatchset!=pGrp->bPatch ){
@@ -225152,18 +226830,38 @@ static int sessionChangesetToHash(
        pTab->zName = (char*)&pTab->abPK[nCol];
        memcpy(pTab->zName, zNew, nNew+1);

+
        if( pGrp->db ){
+
          pTab->nCol = 0;
+
          rc = sessionInitTable(0, pTab, pGrp->db, pGrp->zDb);
+
          if( rc ){
+
            assert( pTab->azCol==0 );
+
            sqlite3_free(pTab);
+
            break;
+
          }
+
        }
+

        /* The new object must be linked on to the end of the list, not
        ** simply added to the start of it. This is to ensure that the
        ** tables within the output of sqlite3changegroup_output() are in
        ** the right order.  */
        for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
        *ppTab = pTab;
-
      }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
+
      }
+

+
      if( !sessionChangesetCheckCompat(pTab, nCol, abPK) ){
        rc = SQLITE_SCHEMA;
        break;
      }
    }

+
    if( nCol<pTab->nCol ){
+
      assert( pGrp->db );
+
      rc = sessionChangesetExtendRecord(pGrp, pTab, nCol, op, aRec, nRec, &rec);
+
      if( rc ) break;
+
      aRec = rec.aBuf;
+
      nRec = rec.nBuf;
+
    }
+

    if( sessionGrowHash(0, pIter->bPatchset, pTab) ){
      rc = SQLITE_NOMEM;
      break;
@@ -225201,6 +226899,7 @@ static int sessionChangesetToHash(
    }
  }

+
  sqlite3_free(rec.aBuf);
  if( rc==SQLITE_OK ) rc = pIter->rc;
  return rc;
}
@@ -225288,6 +226987,31 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
}

/*
+
** Provide a database schema to the changegroup object.
+
*/
+
SQLITE_API int sqlite3changegroup_schema(
+
  sqlite3_changegroup *pGrp,
+
  sqlite3 *db,
+
  const char *zDb
+
){
+
  int rc = SQLITE_OK;
+

+
  if( pGrp->pList || pGrp->db ){
+
    /* Cannot add a schema after one or more calls to sqlite3changegroup_add(),
+
    ** or after sqlite3changegroup_schema() has already been called. */
+
    rc = SQLITE_MISUSE;
+
  }else{
+
    pGrp->zDb = sqlite3_mprintf("%s", zDb);
+
    if( pGrp->zDb==0 ){
+
      rc = SQLITE_NOMEM;
+
    }else{
+
      pGrp->db = db;
+
    }
+
  }
+
  return rc;
+
}
+

+
/*
** Add the changeset currently stored in buffer pData, size nData bytes,
** to changeset-group p.
*/
@@ -225350,6 +227074,7 @@ SQLITE_API int sqlite3changegroup_output_strm(
*/
SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  if( pGrp ){
+
    sqlite3_free(pGrp->zDb);
    sessionDeleteTable(0, pGrp->pList);
    sqlite3_free(pGrp);
  }
@@ -228855,15 +230580,19 @@ static int fts5CInstIterInit(
*/
typedef struct HighlightContext HighlightContext;
struct HighlightContext {
-
  CInstIter iter;                 /* Coalesced Instance Iterator */
-
  int iPos;                       /* Current token offset in zIn[] */
+
  /* Constant parameters to fts5HighlightCb() */
  int iRangeStart;                /* First token to include */
  int iRangeEnd;                  /* If non-zero, last token to include */
  const char *zOpen;              /* Opening highlight */
  const char *zClose;             /* Closing highlight */
  const char *zIn;                /* Input text */
  int nIn;                        /* Size of input text in bytes */
-
  int iOff;                       /* Current offset within zIn[] */
+

+
  /* Variables modified by fts5HighlightCb() */
+
  CInstIter iter;                 /* Coalesced Instance Iterator */
+
  int iPos;                       /* Current token offset in zIn[] */
+
  int iOff;                       /* Have copied up to this offset in zIn[] */
+
  int bOpen;                      /* True if highlight is open */
  char *zOut;                     /* Output value */
};

@@ -228896,8 +230625,8 @@ static int fts5HighlightCb(
  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
  const char *pToken,             /* Buffer containing token */
  int nToken,                     /* Size of token in bytes */
-
  int iStartOff,                  /* Start offset of token */
-
  int iEndOff                     /* End offset of token */
+
  int iStartOff,                  /* Start byte offset of token */
+
  int iEndOff                     /* End byte offset of token */
){
  HighlightContext *p = (HighlightContext*)pContext;
  int rc = SQLITE_OK;
@@ -228913,30 +230642,47 @@ static int fts5HighlightCb(
    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  }

-
  if( iPos==p->iter.iStart ){
+
  /* If the parenthesis is open, and this token is not part of the current
+
  ** phrase, and the starting byte offset of this token is past the point
+
  ** that has currently been copied into the output buffer, close the
+
  ** parenthesis. */
+
  if( p->bOpen
+
   && (iPos<=p->iter.iStart || p->iter.iStart<0)
+
   && iStartOff>p->iOff
+
  ){
+
    fts5HighlightAppend(&rc, p, p->zClose, -1);
+
    p->bOpen = 0;
+
  }
+

+
  /* If this is the start of a new phrase, and the highlight is not open:
+
  **
+
  **   * copy text from the input up to the start of the phrase, and
+
  **   * open the highlight.
+
  */
+
  if( iPos==p->iter.iStart && p->bOpen==0 ){
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
    fts5HighlightAppend(&rc, p, p->zOpen, -1);
    p->iOff = iStartOff;
+
    p->bOpen = 1;
  }

  if( iPos==p->iter.iEnd ){
-
    if( p->iRangeEnd>=0 && p->iter.iStart<p->iRangeStart ){
+
    if( p->bOpen==0 ){
+
      assert( p->iRangeEnd>=0 );
      fts5HighlightAppend(&rc, p, p->zOpen, -1);
+
      p->bOpen = 1;
    }
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
-
    fts5HighlightAppend(&rc, p, p->zClose, -1);
    p->iOff = iEndOff;
+

    if( rc==SQLITE_OK ){
      rc = fts5CInstIterNext(&p->iter);
    }
  }

-
  if( p->iRangeEnd>=0 && iPos==p->iRangeEnd ){
+
  if( iPos==p->iRangeEnd ){
    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
    p->iOff = iEndOff;
-
    if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
-
      fts5HighlightAppend(&rc, p, p->zClose, -1);
-
    }
  }

  return rc;
@@ -228977,6 +230723,9 @@ static void fts5HighlightFunction(
    if( rc==SQLITE_OK ){
      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
    }
+
    if( ctx.bOpen ){
+
      fts5HighlightAppend(&rc, &ctx, ctx.zClose, -1);
+
    }
    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);

    if( rc==SQLITE_OK ){
@@ -229255,6 +231004,9 @@ static void fts5SnippetFunction(
    if( rc==SQLITE_OK ){
      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
    }
+
    if( ctx.bOpen ){
+
      fts5HighlightAppend(&rc, &ctx, ctx.zClose, -1);
+
    }
    if( ctx.iRangeEnd>=(nColSize-1) ){
      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
    }else{
@@ -234472,10 +236224,8 @@ static Fts5HashEntry *fts5HashEntryMerge(
}

/*
-
** Extract all tokens from hash table iHash and link them into a list
-
** in sorted order. The hash table is cleared before returning. It is
-
** the responsibility of the caller to free the elements of the returned
-
** list.
+
** Link all tokens from hash table iHash into a list in sorted order. The
+
** tokens are not removed from the hash table.
*/
static int fts5HashEntrySort(
  Fts5Hash *pHash,
@@ -237341,6 +239091,14 @@ static void fts5SegIterHashInit(
        pLeaf->p = (u8*)pList;
      }
    }
+

+
    /* The call to sqlite3Fts5HashScanInit() causes the hash table to
+
    ** fill the size field of all existing position lists. This means they
+
    ** can no longer be appended to. Since the only scenario in which they
+
    ** can be appended to is if the previous operation on this table was
+
    ** a DELETE, by clearing the Fts5Index.bDelete flag we can avoid this
+
    ** possibility altogether.  */
+
    p->bDelete = 0;
  }else{
    p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
        (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
@@ -237526,7 +239284,6 @@ static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
      assert_nc( i2!=0 );
      pRes->bTermEq = 1;
      if( p1->iRowid==p2->iRowid ){
-
        p1->bDel = p2->bDel;
        return i2;
      }
      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
@@ -237894,7 +239651,7 @@ static Fts5Iter *fts5MultiIterAlloc(
  int nSeg
){
  Fts5Iter *pNew;
-
  int nSlot;                      /* Power of two >= nSeg */
+
  i64 nSlot;                      /* Power of two >= nSeg */

  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  pNew = fts5IdxMalloc(p,
@@ -239019,7 +240776,7 @@ static void fts5WriteAppendPoslistData(
  const u8 *a = aData;
  int n = nData;

-
  assert( p->pConfig->pgsz>0 );
+
  assert( p->pConfig->pgsz>0 || p->rc!=SQLITE_OK );
  while( p->rc==SQLITE_OK
     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  ){
@@ -239670,7 +241427,6 @@ static void fts5DoSecureDelete(
  int iPgIdx = pSeg->pLeaf->szLeaf;

  u64 iDelta = 0;
-
  u64 iNextDelta = 0;
  int iNextOff = 0;
  int iOff = 0;
  int nIdx = 0;
@@ -239678,8 +241434,6 @@ static void fts5DoSecureDelete(
  int bLastInDoclist = 0;
  int iIdx = 0;
  int iStart = 0;
-
  int iKeyOff = 0;
-
  int iPrevKeyOff = 0;
  int iDelKeyOff = 0;       /* Offset of deleted key, if any */

  nIdx = nPg-iPgIdx;
@@ -239704,10 +241458,21 @@ static void fts5DoSecureDelete(
  ** This block sets the following variables:
  **
  **   iStart:
+
  **     The offset of the first byte of the rowid or delta-rowid
+
  **     value for the doclist entry being removed.
+
  **
  **   iDelta:
+
  **     The value of the rowid or delta-rowid value for the doclist
+
  **     entry being removed.
+
  **
+
  **   iNextOff:
+
  **     The offset of the next entry following the position list
+
  **     for the one being removed. If the position list for this
+
  **     entry overflows onto the next leaf page, this value will be
+
  **     greater than pLeaf->szLeaf.
  */
  {
-
    int iSOP;
+
    int iSOP;                     /* Start-Of-Position-list */
    if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
      iStart = pSeg->iTermLeafOffset;
    }else{
@@ -239743,47 +241508,81 @@ static void fts5DoSecureDelete(
  }

  iOff = iStart;
+

+
  /* If the position-list for the entry being removed flows over past
+
  ** the end of this page, delete the portion of the position-list on the
+
  ** next page and beyond.
+
  **
+
  ** Set variable bLastInDoclist to true if this entry happens
+
  ** to be the last rowid in the doclist for its term.  */
  if( iNextOff>=iPgIdx ){
    int pgno = pSeg->iLeafPgno+1;
    fts5SecureDeleteOverflow(p, pSeg->pSeg, pgno, &bLastInDoclist);
    iNextOff = iPgIdx;
-
  }else{
-
    /* Set bLastInDoclist to true if the entry being removed is the last
-
    ** in its doclist.  */
-
    for(iIdx=0, iKeyOff=0; iIdx<nIdx; /* no-op */){
-
      u32 iVal = 0;
-
      iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
-
      iKeyOff += iVal;
-
      if( iKeyOff==iNextOff ){
-
        bLastInDoclist = 1;
+
  }
+

+
  if( pSeg->bDel==0 ){
+
    if( iNextOff!=iPgIdx ){
+
      /* Loop through the page-footer. If iNextOff (offset of the
+
      ** entry following the one we are removing) is equal to the
+
      ** offset of a key on this page, then the entry is the last
+
      ** in its doclist. */
+
      int iKeyOff = 0;
+
      for(iIdx=0; iIdx<nIdx; /* no-op */){
+
        u32 iVal = 0;
+
        iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
+
        iKeyOff += iVal;
+
        if( iKeyOff==iNextOff ){
+
          bLastInDoclist = 1;
+
        }
      }
    }
-
  }

-
  if( fts5GetU16(&aPg[0])==iStart && (bLastInDoclist||iNextOff==iPgIdx) ){
-
    fts5PutU16(&aPg[0], 0);
+
    /* If this is (a) the first rowid on a page and (b) is not followed by
+
    ** another position list on the same page, set the "first-rowid" field
+
    ** of the header to 0.  */
+
    if( fts5GetU16(&aPg[0])==iStart && (bLastInDoclist || iNextOff==iPgIdx) ){
+
      fts5PutU16(&aPg[0], 0);
+
    }
  }

-
  if( bLastInDoclist==0 ){
+
  if( pSeg->bDel ){
+
    iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta);
+
    aPg[iOff++] = 0x01;
+
  }else if( bLastInDoclist==0 ){
    if( iNextOff!=iPgIdx ){
+
      u64 iNextDelta = 0;
      iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
      iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
    }
  }else if(
-
      iStart==pSeg->iTermLeafOffset && pSeg->iLeafPgno==pSeg->iTermLeafPgno
+
      pSeg->iLeafPgno==pSeg->iTermLeafPgno
+
   && iStart==pSeg->iTermLeafOffset
  ){
    /* The entry being removed was the only position list in its
    ** doclist. Therefore the term needs to be removed as well. */
    int iKey = 0;
-
    for(iIdx=0, iKeyOff=0; iIdx<nIdx; iKey++){
+
    int iKeyOff = 0;
+

+
    /* Set iKeyOff to the offset of the term that will be removed - the
+
    ** last offset in the footer that is not greater than iStart. */
+
    for(iIdx=0; iIdx<nIdx; iKey++){
      u32 iVal = 0;
      iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
      if( (iKeyOff+iVal)>(u32)iStart ) break;
      iKeyOff += iVal;
    }
+
    assert_nc( iKey>=1 );

+
    /* Set iDelKeyOff to the value of the footer entry to remove from
+
    ** the page. */
    iDelKeyOff = iOff = iKeyOff;
+

    if( iNextOff!=iPgIdx ){
+
      /* This is the only position-list associated with the term, and there
+
      ** is another term following it on this page. So the subsequent term
+
      ** needs to be moved to replace the term associated with the entry
+
      ** being removed. */
      int nPrefix = 0;
      int nSuffix = 0;
      int nPrefix2 = 0;
@@ -239820,80 +241619,88 @@ static void fts5DoSecureDelete(
      }
    }
  }else if( iStart==4 ){
-
      int iPgno;
-

-
      assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
-
      /* The entry being removed may be the only position list in
-
      ** its doclist. */
-
      for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
-
        Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
-
        int bEmpty = (pPg && pPg->nn==4);
-
        fts5DataRelease(pPg);
-
        if( bEmpty==0 ) break;
-
      }
-

-
      if( iPgno==pSeg->iTermLeafPgno ){
-
        i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
-
        Fts5Data *pTerm = fts5DataRead(p, iId);
-
        if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
-
          u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
-
          int nTermIdx = pTerm->nn - pTerm->szLeaf;
-
          int iTermIdx = 0;
-
          int iTermOff = 0;
-

-
          while( 1 ){
-
            u32 iVal = 0;
-
            int nByte = fts5GetVarint32(&aTermIdx[iTermIdx], iVal);
-
            iTermOff += iVal;
-
            if( (iTermIdx+nByte)>=nTermIdx ) break;
-
            iTermIdx += nByte;
-
          }
-
          nTermIdx = iTermIdx;
+
    int iPgno;
+

+
    assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
+
    /* The entry being removed may be the only position list in
+
    ** its doclist. */
+
    for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
+
      Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
+
      int bEmpty = (pPg && pPg->nn==4);
+
      fts5DataRelease(pPg);
+
      if( bEmpty==0 ) break;
+
    }

-
          memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx);
-
          fts5PutU16(&pTerm->p[2], iTermOff);
+
    if( iPgno==pSeg->iTermLeafPgno ){
+
      i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
+
      Fts5Data *pTerm = fts5DataRead(p, iId);
+
      if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
+
        u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
+
        int nTermIdx = pTerm->nn - pTerm->szLeaf;
+
        int iTermIdx = 0;
+
        int iTermOff = 0;

-
          fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx);
-
          if( nTermIdx==0 ){
-
            fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno);
-
          }
+
        while( 1 ){
+
          u32 iVal = 0;
+
          int nByte = fts5GetVarint32(&aTermIdx[iTermIdx], iVal);
+
          iTermOff += iVal;
+
          if( (iTermIdx+nByte)>=nTermIdx ) break;
+
          iTermIdx += nByte;
+
        }
+
        nTermIdx = iTermIdx;
+

+
        memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx);
+
        fts5PutU16(&pTerm->p[2], iTermOff);
+

+
        fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx);
+
        if( nTermIdx==0 ){
+
          fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno);
        }
-
        fts5DataRelease(pTerm);
      }
+
      fts5DataRelease(pTerm);
    }
+
  }

-
    if( p->rc==SQLITE_OK ){
-
      const int nMove = nPg - iNextOff;
-
      int nShift = 0;
+
  /* Assuming no error has occurred, this block does final edits to the
+
  ** leaf page before writing it back to disk. Input variables are:
+
  **
+
  **   nPg: Total initial size of leaf page.
+
  **   iPgIdx: Initial offset of page footer.
+
  **
+
  **   iOff: Offset to move data to
+
  **   iNextOff: Offset to move data from
+
  */
+
  if( p->rc==SQLITE_OK ){
+
    const int nMove = nPg - iNextOff;     /* Number of bytes to move */
+
    int nShift = iNextOff - iOff;         /* Distance to move them */

-
      memmove(&aPg[iOff], &aPg[iNextOff], nMove);
-
      iPgIdx -= (iNextOff - iOff);
-
      nPg = iPgIdx;
-
      fts5PutU16(&aPg[2], iPgIdx);
+
    int iPrevKeyOut = 0;
+
    int iKeyIn = 0;

-
      nShift = iNextOff - iOff;
-
      for(iIdx=0, iKeyOff=0, iPrevKeyOff=0; iIdx<nIdx; /* no-op */){
-
        u32 iVal = 0;
-
        iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
-
        iKeyOff += iVal;
-
        if( iKeyOff!=iDelKeyOff ){
-
          if( iKeyOff>iOff ){
-
            iKeyOff -= nShift;
-
            nShift = 0;
-
          }
-
          nPg += sqlite3Fts5PutVarint(&aPg[nPg], iKeyOff - iPrevKeyOff);
-
          iPrevKeyOff = iKeyOff;
-
        }
-
      }
+
    memmove(&aPg[iOff], &aPg[iNextOff], nMove);
+
    iPgIdx -= nShift;
+
    nPg = iPgIdx;
+
    fts5PutU16(&aPg[2], iPgIdx);

-
      if( iPgIdx==nPg && nIdx>0 && pSeg->iLeafPgno!=1 ){
-
        fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iLeafPgno);
+
    for(iIdx=0; iIdx<nIdx; /* no-op */){
+
      u32 iVal = 0;
+
      iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
+
      iKeyIn += iVal;
+
      if( iKeyIn!=iDelKeyOff ){
+
        int iKeyOut = (iKeyIn - (iKeyIn>iOff ? nShift : 0));
+
        nPg += sqlite3Fts5PutVarint(&aPg[nPg], iKeyOut - iPrevKeyOut);
+
        iPrevKeyOut = iKeyOut;
      }
+
    }

-
      assert_nc( nPg>4 || fts5GetU16(aPg)==0 );
-
      fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg,nPg);
+
    if( iPgIdx==nPg && nIdx>0 && pSeg->iLeafPgno!=1 ){
+
      fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iLeafPgno);
    }
-
    sqlite3_free(aIdx);
+

+
    assert_nc( nPg>4 || fts5GetU16(aPg)==0 );
+
    fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg, nPg);
+
  }
+
  sqlite3_free(aIdx);
}

/*
@@ -240063,10 +241870,16 @@ static void fts5FlushOneHash(Fts5Index *p){
                fts5WriteFlushLeaf(p, &writer);
              }
            }else{
-
              int bDummy;
-
              int nPos;
-
              int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
-
              nCopy += nPos;
+
              int bDel = 0;
+
              int nPos = 0;
+
              int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDel);
+
              if( bDel && bSecureDelete ){
+
                fts5BufferAppendVarint(&p->rc, pBuf, nPos*2);
+
                iOff += nCopy;
+
                nCopy = nPos;
+
              }else{
+
                nCopy += nPos;
+
              }
              if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
                /* The entire poslist will fit on the current leaf. So copy
                ** it in one go. */
@@ -240104,7 +241917,6 @@ static void fts5FlushOneHash(Fts5Index *p){
        assert( pBuf->n<=pBuf->nSpace );
        if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
      }
-
      sqlite3Fts5HashClear(pHash);
      fts5WriteFinish(p, &writer, &pgnoLast);

      assert( p->rc!=SQLITE_OK || bSecureDelete || pgnoLast>0 );
@@ -240137,7 +241949,6 @@ static void fts5FlushOneHash(Fts5Index *p){
  fts5IndexCrisismerge(p, &pStruct);
  fts5StructureWrite(p, pStruct);
  fts5StructureRelease(pStruct);
-
  p->nContentlessDelete = 0;
}

/*
@@ -240148,8 +241959,12 @@ static void fts5IndexFlush(Fts5Index *p){
  if( p->nPendingData || p->nContentlessDelete ){
    assert( p->pHash );
    fts5FlushOneHash(p);
-
    p->nPendingData = 0;
-
    p->nPendingRow = 0;
+
    if( p->rc==SQLITE_OK ){
+
      sqlite3Fts5HashClear(p->pHash);
+
      p->nPendingData = 0;
+
      p->nPendingRow = 0;
+
      p->nContentlessDelete = 0;
+
    }
  }
}

@@ -240227,8 +242042,9 @@ static int sqlite3Fts5IndexOptimize(Fts5Index *p){

  assert( p->rc==SQLITE_OK );
  fts5IndexFlush(p);
-
  assert( p->nContentlessDelete==0 );
+
  assert( p->rc!=SQLITE_OK || p->nContentlessDelete==0 );
  pStruct = fts5StructureRead(p);
+
  assert( p->rc!=SQLITE_OK || pStruct!=0 );
  fts5StructureInvalidate(p);

  if( pStruct ){
@@ -242891,7 +244707,8 @@ static int sqlite3Fts5IndexInit(sqlite3 *db){
      0,                           /* xSavepoint    */
      0,                           /* xRelease      */
      0,                           /* xRollbackTo   */
-
      0                            /* xShadowName   */
+
      0,                           /* xShadowName   */
+
      0                            /* xIntegrity    */
    };
    rc = sqlite3_create_module(db, "fts5_structure", &fts5structure_module, 0);
  }
@@ -243030,6 +244847,8 @@ struct Fts5FullTable {
  Fts5Storage *pStorage;          /* Document store */
  Fts5Global *pGlobal;            /* Global (connection wide) data */
  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
+
  int iSavepoint;                 /* Successful xSavepoint()+1 */
+
  int bInSavepoint;
#ifdef SQLITE_DEBUG
  struct Fts5TransactionState ts;
#endif
@@ -243318,6 +245137,13 @@ static int fts5InitVtab(
    pConfig->pzErrmsg = 0;
  }

+
  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
+
    rc = sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, (int)1);
+
  }
+
  if( rc==SQLITE_OK ){
+
    rc = sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
+
  }
+

  if( rc!=SQLITE_OK ){
    fts5FreeVtab(pTab);
    pTab = 0;
@@ -244242,6 +246068,9 @@ static int fts5FilterMethod(
    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  }

+
  rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
+
  if( rc!=SQLITE_OK ) goto filter_out;
+

  if( pTab->pSortCsr ){
    /* If pSortCsr is non-NULL, then this call is being made as part of
    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
@@ -244264,6 +246093,7 @@ static int fts5FilterMethod(
    pCsr->pExpr = pTab->pSortCsr->pExpr;
    rc = fts5CursorFirst(pTab, pCsr, bDesc);
  }else if( pCsr->pExpr ){
+
    assert( rc==SQLITE_OK );
    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
    if( rc==SQLITE_OK ){
      if( bOrderByRank ){
@@ -244435,6 +246265,7 @@ static int fts5SpecialInsert(
  Fts5Config *pConfig = pTab->p.pConfig;
  int rc = SQLITE_OK;
  int bError = 0;
+
  int bLoadConfig = 0;

  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
@@ -244446,6 +246277,7 @@ static int fts5SpecialInsert(
    }else{
      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
    }
+
    bLoadConfig = 1;
  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
    if( pConfig->eContent==FTS5_CONTENT_NONE ){
      fts5SetVtabError(pTab,
@@ -244455,6 +246287,7 @@ static int fts5SpecialInsert(
    }else{
      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
    }
+
    bLoadConfig = 1;
  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
@@ -244467,6 +246300,8 @@ static int fts5SpecialInsert(
  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
#endif
+
  }else if( 0==sqlite3_stricmp("flush", zCmd) ){
+
    rc = sqlite3Fts5FlushToDisk(&pTab->p);
  }else{
    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
    if( rc==SQLITE_OK ){
@@ -244480,6 +246315,12 @@ static int fts5SpecialInsert(
      }
    }
  }
+

+
  if( rc==SQLITE_OK && bLoadConfig ){
+
    pTab->p.pConfig->iCookie--;
+
    rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
+
  }
+

  return rc;
}

@@ -244598,7 +246439,7 @@ static int fts5UpdateMethod(
    assert( nArg!=1 || eType0==SQLITE_INTEGER );

    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
-
    ** This is not suported. Except - DELETE is supported if the CREATE
+
    ** This is not suported. Except - they are both supported if the CREATE
    ** VIRTUAL TABLE statement contained "contentless_delete=1". */
    if( eType0==SQLITE_INTEGER
     && pConfig->eContent==FTS5_CONTENT_NONE
@@ -244627,7 +246468,8 @@ static int fts5UpdateMethod(
      }

      else if( eType0!=SQLITE_INTEGER ){
-
        /* If this is a REPLACE, first remove the current entry (if any) */
+
        /* An INSERT statement. If the conflict-mode is REPLACE, first remove
+
        ** the current entry (if any). */
        if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
          i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
@@ -245501,8 +247343,12 @@ static int fts5RenameMethod(
  sqlite3_vtab *pVtab,            /* Virtual table handle */
  const char *zName               /* New name of table */
){
+
  int rc;
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
-
  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
+
  pTab->bInSavepoint = 1;
+
  rc = sqlite3Fts5StorageRename(pTab->pStorage, zName);
+
  pTab->bInSavepoint = 0;
+
  return rc;
}

static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
@@ -245516,9 +247362,29 @@ static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
** Flush the contents of the pending-terms table to disk.
*/
static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
-
  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
-
  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint);
-
  return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
+
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+
  int rc = SQLITE_OK;
+
  char *zSql = 0;
+
  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
+

+
  if( pTab->bInSavepoint==0 ){
+
    zSql = sqlite3_mprintf("INSERT INTO %Q.%Q(%Q) VALUES('flush')",
+
        pTab->p.pConfig->zDb, pTab->p.pConfig->zName, pTab->p.pConfig->zName
+
    );
+
    if( zSql ){
+
      pTab->bInSavepoint = 1;
+
      rc = sqlite3_exec(pTab->p.pConfig->db, zSql, 0, 0, 0);
+
      pTab->bInSavepoint = 0;
+
      sqlite3_free(zSql);
+
    }else{
+
      rc = SQLITE_NOMEM;
+
    }
+
    if( rc==SQLITE_OK ){
+
      pTab->iSavepoint = iSavepoint+1;
+
    }
+
  }
+

+
  return rc;
}

/*
@@ -245527,9 +247393,16 @@ static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
** This is a no-op.
*/
static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
-
  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
-
  fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint);
-
  return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
+
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+
  int rc = SQLITE_OK;
+
  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
+
  if( (iSavepoint+1)<pTab->iSavepoint ){
+
    rc = sqlite3Fts5FlushToDisk(&pTab->p);
+
    if( rc==SQLITE_OK ){
+
      pTab->iSavepoint = iSavepoint;
+
    }
+
  }
+
  return rc;
}

/*
@@ -245539,11 +247412,14 @@ static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
*/
static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
-
  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
+
  int rc = SQLITE_OK;
  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  fts5TripCursors(pTab);
  pTab->p.pConfig->pgsz = 0;
-
  return sqlite3Fts5StorageRollback(pTab->pStorage);
+
  if( (iSavepoint+1)<=pTab->iSavepoint ){
+
    rc = sqlite3Fts5StorageRollback(pTab->pStorage);
+
  }
+
  return rc;
}

/*
@@ -245745,7 +247621,7 @@ static void fts5SourceIdFunc(
){
  assert( nArg==0 );
  UNUSED_PARAM2(nArg, apUnused);
-
  sqlite3_result_text(pCtx, "fts5: 2023-08-24 12:36:59 0f80b798b3f4b81a7bb4233c58294edd0f1156f36b6ecf5ab8e83631d468778c", -1, SQLITE_TRANSIENT);
+
  sqlite3_result_text(pCtx, "fts5: 2023-11-24 11:41:44 ebead0e7230cd33bcec9f95d2183069565b9e709bf745c9b5db65cc0cbf92c0f", -1, SQLITE_TRANSIENT);
}

/*
@@ -245763,9 +247639,46 @@ static int fts5ShadowName(const char *zName){
  return 0;
}

+
/*
+
** Run an integrity check on the FTS5 data structures.  Return a string
+
** if anything is found amiss.  Return a NULL pointer if everything is
+
** OK.
+
*/
+
static int fts5Integrity(
+
  sqlite3_vtab *pVtab,    /* the FTS5 virtual table to check */
+
  const char *zSchema,    /* Name of schema in which this table lives */
+
  const char *zTabname,   /* Name of the table itself */
+
  int isQuick,            /* True if this is a quick-check */
+
  char **pzErr            /* Write error message here */
+
){
+
  Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
+
  Fts5Config *pConfig = pTab->p.pConfig;
+
  char *zSql;
+
  char *zErr = 0;
+
  int rc;
+
  assert( pzErr!=0 && *pzErr==0 );
+
  UNUSED_PARAM(isQuick);
+
  zSql = sqlite3_mprintf(
+
            "INSERT INTO \"%w\".\"%w\"(\"%w\") VALUES('integrity-check');",
+
            zSchema, zTabname, pConfig->zName);
+
  if( zSql==0 ) return SQLITE_NOMEM;
+
  rc = sqlite3_exec(pConfig->db, zSql, 0, 0, &zErr);
+
  sqlite3_free(zSql);
+
  if( (rc&0xff)==SQLITE_CORRUPT ){
+
    *pzErr = sqlite3_mprintf("malformed inverted index for FTS5 table %s.%s",
+
                zSchema, zTabname);
+
  }else if( rc!=SQLITE_OK ){
+
    *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
+
                             " FTS5 table %s.%s: %s",
+
                zSchema, zTabname, zErr);
+
  }
+
  sqlite3_free(zErr);
+
  return SQLITE_OK;
+
}
+

static int fts5Init(sqlite3 *db){
  static const sqlite3_module fts5Mod = {
-
    /* iVersion      */ 3,
+
    /* iVersion      */ 4,
    /* xCreate       */ fts5CreateMethod,
    /* xConnect      */ fts5ConnectMethod,
    /* xBestIndex    */ fts5BestIndexMethod,
@@ -245788,7 +247701,8 @@ static int fts5Init(sqlite3 *db){
    /* xSavepoint    */ fts5SavepointMethod,
    /* xRelease      */ fts5ReleaseMethod,
    /* xRollbackTo   */ fts5RollbackToMethod,
-
    /* xShadowName   */ fts5ShadowName
+
    /* xShadowName   */ fts5ShadowName,
+
    /* xIntegrity    */ fts5Integrity
  };

  int rc;
@@ -247065,7 +248979,9 @@ static int sqlite3Fts5StorageSync(Fts5Storage *p){
  i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  if( p->bTotalsValid ){
    rc = fts5StorageSaveTotals(p);
-
    p->bTotalsValid = 0;
+
    if( rc==SQLITE_OK ){
+
      p->bTotalsValid = 0;
+
    }
  }
  if( rc==SQLITE_OK ){
    rc = sqlite3Fts5IndexSync(p->pIndex);
@@ -250433,7 +252349,8 @@ static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
    /* xSavepoint    */ 0,
    /* xRelease      */ 0,
    /* xRollbackTo   */ 0,
-
    /* xShadowName   */ 0
+
    /* xShadowName   */ 0,
+
    /* xIntegrity    */ 0
  };
  void *p = (void*)pGlobal;

@@ -250762,6 +252679,7 @@ static sqlite3_module stmtModule = {
  0,                         /* xRelease */
  0,                         /* xRollbackTo */
  0,                         /* xShadowName */
+
  0                          /* xIntegrity */
};

#endif /* SQLITE_OMIT_VIRTUALTABLE */
modified external/sqlite/sqlite3.h
@@ -146,9 +146,9 @@ extern "C" {
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
-
#define SQLITE_VERSION        "3.43.0"
-
#define SQLITE_VERSION_NUMBER 3043000
-
#define SQLITE_SOURCE_ID      "2023-08-24 12:36:59 0f80b798b3f4b81a7bb4233c58294edd0f1156f36b6ecf5ab8e83631d468778c"
+
#define SQLITE_VERSION        "3.44.2"
+
#define SQLITE_VERSION_NUMBER 3044002
+
#define SQLITE_SOURCE_ID      "2023-11-24 11:41:44 ebead0e7230cd33bcec9f95d2183069565b9e709bf745c9b5db65cc0cbf92c0f"

/*
** CAPI3REF: Run-Time Library Version Numbers
@@ -2127,7 +2127,7 @@ struct sqlite3_mem_methods {
** is stored in each sorted record and the required column values loaded
** from the database as records are returned in sorted order. The default
** value for this option is to never use this optimization. Specifying a
-
** negative value for this option restores the default behaviour.
+
** negative value for this option restores the default behavior.
** This option is only available if SQLite is compiled with the
** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
**
@@ -2302,7 +2302,7 @@ struct sqlite3_mem_methods {
** database handle, SQLite checks if this will mean that there are now no
** connections at all to the database. If so, it performs a checkpoint
** operation before closing the connection. This option may be used to
-
** override this behaviour. The first parameter passed to this operation
+
** override this behavior. The first parameter passed to this operation
** is an integer - positive to disable checkpoints-on-close, or zero (the
** default) to enable them, and negative to leave the setting unchanged.
** The second parameter is a pointer to an integer
@@ -3955,6 +3955,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename);
**
** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
** text that describes the error, as either UTF-8 or UTF-16 respectively.
+
** (See how SQLite handles [invalid UTF] for exceptions to this rule.)
** ^(Memory to hold the error message string is managed internally.
** The application does not need to worry about freeing the result.
** However, the error string might be overwritten or deallocated by
@@ -5325,6 +5326,7 @@ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
*/
SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);

+

/*
** CAPI3REF: Create Or Redefine SQL Functions
** KEYWORDS: {function creation routines}
@@ -5571,13 +5573,27 @@ SQLITE_API int sqlite3_create_window_function(
** </dd>
**
** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
-
** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
+
** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call
** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
-
** Specifying this flag makes no difference for scalar or aggregate user
-
** functions. However, if it is not specified for a user-defined window
-
** function, then any sub-types belonging to arguments passed to the window
-
** function may be discarded before the window function is called (i.e.
-
** sqlite3_value_subtype() will always return 0).
+
** This flag instructs SQLite to omit some corner-case optimizations that
+
** might disrupt the operation of the [sqlite3_value_subtype()] function,
+
** causing it to return zero rather than the correct subtype().
+
** SQL functions that invokes [sqlite3_value_subtype()] should have this
+
** property.  If the SQLITE_SUBTYPE property is omitted, then the return
+
** value from [sqlite3_value_subtype()] might sometimes be zero even though
+
** a non-zero subtype was specified by the function argument expression.
+
**
+
** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd>
+
** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call
+
** [sqlite3_result_subtype()] to cause a sub-type to be associated with its
+
** result.
+
** Every function that invokes [sqlite3_result_subtype()] should have this
+
** property.  If it does not, then the call to [sqlite3_result_subtype()]
+
** might become a no-op if the function is used as term in an
+
** [expression index].  On the other hand, SQL functions that never invoke
+
** [sqlite3_result_subtype()] should avoid setting this property, as the
+
** purpose of this property is to disable certain optimizations that are
+
** incompatible with subtypes.
** </dd>
** </dl>
*/
@@ -5585,6 +5601,7 @@ SQLITE_API int sqlite3_create_window_function(
#define SQLITE_DIRECTONLY       0x000080000
#define SQLITE_SUBTYPE          0x000100000
#define SQLITE_INNOCUOUS        0x000200000
+
#define SQLITE_RESULT_SUBTYPE   0x001000000

/*
** CAPI3REF: Deprecated Functions
@@ -5781,6 +5798,12 @@ SQLITE_API int sqlite3_value_encoding(sqlite3_value*);
** information can be used to pass a limited amount of context from
** one SQL function to another.  Use the [sqlite3_result_subtype()]
** routine to set the subtype for the return value of an SQL function.
+
**
+
** Every [application-defined SQL function] that invoke this interface
+
** should include the [SQLITE_SUBTYPE] property in the text
+
** encoding argument when the function is [sqlite3_create_function|registered].
+
** If the [SQLITE_SUBTYPE] property is omitted, then sqlite3_value_subtype()
+
** might return zero instead of the upstream subtype in some corner cases.
*/
SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);

@@ -5879,48 +5902,56 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
** METHOD: sqlite3_context
**
** These functions may be used by (non-aggregate) SQL functions to
-
** associate metadata with argument values. If the same value is passed to
-
** multiple invocations of the same SQL function during query execution, under
-
** some circumstances the associated metadata may be preserved.  An example
-
** of where this might be useful is in a regular-expression matching
-
** function. The compiled version of the regular expression can be stored as
-
** metadata associated with the pattern string.
+
** associate auxiliary data with argument values. If the same argument
+
** value is passed to multiple invocations of the same SQL function during
+
** query execution, under some circumstances the associated auxiliary data
+
** might be preserved.  An example of where this might be useful is in a
+
** regular-expression matching function. The compiled version of the regular
+
** expression can be stored as auxiliary data associated with the pattern string.
** Then as long as the pattern string remains the same,
** the compiled regular expression can be reused on multiple
** invocations of the same function.
**
-
** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
+
** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data
** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
** value to the application-defined function.  ^N is zero for the left-most
-
** function argument.  ^If there is no metadata
+
** function argument.  ^If there is no auxiliary data
** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
** returns a NULL pointer.
**
-
** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
-
** argument of the application-defined function.  ^Subsequent
+
** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the
+
** N-th argument of the application-defined function.  ^Subsequent
** calls to sqlite3_get_auxdata(C,N) return P from the most recent
-
** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
-
** NULL if the metadata has been discarded.
+
** sqlite3_set_auxdata(C,N,P,X) call if the auxiliary data is still valid or
+
** NULL if the auxiliary data has been discarded.
** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
** SQLite will invoke the destructor function X with parameter P exactly
-
** once, when the metadata is discarded.
-
** SQLite is free to discard the metadata at any time, including: <ul>
+
** once, when the auxiliary data is discarded.
+
** SQLite is free to discard the auxiliary data at any time, including: <ul>
** <li> ^(when the corresponding function parameter changes)^, or
** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
**      SQL statement)^, or
** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
**       parameter)^, or
** <li> ^(during the original sqlite3_set_auxdata() call when a memory
-
**      allocation error occurs.)^ </ul>
+
**      allocation error occurs.)^
+
** <li> ^(during the original sqlite3_set_auxdata() call if the function
+
**      is evaluated during query planning instead of during query execution,
+
**      as sometimes happens with [SQLITE_ENABLE_STAT4].)^ </ul>
**
-
** Note the last bullet in particular.  The destructor X in
+
** Note the last two bullets in particular.  The destructor X in
** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
** should be called near the end of the function implementation and the
** function implementation should not make any use of P after
-
** sqlite3_set_auxdata() has been called.
-
**
-
** ^(In practice, metadata is preserved between function calls for
+
** sqlite3_set_auxdata() has been called.  Furthermore, a call to
+
** sqlite3_get_auxdata() that occurs immediately after a corresponding call
+
** to sqlite3_set_auxdata() might still return NULL if an out-of-memory
+
** condition occurred during the sqlite3_set_auxdata() call or if the
+
** function is being evaluated during query planning rather than during
+
** query execution.
+
**
+
** ^(In practice, auxiliary data is preserved between function calls for
** function parameters that are compile-time constants, including literal
** values and [parameters] and expressions composed from the same.)^
**
@@ -5930,10 +5961,67 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
**
** These routines must be called from the same thread in which
** the SQL function is running.
+
**
+
** See also: [sqlite3_get_clientdata()] and [sqlite3_set_clientdata()].
*/
SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));

+
/*
+
** CAPI3REF: Database Connection Client Data
+
** METHOD: sqlite3
+
**
+
** These functions are used to associate one or more named pointers
+
** with a [database connection].
+
** A call to sqlite3_set_clientdata(D,N,P,X) causes the pointer P
+
** to be attached to [database connection] D using name N.  Subsequent
+
** calls to sqlite3_get_clientdata(D,N) will return a copy of pointer P
+
** or a NULL pointer if there were no prior calls to
+
** sqlite3_set_clientdata() with the same values of D and N.
+
** Names are compared using strcmp() and are thus case sensitive.
+
**
+
** If P and X are both non-NULL, then the destructor X is invoked with
+
** argument P on the first of the following occurrences:
+
** <ul>
+
** <li> An out-of-memory error occurs during the call to
+
**      sqlite3_set_clientdata() which attempts to register pointer P.
+
** <li> A subsequent call to sqlite3_set_clientdata(D,N,P,X) is made
+
**      with the same D and N parameters.
+
** <li> The database connection closes.  SQLite does not make any guarantees
+
**      about the order in which destructors are called, only that all
+
**      destructors will be called exactly once at some point during the
+
**      database connection closing process.
+
** </ul>
+
**
+
** SQLite does not do anything with client data other than invoke
+
** destructors on the client data at the appropriate time.  The intended
+
** use for client data is to provide a mechanism for wrapper libraries
+
** to store additional information about an SQLite database connection.
+
**
+
** There is no limit (other than available memory) on the number of different
+
** client data pointers (with different names) that can be attached to a
+
** single database connection.  However, the implementation is optimized
+
** for the case of having only one or two different client data names.
+
** Applications and wrapper libraries are discouraged from using more than
+
** one client data name each.
+
**
+
** There is no way to enumerate the client data pointers
+
** associated with a database connection.  The N parameter can be thought
+
** of as a secret key such that only code that knows the secret key is able
+
** to access the associated data.
+
**
+
** Security Warning:  These interfaces should not be exposed in scripting
+
** languages or in other circumstances where it might be possible for an
+
** an attacker to invoke them.  Any agent that can invoke these interfaces
+
** can probably also take control of the process.
+
**
+
** Database connection client data is only available for SQLite
+
** version 3.44.0 ([dateof:3.44.0]) and later.
+
**
+
** See also: [sqlite3_set_auxdata()] and [sqlite3_get_auxdata()].
+
*/
+
SQLITE_API void *sqlite3_get_clientdata(sqlite3*,const char*);
+
SQLITE_API int sqlite3_set_clientdata(sqlite3*, const char*, void*, void(*)(void*));

/*
** CAPI3REF: Constants Defining Special Destructor Behavior
@@ -6135,6 +6223,20 @@ SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
** higher order bits are discarded.
** The number of subtype bytes preserved by SQLite might increase
** in future releases of SQLite.
+
**
+
** Every [application-defined SQL function] that invokes this interface
+
** should include the [SQLITE_RESULT_SUBTYPE] property in its
+
** text encoding argument when the SQL function is
+
** [sqlite3_create_function|registered].  If the [SQLITE_RESULT_SUBTYPE]
+
** property is omitted from the function that invokes sqlite3_result_subtype(),
+
** then in some cases the sqlite3_result_subtype() might fail to set
+
** the result subtype.
+
**
+
** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any
+
** SQL function that invokes the sqlite3_result_subtype() interface
+
** and that does not have the SQLITE_RESULT_SUBTYPE property will raise
+
** an error.  Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1
+
** by default.
*/
SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);

@@ -6566,7 +6668,7 @@ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);

/*
-
** CAPI3REF: Allowed return values from [sqlite3_txn_state()]
+
** CAPI3REF: Allowed return values from sqlite3_txn_state()
** KEYWORDS: {transaction state}
**
** These constants define the current transaction state of a database file.
@@ -6698,7 +6800,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
** ^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
+
** then the autovacuum steps callback is canceled.  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
@@ -7217,6 +7319,10 @@ struct sqlite3_module {
  /* The methods above are in versions 1 and 2 of the sqlite_module object.
  ** Those below are for version 3 and greater. */
  int (*xShadowName)(const char*);
+
  /* The methods above are in versions 1 through 3 of the sqlite_module object.
+
  ** Those below are for version 4 and greater. */
+
  int (*xIntegrity)(sqlite3_vtab *pVTab, const char *zSchema,
+
                    const char *zTabName, int mFlags, char **pzErr);
};

/*
@@ -7704,7 +7810,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
** code is returned and the transaction rolled back.
**
** Calling this function with an argument that is not a NULL pointer or an
-
** open blob handle results in undefined behaviour. ^Calling this routine
+
** open blob handle results in undefined behavior. ^Calling this routine
** with a null pointer (such as would be returned by a failed call to
** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
** is passed a valid open blob handle, the values returned by the
@@ -8184,6 +8290,7 @@ SQLITE_API int sqlite3_test_control(int op, ...);
#define SQLITE_TESTCTRL_PRNG_SAVE                5
#define SQLITE_TESTCTRL_PRNG_RESTORE             6
#define SQLITE_TESTCTRL_PRNG_RESET               7  /* NOT USED */
+
#define SQLITE_TESTCTRL_FK_NO_ACTION             7
#define SQLITE_TESTCTRL_BITVEC_TEST              8
#define SQLITE_TESTCTRL_FAULT_INSTALL            9
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
@@ -9245,8 +9352,8 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
** blocked connection already has a registered unlock-notify callback,
** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
** called with a NULL pointer as its second argument, then any existing
-
** unlock-notify callback is cancelled. ^The blocked connections
-
** unlock-notify callback may also be cancelled by closing the blocked
+
** unlock-notify callback is canceled. ^The blocked connections
+
** unlock-notify callback may also be canceled by closing the blocked
** connection using [sqlite3_close()].
**
** The unlock-notify callback is not reentrant. If an application invokes
@@ -10549,6 +10656,13 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c
** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
** of the database exists.
**
+
** After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set,
+
** the returned buffer content will remain accessible and unchanged
+
** until either the next write operation on the connection or when
+
** the connection is closed, and applications must not modify the
+
** buffer. If the bit had been clear, the returned buffer will not
+
** be accessed by SQLite after the call.
+
**
** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
** allocation error occurs.
@@ -10597,6 +10711,9 @@ SQLITE_API unsigned char *sqlite3_serialize(
** SQLite will try to increase the buffer size using sqlite3_realloc64()
** if writes on the database cause it to grow larger than M bytes.
**
+
** Applications must not modify the buffer P or invalidate it before
+
** the database connection D is closed.
+
**
** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
** database is currently in a read transaction or is involved in a backup
** operation.
@@ -10605,6 +10722,13 @@ SQLITE_API unsigned char *sqlite3_serialize(
** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
** function returns SQLITE_ERROR.
**
+
** The deserialized database should not be in [WAL mode].  If the database
+
** is in WAL mode, then any attempt to use the database file will result
+
** in an [SQLITE_CANTOPEN] error.  The application can set the
+
** [file format version numbers] (bytes 18 and 19) of the input database P
+
** to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the
+
** database file into rollback mode and work around this limitation.
+
**
** 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.
@@ -11678,6 +11802,18 @@ SQLITE_API int sqlite3changeset_concat(


/*
+
** CAPI3REF: Upgrade the Schema of a Changeset/Patchset
+
*/
+
SQLITE_API int sqlite3changeset_upgrade(
+
  sqlite3 *db,
+
  const char *zDb,
+
  int nIn, const void *pIn,       /* Input changeset */
+
  int *pnOut, void **ppOut        /* OUT: Inverse of input */
+
);
+

+

+

+
/*
** CAPI3REF: Changegroup Handle
**
** A changegroup is an object used to combine two or more
@@ -11724,6 +11860,38 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);

/*
+
** CAPI3REF: Add a Schema to a Changegroup
+
** METHOD: sqlite3_changegroup_schema
+
**
+
** This method may be used to optionally enforce the rule that the changesets
+
** added to the changegroup handle must match the schema of database zDb
+
** ("main", "temp", or the name of an attached database). If
+
** sqlite3changegroup_add() is called to add a changeset that is not compatible
+
** with the configured schema, SQLITE_SCHEMA is returned and the changegroup
+
** object is left in an undefined state.
+
**
+
** A changeset schema is considered compatible with the database schema in
+
** the same way as for sqlite3changeset_apply(). Specifically, for each
+
** table in the changeset, there exists a database table with:
+
**
+
** <ul>
+
**   <li> The name identified by the changeset, and
+
**   <li> at least as many columns as recorded in the changeset, and
+
**   <li> the primary key columns in the same position as recorded in
+
**        the changeset.
+
** </ul>
+
**
+
** The output of the changegroup object always has the same schema as the
+
** database nominated using this function. In cases where changesets passed
+
** to sqlite3changegroup_add() have fewer columns than the corresponding table
+
** in the database schema, these are filled in using the default column
+
** values from the database schema. This makes it possible to combined
+
** changesets that have different numbers of columns for a single table
+
** within a changegroup, provided that they are otherwise compatible.
+
*/
+
SQLITE_API int sqlite3changegroup_schema(sqlite3_changegroup*, sqlite3*, const char *zDb);
+

+
/*
** CAPI3REF: Add A Changeset To A Changegroup
** METHOD: sqlite3_changegroup
**
@@ -11791,13 +11959,18 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
** If the new changeset contains changes to a table that is already present
** in the changegroup, then the number of columns and the position of the
** primary key columns for the table must be consistent. If this is not the
-
** case, this function fails with SQLITE_SCHEMA. If the input changeset
-
** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
-
** returned. Or, if an out-of-memory condition occurs during processing, this
-
** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
-
** of the final contents of the changegroup is undefined.
+
** case, this function fails with SQLITE_SCHEMA. Except, if the changegroup
+
** object has been configured with a database schema using the
+
** sqlite3changegroup_schema() API, then it is possible to combine changesets
+
** with different numbers of columns for a single table, provided that
+
** they are otherwise compatible.
**
-
** If no error occurs, SQLITE_OK is returned.
+
** If the input changeset appears to be corrupt and the corruption is
+
** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition
+
** occurs during processing, this function returns SQLITE_NOMEM.
+
**
+
** In all cases, if an error occurs the state of the final contents of the
+
** changegroup is undefined. If no error occurs, SQLITE_OK is returned.
*/
SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);

@@ -12062,10 +12235,17 @@ SQLITE_API int sqlite3changeset_apply_v2(
**    <li>an insert change if all fields of the conflicting row match
**        the row being inserted.
**    </ul>
+
**
+
** <dt>SQLITE_CHANGESETAPPLY_FKNOACTION <dd>
+
**   If this flag it set, then all foreign key constraints in the target
+
**   database behave as if they were declared with "ON UPDATE NO ACTION ON
+
**   DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL
+
**   or SET DEFAULT.
*/
#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
#define SQLITE_CHANGESETAPPLY_INVERT        0x0002
#define SQLITE_CHANGESETAPPLY_IGNORENOOP    0x0004
+
#define SQLITE_CHANGESETAPPLY_FKNOACTION    0x0008

/*
** CAPI3REF: Constants Passed To The Conflict Handler