]> git.ipfire.org Git - thirdparty/sqlite.git/commitdiff
Merge for CLI fix.
authorlarrybr <larrybr@noemail.net>
Thu, 2 Dec 2021 18:09:45 +0000 (18:09 +0000)
committerlarrybr <larrybr@noemail.net>
Thu, 2 Dec 2021 18:09:45 +0000 (18:09 +0000)
FossilOrigin-Name: 98cf18611d4c0ddc7ee38ba2565265ad5bc1c9ceec545f9f8f63987015e64117

1  2 
manifest
manifest.uuid
src/shell.c.in

diff --cc manifest
index 697e2ac2ca72bace936e5fce6d1e0e8115ab7746,fd242e54e1cfbe3781f4afc64e1817933eb18958..54d0a76419025d09180a2610a3becabadae4af8f
+++ b/manifest
@@@ -1,5 -1,5 +1,5 @@@
- C Extensible\sshell\sbuilder\schanges\sin\sprep\sfor\sactual\sextension\sload
- D 2021-12-01T17:46:53.986
 -C Move\sthe\sTK_IS\stoken\sso\sthat\sit\sis\sadjacent\sto\sthe\sTK_IN\stoken,\sas\sthis\nallows\sthe\sC\scompiler\sto\soptimize\sbetter,\sresulting\sin\sa\sslightly\ssmaller\nand\sfaster\sexecutable.
 -D 2021-12-02T14:28:36.785
++C Merge\sfor\sCLI\sfix.
++D 2021-12-02T18:09:45.324
  F .fossil-settings/empty-dirs dbb81e8fc0401ac46a1491ab34a7f2c7c0452f2f06b54ebb845d024ca8283ef1
  F .fossil-settings/ignore-glob 35175cdfcf539b2318cb04a9901442804be81cd677d8b889fcc9149c21f239ea
  F LICENSE.md df5091916dbb40e6e9686186587125e1b2ff51f022cc334e886c19a0e9982724
@@@ -551,8 -551,7 +551,8 @@@ F src/random.c 097dc8b31b8fba5a9aca1697
  F src/resolve.c 4a1db4aadd802683db40ca2dbbb268187bd195f10cbdb7206dbd8ac988795571
  F src/rowset.c ba9515a922af32abe1f7d39406b9d35730ed65efab9443dc5702693b60854c92
  F src/select.c a7a3d9f54eb24821ec5f67f2e5589b68a5d42d46fc5849d7376886777d93a85a
- F src/shell.c.in f40792dd66b7ac516437105f2e2af5315d960d7d15046c352698d42b17bf1619
 -F src/shell.c.in e7ee6517544d075d9f06ee2571567026b89cf9fbeef16a74918019b1cb425764
++F src/shell.c.in 15b03f15d5f56443eabe64e8a1f080e5376c619df6e639abb60f44fec242b9b5
 +F src/shext_linkage.h adf6b1c6a918b3c695a2181f1cec9cc452afd89fdbb9f476d4cd495e6a7c9aa7
  F src/sqlite.h.in 5cd209ac7dc4180f0e19292846f40440b8488015849ca0110c70b906b57d68f0
  F src/sqlite3.rc 5121c9e10c3964d5755191c80dd1180c122fc3a8
  F src/sqlite3ext.h 8ff2fd2c166150b2e48639f5e506fb44e29f1a3f65031710b9e89d1c126ac839
@@@ -1934,7 -1933,7 +1934,7 @@@ F vsixtest/vsixtest.tcl 6a9a6ab600c25a9
  F vsixtest/vsixtest.vcxproj.data 2ed517e100c66dc455b492e1a33350c1b20fbcdc
  F vsixtest/vsixtest.vcxproj.filters 37e51ffedcdb064aad6ff33b6148725226cd608e
  F vsixtest/vsixtest_TemporaryKey.pfx e5b1b036facdb453873e7084e1cae9102ccc67a0
- P 15780cb2bb1e992665a0a7a51206d11d8656d64917d0cf8cc4d72e1005531591
- R 8865642b7dda3fedc9c2b82ba1b01b39
 -P fcc509d325dabe06275e7804183bb8b4ba6470a45b443bc8292eecd0974e6367
 -R 888c8c19b41c8406ec3840142d61350f
 -U drh
 -Z 0b6dacbe87596435aee017d0aa63fe31
++P 00c5af1f7e638de0638aeaa26ecf4eefda16c33fd81bad126909b87fce4c3093 8832fa9088414a8d285a457a4effad0b7d610a87ca73cfb5c5812e784649761e
++R 1486daf937ee23873c5f6e3d6819fcea
 +U larrybr
- Z dcd83e606bd8e5971182d44ac0acaf16
++Z 405b7ff2ea456709cae7ac627ce968a0
diff --cc manifest.uuid
index 7075fc84292f7102e2ad02f5b4ce80b0594d3350,1a7fe9bc70f0423f017e980afe26976a14b7ef45..0f91ed21e5d6089d94417dbe226bd2513174b330
@@@ -1,1 -1,1 +1,1 @@@
- 00c5af1f7e638de0638aeaa26ecf4eefda16c33fd81bad126909b87fce4c3093
 -8832fa9088414a8d285a457a4effad0b7d610a87ca73cfb5c5812e784649761e
++98cf18611d4c0ddc7ee38ba2565265ad5bc1c9ceec545f9f8f63987015e64117
diff --cc src/shell.c.in
index a48f6abeee3690bd7bdea3e51bce8992be6456e5,72fe26339e7911bebbcd031cfef1c769873993aa..8dd1eb53ebd7d0b82be06dbbf4953fce0f42805a
@@@ -6963,2601 -7224,2364 +6963,2604 @@@ static RecoverTable *recoverOrphanTable
    }
    return pTab;
  }
 +#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
  
 -/*
 -** This function is called to recover data from the database. A script
 -** to construct a new database containing all recovered data is output
 -** on stream pState->out.
 -*/
 -static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
 -  int rc = SQLITE_OK;
 -  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
 -  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
 -  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
 -  const char *zRecoveryDb = "";   /* Name of "recovery" database */
 -  const char *zLostAndFound = "lost_and_found";
 -  int i;
 -  int nOrphan = -1;
 -  RecoverTable *pOrphan = 0;
 -
 -  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
 -  int bRowids = 1;                /* 0 if --no-rowids */
 -  for(i=1; i<nArg; i++){
 -    char *z = azArg[i];
 -    int n;
 -    if( z[0]=='-' && z[1]=='-' ) z++;
 -    n = strlen30(z);
 -    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
 -      bFreelist = 0;
 -    }else
 -    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
 -      i++;
 -      zRecoveryDb = azArg[i];
 -    }else
 -    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
 -      i++;
 -      zLostAndFound = azArg[i];
 -    }else
 -    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
 -      bRowids = 0;
 -    }
 -    else{
 -      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 
 -      showHelp(pState->out, azArg[0]);
 -      return 1;
 +static int writeDb( char *azArg[], int nArg, ShellState *p ){
 +  int rc = 0;
 +  const char *zDestFile = 0;
 +  const char *zDb = 0;
 +  sqlite3 *pDest;
 +  sqlite3_backup *pBackup;
 +  int j;
 +  int bAsync = 0;
 +  const char *zVfs = 0;
 +  failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
 +  for(j=1; j<nArg; j++){
 +    const char *z = azArg[j];
 +    if( z[0]=='-' ){
 +      if( z[1]=='-' ) z++;
 +      if( strcmp(z, "-append")==0 ){
 +        zVfs = "apndvfs";
 +      }else
 +        if( strcmp(z, "-async")==0 ){
 +          bAsync = 1;
 +        }else
 +          {
 +            utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
 +            return INVALID_ARGS;
 +          }
 +    }else if( zDestFile==0 ){
 +      zDestFile = azArg[j];
 +    }else if( zDb==0 ){
 +      zDb = zDestFile;
 +      zDestFile = azArg[j];
 +    }else{
 +      raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
 +      return INVALID_ARGS;
      }
    }
 -
 -  shellExecPrintf(pState->db, &rc,
 -    /* Attach an in-memory database named 'recovery'. Create an indexed 
 -    ** cache of the sqlite_dbptr virtual table. */
 -    "PRAGMA writable_schema = on;"
 -    "ATTACH %Q AS recovery;"
 -    "DROP TABLE IF EXISTS recovery.dbptr;"
 -    "DROP TABLE IF EXISTS recovery.freelist;"
 -    "DROP TABLE IF EXISTS recovery.map;"
 -    "DROP TABLE IF EXISTS recovery.schema;"
 -    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
 -  );
 -
 -  if( bFreelist ){
 -    shellExec(pState->db, &rc,
 -      "WITH trunk(pgno) AS ("
 -      "  SELECT shell_int32("
 -      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
 -      "      WHERE x>0"
 -      "    UNION"
 -      "  SELECT shell_int32("
 -      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
 -      "      FROM trunk WHERE x>0"
 -      "),"
 -      "freelist(data, n, freepgno) AS ("
 -      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
 -      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
 -      "    UNION ALL"
 -      "  SELECT data, n-1, shell_int32(data, 2+n) "
 -      "      FROM freelist WHERE n>=0"
 -      ")"
 -      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
 -    );
 +  if( zDestFile==0 ){
 +    raw_printf(stderr, "missing FILENAME argument on .backup\n");
 +    return INVALID_ARGS;
 +  }
 +  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);
 +    close_db(pDest);
 +    return 1;
 +  }
 +  if( bAsync ){
 +    sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
 +                 0, 0, 0);
 +  }
 +  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));
 +    close_db(pDest);
 +    return 1;
    }
 +  while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
 +  sqlite3_backup_finish(pBackup);
 +  if( rc==SQLITE_DONE ){
 +    rc = 0;
 +  }else{
 +    utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
 +    rc = 1;
 +  }
 +  close_db(pDest);
 +  return rc;
 +}
  
 -  /* If this is an auto-vacuum database, add all pointer-map pages to
 -  ** the freelist table. Do this regardless of whether or not 
 -  ** --freelist-corrupt was specified.  */
 -  shellExec(pState->db, &rc, 
 -    "WITH ptrmap(pgno) AS ("
 -    "  SELECT 2 WHERE shell_int32("
 -    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
 -    "  )"
 -    "    UNION ALL "
 -    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
 -    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
 -    ")"
 -    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
 -  );
 +#ifndef OBJECTIFY_COMMANDS
 +# define OBJECTIFY_COMMANDS 1
 +#endif
 +
 +/* Meta-command implementation functions are defined in this section.
 +COMMENT  Define meta-commands and provide for their dispatch and .help text.
 +COMMENT  These should be kept in command name order for coding convenience
 +COMMENT  except where meta-commands share implementation. (The ordering
 +COMMENT  required for dispatch and help text is effected regardless.) The
 +COMMENT  effect of this configuration can be seen in generated output or by
 +COMMENT  executing tool/mkshellc.tcl --parameters (or --details or --help).
 +COMMENT  Generally, this section defines dispatchable functions inline and
 +COMMENT  causes collection of dispatch and help table entries, to be later
 +COMMENT  emitted by certain macros. (See EMIT_* further on.)
 +*/
 +DISPATCH_CONFIG[
 +  RETURN_TYPE=int
 +  STORAGE_CLASS=static
 +  ARGS_SIGNATURE=char *$arg4\[\], int $arg5, ShellState *$arg6
 +  DISPATCH_ENTRY={ "$cmd", ${cmd}Command, $arg1, $arg2, $arg3 },
 +  CMD_CAPTURE_RE=^\s*{\s*"(\w+)"
 +  DISPATCHEE_NAME=${cmd}Command
 +  DC_ARG1_DEFAULT=[string length $cmd]
 +  DC_ARG2_DEFAULT=0
 +  DC_ARG3_DEFAULT=0
 +  DC_ARG4_DEFAULT=azArg
 +  DC_ARG5_DEFAULT=nArg
 +  DC_ARG6_DEFAULT=p
 +  DC_ARG_COUNT=7
 +];
 +
 +CONDITION_COMMAND(seeargs defined(SQLITE_GIMME_SEEARGS));
 +/*****************
 + * The .seeargs command
 + */
 +COLLECT_HELP_TEXT[
 +  ".seeargs                 Echo arguments separated by |",
 +  "    A near-dummy command for use as a template (to vanish soon)",
 +];
 +DISPATCHABLE_COMMAND( seeargs ? 0 0 azArg nArg p ){
 +  int rc = 0;
 +  for (rc=1; rc<nArg; ++rc)
 +    raw_printf(p->out, "%s%s", azArg[rc], (rc==nArg-1)? "\n" : "|");
 +  return rc;
 +}
  
 -  shellExec(pState->db, &rc, 
 -    "CREATE TABLE recovery.dbptr("
 -    "      pgno, child, PRIMARY KEY(child, pgno)"
 -    ") WITHOUT ROWID;"
 -    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
 -    "    SELECT * FROM sqlite_dbptr"
 -    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
 +CONDITION_COMMAND(archive !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB));
 +/*****************
 + * The .archive command
 + */
 +COLLECT_HELP_TEXT[
 +  ".archive ...             Manage SQL archives",
 +  "   Each command must have exactly one of the following options:",
 +  "     -c, --create               Create a new archive",
 +  "     -u, --update               Add or update files with changed mtime",
 +  "     -i, --insert               Like -u but always add even if unchanged",
 +  "     -r, --remove               Remove files from archive",
 +  "     -t, --list                 List contents of archive",
 +  "     -x, --extract              Extract files from archive",
 +  "   Optional arguments:",
 +  "     -v, --verbose              Print each filename as it is processed",
 +  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
 +  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
 +  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
 +  "     -g, --glob                 Use glob matching for names in archive",
 +  "     -n, --dryrun               Show the SQL that would have occurred",
 +  "   Examples:",
 +  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
 +  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
 +  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
 +  "   See also:",
 +  "      http://sqlite.org/cli.html#sqlite_archive_support",
 +];
 +DISPATCHABLE_COMMAND( archive ? 3 0 azArg nArg p ){
 +  open_db(p, 0);
 +  failIfSafeMode(p, "cannot run .archive in safe mode");
 +  return arDotCommand(p, 0, azArg, nArg);
 +}
  
 -    /* Delete any pointer to page 1. This ensures that page 1 is considered
 -    ** a root page, regardless of how corrupt the db is. */
 -    "DELETE FROM recovery.dbptr WHERE child = 1;"
 +/*****************
 + * The .auth command
 + */
 +CONDITION_COMMAND(auth !defined(SQLITE_OMIT_AUTHORIZATION));
 +COLLECT_HELP_TEXT[
 +  ".auth ON|OFF             Show authorizer callbacks",
 +];
 +DISPATCHABLE_COMMAND( auth 3 2 2 azArg nArg p ){
 +  int rc = 0;
 +  open_db(p, 0);
 +  if( booleanValue(azArg[1]) ){
 +    sqlite3_set_authorizer(p->db, shellAuth, p);
 +  }else if( p->bSafeModeFuture ){
 +    sqlite3_set_authorizer(p->db, safeModeAuth, p);
 +  }else{
 +    sqlite3_set_authorizer(p->db, 0, 0);
 +  }
 +  return rc;
 +}
  
 -    /* Delete all pointers to any pages that have more than one pointer
 -    ** to them. Such pages will be treated as root pages when recovering
 -    ** data.  */
 -    "DELETE FROM recovery.dbptr WHERE child IN ("
 -    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
 -    ");"
 +/*****************
 + * The .backup and .save commands (aliases for each other)
 + * These defer to writeDb in the dispatch table, so are not here.
 + */
 +COLLECT_HELP_TEXT[
 +  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
 +  "   Options:",
 +  "     --append               Use the appendvfs",
 +  "     --async                Write the FILE without journal and fsync()",
 +  ".save ?DB? FILE          Write DB (default \"main\") to FILE",
 +  "   Options:",
 +  "     --append               Use the appendvfs",
 +  "     --async                Write the FILE without journal and fsync()",
 +];
 +COLLECT_DISPATCH( * )[
 +  { "backup", writeDb, 4, 2, 5 },
 +  { "save", writeDb, 3, 2, 5 },
 +];
 +
 +/*****************
 + * The .bail command
 + */
 +COLLECT_HELP_TEXT[
 +  ".bail on|off             Stop after hitting an error.  Default OFF",
 +];
 +DISPATCHABLE_COMMAND( bail 3 2 2 ){
 +  if( nArg==2 ){
 +    bail_on_error = booleanValue(azArg[1]);
 +    return 0;
 +  }else{
 +    raw_printf(stderr, "Usage: .bail on|off\n");
 +    return 1;
 +  }
 +}
  
 -    /* Create the "map" table that will (eventually) contain instructions
 -    ** for dealing with each page in the db that contains one or more 
 -    ** records. */
 -    "CREATE TABLE recovery.map("
 -      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
 -    ");"
 +/*****************
 + * The .binary and .cd commands
 + */
 +COLLECT_HELP_TEXT[
 +  ".binary on|off           Turn binary output on or off.  Default OFF",
 +  ".cd DIRECTORY            Change the working directory to DIRECTORY",
 +];
 +DISPATCHABLE_COMMAND( binary 3 2 2 ){
 +  if( booleanValue(azArg[1]) ){
 +    setBinaryMode(p->out, 1);
 +  }else{
 +    setTextMode(p->out, 1);
 +  }
 +  return 0;
 +}
  
 -    /* Populate table [map]. If there are circular loops of pages in the
 -    ** database, the following adds all pages in such a loop to the map
 -    ** as individual root pages. This could be handled better.  */
 -    "WITH pages(i, maxlen) AS ("
 -    "  SELECT page_count, ("
 -    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
 -    "  ) FROM pragma_page_count WHERE page_count>0"
 -    "    UNION ALL"
 -    "  SELECT i-1, ("
 -    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
 -    "  ) FROM pages WHERE i>=2"
 -    ")"
 -    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
 -    "  SELECT i, maxlen, NULL, ("
 -    "    WITH p(orig, pgno, parent) AS ("
 -    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
 -    "        UNION "
 -    "      SELECT i, p.parent, "
 -    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
 -    "    )"
 -    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
 -    ") "
 -    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
 -    "UPDATE recovery.map AS o SET intkey = ("
 -    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
 -    ");"
 +DISPATCHABLE_COMMAND( cd ? 2 2 ){
 +  int rc=0;
 +  failIfSafeMode(p, "cannot run .cd in safe mode");
 +#if defined(_WIN32) || defined(WIN32)
 +  wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
 +  rc = !SetCurrentDirectoryW(z);
 +  sqlite3_free(z);
 +#else
 +  rc = chdir(azArg[1]);
 +#endif
 +  if( rc ){
 +    utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
 +    rc = 1;
 +  }
 +  return rc;
 +}
  
 -    /* Extract data from page 1 and any linked pages into table
 -    ** recovery.schema. With the same schema as an sqlite_schema table.  */
 -    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
 -    "INSERT INTO recovery.schema SELECT "
 -    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
 -    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
 -    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
 -    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
 -    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
 -    "FROM sqlite_dbdata WHERE pgno IN ("
 -    "  SELECT pgno FROM recovery.map WHERE root=1"
 -    ")"
 -    "GROUP BY pgno, cell;"
 -    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
 -  );
 +/* The undocumented ".breakpoint" command causes a call
 +** to the no-op routine named test_breakpoint().
 +*/
 +DISPATCHABLE_COMMAND( breakpoint 3 1 1 ){
 +  test_breakpoint();
 +  return 0;
 +}
  
 -  /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 
 -  ** CREATE TABLE statements that extracted from the existing schema.  */
 -  if( rc==SQLITE_OK ){
 -    sqlite3_stmt *pStmt = 0;
 -    /* ".recover" might output content in an order which causes immediate
 -    ** foreign key constraints to be violated. So disable foreign-key
 -    ** constraint enforcement to prevent problems when running the output
 -    ** script. */
 -    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
 -    raw_printf(pState->out, "BEGIN;\n");
 -    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
 -    shellPrepare(pState->db, &rc,
 -        "SELECT sql FROM recovery.schema "
 -        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
 -    );
 -    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
 -      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
 -      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 
 -          &zCreateTable[12]
 -      );
 -    }
 -    shellFinalize(&rc, pStmt);
 -  }
 -
 -  /* Figure out if an orphan table will be required. And if so, how many
 -  ** user columns it should contain */
 -  shellPrepare(pState->db, &rc, 
 -      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
 -      , &pLoop
 -  );
 -  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
 -    nOrphan = sqlite3_column_int(pLoop, 0);
 +/*****************
 + * The .changes, .check, .clone and .connection commands
 + */
 +COLLECT_HELP_TEXT[
 +  ".changes on|off          Show number of rows changed by SQL",
 +  ".check GLOB              Fail if output since .testcase does not match",
 +  ".clone NEWDB             Clone data into NEWDB from the existing database",
 +  ".connection [close] [#]  Open or close an auxiliary database connection",
 +];
 +DISPATCHABLE_COMMAND( changes 3 2 2 ){
 +  setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( check 3 0 0 ){
 +  /* Cancel output redirection, if it is currently set (by .testcase)
 +  ** Then read the content of the testcase-out.txt file and compare against
 +  ** azArg[1].  If there are differences, report an error and exit.
 +  */
 +  char *zRes = 0;
 +  int rc=0;
 +  output_reset(p);
 +  if( nArg!=2 ){
 +    raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
 +    rc = 2;
 +  }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
 +    raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
 +    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);
 +    rc = 1;
 +  }else{
 +    utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
 +    p->nCheck++;
    }
 -  shellFinalize(&rc, pLoop);
 -  pLoop = 0;
 -
 -  shellPrepare(pState->db, &rc,
 -      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
 -  );
 -
 -  shellPrepare(pState->db, &rc,
 -      "SELECT max(field), group_concat(shell_escape_crnl(quote"
 -      "(case when (? AND field<0) then NULL else value end)"
 -      "), ', ')"
 -      ", min(field) "
 -      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
 -      "GROUP BY cell", &pCells
 -  );
 -
 -  /* Loop through each root page. */
 -  shellPrepare(pState->db, &rc, 
 -      "SELECT root, intkey, max(maxlen) FROM recovery.map" 
 -      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
 -      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
 -      ")", &pLoop
 -  );
 -  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
 -    int iRoot = sqlite3_column_int(pLoop, 0);
 -    int bIntkey = sqlite3_column_int(pLoop, 1);
 -    int nCol = sqlite3_column_int(pLoop, 2);
 -    int bNoop = 0;
 -    RecoverTable *pTab;
 -
 -    assert( bIntkey==0 || bIntkey==1 );
 -    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
 -    if( bNoop || rc ) continue;
 -    if( pTab==0 ){
 -      if( pOrphan==0 ){
 -        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
 -      }
 -      pTab = pOrphan;
 -      if( pTab==0 ) break;
 +  sqlite3_free(zRes);
 +  return rc;
 +}
 +DISPATCHABLE_COMMAND( clone ? 2 2 ){
 +  failIfSafeMode(p, "cannot run .clone in safe mode");
 +  tryToClone(p, azArg[1]);
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( connection ? 1 4 ){
 +  if( nArg==1 ){
 +    /* List available connections */
 +    int i;
 +    for(i=0; i<ArraySize(p->aAuxDb); i++){
 +      const char *zFile = p->aAuxDb[i].zDbFilename;
 +      if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
 +      zFile = "(not open)";
 +      }else if( zFile==0 ){
 +      zFile = "(memory)";
 +      }else if( zFile[0]==0 ){
 +      zFile = "(temporary-file)";
 +      }
 +      if( p->pAuxDb == &p->aAuxDb[i] ){
 +      utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
 +      }else if( p->aAuxDb[i].db!=0 ){
 +      utf8_printf(stdout, "       %d: %s\n", i, zFile);
 +      }
 +    }
 +  }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
 +    int i = azArg[1][0] - '0';
 +    if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
 +      p->pAuxDb->db = p->db;
 +      p->pAuxDb = &p->aAuxDb[i];
 +      globalDb = p->db = p->pAuxDb->db;
 +      p->pAuxDb->db = 0;
 +    }
 +  }else if( nArg==3 && strcmp(azArg[1], "close")==0
 +          && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
 +    int i = azArg[2][0] - '0';
 +    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");
 +      return 1;
 +    }else if( p->aAuxDb[i].db ){
 +      session_close_all(p, i);
 +      close_db(p->aAuxDb[i].db);
 +      p->aAuxDb[i].db = 0;
      }
 +  }else{
 +    raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
 +    return 1;
 +  }
 +  return 0;
 +}
  
 -    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
 -      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
 +/*****************
 + * The .databases, .dbconfig and .dbinfo commands
 + */
 +COLLECT_HELP_TEXT[
 +  ".databases               List names and files of attached databases",
 +  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
 +  ".dbinfo ?DB?             Show status information about the database",
 +];
 +DISPATCHABLE_COMMAND( databases 2 1 1 ){
 +  int rc;
 +  char **azName = 0;
 +  int nName = 0;
 +  sqlite3_stmt *pStmt;
 +  int i;
 +  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));
 +    rc = 1;
 +  }else{
 +    while( sqlite3_step(pStmt)==SQLITE_ROW ){
 +      const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
 +      const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
 +      azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
 +      if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
 +      azName[nName*2] = strdup(zSchema);
 +      azName[nName*2+1] = strdup(zFile);
 +      nName++;
      }
 -    sqlite3_bind_int(pPages, 1, iRoot);
 -    if( bRowids==0 && pTab->iPk<0 ){
 -      sqlite3_bind_int(pCells, 1, 1);
 -    }else{
 -      sqlite3_bind_int(pCells, 1, 0);
 +  }
 +  sqlite3_finalize(pStmt);
 +  for(i=0; i<nName; i++){
 +    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 ? "" :
 +                eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
 +    free(azName[i*2]);
 +    free(azName[i*2+1]);
 +  }
 +  sqlite3_free(azName);
 +  return rc;
 +}
 +DISPATCHABLE_COMMAND( dbconfig 3 1 3 ){
 +  static const struct DbConfigChoices {
 +    const char *zName;
 +    int op;
 +  } aDbConfig[] = {
 +    { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
 +    { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
 +    { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
 +    { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
 +    { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
 +    { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
 +    { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
 +    { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
 +    { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
 +    { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
 +    { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
 +    { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
 +    { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
 +    { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
 +    { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
 +    { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
 +  };
 +  int ii, v;
 +  open_db(p, 0);
 +  for(ii=0; ii<ArraySize(aDbConfig); ii++){
 +    if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
 +    if( nArg>=3 ){
 +      sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
      }
 -    sqlite3_bind_int(pCells, 3, pTab->iPk);
 -
 -    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
 -      int iPgno = sqlite3_column_int(pPages, 0);
 -      sqlite3_bind_int(pCells, 2, iPgno);
 -      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
 -        int nField = sqlite3_column_int(pCells, 0);
 -        int iMin = sqlite3_column_int(pCells, 2);
 -        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
 -
 -        RecoverTable *pTab2 = pTab;
 -        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
 -          if( pOrphan==0 ){
 -            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
 -          }
 -          pTab2 = pOrphan;
 -          if( pTab2==0 ) break;
 -        }
 +    sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
 +    utf8_printf(p->out, "%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");
 +    return 1;
 +  }   
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( dbinfo 3 1 2 ){
 +  return shell_dbinfo_command(p, nArg, azArg);
 +}
  
 -        nField = nField+1;
 -        if( pTab2==pOrphan ){
 -          raw_printf(pState->out, 
 -              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
 -              pTab2->zQuoted, iRoot, iPgno, nField,
 -              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
 -          );
 +/*****************
 + * The .dump, .echo and .eqp commands
 + */
 +COLLECT_HELP_TEXT[
 +  ".dump ?OBJECTS?          Render database content as SQL",
 +  "   Options:",
 +  "     --data-only            Output only INSERT statements",
 +  "     --newlines             Allow unescaped newline characters in output",
 +  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
 +  "     --preserve-rowids      Include ROWID values in the output",
 +  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
 +  "   Additional LIKE patterns can be given in subsequent arguments",
 +  ".echo on|off             Turn command echo on or off",
 +  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
 +  "   Other Modes:",
 +#ifdef SQLITE_DEBUG
 +  "      test                  Show raw EXPLAIN QUERY PLAN output",
 +  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
 +#endif
 +  "      trigger               Like \"full\" but also show trigger bytecode",
 +];
 +DISPATCHABLE_COMMAND( dump ? 1 2 ){
 +  char *zLike = 0;
 +  char *zSql;
 +  int i;
 +  int savedShowHeader = p->showHeader;
 +  int savedShellFlags = p->shellFlgs;
 +  ShellClearFlag(p, 
 +     SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
 +     |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
 +  for(i=1; i<nArg; i++){
 +    if( azArg[i][0]=='-' ){
 +      const char *z = azArg[i]+1;
 +      if( z[0]=='-' ) z++;
 +      if( strcmp(z,"preserve-rowids")==0 ){
 +#ifdef SQLITE_OMIT_VIRTUALTABLE
 +        raw_printf(stderr, "The --preserve-rowids option is not compatible"
 +                   " with SQLITE_OMIT_VIRTUALTABLE\n");
 +        sqlite3_free(zLike);
 +        return 1;
 +#else
 +        ShellSetFlag(p, SHFLG_PreserveRowid);
 +#endif
 +      }else{
 +        if( strcmp(z,"newlines")==0 ){
 +          ShellSetFlag(p, SHFLG_Newlines);
 +        }else if( strcmp(z,"data-only")==0 ){
 +          ShellSetFlag(p, SHFLG_DumpDataOnly);
 +        }else if( strcmp(z,"nosys")==0 ){
 +          ShellSetFlag(p, SHFLG_DumpNoSys);
          }else{
 -          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 
 -              pTab2->zQuoted, pTab2->azlCol[nField], zVal
 -          );
 +          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
 +          sqlite3_free(zLike);
 +          return 1;
          }
        }
 -      shellReset(&rc, pCells);
 -    }
 -    shellReset(&rc, pPages);
 -    if( pTab!=pOrphan ) recoverFreeTable(pTab);
 -  }
 -  shellFinalize(&rc, pLoop);
 -  shellFinalize(&rc, pPages);
 -  shellFinalize(&rc, pCells);
 -  recoverFreeTable(pOrphan);
 -
 -  /* The rest of the schema */
 -  if( rc==SQLITE_OK ){
 -    sqlite3_stmt *pStmt = 0;
 -    shellPrepare(pState->db, &rc, 
 -        "SELECT sql, name FROM recovery.schema "
 -        "WHERE sql NOT LIKE 'create table%'", &pStmt
 -    );
 -    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
 -      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
 -      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
 -        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
 -        char *zPrint = shellMPrintf(&rc, 
 -          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
 -          zName, zName, zSql
 -        );
 -        raw_printf(pState->out, "%s;\n", zPrint);
 -        sqlite3_free(zPrint);
 +    }else{
 +      /* azArg[i] contains a LIKE pattern. This ".dump" request should
 +      ** only dump data for tables for which either the table name matches
 +      ** the LIKE pattern, or the table appears to be a shadow table of
 +      ** a virtual table for which the name matches the LIKE pattern.
 +      */
 +      char *zExpr = sqlite3_mprintf(
 +                    "name LIKE %Q ESCAPE '\\' OR EXISTS ("
 +                    "  SELECT 1 FROM sqlite_schema WHERE "
 +                    "    name LIKE %Q ESCAPE '\\' AND"
 +                    "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
 +                    "    substr(o.name, 1, length(name)+1) == (name||'_')"
 +                    ")", azArg[i], azArg[i]
 +                    );
 +      
 +      if( zLike ){
 +        zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
        }else{
 -        raw_printf(pState->out, "%s;\n", zSql);
 +        zLike = zExpr;
        }
      }
 -    shellFinalize(&rc, pStmt);
 -  }
 -
 -  if( rc==SQLITE_OK ){
 -    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
 -    raw_printf(pState->out, "COMMIT;\n");
    }
 -  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
 -  return rc;
 -}
 -#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
  
 -/*
 -** If an input line begins with "." then invoke this routine to
 -** process that line.
 -**
 -** Return 1 on error, 2 to exit, and 0 otherwise.
 -*/
 -static int do_meta_command(char *zLine, ShellState *p){
 -  int h = 1;
 -  int nArg = 0;
 -  int n, c;
 -  int rc = 0;
 -  char *azArg[52];
 +  open_db(p, 0);
  
 -#ifndef SQLITE_OMIT_VIRTUALTABLE
 -  if( p->expert.pExpert ){
 -    expertFinish(p, 1, 0);
 +  if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
 +    /* 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");
 +  }
 +  p->writableSchema = 0;
 +  p->showHeader = 0;
 +  /* Set writable_schema=ON since doing so forces SQLite to initialize
 +  ** as much of the schema as it can even if the sqlite_schema table is
 +  ** corrupt. */
 +  sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
 +  p->nErr = 0;
 +  if( zLike==0 ) zLike = sqlite3_mprintf("true");
 +  zSql = sqlite3_mprintf(
 +           "SELECT name, type, sql FROM sqlite_schema AS o "
 +           "WHERE (%s) AND type=='table'"
 +           "  AND sql NOT NULL"
 +           " ORDER BY tbl_name='sqlite_sequence', rowid",
 +           zLike
 +         );
 +  run_schema_dump_query(p,zSql);
 +  sqlite3_free(zSql);
 +  if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
 +    zSql = sqlite3_mprintf(
 +             "SELECT sql FROM sqlite_schema AS o "
 +             "WHERE (%s) AND sql NOT NULL"
 +             "  AND type IN ('index','trigger','view')",
 +             zLike
 +           );
 +    run_table_dump_query(p, zSql);
 +    sqlite3_free(zSql);
    }
 -#endif
 +  sqlite3_free(zLike);
 +  if( p->writableSchema ){
 +    raw_printf(p->out, "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");
 +  }
 +  p->showHeader = savedShowHeader;
 +  p->shellFlgs = savedShellFlags;
  
 -  /* Parse the input line into tokens.
 -  */
 -  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
 -    while( IsSpace(zLine[h]) ){ h++; }
 -    if( zLine[h]==0 ) break;
 -    if( zLine[h]=='\'' || zLine[h]=='"' ){
 -      int delim = zLine[h++];
 -      azArg[nArg++] = &zLine[h];
 -      while( zLine[h] && zLine[h]!=delim ){
 -        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
 -        h++;
 -      }
 -      if( zLine[h]==delim ){
 -        zLine[h++] = 0;
 -      }
 -      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( echo ? 2 2 ){
 +  setOrClearFlag(p, SHFLG_Echo, azArg[1]);
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( eqp ? 0 0 ){
 +  if( nArg==2 ){
 +    p->autoEQPtest = 0;
 +    if( p->autoEQPtrace ){
 +      if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
 +      p->autoEQPtrace = 0;
 +    }
 +    if( strcmp(azArg[1],"full")==0 ){
 +      p->autoEQP = AUTOEQP_full;
 +    }else if( strcmp(azArg[1],"trigger")==0 ){
 +      p->autoEQP = AUTOEQP_trigger;
 +#ifdef SQLITE_DEBUG
 +    }else if( strcmp(azArg[1],"test")==0 ){
 +      p->autoEQP = AUTOEQP_on;
 +      p->autoEQPtest = 1;
 +    }else if( strcmp(azArg[1],"trace")==0 ){
 +      p->autoEQP = AUTOEQP_full;
 +      p->autoEQPtrace = 1;
 +      open_db(p, 0);
 +      sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
 +      sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
 +#endif
      }else{
 -      azArg[nArg++] = &zLine[h];
 -      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
 -      if( zLine[h] ) zLine[h++] = 0;
 -      resolve_backslashes(azArg[nArg-1]);
 +      p->autoEQP = (u8)booleanValue(azArg[1]);
      }
 +  }else{
 +    raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
 +    return 1;
    }
 -  azArg[nArg] = 0;
 -
 -  /* Process the input line.
 -  */
 -  if( nArg==0 ) return 0; /* no tokens, no error */
 -  n = strlen30(azArg[0]);
 -  c = azArg[0][0];
 -  clearTempFile(p);
 +}
  
 -#ifndef SQLITE_OMIT_AUTHORIZATION
 -  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
 -    if( nArg!=2 ){
 -      raw_printf(stderr, "Usage: .auth ON|OFF\n");
 -      rc = 1;
 -      goto meta_command_exit;
 -    }
 -    open_db(p, 0);
 -    if( booleanValue(azArg[1]) ){
 -      sqlite3_set_authorizer(p->db, shellAuth, p);
 -    }else if( p->bSafeModePersist ){
 -      sqlite3_set_authorizer(p->db, safeModeAuth, p);
 +/*****************
 + * The .expert and .explain commands
 + */
 +CONDITION_COMMAND( expert !defined(SQLITE_OMIT_VIRTUALTABLE) );
 +COLLECT_HELP_TEXT[
 +  ".expert                  Suggest indexes for queries",
 +  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
 +];
 +DISPATCHABLE_COMMAND( explain ? 1 2 ){
 +  /* The ".explain" command is automatic now.  It is largely
 +  ** pointless, retained purely for backwards compatibility */
 +  int val = 1;
 +  if( nArg==2 ){
 +    if( strcmp(azArg[1],"auto")==0 ){
 +      val = 99;
      }else{
 -      sqlite3_set_authorizer(p->db, 0, 0);
 +      val =  booleanValue(azArg[1]);
      }
 -  }else
 -#endif
 +  }
 +  if( val==1 && p->mode!=MODE_Explain ){
 +    p->normalMode = p->mode;
 +    p->mode = MODE_Explain;
 +    p->autoExplain = 0;
 +  }else if( val==0 ){
 +    if( p->mode==MODE_Explain ) p->mode = p->normalMode;
 +    p->autoExplain = 0;
 +  }else if( val==99 ){
 +    if( p->mode==MODE_Explain ) p->mode = p->normalMode;
 +    p->autoExplain = 1;
 +  }
 +}
 +DISPATCHABLE_COMMAND( expert ? 1 1 ){
 +  open_db(p, 0);
 +  expertDotCommand(p, azArg, nArg);
 +  return 0;
 +}
  
 -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
 -  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
 -    open_db(p, 0);
 -    failIfSafeMode(p, "cannot run .archive in safe mode");
 -    rc = arDotCommand(p, 0, azArg, nArg);
 -  }else
 -#endif
 +/*****************
 + * The .excel, .once and .output commands
 + * These share much implementation, so they stick together.
 + */
 +COLLECT_HELP_TEXT[
 +  ".excel                   Display the output of next command in spreadsheet",
 +  "   --bom                   Prefix the file with a UTF8 byte-order mark",
 +  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
 +  "   If FILE begins with '|' then open it as a command to be piped into.",
 +  "   Options:",
 +  "     --bom                 Prefix output with a UTF8 byte-order mark",
 +  "     -e                    Send output to the system text editor",
 +  "     -x       Send output as CSV to a spreadsheet (same as \".excel\")",
 +  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
 +  "   If FILE begins with '|' then open it as a command to be piped into.",
 +  "   Options:",
 +  "     --bom                 Prefix output with a UTF8 byte-order mark",
 +  "     -e                    Send output to the system text editor",
 +  "     -x       Send output as CSV to a spreadsheet (same as \".excel\")",
 +];
 +static int outputRedirs(char *[], int, ShellState *, int bOnce, int eMode);
 +DISPATCHABLE_COMMAND( excel ? 1 2 ){
 +  return outputRedirs(azArg, nArg, p, 2, 'x');
 +}
 +DISPATCHABLE_COMMAND( once ? 1 6 ){
 +  return outputRedirs(azArg, nArg, p, 1, 0);
 +}
 +DISPATCHABLE_COMMAND( output ? 1 6 ){
 +  return outputRedirs(azArg, nArg, p, 0, 0);
 +}
  
 -  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
 -   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
 -  ){
 -    const char *zDestFile = 0;
 -    const char *zDb = 0;
 -    sqlite3 *pDest;
 -    sqlite3_backup *pBackup;
 -    int j;
 -    int bAsync = 0;
 -    const char *zVfs = 0;
 -    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
 -    for(j=1; j<nArg; j++){
 -      const char *z = azArg[j];
 -      if( z[0]=='-' ){
 -        if( z[1]=='-' ) z++;
 -        if( strcmp(z, "-append")==0 ){
 -          zVfs = "apndvfs";
 -        }else
 -        if( strcmp(z, "-async")==0 ){
 -          bAsync = 1;
 -        }else
 -        {
 -          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
 -          return 1;
 -        }
 -      }else if( zDestFile==0 ){
 -        zDestFile = azArg[j];
 -      }else if( zDb==0 ){
 -        zDb = zDestFile;
 -        zDestFile = azArg[j];
 +static int outputRedirs(char *azArg[], int nArg, ShellState *p,
 +                        int bOnce, int eMode){
 +  /* bOnce => 0: .output, 1: .once, 2: .excel */
 +  /* eMode => 'x' for excel, else 0 */
 +  int rc = 0;
 +  char *zFile = 0;
 +  int bTxtMode = 0;
 +  int i;
 +  int bBOM = 0;
 +  failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
 +  for(i=1; i<nArg; i++){
 +    char *z = azArg[i];
 +    if( z[0]=='-' ){
 +      if( z[1]=='-' ) z++;
 +      if( strcmp(z,"-bom")==0 ){
 +        bBOM = 1;
 +      }else if( bOnce!=2 && strcmp(z,"-x")==0 ){
 +        eMode = 'x';  /* spreadsheet */
 +      }else if( bOnce!=2 && strcmp(z,"-e")==0 ){
 +        eMode = 'e';  /* text editor */
        }else{
 -        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
 +        utf8_printf(p->out,"ERROR: unknown option: \"%s\".  Usage:\n",azArg[i]);
 +        showHelp(p->out, azArg[0]);
          return 1;
        }
 -    }
 -    if( zDestFile==0 ){
 -      raw_printf(stderr, "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);
 -      close_db(pDest);
 -      return 1;
 -    }
 -    if( bAsync ){
 -      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
 -                   0, 0, 0);
 -    }
 -    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));
 -      close_db(pDest);
 +    }else if( zFile==0 && eMode!='e' && eMode!='x' ){
 +      zFile = sqlite3_mprintf("%s", z);
 +      if( zFile[0]=='|' ){
 +        while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
 +        break;
 +      }
 +    }else{
 +      utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
 +      showHelp(p->out, azArg[0]);
 +      sqlite3_free(zFile);
        return 1;
      }
 -    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
 -    sqlite3_backup_finish(pBackup);
 -    if( rc==SQLITE_DONE ){
 -      rc = 0;
 +  }
 +  if( zFile==0 ) zFile = sqlite3_mprintf("stdout");
 +  if( bOnce ){
 +    p->outCount = 2;
 +  }else{
 +    p->outCount = 0;
 +  }
 +  output_reset(p);
 +#ifndef SQLITE_NOHAVE_SYSTEM
 +  if( eMode=='e' || eMode=='x' ){
 +    p->doXdgOpen = 1;
 +    outputModePush(p);
 +    if( eMode=='x' ){
 +      /* spreadsheet mode.  Output as CSV. */
 +      newTempFile(p, "csv");
 +      ShellClearFlag(p, SHFLG_Echo);
 +      p->mode = MODE_Csv;
 +      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
 +      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
      }else{
 -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
 -      rc = 1;
 +      /* text editor mode */
 +      newTempFile(p, "txt");
 +      bTxtMode = 1;
      }
 -    close_db(pDest);
 -  }else
 -
 -  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
 -    if( nArg==2 ){
 -      bail_on_error = booleanValue(azArg[1]);
 -    }else{
 -      raw_printf(stderr, "Usage: .bail on|off\n");
 +    sqlite3_free(zFile);
 +    zFile = sqlite3_mprintf("%s", p->zTempFile);
 +  }
 +#endif /* SQLITE_NOHAVE_SYSTEM */
 +  if( zFile[0]=='|' ){
 +#ifdef SQLITE_OMIT_POPEN
 +    raw_printf(stderr, "Error: pipes are not supported in this OS\n");
 +    rc = 1;
 +    p->out = 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;
        rc = 1;
 -    }
 -  }else
 -
 -  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
 -    if( nArg==2 ){
 -      if( booleanValue(azArg[1]) ){
 -        setBinaryMode(p->out, 1);
 -      }else{
 -        setTextMode(p->out, 1);
 -      }
      }else{
 -      raw_printf(stderr, "Usage: .binary on|off\n");
 -      rc = 1;
 +      if( bBOM ) fprintf(p->out,"\357\273\277");
 +      sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
      }
 -  }else
 -
 -  /* The undocumented ".breakpoint" command causes a call to the no-op
 -  ** routine named test_breakpoint().
 -  */
 -  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
 -    test_breakpoint();
 -  }else
 -
 -  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
 -    failIfSafeMode(p, "cannot run .cd in safe mode");
 -    if( nArg==2 ){
 -#if defined(_WIN32) || defined(WIN32)
 -      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
 -      rc = !SetCurrentDirectoryW(z);
 -      sqlite3_free(z);
 -#else
 -      rc = chdir(azArg[1]);
  #endif
 -      if( rc ){
 -        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
 -        rc = 1;
 +  }else{
 +    p->out = output_file_open(zFile, bTxtMode);
 +    if( p->out==0 ){
 +      if( strcmp(zFile,"off")!=0 ){
 +        utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
        }
 -    }else{
 -      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
 +      p->out = stdout;
        rc = 1;
 +    } else {
 +      if( bBOM ) fprintf(p->out,"\357\273\277");
 +      sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
      }
 -  }else
 +  }
 +  sqlite3_free(zFile);
 +  return rc;
 +}
  
 -  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
 -    if( nArg==2 ){
 -      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
 -    }else{
 -      raw_printf(stderr, "Usage: .changes on|off\n");
 -      rc = 1;
 -    }
 -  }else
  
 -  /* Cancel output redirection, if it is currently set (by .testcase)
 -  ** Then read the content of the testcase-out.txt file and compare against
 -  ** azArg[1].  If there are differences, report an error and exit.
 -  */
 -  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
 -    char *zRes = 0;
 -    output_reset(p);
 -    if( nArg!=2 ){
 -      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
 -      rc = 2;
 -    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
 -      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
 -      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);
 -      rc = 1;
 -    }else{
 -      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
 -      p->nCheck++;
 -    }
 -    sqlite3_free(zRes);
 -  }else
 +/*****************
 + * The .filectrl and fullschema commands
 + */
 +COLLECT_HELP_TEXT[
 +  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
 +  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
 +  "   --help                  Show CMD details",
 +  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
 +];
 +DISPATCHABLE_COMMAND( filectrl ? 2 0 ){
 +  static const struct {
 +    const char *zCtrlName;   /* Name of a test-control option */
 +    int ctrlCode;            /* Integer code for that option */
 +    const char *zUsage;      /* Usage notes */
 +  } aCtrl[] = {
 +    { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
 +    { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
 +    { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },  
 +    { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
 +    { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
 + /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
 +    { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
 +    { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
 +    { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
 +    { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
 + /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
 +  };
 +  int filectrl = -1;
 +  int iCtrl = -1;
 +  sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
 +  int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
 +  int n2, i;
 +  const char *zCmd = 0;
 +  const char *zSchema = 0;
  
 -  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
 -    failIfSafeMode(p, "cannot run .clone in safe mode");
 -    if( nArg==2 ){
 -      tryToClone(p, azArg[1]);
 -    }else{
 -      raw_printf(stderr, "Usage: .clone FILENAME\n");
 -      rc = 1;
 -    }
 -  }else
 +  open_db(p, 0);
 +  zCmd = nArg>=2 ? azArg[1] : "help";
  
 -  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
 -    if( nArg==1 ){
 -      /* List available connections */
 -      int i;
 -      for(i=0; i<ArraySize(p->aAuxDb); i++){
 -        const char *zFile = p->aAuxDb[i].zDbFilename;
 -        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
 -          zFile = "(not open)";
 -        }else if( zFile==0 ){
 -          zFile = "(memory)";
 -        }else if( zFile[0]==0 ){
 -          zFile = "(temporary-file)";
 -        }
 -        if( p->pAuxDb == &p->aAuxDb[i] ){
 -          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
 -        }else if( p->aAuxDb[i].db!=0 ){
 -          utf8_printf(stdout, "       %d: %s\n", i, zFile);
 -        }
 -      }
 -    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
 -      int i = azArg[1][0] - '0';
 -      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
 -        p->pAuxDb->db = p->db;
 -        p->pAuxDb = &p->aAuxDb[i];
 -        globalDb = p->db = p->pAuxDb->db;
 -        p->pAuxDb->db = 0;
 -      }
 -    }else if( nArg==3 && strcmp(azArg[1], "close")==0
 -           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
 -      int i = azArg[2][0] - '0';
 -      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");
 -        rc = 1;
 -      }else if( p->aAuxDb[i].db ){
 -        session_close_all(p, i);
 -        close_db(p->aAuxDb[i].db);
 -        p->aAuxDb[i].db = 0;
 -      }
 -    }else{
 -      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
 -      rc = 1;
 -    }
 -  }else
 +  if( zCmd[0]=='-' 
 +      && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
 +      && nArg>=4
 +      ){
 +    zSchema = azArg[2];
 +    for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
 +    nArg -= 2;
 +    zCmd = azArg[1];
 +  }
  
 -  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
 -    char **azName = 0;
 -    int nName = 0;
 -    sqlite3_stmt *pStmt;
 -    int i;
 -    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));
 -      rc = 1;
 -    }else{
 -      while( sqlite3_step(pStmt)==SQLITE_ROW ){
 -        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
 -        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
 -        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
 -        if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
 -        azName[nName*2] = strdup(zSchema);
 -        azName[nName*2+1] = strdup(zFile);
 -        nName++;
 -      }
 -    }
 -    sqlite3_finalize(pStmt);
 -    for(i=0; i<nName; i++){
 -      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 ? "" :
 -            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
 -      free(azName[i*2]);
 -      free(azName[i*2+1]);
 -    }
 -    sqlite3_free(azName);
 -  }else
 +  /* The argument can optionally begin with "-" or "--" */
 +  if( zCmd[0]=='-' && zCmd[1] ){
 +    zCmd++;
 +    if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
 +  }
  
 -  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
 -    static const struct DbConfigChoices {
 -      const char *zName;
 -      int op;
 -    } aDbConfig[] = {
 -        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
 -        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
 -        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
 -        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
 -        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
 -        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
 -        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
 -        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
 -        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
 -        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
 -        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
 -        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
 -        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
 -        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
 -        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
 -        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
 -    };
 -    int ii, v;
 -    open_db(p, 0);
 -    for(ii=0; ii<ArraySize(aDbConfig); ii++){
 -      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
 -      if( nArg>=3 ){
 -        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");
 -      if( nArg>1 ) break;
 +  /* --help lists all file-controls */
 +  if( strcmp(zCmd,"help")==0 ){
 +    utf8_printf(p->out, "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);
      }
 -    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");
 -    }   
 -  }else
 -
 -  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
 -    rc = shell_dbinfo_command(p, nArg, azArg);
 -  }else
 -
 -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
 -  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
 -    open_db(p, 0);
 -    rc = recoverDatabaseCmd(p, nArg, azArg);
 -  }else
 -#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
 -
 -  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
 -    char *zLike = 0;
 -    char *zSql;
 -    int i;
 -    int savedShowHeader = p->showHeader;
 -    int savedShellFlags = p->shellFlgs;
 -    ShellClearFlag(p, 
 -       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
 -       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
 -    for(i=1; i<nArg; i++){
 -      if( azArg[i][0]=='-' ){
 -        const char *z = azArg[i]+1;
 -        if( z[0]=='-' ) z++;
 -        if( strcmp(z,"preserve-rowids")==0 ){
 -#ifdef SQLITE_OMIT_VIRTUALTABLE
 -          raw_printf(stderr, "The --preserve-rowids option is not compatible"
 -                             " with SQLITE_OMIT_VIRTUALTABLE\n");
 -          rc = 1;
 -          sqlite3_free(zLike);
 -          goto meta_command_exit;
 -#else
 -          ShellSetFlag(p, SHFLG_PreserveRowid);
 -#endif
 -        }else
 -        if( strcmp(z,"newlines")==0 ){
 -          ShellSetFlag(p, SHFLG_Newlines);
 -        }else
 -        if( strcmp(z,"data-only")==0 ){
 -          ShellSetFlag(p, SHFLG_DumpDataOnly);
 -        }else
 -        if( strcmp(z,"nosys")==0 ){
 -          ShellSetFlag(p, SHFLG_DumpNoSys);
 -        }else
 -        {
 -          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
 -          rc = 1;
 -          sqlite3_free(zLike);
 -          goto meta_command_exit;
 -        }
 +    return 1;
 +  }
 +  
 +  /* Convert filectrl text option to value. Allow any
 +  ** unique prefix of the option name, or a numerical value. */
 +  n2 = strlen30(zCmd);
 +  for(i=0; i<ArraySize(aCtrl); i++){
 +    if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
 +      if( filectrl<0 ){
 +        filectrl = aCtrl[i].ctrlCode;
 +        iCtrl = i;
        }else{
 -        /* azArg[i] contains a LIKE pattern. This ".dump" request should
 -        ** only dump data for tables for which either the table name matches
 -        ** the LIKE pattern, or the table appears to be a shadow table of
 -        ** a virtual table for which the name matches the LIKE pattern.
 -        */
 -        char *zExpr = sqlite3_mprintf(
 -            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
 -            "  SELECT 1 FROM sqlite_schema WHERE "
 -            "    name LIKE %Q ESCAPE '\\' AND"
 -            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
 -            "    substr(o.name, 1, length(name)+1) == (name||'_')"
 -            ")", azArg[i], azArg[i]
 -        );
 -      
 -        if( zLike ){
 -          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
 -        }else{
 -          zLike = zExpr;
 -        }
 +        utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
 +                    "Use \".filectrl --help\" for help\n", zCmd);
 +        return 1;
        }
      }
 -
 -    open_db(p, 0);
 -
 -    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
 -      /* 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");
 -    }
 -    p->writableSchema = 0;
 -    p->showHeader = 0;
 -    /* Set writable_schema=ON since doing so forces SQLite to initialize
 -    ** as much of the schema as it can even if the sqlite_schema table is
 -    ** corrupt. */
 -    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
 -    p->nErr = 0;
 -    if( zLike==0 ) zLike = sqlite3_mprintf("true");
 -    zSql = sqlite3_mprintf(
 -      "SELECT name, type, sql FROM sqlite_schema AS o "
 -      "WHERE (%s) AND type=='table'"
 -      "  AND sql NOT NULL"
 -      " ORDER BY tbl_name='sqlite_sequence', rowid",
 -      zLike
 -    );
 -    run_schema_dump_query(p,zSql);
 -    sqlite3_free(zSql);
 -    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
 -      zSql = sqlite3_mprintf(
 -        "SELECT sql FROM sqlite_schema AS o "
 -        "WHERE (%s) AND sql NOT NULL"
 -        "  AND type IN ('index','trigger','view')",
 -        zLike
 -      );
 -      run_table_dump_query(p, zSql);
 -      sqlite3_free(zSql);
 +  }
 +  if( filectrl<0 ){
 +    utf8_printf(stderr,"Error: unknown file-control: %s\n"
 +                "Use \".filectrl --help\" for help\n", zCmd);
 +  }else{
 +   switch(filectrl){
 +    case SQLITE_FCNTL_SIZE_LIMIT: {
 +      if( nArg!=2 && nArg!=3 ) break;
 +      iRes = nArg==3 ? integerValue(azArg[2]) : -1;
 +      sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
 +      isOk = 1;
 +      break;
      }
 -    sqlite3_free(zLike);
 -    if( p->writableSchema ){
 -      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
 -      p->writableSchema = 0;
 +    case SQLITE_FCNTL_LOCK_TIMEOUT:
 +    case SQLITE_FCNTL_CHUNK_SIZE: {
 +      int x;
 +      if( nArg!=3 ) break;
 +      x = (int)integerValue(azArg[2]);
 +      sqlite3_file_control(p->db, zSchema, filectrl, &x);
 +      isOk = 2;
 +      break;
      }
 -    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");
 +    case SQLITE_FCNTL_PERSIST_WAL:
 +    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 +      int x;
 +      if( nArg!=2 && nArg!=3 ) break;
 +      x = nArg==3 ? booleanValue(azArg[2]) : -1;
 +      sqlite3_file_control(p->db, zSchema, filectrl, &x);
 +      iRes = x;
 +      isOk = 1;
 +      break;
      }
 -    p->showHeader = savedShowHeader;
 -    p->shellFlgs = savedShellFlags;
 -  }else
 -
 -  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
 -    if( nArg==2 ){
 -      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
 -    }else{
 -      raw_printf(stderr, "Usage: .echo on|off\n");
 -      rc = 1;
 +    case SQLITE_FCNTL_DATA_VERSION:
 +    case SQLITE_FCNTL_HAS_MOVED: {
 +      int x;
 +      if( nArg!=2 ) break;
 +      sqlite3_file_control(p->db, zSchema, filectrl, &x);
 +      iRes = x;
 +      isOk = 1;
 +      break;
      }
 -  }else
 -
 -  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
 -    if( nArg==2 ){
 -      p->autoEQPtest = 0;
 -      if( p->autoEQPtrace ){
 -        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
 -        p->autoEQPtrace = 0;
 -      }
 -      if( strcmp(azArg[1],"full")==0 ){
 -        p->autoEQP = AUTOEQP_full;
 -      }else if( strcmp(azArg[1],"trigger")==0 ){
 -        p->autoEQP = AUTOEQP_trigger;
 -#ifdef SQLITE_DEBUG
 -      }else if( strcmp(azArg[1],"test")==0 ){
 -        p->autoEQP = AUTOEQP_on;
 -        p->autoEQPtest = 1;
 -      }else if( strcmp(azArg[1],"trace")==0 ){
 -        p->autoEQP = AUTOEQP_full;
 -        p->autoEQPtrace = 1;
 -        open_db(p, 0);
 -        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
 -        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
 -#endif
 -      }else{
 -        p->autoEQP = (u8)booleanValue(azArg[1]);
 +    case SQLITE_FCNTL_TEMPFILENAME: {
 +      char *z = 0;
 +      if( nArg!=2 ) break;
 +      sqlite3_file_control(p->db, zSchema, filectrl, &z);
 +      if( z ){
 +        utf8_printf(p->out, "%s\n", z);
 +        sqlite3_free(z);
        }
 -    }else{
 -      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
 -      rc = 1;
 +      isOk = 2;
 +      break;
      }
 -  }else
 -
 -  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
 -    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
 -    rc = 2;
 -  }else
 -
 -  /* The ".explain" command is automatic now.  It is largely pointless.  It
 -  ** retained purely for backwards compatibility */
 -  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
 -    int val = 1;
 -    if( nArg>=2 ){
 -      if( strcmp(azArg[1],"auto")==0 ){
 -        val = 99;
 -      }else{
 -        val =  booleanValue(azArg[1]);
 +    case SQLITE_FCNTL_RESERVE_BYTES: {
 +      int x;
 +      if( nArg>=3 ){
 +        x = atoi(azArg[2]);
 +        sqlite3_file_control(p->db, zSchema, filectrl, &x);
        }
 +      x = -1;
 +      sqlite3_file_control(p->db, zSchema, filectrl, &x);
 +      utf8_printf(p->out,"%d\n", x);
 +      isOk = 2;
 +      break;
      }
 -    if( val==1 && p->mode!=MODE_Explain ){
 -      p->normalMode = p->mode;
 -      p->mode = MODE_Explain;
 -      p->autoExplain = 0;
 -    }else if( val==0 ){
 -      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
 -      p->autoExplain = 0;
 -    }else if( val==99 ){
 -      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
 -      p->autoExplain = 1;
 -    }
 -  }else
 -
 -#ifndef SQLITE_OMIT_VIRTUALTABLE
 -  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
 -    open_db(p, 0);
 -    expertDotCommand(p, azArg, nArg);
 -  }else
 -#endif
 +   }
 +  }
 +  if( isOk==0 && iCtrl>=0 ){
 +    utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
 +    return 1;
 +  }else if( isOk==1 ){
 +    char zBuf[100];
 +    sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
 +    raw_printf(p->out, "%s\n", zBuf);
 +  }
 +  return 0;
 +}
  
 -  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
 -    static const struct {
 -       const char *zCtrlName;   /* Name of a test-control option */
 -       int ctrlCode;            /* Integer code for that option */
 -       const char *zUsage;      /* Usage notes */
 -    } aCtrl[] = {
 -      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
 -      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
 -      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },  
 -      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
 -      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
 -   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
 -      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
 -      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
 -      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
 -      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
 -   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
 -    };
 -    int filectrl = -1;
 -    int iCtrl = -1;
 -    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
 -    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
 -    int n2, i;
 -    const char *zCmd = 0;
 -    const char *zSchema = 0;
 +DISPATCHABLE_COMMAND( fullschema ? 1 2 ){
 +  int rc;
 +  ShellState data;
 +  int doStats = 0;
 +  memcpy(&data, p, sizeof(data));
 +  data.showHeader = 0;
 +  data.cMode = data.mode = MODE_Semi;
 +  if( nArg==2 && optionMatch(azArg[1], "indent") ){
 +    data.cMode = data.mode = MODE_Pretty;
 +    nArg = 1;
 +  }
 +  if( nArg!=1 ){
 +    raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
 +    return 1;
 +  }
 +  open_db(p, 0);
 +  rc = sqlite3_exec(p->db,
 +    "SELECT sql FROM"
 +    "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
 +    "     FROM sqlite_schema UNION ALL"
 +    "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
 +    "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
 +    "ORDER BY x",
 +    callback, &data, 0
 +  );
 +  if( rc==SQLITE_OK ){
 +    sqlite3_stmt *pStmt;
 +    rc = sqlite3_prepare_v2(p->db,
 +                            "SELECT rowid FROM sqlite_schema"
 +                            " WHERE name GLOB 'sqlite_stat[134]'",
 +                            -1, &pStmt, 0);
 +    doStats = sqlite3_step(pStmt)==SQLITE_ROW;
 +    sqlite3_finalize(pStmt);
 +  }
 +  if( doStats==0 ){
 +    raw_printf(p->out, "/* No STAT tables available */\n");
 +  }else{
 +    raw_printf(p->out, "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");
 +  }
 +  return rc > 0;
 +}
  
 -    open_db(p, 0);
 -    zCmd = nArg>=2 ? azArg[1] : "help";
 -
 -    if( zCmd[0]=='-' 
 -     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
 -     && nArg>=4
 -    ){
 -      zSchema = azArg[2];
 -      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
 -      nArg -= 2;
 -      zCmd = azArg[1];
 -    }
 -
 -    /* The argument can optionally begin with "-" or "--" */
 -    if( zCmd[0]=='-' && zCmd[1] ){
 -      zCmd++;
 -      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
 -    }
 -
 -    /* --help lists all file-controls */
 -    if( strcmp(zCmd,"help")==0 ){
 -      utf8_printf(p->out, "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);
 -      }
 -      rc = 1;
 -      goto meta_command_exit;
 -    }
 +/*****************
 + * The .headers command
 + */
 +COLLECT_HELP_TEXT[
 +  ".headers on|off          Turn display of headers on or off",
 +];
 +DISPATCHABLE_COMMAND( headers 6 1 2 ){
 +  p->showHeader = booleanValue(azArg[1]);
 +  p->shellFlgs |= SHFLG_HeaderSet;
 +  return 0;
 +}
  
 -    /* convert filectrl text option to value. allow any unique prefix
 -    ** of the option name, or a numerical value. */
 -    n2 = strlen30(zCmd);
 -    for(i=0; i<ArraySize(aCtrl); i++){
 -      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
 -        if( filectrl<0 ){
 -          filectrl = aCtrl[i].ctrlCode;
 -          iCtrl = i;
 -        }else{
 -          utf8_printf(stderr, "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);
 +/*****************
 + * The .help command
 + */
 +COLLECT_HELP_TEXT[
 +  ".help ?(PATTERN|-all)? Show help text for some or all command(s)",
 +  "   PATTERN                Show help for matching command(s)",
 +  "   -all                   Show all help for all commands",
 +];
 +DISPATCHABLE_COMMAND( help 3 1 2 ){
 +  const char *zPat = 0;
 +  if( nArg>1 ){
 +    char *z = azArg[1];
 +    if( strcmp(z,"-a")==0
 +        || strcmp(z,"-all")==0
 +        || strcmp(z,"--all")==0 ){
 +      zPat = "";
      }else{
 -      switch(filectrl){
 -        case SQLITE_FCNTL_SIZE_LIMIT: {
 -          if( nArg!=2 && nArg!=3 ) break;
 -          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
 -          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
 -          isOk = 1;
 -          break;
 -        }
 -        case SQLITE_FCNTL_LOCK_TIMEOUT:
 -        case SQLITE_FCNTL_CHUNK_SIZE: {
 -          int x;
 -          if( nArg!=3 ) break;
 -          x = (int)integerValue(azArg[2]);
 -          sqlite3_file_control(p->db, zSchema, filectrl, &x);
 -          isOk = 2;
 -          break;
 -        }
 -        case SQLITE_FCNTL_PERSIST_WAL:
 -        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 -          int x;
 -          if( nArg!=2 && nArg!=3 ) break;
 -          x = nArg==3 ? booleanValue(azArg[2]) : -1;
 -          sqlite3_file_control(p->db, zSchema, filectrl, &x);
 -          iRes = x;
 -          isOk = 1;
 -          break;
 -        }
 -        case SQLITE_FCNTL_DATA_VERSION:
 -        case SQLITE_FCNTL_HAS_MOVED: {
 -          int x;
 -          if( nArg!=2 ) break;
 -          sqlite3_file_control(p->db, zSchema, filectrl, &x);
 -          iRes = x;
 -          isOk = 1;
 -          break;
 -        }
 -        case SQLITE_FCNTL_TEMPFILENAME: {
 -          char *z = 0;
 -          if( nArg!=2 ) break;
 -          sqlite3_file_control(p->db, zSchema, filectrl, &z);
 -          if( z ){
 -            utf8_printf(p->out, "%s\n", z);
 -            sqlite3_free(z);
 -          }
 -          isOk = 2;
 -          break;
 -        }
 -        case SQLITE_FCNTL_RESERVE_BYTES: {
 -          int x;
 -          if( nArg>=3 ){
 -            x = atoi(azArg[2]);
 -            sqlite3_file_control(p->db, zSchema, filectrl, &x);
 -          }
 -          x = -1;
 -          sqlite3_file_control(p->db, zSchema, filectrl, &x);
 -          utf8_printf(p->out,"%d\n", x);
 -          isOk = 2;
 -          break;
 -        }
 -      }
 +      zPat = z;
      }
 -    if( isOk==0 && iCtrl>=0 ){
 -      utf8_printf(p->out, "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);
 -    }
 -  }else
 +  }
 +  if( showHelp(p->out, zPat)==0 ){
 +    utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
 +  }
 +  /* Help pleas never fail! */
 +  return 0;
 +}
  
 -  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
 -    ShellState data;
 -    int doStats = 0;
 -    memcpy(&data, p, sizeof(data));
 -    data.showHeader = 0;
 -    data.cMode = data.mode = MODE_Semi;
 -    if( nArg==2 && optionMatch(azArg[1], "indent") ){
 -      data.cMode = data.mode = MODE_Pretty;
 -      nArg = 1;
 -    }
 -    if( nArg!=1 ){
 -      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
 -      rc = 1;
 -      goto meta_command_exit;
 -    }
 -    open_db(p, 0);
 -    rc = sqlite3_exec(p->db,
 -       "SELECT sql FROM"
 -       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
 -       "     FROM sqlite_schema UNION ALL"
 -       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
 -       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
 -       "ORDER BY x",
 -       callback, &data, 0
 -    );
 -    if( rc==SQLITE_OK ){
 -      sqlite3_stmt *pStmt;
 -      rc = sqlite3_prepare_v2(p->db,
 -               "SELECT rowid FROM sqlite_schema"
 -               " WHERE name GLOB 'sqlite_stat[134]'",
 -               -1, &pStmt, 0);
 -      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
 -      sqlite3_finalize(pStmt);
 -    }
 -    if( doStats==0 ){
 -      raw_printf(p->out, "/* No STAT tables available */\n");
 -    }else{
 -      raw_printf(p->out, "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");
 -    }
 -  }else
 +/*****************
 + * The .import command
 + */
 +COLLECT_HELP_TEXT[
 +  ".import FILE TABLE       Import data from FILE into TABLE",
 +  "   Options:",
 +  "     --ascii               Use \\037 and \\036 as column and row separators",
 +  "     --csv                 Use , and \\n as column and row separators",
 +  "     --skip N              Skip the first N rows of input",
 +  "     -v                    \"Verbose\" - increase auxiliary output",
 +  "   Notes:",
 +  "     *  If TABLE does not exist, it is created.  The first row of input",
 +  "        determines the column names.",
 +  "     *  If neither --csv or --ascii are used, the input mode is derived",
 +  "        from the \".mode\" output mode",
 +  "     *  If FILE begins with \"|\" then it is a command that generates the",
 +  "        input text.",
 +];
 +DISPATCHABLE_COMMAND( import ? 3 7 ){
 +  char *zTable = 0;           /* Insert data into this table */
 +  char *zFile = 0;            /* Name of file to extra content from */
 +  sqlite3_stmt *pStmt = NULL; /* A statement */
 +  int nCol;                   /* Number of columns in the table */
 +  int nByte;                  /* Number of bytes in an SQL string */
 +  int i, j;                   /* Loop counters */
 +  int needCommit;             /* True to COMMIT or ROLLBACK at end */
 +  int nSep;                   /* Number of bytes in p->colSeparator[] */
 +  char *zSql;                 /* An SQL statement */
 +  ImportCtx sCtx;             /* Reader context */
 +  char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
 +  int eVerbose = 0;           /* Larger for more console output */
 +  int nSkip = 0;              /* Initial lines to skip */
 +  int useOutputMode = 1;      /* Use output mode to determine separators */
 +  int rc = 0;
  
 -  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
 -    if( nArg==2 ){
 -      p->showHeader = booleanValue(azArg[1]);
 -      p->shellFlgs |= SHFLG_HeaderSet;
 -    }else{
 -      raw_printf(stderr, "Usage: .headers on|off\n");
 -      rc = 1;
 -    }
 -  }else
 +  failIfSafeMode(p, "cannot run .import in safe mode");
 +  memset(&sCtx, 0, sizeof(sCtx));
 +  if( 0==(sCtx.z = sqlite3_malloc64(120)) ){
 +    shell_out_of_memory();
 +  }
  
 -  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
 -    if( nArg>=2 ){
 -      n = showHelp(p->out, azArg[1]);
 -      if( n==0 ){
 -        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
 +  if( p->mode==MODE_Ascii ){
 +    xRead = ascii_read_one_field;
 +  }else{
 +    xRead = csv_read_one_field;
 +  }
 +  for(i=1; i<nArg; i++){
 +    char *z = azArg[i];
 +    if( z[0]=='-' && z[1]=='-' ) z++;
 +    if( z[0]!='-' ){
 +      if( zFile==0 ){
 +        zFile = z;
 +      }else if( zTable==0 ){
 +        zTable = z;
 +      }else{
 +        utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
 +        showHelp(p->out, "import");
 +        return 1;
        }
 -    }else{
 -      showHelp(p->out, 0);
 -    }
 -  }else
 -
 -  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
 -    char *zTable = 0;           /* Insert data into this table */
 -    char *zFile = 0;            /* Name of file to extra content from */
 -    sqlite3_stmt *pStmt = NULL; /* A statement */
 -    int nCol;                   /* Number of columns in the table */
 -    int nByte;                  /* Number of bytes in an SQL string */
 -    int i, j;                   /* Loop counters */
 -    int needCommit;             /* True to COMMIT or ROLLBACK at end */
 -    int nSep;                   /* Number of bytes in p->colSeparator[] */
 -    char *zSql;                 /* An SQL statement */
 -    ImportCtx sCtx;             /* Reader context */
 -    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
 -    int eVerbose = 0;           /* Larger for more console output */
 -    int nSkip = 0;              /* Initial lines to skip */
 -    int useOutputMode = 1;      /* Use output mode to determine separators */
 -
 -    failIfSafeMode(p, "cannot run .import in safe mode");
 -    memset(&sCtx, 0, sizeof(sCtx));
 -    sCtx.z = sqlite3_malloc64(120);
 -    if( sCtx.z==0 ){
 -      import_cleanup(&sCtx);
 -      shell_out_of_memory();
 -    }
 -    if( p->mode==MODE_Ascii ){
 +    }else if( strcmp(z,"-v")==0 ){
 +      eVerbose++;
 +    }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
 +      nSkip = integerValue(azArg[++i]);
 +    }else if( strcmp(z,"-ascii")==0 ){
 +      sCtx.cColSep = SEP_Unit[0];
 +      sCtx.cRowSep = SEP_Record[0];
        xRead = ascii_read_one_field;
 -    }else{
 +      useOutputMode = 0;
 +    }else if( strcmp(z,"-csv")==0 ){
 +      sCtx.cColSep = ',';
 +      sCtx.cRowSep = '\n';
        xRead = csv_read_one_field;
 +      useOutputMode = 0;
 +    }else{
 +      utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
 +      showHelp(p->out, "import");
 +      return 1;
      }
 -    for(i=1; i<nArg; i++){
 -      char *z = azArg[i];
 -      if( z[0]=='-' && z[1]=='-' ) z++;
 -      if( z[0]!='-' ){
 -        if( zFile==0 ){
 -          zFile = z;
 -        }else if( zTable==0 ){
 -          zTable = z;
 -        }else{
 -          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
 -          showHelp(p->out, "import");
 -          rc = 1;
 -          goto meta_command_exit;
 -        }
 -      }else if( strcmp(z,"-v")==0 ){
 -        eVerbose++;
 -      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
 -        nSkip = integerValue(azArg[++i]);
 -      }else if( strcmp(z,"-ascii")==0 ){
 -        sCtx.cColSep = SEP_Unit[0];
 -        sCtx.cRowSep = SEP_Record[0];
 -        xRead = ascii_read_one_field;
 -        useOutputMode = 0;
 -      }else if( strcmp(z,"-csv")==0 ){
 -        sCtx.cColSep = ',';
 -        sCtx.cRowSep = '\n';
 -        xRead = csv_read_one_field;
 -        useOutputMode = 0;
 -      }else{
 -        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
 -        showHelp(p->out, "import");
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 +  }
 +  if( zTable==0 ){
 +    utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
 +                zFile==0 ? "FILE" : "TABLE");
 +    showHelp(p->out, "import");
 +    return 1;
 +  }
 +  seenInterrupt = 0;
 +  open_db(p, 0);
 +  if( useOutputMode ){
 +    /* If neither the --csv or --ascii options are specified, then set
 +    ** 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");
 +      return 1;
      }
 -    if( zTable==0 ){
 -      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
 -                  zFile==0 ? "FILE" : "TABLE");
 -      showHelp(p->out, "import");
 -      rc = 1;
 -      goto meta_command_exit;
 +    if( nSep>1 ){
 +      raw_printf(stderr, 
 +                 "Error: multi-character or multi-byte column separators"
 +                 " not allowed for import\n");
 +      return 1;
      }
 -    seenInterrupt = 0;
 -    open_db(p, 0);
 -    if( useOutputMode ){
 -      /* If neither the --csv or --ascii options are specified, then set
 -      ** 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");
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -      if( nSep>1 ){
 -        raw_printf(stderr, 
 -              "Error: multi-character column separators not allowed"
 -              " for import\n");
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 +    nSep = strlen30(p->rowSeparator);
 +    if( nSep==0 ){
 +      raw_printf(stderr,
 +                 "Error: non-null row separator required for import\n");
 +      return 1;
 +    }
 +    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
 +      /* When importing CSV (only), if the row separator is set to the
 +      ** default output row separator, change it to the default input
 +      ** row separator.  This avoids having to maintain different input
 +      ** and output row separators. */
 +      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
        nSep = strlen30(p->rowSeparator);
 -      if( nSep==0 ){
 -        raw_printf(stderr,
 -            "Error: non-null row separator required for import\n");
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
 -        /* When importing CSV (only), if the row separator is set to the
 -        ** default output row separator, change it to the default input
 -        ** row separator.  This avoids having to maintain different input
 -        ** and output row separators. */
 -        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 -        nSep = strlen30(p->rowSeparator);
 -      }
 -      if( nSep>1 ){
 -        raw_printf(stderr, "Error: multi-character row separators not allowed"
 -                           " for import\n");
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -      sCtx.cColSep = p->colSeparator[0];
 -      sCtx.cRowSep = p->rowSeparator[0];
      }
 -    sCtx.zFile = zFile;
 -    sCtx.nLine = 1;
 -    if( sCtx.zFile[0]=='|' ){
 +    if( nSep>1 ){
 +      raw_printf(stderr, "Error: multi-character row separators not allowed"
 +                 " for import\n");
 +      return 1;
 +    }
 +    sCtx.cColSep = p->colSeparator[0];
 +    sCtx.cRowSep = p->rowSeparator[0];
 +  }
 +  sCtx.zFile = zFile;
 +  sCtx.nLine = 1;
 +  if( sCtx.zFile[0]=='|' ){
  #ifdef SQLITE_OMIT_POPEN
 -      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
 -      rc = 1;
 -      goto meta_command_exit;
 +    raw_printf(stderr, "Error: pipes are not supported in this OS\n");
 +    return 1;
  #else
 -      sCtx.in = popen(sCtx.zFile+1, "r");
 -      sCtx.zFile = "<pipe>";
 -      sCtx.xCloser = pclose;
 +    sCtx.in = popen(sCtx.zFile+1, "r");
 +    sCtx.zFile = "<pipe>";
 +    sCtx.xCloser = pclose;
  #endif
 -    }else{
 -      sCtx.in = fopen(sCtx.zFile, "rb");
 -      sCtx.xCloser = fclose;
 -    }
 -    if( sCtx.in==0 ){
 -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
 -      rc = 1;
 -      import_cleanup(&sCtx);
 -      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 ");
 -      zSep[0] = sCtx.cRowSep;
 -      output_c_string(p->out, zSep);
 -      utf8_printf(p->out, "\n");
 -    }
 -    while( (nSkip--)>0 ){
 -      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
 -    }
 -    zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
 -    if( zSql==0 ){
 -      import_cleanup(&sCtx);
 -      shell_out_of_memory();
 -    }
 -    nByte = strlen30(zSql);
 -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 -    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
 -    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
 -      char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
 -      char cSep = '(';
 -      while( xRead(&sCtx) ){
 -        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
 -        cSep = ',';
 -        if( sCtx.cTerm!=sCtx.cColSep ) break;
 -      }
 -      if( cSep=='(' ){
 -        sqlite3_free(zCreate);
 -        import_cleanup(&sCtx);
 -        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -      zCreate = sqlite3_mprintf("%z\n)", zCreate);
 -      if( eVerbose>=1 ){
 -        utf8_printf(p->out, "%s\n", zCreate);
 -      }
 -      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
 +  }else{
 +    sCtx.in = fopen(sCtx.zFile, "rb");
 +    sCtx.xCloser = fclose;
 +  }
 +  if( sCtx.in==0 ){
 +    utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
 +    import_cleanup(&sCtx);
 +    return 1;
 +  }
 +  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 ");
 +    zSep[0] = sCtx.cRowSep;
 +    output_c_string(p->out, zSep);
 +    utf8_printf(p->out, "\n");
 +  }
 +  while( (nSkip--)>0 ){
 +    while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
 +  }
 +  zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
 +  if( zSql==0 ){
 +    import_cleanup(&sCtx);
 +    shell_out_of_memory();
 +  }
 +  nByte = strlen30(zSql);
 +  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 +  import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
 +  if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
 +    char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
 +    char cSep = '(';
 +    while( xRead(&sCtx) ){
 +      zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
 +      cSep = ',';
 +      if( sCtx.cTerm!=sCtx.cColSep ) break;
 +    }
 +    if( cSep=='(' ){
        sqlite3_free(zCreate);
 -      if( rc ){
 -        utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
 -                sqlite3_errmsg(p->db));
 -        import_cleanup(&sCtx);
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 -    }
 -    sqlite3_free(zSql);
 -    if( rc ){
 -      if (pStmt) sqlite3_finalize(pStmt);
 -      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
 -      import_cleanup(&sCtx);
 -      rc = 1;
 -      goto meta_command_exit;
 -    }
 -    nCol = sqlite3_column_count(pStmt);
 -    sqlite3_finalize(pStmt);
 -    pStmt = 0;
 -    if( nCol==0 ) return 0; /* no columns, no error */
 -    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
 -    if( zSql==0 ){
        import_cleanup(&sCtx);
 -      shell_out_of_memory();
 -    }
 -    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
 -    j = strlen30(zSql);
 -    for(i=1; i<nCol; i++){
 -      zSql[j++] = ',';
 -      zSql[j++] = '?';
 +      utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
 +      return 1;
      }
 -    zSql[j++] = ')';
 -    zSql[j] = 0;
 -    if( eVerbose>=2 ){
 -      utf8_printf(p->out, "Insert using: %s\n", zSql);
 +    zCreate = sqlite3_mprintf("%z\n)", zCreate);
 +    if( eVerbose>=1 ){
 +      utf8_printf(p->out, "%s\n", zCreate);
      }
 -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 -    sqlite3_free(zSql);
 +    rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
 +    sqlite3_free(zCreate);
      if( rc ){
 -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
 -      if (pStmt) sqlite3_finalize(pStmt);
 +      utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
 +                  sqlite3_errmsg(p->db));
        import_cleanup(&sCtx);
 -      rc = 1;
 -      goto meta_command_exit;
 -    }
 -    needCommit = sqlite3_get_autocommit(p->db);
 -    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
 -    do{
 -      int startLine = sCtx.nLine;
 -      for(i=0; i<nCol; i++){
 -        char *z = xRead(&sCtx);
 -        /*
 -        ** Did we reach end-of-file before finding any columns?
 -        ** If so, stop instead of NULL filling the remaining columns.
 -        */
 -        if( z==0 && i==0 ) break;
 -        /*
 -        ** Did we reach end-of-file OR end-of-line before finding any
 -        ** columns in ASCII mode?  If so, stop instead of NULL filling
 -        ** the remaining columns.
 -        */
 -        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
 -        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);
 -          i += 2;
 -          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
 -        }
 -      }
 -      if( sCtx.cTerm==sCtx.cColSep ){
 -        do{
 -          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);
 -      }
 -      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));
 -          sCtx.nErr++;
 -        }else{
 -          sCtx.nRow++;
 -        }
 -      }
 -    }while( sCtx.cTerm!=EOF );
 -
 -    import_cleanup(&sCtx);
 -    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);
 -    }
 -  }else
 -
 -#ifndef SQLITE_UNTESTABLE
 -  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
 -    char *zSql;
 -    char *zCollist = 0;
 -    sqlite3_stmt *pStmt;
 -    int tnum = 0;
 -    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
 -    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
 -    int i;
 -    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
 -      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
 -                          "       .imposter off\n");
 -      /* Also allowed, but not documented:
 -      **
 -      **    .imposter TABLE IMPOSTER
 -      **
 -      ** where TABLE is a WITHOUT ROWID table.  In that case, the
 -      ** imposter is another WITHOUT ROWID table with the columns in
 -      ** storage order. */
 -      rc = 1;
 -      goto meta_command_exit;
 -    }
 -    open_db(p, 0);
 -    if( nArg==2 ){
 -      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
 -      goto meta_command_exit;
 -    }
 -    zSql = sqlite3_mprintf(
 -      "SELECT rootpage, 0 FROM sqlite_schema"
 -      " WHERE name='%q' AND type='index'"
 -      "UNION ALL "
 -      "SELECT rootpage, 1 FROM sqlite_schema"
 -      " WHERE name='%q' AND type='table'"
 -      "   AND sql LIKE '%%without%%rowid%%'",
 -      azArg[1], azArg[1]
 -    );
 -    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 -    sqlite3_free(zSql);
 -    if( sqlite3_step(pStmt)==SQLITE_ROW ){
 -      tnum = sqlite3_column_int(pStmt, 0);
 -      isWO = sqlite3_column_int(pStmt, 1);
 +      return 1;
      }
 -    sqlite3_finalize(pStmt);
 -    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 -    sqlite3_free(zSql);
 -    i = 0;
 -    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
 -      char zLabel[20];
 -      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
 -      i++;
 -      if( zCol==0 ){
 -        if( sqlite3_column_int(pStmt,1)==-1 ){
 -          zCol = "_ROWID_";
 -        }else{
 -          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
 -          zCol = zLabel;
 -        }
 -      }
 -      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
 -        lenPK = (int)strlen(zCollist);
 -      }
 -      if( zCollist==0 ){
 -        zCollist = sqlite3_mprintf("\"%w\"", zCol);
 -      }else{
 -        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
 +  }
 +  sqlite3_free(zSql);
 +  if( rc ){
 +    if (pStmt) sqlite3_finalize(pStmt);
 +    utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
 +    import_cleanup(&sCtx);
 +    return 1;
 +  }
 +  nCol = sqlite3_column_count(pStmt);
 +  sqlite3_finalize(pStmt);
 +  pStmt = 0;
 +  if( nCol==0 ) return 0; /* no columns, no error */
 +  zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
 +  if( zSql==0 ){
 +    import_cleanup(&sCtx);
 +    shell_out_of_memory();
 +  }
 +  sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
 +  j = strlen30(zSql);
 +  for(i=1; i<nCol; i++){
 +    zSql[j++] = ',';
 +    zSql[j++] = '?';
 +  }
 +  zSql[j++] = ')';
 +  zSql[j] = 0;
 +  if( eVerbose>=2 ){
 +    utf8_printf(p->out, "Insert using: %s\n", zSql);
 +  }
 +  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 +  sqlite3_free(zSql);
 +  if( rc ){
 +    utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
 +    if (pStmt) sqlite3_finalize(pStmt);
 +    import_cleanup(&sCtx);
 +    return 1;
 +  }
 +  needCommit = sqlite3_get_autocommit(p->db);
 +  if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
 +  do{
 +    int startLine = sCtx.nLine;
 +    for(i=0; i<nCol; i++){
 +      char *z = xRead(&sCtx);
 +      /*
 +      ** Did we reach end-of-file before finding any columns?
 +      ** If so, stop instead of NULL filling the remaining columns.
 +      */
 +      if( z==0 && i==0 ) break;
 +      /*
 +      ** Did we reach end-of-file OR end-of-line before finding any
 +      ** columns in ASCII mode?  If so, stop instead of NULL filling
 +      ** the remaining columns.
 +      */
 +      if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
 +      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);
 +        i += 2;
 +        while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
        }
      }
 -    sqlite3_finalize(pStmt);
 -    if( i==0 || tnum==0 ){
 -      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
 -      rc = 1;
 -      sqlite3_free(zCollist);
 -      goto meta_command_exit;
 +    if( sCtx.cTerm==sCtx.cColSep ){
 +      do{
 +        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);
      }
 -    if( lenPK==0 ) lenPK = 100000;
 -    zSql = sqlite3_mprintf(
 -          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
 -          azArg[2], zCollist, lenPK, zCollist);
 -    sqlite3_free(zCollist);
 -    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
 -    if( rc==SQLITE_OK ){
 -      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));
 +    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));
 +        sCtx.nErr++;
        }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"
 -        );
 +        sCtx.nRow++;
        }
 -    }else{
 -      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
 -      rc = 1;
      }
 -    sqlite3_free(zSql);
 -  }else
 -#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
 +  }while( sCtx.cTerm!=EOF );
  
 -#ifdef SQLITE_ENABLE_IOTRACE
 -  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
 -    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
 -    if( iotrace && iotrace!=stdout ) fclose(iotrace);
 -    iotrace = 0;
 -    if( nArg<2 ){
 -      sqlite3IoTrace = 0;
 -    }else if( strcmp(azArg[1], "-")==0 ){
 -      sqlite3IoTrace = iotracePrintf;
 -      iotrace = stdout;
 -    }else{
 -      iotrace = fopen(azArg[1], "w");
 -      if( iotrace==0 ){
 -        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
 -        sqlite3IoTrace = 0;
 -        rc = 1;
 -      }else{
 -        sqlite3IoTrace = iotracePrintf;
 -      }
 -    }
 -  }else
 -#endif
 +  import_cleanup(&sCtx);
 +  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);
 +  }
 +  return 0;
 +}
  
 -  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
 -    static const struct {
 -       const char *zLimitName;   /* Name of a limit */
 -       int limitCode;            /* Integer code for that limit */
 -    } aLimit[] = {
 -      { "length",                SQLITE_LIMIT_LENGTH                    },
 -      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
 -      { "column",                SQLITE_LIMIT_COLUMN                    },
 -      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
 -      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
 -      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
 -      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
 -      { "attached",              SQLITE_LIMIT_ATTACHED                  },
 -      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
 -      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
 -      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
 -      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
 -    };
 -    int i, n2;
 -    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));
 +
 +/*****************
 + * The .imposter, .iotrace, limit, lint, .load and .log commands
 + */
 +CONDITION_COMMAND( imposter !defined(SQLITE_OMIT_TEST_CONTROL) );
 +CONDITION_COMMAND( iotrace defined(SQLITE_ENABLE_IOTRACE) );
 +CONDITION_COMMAND( load !defined(SQLITE_OMIT_LOAD_EXTENSION) );
 +COLLECT_HELP_TEXT[
 +  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
 +  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
 +  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
 +  ".lint OPTIONS            Report potential schema issues.",
 +  "     Options:",
 +  "        fkey-indexes     Find missing foreign key indexes",
 +  ".load FILE ?ENTRY?       Load an extension library",
 +  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
 +];
 +DISPATCHABLE_COMMAND( imposter ? 3 3 ){
 +  int rc = 0;
 +  char *zSql;
 +  char *zCollist = 0;
 +  sqlite3_stmt *pStmt;
 +  int tnum = 0;
 +  int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
 +  int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
 +  int i;
 +  if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
 +    utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
 +                "       .imposter off\n");
 +    /* Also allowed, but not documented:
 +    **
 +    **    .imposter TABLE IMPOSTER
 +    **
 +    ** where TABLE is a WITHOUT ROWID table.  In that case, the
 +    ** imposter is another WITHOUT ROWID table with the columns in
 +    ** storage order. */
 +    return 1;
 +  }
 +  open_db(p, 0);
 +  if( nArg==2 ){
 +    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
 +    return 0;
 +  }
 +  zSql = sqlite3_mprintf(
 +                         "SELECT rootpage, 0 FROM sqlite_schema"
 +                         " WHERE name='%q' AND type='index'"
 +                         "UNION ALL "
 +                         "SELECT rootpage, 1 FROM sqlite_schema"
 +                         " WHERE name='%q' AND type='table'"
 +                         "   AND sql LIKE '%%without%%rowid%%'",
 +                         azArg[1], azArg[1]
 +                         );
 +  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 +  sqlite3_free(zSql);
 +  if( sqlite3_step(pStmt)==SQLITE_ROW ){
 +    tnum = sqlite3_column_int(pStmt, 0);
 +    isWO = sqlite3_column_int(pStmt, 1);
 +  }
 +  sqlite3_finalize(pStmt);
 +  zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
 +  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 +  sqlite3_free(zSql);
 +  i = 0;
 +  while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
 +    char zLabel[20];
 +    const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
 +    i++;
 +    if( zCol==0 ){
 +      if( sqlite3_column_int(pStmt,1)==-1 ){
 +        zCol = "_ROWID_";
 +      }else{
 +        sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
 +        zCol = zLabel;
        }
 -    }else if( nArg>3 ){
 -      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
 -      rc = 1;
 -      goto meta_command_exit;
 +    }
 +    if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
 +      lenPK = (int)strlen(zCollist);
 +    }
 +    if( zCollist==0 ){
 +      zCollist = sqlite3_mprintf("\"%w\"", zCol);
      }else{
 -      int iLimit = -1;
 -      n2 = strlen30(azArg[1]);
 -      for(i=0; i<ArraySize(aLimit); i++){
 -        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
 -          if( iLimit<0 ){
 -            iLimit = i;
 -          }else{
 -            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
 -            rc = 1;
 -            goto meta_command_exit;
 -          }
 +      zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
 +    }
 +  }
 +  sqlite3_finalize(pStmt);
 +  if( i==0 || tnum==0 ){
 +    utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
 +    sqlite3_free(zCollist);
 +    return 1;
 +  }
 +  if( lenPK==0 ) lenPK = 100000;
 +  zSql = sqlite3_mprintf(
 +                         "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
 +                         azArg[2], zCollist, lenPK, zCollist);
 +  sqlite3_free(zCollist);
 +  rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
 +  if( rc==SQLITE_OK ){
 +    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));
 +    }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"
 +                 );
 +    }
 +  }else{
 +    raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
 +  }
 +  sqlite3_free(zSql);
 +  return rc != 0;
 +}
 +DISPATCHABLE_COMMAND( iotrace ? 2 2 ){
 +  SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
 +  if( iotrace && iotrace!=stdout ) fclose(iotrace);
 +  iotrace = 0;
 +  if( nArg<2 ){
 +    sqlite3IoTrace = 0;
 +  }else if( strcmp(azArg[1], "-")==0 ){
 +    sqlite3IoTrace = iotracePrintf;
 +    iotrace = stdout;
 +  }else{
 +    iotrace = fopen(azArg[1], "w");
 +    if( iotrace==0 ){
 +      utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
 +      sqlite3IoTrace = 0;
 +      return 1;
 +    }else{
 +      sqlite3IoTrace = iotracePrintf;
 +    }
 +  }
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( limits 5 1 3 ){
 +  static const struct {
 +    const char *zLimitName;   /* Name of a limit */
 +    int limitCode;            /* Integer code for that limit */
 +  } aLimit[] = {
 +    { "length",                SQLITE_LIMIT_LENGTH                    },
 +    { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
 +    { "column",                SQLITE_LIMIT_COLUMN                    },
 +    { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
 +    { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
 +    { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
 +    { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
 +    { "attached",              SQLITE_LIMIT_ATTACHED                  },
 +    { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
 +    { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
 +    { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
 +    { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
 +  };
 +  int i, n2;
 +  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));
 +    }
 +  }else if( nArg>3 ){
 +    raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
 +    return 1;
 +  }else{
 +    int iLimit = -1;
 +    n2 = strlen30(azArg[1]);
 +    for(i=0; i<ArraySize(aLimit); i++){
 +      if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
 +        if( iLimit<0 ){
 +          iLimit = i;
 +        }else{
 +          utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
 +          return 1;
          }
        }
 -      if( iLimit<0 ){
 -        utf8_printf(stderr, "unknown limit: \"%s\"\n"
 -                        "enter \".limits\" with no arguments for a list.\n",
 -                         azArg[1]);
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -      if( nArg==3 ){
 -        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));
      }
 -  }else
 -
 -  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
 -    open_db(p, 0);
 -    lintDotCommand(p, azArg, nArg);
 -  }else
 -
 -#ifndef SQLITE_OMIT_LOAD_EXTENSION
 -  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
 -    const char *zFile, *zProc;
 -    char *zErrMsg = 0;
 -    failIfSafeMode(p, "cannot run .load in safe mode");
 -    if( nArg<2 ){
 -      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
 -      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]);
 +      return 1;
      }
 -    zFile = azArg[1];
 -    zProc = nArg>=3 ? azArg[2] : 0;
 -    open_db(p, 0);
 -    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
 -    if( rc!=SQLITE_OK ){
 -      utf8_printf(stderr, "Error: %s\n", zErrMsg);
 -      sqlite3_free(zErrMsg);
 -      rc = 1;
 +    if( nArg==3 ){
 +      sqlite3_limit(p->db, aLimit[iLimit].limitCode,
 +                    (int)integerValue(azArg[2]));
      }
 -  }else
 -#endif
 +    printf("%20s %d\n", aLimit[iLimit].zLimitName,
 +           sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
 +  }
 +  return 0;
 +}
  
 -  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
 -    failIfSafeMode(p, "cannot run .log in safe mode");
 -    if( nArg!=2 ){
 -      raw_printf(stderr, "Usage: .log FILENAME\n");
 -      rc = 1;
 -    }else{
 -      const char *zFile = azArg[1];
 -      output_file_close(p->pLog);
 -      p->pLog = output_file_open(zFile, 0);
 -    }
 -  }else
 +DISPATCHABLE_COMMAND( lint 3 1 0 ){
 +  open_db(p, 0);
 +  int n = (nArg>=2 ? strlen30(azArg[1]) : 0);
 +  if( n>0 && !sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ){
 +    return lintFkeyIndexes(p, azArg, nArg);
 +  }
 +  raw_printf(stderr,
 +             "Usage %s sub-command ?switches...?\n"
 +             "Where sub-commands are:\n"
 +             "    fkey-indexes\n", azArg[0]);
 +  return 1;
 +}
  
 -  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
 -    const char *zMode = nArg>=2 ? azArg[1] : "";
 -    int n2 = strlen30(zMode);
 -    int c2 = zMode[0];
 -    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
 -      p->mode = MODE_Line;
 -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 -    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
 -      p->mode = MODE_Column;
 -      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
 -        p->showHeader = 1;
 +DISPATCHABLE_COMMAND( load ? 2 3 ){
 +  const char *zFile, *zProc;
 +  char *zErrMsg = 0;
 +  failIfSafeMode(p, "cannot run .load in safe mode");
 +  zFile = azArg[1];
 +  zProc = nArg>=3 ? azArg[2] : 0;
 +  open_db(p, 0);
 +  if( SQLITE_OK!=sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg)){
 +    utf8_printf(stderr, "Error: %s\n", zErrMsg);
 +    sqlite3_free(zErrMsg);
 +    return 1;
 +  }
 +  return 0;
 +}
 +
 +DISPATCHABLE_COMMAND( log ? 2 2 ){
 +  const char *zFile = azArg[1];
 +  failIfSafeMode(p, "cannot run .log in safe mode");
 +  output_file_close(p->pLog);
 +  p->pLog = output_file_open(zFile, 0);
 +  return 0;
 +}
 +
 +/*****************
 + * The .mode command
 + */
 +COLLECT_HELP_TEXT[
 +  ".mode MODE ?TABLE?       Set output mode",
 +  "   MODE is one of:",
 +  "     ascii     Columns/rows delimited by 0x1F and 0x1E",
 +  "     box       Tables using unicode box-drawing characters",
 +  "     csv       Comma-separated values",
 +  "     column    Output in columns.  (See .width)",
 +  "     html      HTML <table> code",
 +  "     insert    SQL insert statements for TABLE",
 +  "     json      Results in a JSON array",
 +  "     line      One value per line",
 +  "     list      Values delimited by \"|\"",
 +  "     markdown  Markdown table format",
 +  "     quote     Escape answers as for SQL",
 +  "     table     ASCII-art table",
 +  "     tabs      Tab-separated values",
 +  "     tcl       TCL list elements",
 +];
 +DISPATCHABLE_COMMAND( mode ? 2 3 ){
 +  const char *zMode = nArg>=2 ? azArg[1] : "";
 +  int n2 = strlen30(zMode);
 +  int c2 = zMode[0];
 +  if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
 +    p->mode = MODE_Line;
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 +  }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
 +    p->mode = MODE_Column;
 +    if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
 +      p->showHeader = 1;
 +    }
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 +  }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
 +    p->mode = MODE_List;
 +    sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 +  }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
 +    p->mode = MODE_Html;
 +  }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
 +    p->mode = MODE_Tcl;
 +    sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 +  }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
 +    p->mode = MODE_Csv;
 +    sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
 +  }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
 +    p->mode = MODE_List;
 +    sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
 +  }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
 +    p->mode = MODE_Insert;
 +    set_table_name(p, nArg>=3 ? azArg[2] : "table");
 +  }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
 +    p->mode = MODE_Quote;
 +    sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 +  }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
 +    p->mode = MODE_Ascii;
 +    sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
 +  }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
 +    p->mode = MODE_Markdown;
 +  }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
 +    p->mode = MODE_Table;
 +  }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
 +    p->mode = MODE_Box;
 +  }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
 +    p->mode = MODE_Json;
 +  }else if( nArg==1 ){
 +    raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
 +  }else{
 +    raw_printf(stderr, "Error: mode should be one of: "
 +               "ascii box column csv html insert json line\n"
 +               " list markdown quote table tabs tcl\n");
 +    return 1;
 +  }
 +  p->cMode = p->mode;
 +  return 0;
 +}
 +
 +/*****************
 + * The .oom command
 + */
 +CONDITION_COMMAND( oom defined(SQLITE_DEBUG) );
 +COLLECT_HELP_TEXT[
 +  ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
 +];
 +DISPATCHABLE_COMMAND( oom ? 1 4 ){
 +  int i;
 +  for(i=1; i<nArg; i++){
 +    const char *z = azArg[i];
 +    if( z[0]=='-' && z[1]=='-' ) z++;
 +    if( strcmp(z,"-repeat")==0 ){
 +      if( i==nArg-1 ){
 +        raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
 +        return 1;
 +      }else{
 +        oomRepeat = (int)integerValue(azArg[++i]);
        }
 -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 -    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
 -      p->mode = MODE_List;
 -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
 -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 -    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
 -      p->mode = MODE_Html;
 -    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
 -      p->mode = MODE_Tcl;
 -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
 -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 -    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
 -      p->mode = MODE_Csv;
 -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
 -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
 -    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
 -      p->mode = MODE_List;
 -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
 -    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
 -      p->mode = MODE_Insert;
 -      set_table_name(p, nArg>=3 ? azArg[2] : "table");
 -    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
 -      p->mode = MODE_Quote;
 -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
 -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
 -    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
 -      p->mode = MODE_Ascii;
 -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
 -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
 -    }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
 -      p->mode = MODE_Markdown;
 -    }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
 -      p->mode = MODE_Table;
 -    }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
 -      p->mode = MODE_Box;
 -    }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
 -      p->mode = MODE_Json;
 -    }else if( nArg==1 ){
 -      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
 +    }else if( IsDigit(z[0]) ){
 +      oomCounter = (int)integerValue(azArg[i]);
      }else{
 -      raw_printf(stderr, "Error: mode should be one of: "
 -         "ascii box column csv html insert json line list markdown "
 -         "quote table tabs tcl\n");
 -      rc = 1;
 +      raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
 +      raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
 +      return 1;
      }
 -    p->cMode = p->mode;
 -  }else
 +  }
 +  raw_printf(p->out, "oomCounter = %d\n", oomCounter);
 +  raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
 +  return 0;
 +}
  
 -  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
 -    if( nArg!=2 ){
 -      raw_printf(stderr, "Usage: .nonce NONCE\n");
 -      rc = 1;
 -    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
 -      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n", p->lineno, azArg[1]);
 -      exit(1);
 +/*****************
 + * The .open, .nonce and .nullvalue commands
 + */
 +COLLECT_HELP_TEXT[
 +  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
 +  "     Options:",
 +  "        --append        Use appendvfs to append database to the end of FILE",
 +#ifndef SQLITE_OMIT_DESERIALIZE
 +  "        --deserialize   Load into memory using sqlite3_deserialize()",
 +  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
 +  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
 +#endif
 +  "        --new           Initialize FILE to an empty database",
 +  "        --nofollow      Do not follow symbolic links",
 +  "        --readonly      Open FILE readonly",
 +  "        --zip           FILE is a ZIP archive",
 +  ".nonce STRING            Disable safe mode for one command if nonce matches",
 +  ".nullvalue STRING        Use STRING in place of NULL values",
 +];
 +DISPATCHABLE_COMMAND( open 3 1 0 ){
 +  char *zNewFilename = 0;  /* Name of the database file to open */
 +  int iName = 1;           /* Index in azArg[] of the filename */
 +  int newFlag = 0;         /* True to delete file before opening */
-   /* Close the existing database */
-   session_close_all(p, -1);
-   close_db(p->db);
-   p->db = 0;
-   p->pAuxDb->zDbFilename = 0;
-   sqlite3_free(p->pAuxDb->zFreeOnClose);
-   p->pAuxDb->zFreeOnClose = 0;
-   p->openMode = SHELL_OPEN_UNSPEC;
-   p->openFlags = 0;
-   p->szMax = 0;
++  int openMode = SHELL_OPEN_UNSPEC;
 +  /* Check for command-line arguments */
 +  for(iName=1; iName<nArg; iName++){
 +    const char *z = azArg[iName];
 +    if( optionMatch(z,"new") ){
 +      newFlag = 1;
 +#ifdef SQLITE_HAVE_ZLIB
 +    }else if( optionMatch(z, "zip") ){
-       p->openMode = SHELL_OPEN_ZIPFILE;
++      openMode = SHELL_OPEN_ZIPFILE;
 +#endif
 +    }else if( optionMatch(z, "append") ){
-       p->openMode = SHELL_OPEN_APPENDVFS;
++      openMode = SHELL_OPEN_APPENDVFS;
 +    }else if( optionMatch(z, "readonly") ){
-       p->openMode = SHELL_OPEN_READONLY;
++      openMode = SHELL_OPEN_READONLY;
 +    }else if( optionMatch(z, "nofollow") ){
 +      p->openFlags |= SQLITE_OPEN_NOFOLLOW;
 +#ifndef SQLITE_OMIT_DESERIALIZE
 +    }else if( optionMatch(z, "deserialize") ){
-       p->openMode = SHELL_OPEN_DESERIALIZE;
++      openMode = SHELL_OPEN_DESERIALIZE;
 +    }else if( optionMatch(z, "hexdb") ){
-       p->openMode = SHELL_OPEN_HEXDB;
++      openMode = SHELL_OPEN_HEXDB;
 +    }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
 +      p->szMax = integerValue(azArg[++iName]);
 +#endif /* SQLITE_OMIT_DESERIALIZE */
 +    }else if( z[0]=='-' ){
 +      utf8_printf(stderr, "unknown option: %s\n", z);
 +      return 1;
 +    }else if( zNewFilename ){
 +      utf8_printf(stderr, "extra argument: \"%s\"\n", z);
 +      return 1;
      }else{
 -      p->bSafeMode = 0;
 -      return 0;  /* Return immediately to bypass the safe mode reset
 -                 ** at the end of this procedure */
 +      zNewFilename = sqlite3_mprintf("%s", z);
 +    }
 +  }
++
++  /* Close the existing database */
++  session_close_all(p, -1);
++  close_db(p->db);
++  p->db = 0;
++  p->pAuxDb->zDbFilename = 0;
++  sqlite3_free(p->pAuxDb->zFreeOnClose);
++  p->pAuxDb->zFreeOnClose = 0;
++  p->openMode = openMode;
++  p->openFlags = 0;
++  p->szMax = 0;
++
 +  /* If a filename is specified, try to open it first */
 +  if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
 +    if( newFlag && !p->bSafeMode ) shellDeleteFile(zNewFilename);
 +    if( p->bSafeMode
 +        && p->openMode!=SHELL_OPEN_HEXDB
 +        && zNewFilename
 +        && strcmp(zNewFilename,":memory:")!=0
 +        ){
 +      failIfSafeMode(p, "cannot open disk-based database files in safe mode");
      }
 -  }else
 -
 -  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
 -    if( nArg==2 ){
 -      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
 -                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
 +    p->pAuxDb->zDbFilename = zNewFilename;
 +    open_db(p, OPEN_DB_KEEPALIVE);
 +    if( p->db==0 ){
 +      utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
 +      sqlite3_free(zNewFilename);
      }else{
 -      raw_printf(stderr, "Usage: .nullvalue STRING\n");
 -      rc = 1;
 +      p->pAuxDb->zFreeOnClose = zNewFilename;
      }
 +  }
 +  if( p->db==0 ){
 +    /* As a fall-back open a TEMP database */
 +    p->pAuxDb->zDbFilename = 0;
 +    open_db(p, 0);
 +  }
 +  return 0;
 +}
 +
 +DISPATCHABLE_COMMAND( nonce ? 2 2 ){
 +  if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
 +    raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
 +               p->lineno, azArg[1]);
 +    exit(1);
 +  }
 +  /* Suspend safe mode for 1 meta-command after this. */
 +  p->bSafeModeFuture = 2;
 +  return 0;
 +}
 +
 +DISPATCHABLE_COMMAND( nullvalue ? 2 2 ){
 +  sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
 +                   "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
 +  return 0;
 +}
 +
 +/*****************
 + * The .parameter command
 + */
 +COLLECT_HELP_TEXT[
 +  ".parameter CMD ...       Manage SQL parameter bindings",
 +  "   clear                   Erase all bindings",
 +  "   init                    Initialize the TEMP table that holds bindings",
 +  "   list                    List the current parameter bindings",
 +  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
 +  "                           PARAMETER should start with one of: $ : @ ?",
 +  "   unset PARAMETER         Remove PARAMETER from the binding table",
 +];
 +DISPATCHABLE_COMMAND( parameter 4 2 4 ){
 +  int rc = 0;
 +  open_db(p,0);
 +
 +  /* .parameter clear
 +  ** Clear all bind parameters by dropping the TEMP table that holds them.
 +  */
 +  if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
 +    sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
 +                 0, 0, 0);
    }else
  
 -#ifdef SQLITE_DEBUG
 -  if( c=='o' && strcmp(azArg[0],"oom")==0 ){
 -    int i;
 -    for(i=1; i<nArg; i++){
 -      const char *z = azArg[i];
 -      if( z[0]=='-' && z[1]=='-' ) z++;
 -      if( strcmp(z,"-repeat")==0 ){
 -        if( i==nArg-1 ){
 -          raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
 -          rc = 1;
 -        }else{
 -          oomRepeat = (int)integerValue(azArg[++i]);
 -        }
 -      }else if( IsDigit(z[0]) ){
 -        oomCounter = (int)integerValue(azArg[i]);
 -      }else{
 -        raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
 -        raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
 -        rc = 1;
 -      }
 +  /* .parameter list
 +  ** List all bind parameters.
 +  */
 +  if( nArg==2 && strcmp(azArg[1],"list")==0 ){
 +    sqlite3_stmt *pStmt = 0;
 +    int rx;
 +    int len = 0;
 +    rx = sqlite3_prepare_v2(p->db,
 +                            "SELECT max(length(key)) "
 +                            "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
 +    if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
 +      len = sqlite3_column_int(pStmt, 0);
 +      if( len>40 ) len = 40;
      }
 -    if( rc==0 ){
 -      raw_printf(p->out, "oomCounter = %d\n", oomCounter);
 -      raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
 +    sqlite3_finalize(pStmt);
 +    pStmt = 0;
 +    if( len ){
 +      rx = sqlite3_prepare_v2(p->db,
 +                              "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));
 +      }
 +      sqlite3_finalize(pStmt);
      }
    }else
 -#endif /* SQLITE_DEBUG */
  
 -  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
 -    char *zNewFilename = 0;  /* Name of the database file to open */
 -    int iName = 1;           /* Index in azArg[] of the filename */
 -    int newFlag = 0;         /* True to delete file before opening */
 -    int openMode = SHELL_OPEN_UNSPEC;
 -
 -    /* Check for command-line arguments */
 -    for(iName=1; iName<nArg; iName++){
 -      const char *z = azArg[iName];
 -      if( optionMatch(z,"new") ){
 -        newFlag = 1;
 -#ifdef SQLITE_HAVE_ZLIB
 -      }else if( optionMatch(z, "zip") ){
 -        openMode = SHELL_OPEN_ZIPFILE;
 -#endif
 -      }else if( optionMatch(z, "append") ){
 -        openMode = SHELL_OPEN_APPENDVFS;
 -      }else if( optionMatch(z, "readonly") ){
 -        openMode = SHELL_OPEN_READONLY;
 -      }else if( optionMatch(z, "nofollow") ){
 -        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
 -#ifndef SQLITE_OMIT_DESERIALIZE
 -      }else if( optionMatch(z, "deserialize") ){
 -        openMode = SHELL_OPEN_DESERIALIZE;
 -      }else if( optionMatch(z, "hexdb") ){
 -        openMode = SHELL_OPEN_HEXDB;
 -      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
 -        p->szMax = integerValue(azArg[++iName]);
 -#endif /* SQLITE_OMIT_DESERIALIZE */
 -      }else if( z[0]=='-' ){
 -        utf8_printf(stderr, "unknown option: %s\n", z);
 -        rc = 1;
 -        goto meta_command_exit;
 -      }else if( zNewFilename ){
 -        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
 +  /* .parameter init
 +  ** Make sure the TEMP table used to hold bind parameters exists.
 +  ** Create it if necessary.
 +  */
 +  if( nArg==2 && strcmp(azArg[1],"init")==0 ){
 +    bind_table_init(p);
 +  }else
 +
 +  /* .parameter set NAME VALUE
 +  ** Set or reset a bind parameter.  NAME should be the full parameter
 +  ** name exactly as it appears in the query.  (ex: $abc, @def).  The
 +  ** VALUE can be in either SQL literal notation, or if not it will be
 +  ** understood to be a text string.
 +  */
 +  if( nArg==4 && strcmp(azArg[1],"set")==0 ){
 +    int rx;
 +    char *zSql;
 +    sqlite3_stmt *pStmt;
 +    const char *zKey = azArg[2];
 +    const char *zValue = azArg[3];
 +    bind_table_init(p);
 +    zSql = sqlite3_mprintf(
 +                "REPLACE INTO temp.sqlite_parameters(key,value)"
 +                "VALUES(%Q,%s);", zKey, zValue);
 +    if( zSql==0 ) shell_out_of_memory();
 +    pStmt = 0;
 +    rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 +    sqlite3_free(zSql);
 +    if( rx!=SQLITE_OK ){
 +      sqlite3_finalize(pStmt);
 +      pStmt = 0;
 +      zSql = sqlite3_mprintf(
 +                 "REPLACE INTO temp.sqlite_parameters(key,value)"
 +                 "VALUES(%Q,%Q);", zKey, zValue);
 +      if( zSql==0 ) shell_out_of_memory();
 +      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));
 +        sqlite3_finalize(pStmt);
 +        pStmt = 0;
          rc = 1;
 -        goto meta_command_exit;
 -      }else{
 -        zNewFilename = sqlite3_mprintf("%s", z);
        }
      }
 +    sqlite3_step(pStmt);
 +    sqlite3_finalize(pStmt);
 +  }else
  
 -    /* Close the existing database */
 -    session_close_all(p, -1);
 -    close_db(p->db);
 -    p->db = 0;
 -    p->pAuxDb->zDbFilename = 0;
 -    sqlite3_free(p->pAuxDb->zFreeOnClose);
 -    p->pAuxDb->zFreeOnClose = 0;
 -    p->openMode = openMode;
 -    p->openFlags = 0;
 -    p->szMax = 0;
 -
 -    /* If a filename is specified, try to open it first */
 -    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
 -      if( newFlag && !p->bSafeMode ) shellDeleteFile(zNewFilename);
 -      if( p->bSafeMode
 -       && p->openMode!=SHELL_OPEN_HEXDB
 -       && zNewFilename
 -       && strcmp(zNewFilename,":memory:")!=0
 -      ){
 -        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
 -      }
 -      p->pAuxDb->zDbFilename = zNewFilename;
 -      open_db(p, OPEN_DB_KEEPALIVE);
 -      if( p->db==0 ){
 -        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
 -        sqlite3_free(zNewFilename);
 -      }else{
 -        p->pAuxDb->zFreeOnClose = zNewFilename;
 -      }
 -    }
 -    if( p->db==0 ){
 -      /* As a fall-back open a TEMP database */
 -      p->pAuxDb->zDbFilename = 0;
 -      open_db(p, 0);
 -    }
 +  /* .parameter unset NAME
 +  ** Remove the NAME binding from the parameter binding table, if it
 +  ** exists.
 +  */
 +  if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
 +    char *zSql = sqlite3_mprintf(
 +        "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
 +    if( zSql==0 ) shell_out_of_memory();
 +    sqlite3_exec(p->db, zSql, 0, 0, 0);
 +    sqlite3_free(zSql);
    }else
  
 -  if( (c=='o'
 -        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
 -   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
 -  ){
 -    char *zFile = 0;
 -    int bTxtMode = 0;
 -    int i;
 -    int eMode = 0;
 -    int bBOM = 0;
 -    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
 +  {  /* If no command name and arg count matches, show a syntax error */
 +    showHelp(p->out, "parameter");
 +    return 1;
 +  }
  
 -    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
 -    if( c=='e' ){
 -      eMode = 'x';
 -      bOnce = 2;
 -    }else if( strncmp(azArg[0],"once",n)==0 ){
 -      bOnce = 1;
 -    }
 -    for(i=1; i<nArg; i++){
 -      char *z = azArg[i];
 -      if( z[0]=='-' ){
 -        if( z[1]=='-' ) z++;
 -        if( strcmp(z,"-bom")==0 ){
 -          bBOM = 1;
 -        }else if( c!='e' && strcmp(z,"-x")==0 ){
 -          eMode = 'x';  /* spreadsheet */
 -        }else if( c!='e' && strcmp(z,"-e")==0 ){
 -          eMode = 'e';  /* text editor */
 +  return rc;
 +}
 +
 +/*****************
 + * The .print, .progress and .prompt commands
 + */
 +CONDITION_COMMAND( progress !defined(SQLITE_OMIT_PROGRESS_CALLBACK) );
 +COLLECT_HELP_TEXT[
 +  ".print STRING...         Print literal STRING",
 +  ".progress N              Invoke progress handler after every N opcodes",
 +  "   --limit N                 Interrupt after N progress callbacks",
 +  "   --once                    Do no more than one progress interrupt",
 +  "   --quiet|-q                No output except at interrupts",
 +  "   --reset                   Reset the count for each input and interrupt",
 +  ".prompt MAIN CONTINUE    Replace the standard prompts",
 +];
 +DISPATCHABLE_COMMAND( print 3 1 0 ){
 +  int i;
 +  for(i=1; i<nArg; i++){
 +    if( i>1 ) raw_printf(p->out, " ");
 +    utf8_printf(p->out, "%s", azArg[i]);
 +  }
 +  raw_printf(p->out, "\n");
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( progress 3 2 0 ){
 +  int i;
 +  int nn = 0;
 +  p->flgProgress = 0;
 +  p->mxProgress = 0;
 +  p->nProgress = 0;
 +  for(i=1; i<nArg; i++){
 +    const char *z = azArg[i];
 +    if( z[0]=='-' ){
 +      z++;
 +      if( z[0]=='-' ) z++;
 +      if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
 +        p->flgProgress |= SHELL_PROGRESS_QUIET;
 +        continue;
 +      }
 +      if( strcmp(z,"reset")==0 ){
 +        p->flgProgress |= SHELL_PROGRESS_RESET;
 +        continue;
 +      }
 +      if( strcmp(z,"once")==0 ){
 +        p->flgProgress |= SHELL_PROGRESS_ONCE;
 +        continue;
 +      }
 +      if( strcmp(z,"limit")==0 ){
 +        if( i+1>=nArg ){
 +          utf8_printf(stderr, "Error: missing argument on --limit\n");
 +          return 1;
          }else{
 -          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
 -                      azArg[i]);
 -          showHelp(p->out, azArg[0]);
 -          rc = 1;
 -          goto meta_command_exit;
 -        }
 -      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
 -        zFile = sqlite3_mprintf("%s", z);
 -        if( zFile[0]=='|' ){
 -          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
 -          break;
 +          p->mxProgress = (int)integerValue(azArg[++i]);
          }
 -      }else{
 -        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
 -                    azArg[i]);
 -        showHelp(p->out, azArg[0]);
 -        rc = 1;
 -        sqlite3_free(zFile);
 -        goto meta_command_exit;
 +        continue;
 +      }
 +      utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
 +      return 1;
 +    }else{
 +      nn = (int)integerValue(z);
 +    }
 +  }
 +  open_db(p, 0);
 +  sqlite3_progress_handler(p->db, nn, progress_handler, p);
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( prompt ? 2 3 ){
 +  if( nArg >= 2) {
 +    strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
 +  }
 +  if( nArg >= 3) {
 +    strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
 +  }
 +  return 0;
 +}
 +
 +/*****************
 + * The .read, .recover and .restore commands
 + */
 +CONDITION_COMMAND( recover !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) );
 +COLLECT_HELP_TEXT[
 +  ".read FILE               Read input from FILE",
 +  ".recover                 Recover as much data as possible from corrupt db.",
 +  "   --freelist-corrupt       Assume the freelist is corrupt",
 +  "   --recovery-db NAME       Store recovery metadata in database file NAME",
 +  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
 +  "   --no-rowids              Do not attempt to recover rowid values",
 +  "                            that are not also INTEGER PRIMARY KEYs",
 +  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
 +];
 +DISPATCHABLE_COMMAND( read 3 2 2 ){
 +  int rc = 0;
 +  FILE *inSaved = p->in;
 +  int savedLineno = p->lineno;
 +  failIfSafeMode(p, "cannot run .read in safe mode");
 +  if( azArg[1][0]=='|' ){
 +#ifdef SQLITE_OMIT_POPEN
 +    raw_printf(stderr, "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]);
 +      rc = 1;
 +    }else{
 +      rc = process_input(p);
 +      pclose(p->in);
 +    }
 +#endif
 +  }else if( (p->in = openChrSource(azArg[1]))==0 ){
 +    utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
 +    rc = 1;
 +  }else{
 +    rc = process_input(p);
 +    fclose(p->in);
 +  }
 +  p->in = inSaved;
 +  p->lineno = savedLineno;
 +  return rc;
 +}
 +
 +/*
 +** This command is invoked to recover data from the database. A script
 +** to construct a new database containing all recovered data is output
 +** on stream pState->out.
 +*/
 +DISPATCHABLE_COMMAND( recover ? 1 7 ){
 +  open_db(p, 0);
 +  int rc = SQLITE_OK;
 +  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
 +  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
 +  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
 +  const char *zRecoveryDb = "";   /* Name of "recovery" database */
 +  const char *zLostAndFound = "lost_and_found";
 +  int i;
 +  int nOrphan = -1;
 +  RecoverTable *pOrphan = 0;
 +
 +  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
 +  int bRowids = 1;                /* 0 if --no-rowids */
 +  for(i=1; i<nArg; i++){
 +    char *z = azArg[i];
 +    int n;
 +    if( z[0]=='-' && z[1]=='-' ) z++;
 +    n = strlen30(z);
 +    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
 +      bFreelist = 0;
 +    }else
 +    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
 +      i++;
 +      zRecoveryDb = azArg[i];
 +    }else
 +    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
 +      i++;
 +      zLostAndFound = azArg[i];
 +    }else
 +    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
 +      bRowids = 0;
 +    }
 +    else{
 +      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 
 +      showHelp(p->out, azArg[0]);
 +      return 1;
 +    }
 +  }
 +
 +  shellExecPrintf(p->db, &rc,
 +    /* Attach an in-memory database named 'recovery'. Create an indexed 
 +    ** cache of the sqlite_dbptr virtual table. */
 +    "PRAGMA writable_schema = on;"
 +    "ATTACH %Q AS recovery;"
 +    "DROP TABLE IF EXISTS recovery.dbptr;"
 +    "DROP TABLE IF EXISTS recovery.freelist;"
 +    "DROP TABLE IF EXISTS recovery.map;"
 +    "DROP TABLE IF EXISTS recovery.schema;"
 +    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
 +  );
 +
 +  if( bFreelist ){
 +    shellExec(p->db, &rc,
 +      "WITH trunk(pgno) AS ("
 +      "  SELECT shell_int32("
 +      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
 +      "      WHERE x>0"
 +      "    UNION"
 +      "  SELECT shell_int32("
 +      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
 +      "      FROM trunk WHERE x>0"
 +      "),"
 +      "freelist(data, n, freepgno) AS ("
 +      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
 +      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
 +      "    UNION ALL"
 +      "  SELECT data, n-1, shell_int32(data, 2+n) "
 +      "      FROM freelist WHERE n>=0"
 +      ")"
 +      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
 +    );
 +  }
 +
 +  /* If this is an auto-vacuum database, add all pointer-map pages to
 +  ** the freelist table. Do this regardless of whether or not 
 +  ** --freelist-corrupt was specified.  */
 +  shellExec(p->db, &rc, 
 +    "WITH ptrmap(pgno) AS ("
 +    "  SELECT 2 WHERE shell_int32("
 +    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
 +    "  )"
 +    "    UNION ALL "
 +    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
 +    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
 +    ")"
 +    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
 +  );
 +
 +  shellExec(p->db, &rc, 
 +    "CREATE TABLE recovery.dbptr("
 +    "      pgno, child, PRIMARY KEY(child, pgno)"
 +    ") WITHOUT ROWID;"
 +    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
 +    "    SELECT * FROM sqlite_dbptr"
 +    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
 +
 +    /* Delete any pointer to page 1. This ensures that page 1 is considered
 +    ** a root page, regardless of how corrupt the db is. */
 +    "DELETE FROM recovery.dbptr WHERE child = 1;"
 +
 +    /* Delete all pointers to any pages that have more than one pointer
 +    ** to them. Such pages will be treated as root pages when recovering
 +    ** data.  */
 +    "DELETE FROM recovery.dbptr WHERE child IN ("
 +    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
 +    ");"
 +
 +    /* Create the "map" table that will (eventually) contain instructions
 +    ** for dealing with each page in the db that contains one or more 
 +    ** records. */
 +    "CREATE TABLE recovery.map("
 +      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
 +    ");"
 +
 +    /* Populate table [map]. If there are circular loops of pages in the
 +    ** database, the following adds all pages in such a loop to the map
 +    ** as individual root pages. This could be handled better.  */
 +    "WITH pages(i, maxlen) AS ("
 +    "  SELECT page_count, ("
 +    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
 +    "  ) FROM pragma_page_count WHERE page_count>0"
 +    "    UNION ALL"
 +    "  SELECT i-1, ("
 +    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
 +    "  ) FROM pages WHERE i>=2"
 +    ")"
 +    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
 +    "  SELECT i, maxlen, NULL, ("
 +    "    WITH p(orig, pgno, parent) AS ("
 +    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
 +    "        UNION "
 +    "      SELECT i, p.parent, "
 +    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
 +    "    )"
 +    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
 +    ") "
 +    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
 +    "UPDATE recovery.map AS o SET intkey = ("
 +    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
 +    ");"
 +
 +    /* Extract data from page 1 and any linked pages into table
 +    ** recovery.schema. With the same schema as an sqlite_schema table.  */
 +    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
 +    "INSERT INTO recovery.schema SELECT "
 +    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
 +    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
 +    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
 +    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
 +    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
 +    "FROM sqlite_dbdata WHERE pgno IN ("
 +    "  SELECT pgno FROM recovery.map WHERE root=1"
 +    ")"
 +    "GROUP BY pgno, cell;"
 +    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
 +  );
 +
 +  /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 
 +  ** CREATE TABLE statements that extracted from the existing schema.  */
 +  if( rc==SQLITE_OK ){
 +    sqlite3_stmt *pStmt = 0;
 +    /* ".recover" might output content in an order which causes immediate
 +    ** foreign key constraints to be violated. So disable foreign-key
 +    ** constraint enforcement to prevent problems when running the output
 +    ** script. */
 +    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
 +    raw_printf(p->out, "BEGIN;\n");
 +    raw_printf(p->out, "PRAGMA writable_schema = on;\n");
 +    shellPrepare(p->db, &rc,
 +        "SELECT sql FROM recovery.schema "
 +        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
 +    );
 +    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
 +      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
 +      raw_printf(p->out, "CREATE TABLE IF NOT EXISTS %s;\n", 
 +          &zCreateTable[12]
 +      );
 +    }
 +    shellFinalize(&rc, pStmt);
 +  }
 +
 +  /* Figure out if an orphan table will be required. And if so, how many
 +  ** user columns it should contain */
 +  shellPrepare(p->db, &rc, 
 +      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
 +      , &pLoop
 +  );
 +  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
 +    nOrphan = sqlite3_column_int(pLoop, 0);
 +  }
 +  shellFinalize(&rc, pLoop);
 +  pLoop = 0;
 +
 +  shellPrepare(p->db, &rc,
 +      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
 +  );
 +
 +  shellPrepare(p->db, &rc,
 +      "SELECT max(field), group_concat(shell_escape_crnl(quote"
 +      "(case when (? AND field<0) then NULL else value end)"
 +      "), ', ')"
 +      ", min(field) "
 +      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
 +      "GROUP BY cell", &pCells
 +  );
 +
 +  /* Loop through each root page. */
 +  shellPrepare(p->db, &rc, 
 +      "SELECT root, intkey, max(maxlen) FROM recovery.map" 
 +      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
 +      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
 +      ")", &pLoop
 +  );
 +  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
 +    int iRoot = sqlite3_column_int(pLoop, 0);
 +    int bIntkey = sqlite3_column_int(pLoop, 1);
 +    int nCol = sqlite3_column_int(pLoop, 2);
 +    int bNoop = 0;
 +    RecoverTable *pTab;
 +
 +    assert( bIntkey==0 || bIntkey==1 );
 +    pTab = recoverFindTable(p, &rc, iRoot, bIntkey, nCol, &bNoop);
 +    if( bNoop || rc ) continue;
 +    if( pTab==0 ){
 +      if( pOrphan==0 ){
 +        pOrphan = recoverOrphanTable(p, &rc, zLostAndFound, nOrphan);
        }
 +      pTab = pOrphan;
 +      if( pTab==0 ) break;
      }
 -    if( zFile==0 ) zFile = sqlite3_mprintf("stdout");
 -    if( bOnce ){
 -      p->outCount = 2;
 -    }else{
 -      p->outCount = 0;
 -    }
 -    output_reset(p);
 -#ifndef SQLITE_NOHAVE_SYSTEM
 -    if( eMode=='e' || eMode=='x' ){
 -      p->doXdgOpen = 1;
 -      outputModePush(p);
 -      if( eMode=='x' ){
 -        /* spreadsheet mode.  Output as CSV. */
 -        newTempFile(p, "csv");
 -        ShellClearFlag(p, SHFLG_Echo);
 -        p->mode = MODE_Csv;
 -        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
 -        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
 -      }else{
 -        /* text editor mode */
 -        newTempFile(p, "txt");
 -        bTxtMode = 1;
 -      }
 -      sqlite3_free(zFile);
 -      zFile = sqlite3_mprintf("%s", p->zTempFile);
 +
 +    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
 +      raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
      }
 -#endif /* SQLITE_NOHAVE_SYSTEM */
 -    if( zFile[0]=='|' ){
 -#ifdef SQLITE_OMIT_POPEN
 -      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
 -      rc = 1;
 -      p->out = 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;
 -        rc = 1;
 -      }else{
 -        if( bBOM ) fprintf(p->out,"\357\273\277");
 -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
 -      }
 -#endif
 +    sqlite3_bind_int(pPages, 1, iRoot);
 +    if( bRowids==0 && pTab->iPk<0 ){
 +      sqlite3_bind_int(pCells, 1, 1);
      }else{
 -      p->out = output_file_open(zFile, bTxtMode);
 -      if( p->out==0 ){
 -        if( strcmp(zFile,"off")!=0 ){
 -          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
 -        }
 -        p->out = stdout;
 -        rc = 1;
 -      } else {
 -        if( bBOM ) fprintf(p->out,"\357\273\277");
 -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
 -      }
 +      sqlite3_bind_int(pCells, 1, 0);
      }
 -    sqlite3_free(zFile);
 -  }else
 -
 -  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
 -    open_db(p,0);
 -    if( nArg<=1 ) goto parameter_syntax_error;
 +    sqlite3_bind_int(pCells, 3, pTab->iPk);
  
 -    /* .parameter clear
 -    ** Clear all bind parameters by dropping the TEMP table that holds them.
 -    */
 -    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
 -      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
 -                   0, 0, 0);
 -    }else
 +    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
 +      int iPgno = sqlite3_column_int(pPages, 0);
 +      sqlite3_bind_int(pCells, 2, iPgno);
 +      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
 +        int nField = sqlite3_column_int(pCells, 0);
 +        int iMin = sqlite3_column_int(pCells, 2);
 +        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
  
 -    /* .parameter list
 -    ** List all bind parameters.
 -    */
 -    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
 -      sqlite3_stmt *pStmt = 0;
 -      int rx;
 -      int len = 0;
 -      rx = sqlite3_prepare_v2(p->db,
 -             "SELECT max(length(key)) "
 -             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
 -      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
 -        len = sqlite3_column_int(pStmt, 0);
 -        if( len>40 ) len = 40;
 -      }
 -      sqlite3_finalize(pStmt);
 -      pStmt = 0;
 -      if( len ){
 -        rx = sqlite3_prepare_v2(p->db,
 -             "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));
 +        RecoverTable *pTab2 = pTab;
 +        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
 +          if( pOrphan==0 ){
 +            pOrphan = recoverOrphanTable(p, &rc, zLostAndFound, nOrphan);
 +          }
 +          pTab2 = pOrphan;
 +          if( pTab2==0 ) break;
          }
 -        sqlite3_finalize(pStmt);
 -      }
 -    }else
 -
 -    /* .parameter init
 -    ** Make sure the TEMP table used to hold bind parameters exists.
 -    ** Create it if necessary.
 -    */
 -    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
 -      bind_table_init(p);
 -    }else
  
 -    /* .parameter set NAME VALUE
 -    ** Set or reset a bind parameter.  NAME should be the full parameter
 -    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
 -    ** VALUE can be in either SQL literal notation, or if not it will be
 -    ** understood to be a text string.
 -    */
 -    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
 -      int rx;
 -      char *zSql;
 -      sqlite3_stmt *pStmt;
 -      const char *zKey = azArg[2];
 -      const char *zValue = azArg[3];
 -      bind_table_init(p);
 -      zSql = sqlite3_mprintf(
 -                  "REPLACE INTO temp.sqlite_parameters(key,value)"
 -                  "VALUES(%Q,%s);", zKey, zValue);
 -      if( zSql==0 ) shell_out_of_memory();
 -      pStmt = 0;
 -      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
 -      sqlite3_free(zSql);
 -      if( rx!=SQLITE_OK ){
 -        sqlite3_finalize(pStmt);
 -        pStmt = 0;
 -        zSql = sqlite3_mprintf(
 -                   "REPLACE INTO temp.sqlite_parameters(key,value)"
 -                   "VALUES(%Q,%Q);", zKey, zValue);
 -        if( zSql==0 ) shell_out_of_memory();
 -        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));
 -          sqlite3_finalize(pStmt);
 -          pStmt = 0;
 -          rc = 1;
 +        nField = nField+1;
 +        if( pTab2==pOrphan ){
 +          raw_printf(p->out, 
 +              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
 +              pTab2->zQuoted, iRoot, iPgno, nField,
 +              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
 +          );
 +        }else{
 +          raw_printf(p->out, "INSERT INTO %s(%s) VALUES( %s );\n", 
 +              pTab2->zQuoted, pTab2->azlCol[nField], zVal
 +          );
          }
        }
 -      sqlite3_step(pStmt);
 -      sqlite3_finalize(pStmt);
 -    }else
 -
 -    /* .parameter unset NAME
 -    ** Remove the NAME binding from the parameter binding table, if it
 -    ** exists.
 -    */
 -    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
 -      char *zSql = sqlite3_mprintf(
 -          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
 -      if( zSql==0 ) shell_out_of_memory();
 -      sqlite3_exec(p->db, zSql, 0, 0, 0);
 -      sqlite3_free(zSql);
 -    }else
 -    /* If no command name matches, show a syntax error */
 -    parameter_syntax_error:
 -    showHelp(p->out, "parameter");
 -  }else
 -
 -  if( c=='p' && n>=3 && 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]);
 +      shellReset(&rc, pCells);
      }
 -    raw_printf(p->out, "\n");
 -  }else
 +    shellReset(&rc, pPages);
 +    if( pTab!=pOrphan ) recoverFreeTable(pTab);
 +  }
 +  shellFinalize(&rc, pLoop);
 +  shellFinalize(&rc, pPages);
 +  shellFinalize(&rc, pCells);
 +  recoverFreeTable(pOrphan);
  
 -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 -  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
 -    int i;
 -    int nn = 0;
 -    p->flgProgress = 0;
 -    p->mxProgress = 0;
 -    p->nProgress = 0;
 -    for(i=1; i<nArg; i++){
 -      const char *z = azArg[i];
 -      if( z[0]=='-' ){
 -        z++;
 -        if( z[0]=='-' ) z++;
 -        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
 -          p->flgProgress |= SHELL_PROGRESS_QUIET;
 -          continue;
 -        }
 -        if( strcmp(z,"reset")==0 ){
 -          p->flgProgress |= SHELL_PROGRESS_RESET;
 -          continue;
 -        }
 -        if( strcmp(z,"once")==0 ){
 -          p->flgProgress |= SHELL_PROGRESS_ONCE;
 -          continue;
 -        }
 -        if( strcmp(z,"limit")==0 ){
 -          if( i+1>=nArg ){
 -            utf8_printf(stderr, "Error: missing argument on --limit\n");
 -            rc = 1;
 -            goto meta_command_exit;
 -          }else{
 -            p->mxProgress = (int)integerValue(azArg[++i]);
 -          }
 -          continue;
 -        }
 -        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
 -        rc = 1;
 -        goto meta_command_exit;
 +  /* The rest of the schema */
 +  if( rc==SQLITE_OK ){
 +    sqlite3_stmt *pStmt = 0;
 +    shellPrepare(p->db, &rc, 
 +        "SELECT sql, name FROM recovery.schema "
 +        "WHERE sql NOT LIKE 'create table%'", &pStmt
 +    );
 +    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
 +      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
 +      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
 +        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
 +        char *zPrint = shellMPrintf(&rc, 
 +          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
 +          zName, zName, zSql
 +        );
 +        raw_printf(p->out, "%s;\n", zPrint);
 +        sqlite3_free(zPrint);
        }else{
 -        nn = (int)integerValue(z);
 +        raw_printf(p->out, "%s;\n", zSql);
        }
      }
 -    open_db(p, 0);
 -    sqlite3_progress_handler(p->db, nn, progress_handler, p);
 -  }else
 -#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
 -
 -  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
 -    if( nArg >= 2) {
 -      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
 -    }
 -    if( nArg >= 3) {
 -      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
 -    }
 -  }else
 +    shellFinalize(&rc, pStmt);
 +  }
  
 -  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
 -    rc = 2;
 -  }else
 +  if( rc==SQLITE_OK ){
 +    raw_printf(p->out, "PRAGMA writable_schema = off;\n");
 +    raw_printf(p->out, "COMMIT;\n");
 +  }
 +  sqlite3_exec(p->db, "DETACH recovery", 0, 0, 0);
 +  return rc;
 +}
  
 -  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
 -    FILE *inSaved = p->in;
 -    int savedLineno = p->lineno;
 -    failIfSafeMode(p, "cannot run .read in safe mode");
 -    if( nArg!=2 ){
 -      raw_printf(stderr, "Usage: .read FILE\n");
 -      rc = 1;
 -      goto meta_command_exit;
 +DISPATCHABLE_COMMAND( restore ? 2 3 ){
 +  int rc;
 +  const char *zSrcFile;
 +  const char *zDb;
 +  sqlite3 *pSrc;
 +  sqlite3_backup *pBackup;
 +  int nTimeout = 0;
 +
 +  failIfSafeMode(p, "cannot run .restore in safe mode");
 +  if( nArg==2 ){
 +    zSrcFile = azArg[1];
 +    zDb = "main";
 +  }else if( nArg==3 ){
 +    zSrcFile = azArg[2];
 +    zDb = azArg[1];
 +  }else{
 +    raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
 +    return 1;
 +  }
 +  rc = sqlite3_open(zSrcFile, &pSrc);
 +  if( rc!=SQLITE_OK ){
 +    utf8_printf(stderr, "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));
 +    close_db(pSrc);
 +    return 1;
 +  }
 +  while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
 +         || rc==SQLITE_BUSY  ){
 +    if( rc==SQLITE_BUSY ){
 +      if( nTimeout++ >= 3 ) break;
 +      sqlite3_sleep(100);
      }
 -    if( azArg[1][0]=='|' ){
 -#ifdef SQLITE_OMIT_POPEN
 -      raw_printf(stderr, "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]);
 -        rc = 1;
 -      }else{
 -        rc = process_input(p);
 -        pclose(p->in);
 -      }
 +  }
 +  sqlite3_backup_finish(pBackup);
 +  if( rc==SQLITE_DONE ){
 +    rc = 0;
 +  }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
 +    raw_printf(stderr, "Error: source database is busy\n");
 +    rc = 1;
 +  }else{
 +    utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
 +    rc = 1;
 +  }
 +  close_db(pSrc);
 +  return rc;
 +}
 +
 +/*****************
 + * The .scanstats and .schema commands
 + */
 +COLLECT_HELP_TEXT[
 +  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
 +  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
 +  "   Options:",
 +  "      --indent             Try to pretty-print the schema",
 +  "      --nosys              Omit objects whose names start with \"sqlite_\"",
 +];
 +DISPATCHABLE_COMMAND( scanstats ? 2 2 ){
 +    p->scanstatsOn = (u8)booleanValue(azArg[1]);
 +#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
 +    raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  #endif
 -    }else if( (p->in = openChrSource(azArg[1]))==0 ){
 -      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
 -      rc = 1;
 -    }else{
 -      rc = process_input(p);
 -      fclose(p->in);
 -    }
 -    p->in = inSaved;
 -    p->lineno = savedLineno;
 -  }else
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( schema ? 1 2 ){
 +  int rc;
 +  ShellText sSelect;
 +  ShellState data;
 +  char *zErrMsg = 0;
 +  const char *zDiv = "(";
 +  const char *zName = 0;
 +  int iSchema = 0;
 +  int bDebug = 0;
 +  int bNoSystemTabs = 0;
 +  int ii;
  
 -  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
 -    const char *zSrcFile;
 -    const char *zDb;
 -    sqlite3 *pSrc;
 -    sqlite3_backup *pBackup;
 -    int nTimeout = 0;
 -
 -    failIfSafeMode(p, "cannot run .restore in safe mode");
 -    if( nArg==2 ){
 -      zSrcFile = azArg[1];
 -      zDb = "main";
 -    }else if( nArg==3 ){
 -      zSrcFile = azArg[2];
 -      zDb = azArg[1];
 +  open_db(p, 0);
 +  memcpy(&data, p, sizeof(data));
 +  data.showHeader = 0;
 +  data.cMode = data.mode = MODE_Semi;
 +  initText(&sSelect);
 +  for(ii=1; ii<nArg; ii++){
 +    if( optionMatch(azArg[ii],"indent") ){
 +      data.cMode = data.mode = MODE_Pretty;
 +    }else if( optionMatch(azArg[ii],"debug") ){
 +      bDebug = 1;
 +    }else if( optionMatch(azArg[ii],"nosys") ){
 +      bNoSystemTabs = 1;
 +    }else if( azArg[ii][0]=='-' ){
 +      utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
 +      return 1;
 +    }else if( zName==0 ){
 +      zName = azArg[ii];
      }else{
 -      raw_printf(stderr, "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);
 -      close_db(pSrc);
 +      raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
        return 1;
      }
 -    open_db(p, 0);
 -    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
 -    if( pBackup==0 ){
 +  }
 +  if( zName!=0 ){
 +    int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
 +      || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
 +      || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
 +      || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
 +    if( isSchema ){
 +      char *new_argv[2], *new_colv[2];
 +      new_argv[0] = sqlite3_mprintf(
 +                                    "CREATE TABLE %s (\n"
 +                                    "  type text,\n"
 +                                    "  name text,\n"
 +                                    "  tbl_name text,\n"
 +                                    "  rootpage integer,\n"
 +                                    "  sql text\n"
 +                                    ")", zName);
 +      new_argv[1] = 0;
 +      new_colv[0] = "sql";
 +      new_colv[1] = 0;
 +      callback(&data, 1, new_argv, new_colv);
 +      sqlite3_free(new_argv[0]);
 +    }
 +  }
 +  if( zDiv ){
 +    sqlite3_stmt *pStmt = 0;
 +    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));
 -      close_db(pSrc);
 +      sqlite3_finalize(pStmt);
        return 1;
      }
 -    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
 -          || rc==SQLITE_BUSY  ){
 -      if( rc==SQLITE_BUSY ){
 -        if( nTimeout++ >= 3 ) break;
 -        sqlite3_sleep(100);
 -      }
 -    }
 -    sqlite3_backup_finish(pBackup);
 -    if( rc==SQLITE_DONE ){
 -      rc = 0;
 -    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
 -      raw_printf(stderr, "Error: source database is busy\n");
 -      rc = 1;
 -    }else{
 -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
 -      rc = 1;
 -    }
 -    close_db(pSrc);
 -  }else
 -
 -  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
 -    if( nArg==2 ){
 -      p->scanstatsOn = (u8)booleanValue(azArg[1]);
 -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
 -      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
 -#endif
 -    }else{
 -      raw_printf(stderr, "Usage: .scanstats on|off\n");
 -      rc = 1;
 -    }
 -  }else
 -
 -  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
 -    ShellText sSelect;
 -    ShellState data;
 -    char *zErrMsg = 0;
 -    const char *zDiv = "(";
 -    const char *zName = 0;
 -    int iSchema = 0;
 -    int bDebug = 0;
 -    int bNoSystemTabs = 0;
 -    int ii;
 -
 -    open_db(p, 0);
 -    memcpy(&data, p, sizeof(data));
 -    data.showHeader = 0;
 -    data.cMode = data.mode = MODE_Semi;
 -    initText(&sSelect);
 -    for(ii=1; ii<nArg; ii++){
 -      if( optionMatch(azArg[ii],"indent") ){
 -        data.cMode = data.mode = MODE_Pretty;
 -      }else if( optionMatch(azArg[ii],"debug") ){
 -        bDebug = 1;
 -      }else if( optionMatch(azArg[ii],"nosys") ){
 -        bNoSystemTabs = 1;
 -      }else if( azArg[ii][0]=='-' ){
 -        utf8_printf(stderr, "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");
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -    }
 -    if( zName!=0 ){
 -      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
 -                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
 -                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
 -                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
 -      if( isSchema ){
 -        char *new_argv[2], *new_colv[2];
 -        new_argv[0] = sqlite3_mprintf(
 -                      "CREATE TABLE %s (\n"
 -                      "  type text,\n"
 -                      "  name text,\n"
 -                      "  tbl_name text,\n"
 -                      "  rootpage integer,\n"
 -                      "  sql text\n"
 -                      ")", zName);
 -        new_argv[1] = 0;
 -        new_colv[0] = "sql";
 -        new_colv[1] = 0;
 -        callback(&data, 1, new_argv, new_colv);
 -        sqlite3_free(new_argv[0]);
 -      }
 -    }
 -    if( zDiv ){
 -      sqlite3_stmt *pStmt = 0;
 -      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));
 -        sqlite3_finalize(pStmt);
 -        rc = 1;
 -        goto meta_command_exit;
 -      }
 -      appendText(&sSelect, "SELECT sql FROM", 0);
 -      iSchema = 0;
 -      while( sqlite3_step(pStmt)==SQLITE_ROW ){
 -        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
 -        char zScNum[30];
 -        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
 -        appendText(&sSelect, zDiv, 0);
 -        zDiv = " UNION ALL ";
 -        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
 -        if( sqlite3_stricmp(zDb, "main")!=0 ){
 -          appendText(&sSelect, zDb, '\'');
 -        }else{
 -          appendText(&sSelect, "NULL", 0);
 -        }
 -        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
 -        appendText(&sSelect, zScNum, 0);
 -        appendText(&sSelect, " AS snum, ", 0);
 +    appendText(&sSelect, "SELECT sql FROM", 0);
 +    iSchema = 0;
 +    while( sqlite3_step(pStmt)==SQLITE_ROW ){
 +      const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
 +      char zScNum[30];
 +      sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
 +      appendText(&sSelect, zDiv, 0);
 +      zDiv = " UNION ALL ";
 +      appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
 +      if( sqlite3_stricmp(zDb, "main")!=0 ){
          appendText(&sSelect, zDb, '\'');
 -        appendText(&sSelect, " AS sname FROM ", 0);
 -        appendText(&sSelect, zDb, quoteChar(zDb));
 -        appendText(&sSelect, ".sqlite_schema", 0);
 -      }
 -      sqlite3_finalize(pStmt);
 -#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
 -      if( zName ){
 -        appendText(&sSelect,
 -           " UNION ALL SELECT shell_module_schema(name),"
 -           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
 -        0);
 -      }
 -#endif
 -      appendText(&sSelect, ") WHERE ", 0);
 -      if( zName ){
 -        char *zQarg = sqlite3_mprintf("%Q", zName);
 -        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
 -                    strchr(zName, '[') != 0;
 -        if( strchr(zName, '.') ){
 -          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
 -        }else{
 -          appendText(&sSelect, "lower(tbl_name)", 0);
 -        }
 -        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
 -        appendText(&sSelect, zQarg, 0);
 -        if( !bGlob ){
 -          appendText(&sSelect, " ESCAPE '\\' ", 0);
 -        }
 -        appendText(&sSelect, " AND ", 0);
 -        sqlite3_free(zQarg);
 -      }
 -      if( bNoSystemTabs ){
 -        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
 +      }else{
 +        appendText(&sSelect, "NULL", 0);
        }
 -      appendText(&sSelect, "sql IS NOT NULL"
 -                           " ORDER BY snum, rowid", 0);
 -      if( bDebug ){
 -        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
 +      appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
 +      appendText(&sSelect, zScNum, 0);
 +      appendText(&sSelect, " AS snum, ", 0);
 +      appendText(&sSelect, zDb, '\'');
 +      appendText(&sSelect, " AS sname FROM ", 0);
 +      appendText(&sSelect, zDb, quoteChar(zDb));
 +      appendText(&sSelect, ".sqlite_schema", 0);
 +    }
 +    sqlite3_finalize(pStmt);
 +#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
 +    if( zName ){
 +      appendText(&sSelect,
 +                 " UNION ALL SELECT shell_module_schema(name),"
 +                 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
 +                 0);
 +    }
 +#endif
 +    appendText(&sSelect, ") WHERE ", 0);
 +    if( zName ){
 +      char *zQarg = sqlite3_mprintf("%Q", zName);
 +      int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
 +        strchr(zName, '[') != 0;
 +      if( strchr(zName, '.') ){
 +        appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
        }else{
 -        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
 +        appendText(&sSelect, "lower(tbl_name)", 0);
 +      }
 +      appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
 +      appendText(&sSelect, zQarg, 0);
 +      if( !bGlob ){
 +        appendText(&sSelect, " ESCAPE '\\' ", 0);
        }
 -      freeText(&sSelect);
 +      appendText(&sSelect, " AND ", 0);
 +      sqlite3_free(zQarg);
      }
 -    if( zErrMsg ){
 -      utf8_printf(stderr,"Error: %s\n", zErrMsg);
 -      sqlite3_free(zErrMsg);
 -      rc = 1;
 -    }else if( rc != SQLITE_OK ){
 -      raw_printf(stderr,"Error: querying schema information\n");
 -      rc = 1;
 +    if( bNoSystemTabs ){
 +      appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
 +    }
 +    appendText(&sSelect, "sql IS NOT NULL"
 +               " ORDER BY snum, rowid", 0);
 +    if( bDebug ){
 +      utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
      }else{
 -      rc = 0;
 +      rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
      }
 -  }else
 -
 -  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
 -    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
 -    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
 -  }else
 +    freeText(&sSelect);
 +  }
 +  if( zErrMsg ){
 +    utf8_printf(stderr,"Error: %s\n", zErrMsg);
 +    sqlite3_free(zErrMsg);
 +    rc = 1;
 +  }else if( rc != SQLITE_OK ){
 +    raw_printf(stderr,"Error: querying schema information\n");
 +    rc = 1;
 +  }else{
 +    rc = 0;
 +  }
 +  return rc;
 +}
  
 -#if defined(SQLITE_ENABLE_SESSION)
 -  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
 -    struct AuxDb *pAuxDb = p->pAuxDb;
 -    OpenSession *pSession = &pAuxDb->aSession[0];
 -    char **azCmd = &azArg[1];
 -    int iSes = 0;
 -    int nCmd = nArg - 1;
 -    int i;
 -    if( nArg<=1 ) goto session_syntax_error;
 -    open_db(p, 0);
 -    if( nArg>=3 ){
 -      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
 -        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
 -      }
 -      if( iSes<pAuxDb->nSession ){
 -        pSession = &pAuxDb->aSession[iSes];
 -        azCmd++;
 -        nCmd--;
 -      }else{
 -        pSession = &pAuxDb->aSession[0];
 -        iSes = 0;
 -      }
 +/*****************
 + * The .selecttrace, .separator, .session and .sha3sum commands
 + */
 +CONDITION_COMMAND( session defined(SQLITE_ENABLE_SESSION) );
 +COLLECT_HELP_TEXT[
 +  ".separator COL ?ROW?     Change the column and row separators",
 +  ".session ?NAME? CMD ...  Create or control sessions",
 +  "   Subcommands:",
 +  "     attach TABLE             Attach TABLE",
 +  "     changeset FILE           Write a changeset into FILE",
 +  "     close                    Close one session",
 +  "     enable ?BOOLEAN?         Set or query the enable bit",
 +  "     filter GLOB...           Reject tables matching GLOBs",
 +  "     indirect ?BOOLEAN?       Mark or query the indirect status",
 +  "     isempty                  Query whether the session is empty",
 +  "     list                     List currently open session names",
 +  "     open DB NAME             Open a new session on DB",
 +  "     patchset FILE            Write a patchset into FILE",
 +  "   If ?NAME? is omitted, the first defined session is used.",
 +  ".sha3sum ...             Compute a SHA3 hash of database content",
 +  "    Options:",
 +  "      --schema              Also hash the sqlite_schema table",
 +  "      --sha3-224            Use the sha3-224 algorithm",
 +  "      --sha3-256            Use the sha3-256 algorithm (default)",
 +  "      --sha3-384            Use the sha3-384 algorithm",
 +  "      --sha3-512            Use the sha3-512 algorithm",
 +  "    Any other argument is a LIKE pattern for tables to hash",
 +];
 +DISPATCHABLE_COMMAND( selecttrace ? 1 0 ){
 +  unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
 +  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( separator ? 2 3 ){
 +  if( nArg>=2 ){
 +    sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
 +                     "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
 +  }
 +  if( nArg>=3 ){
 +    sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
 +                     "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
 +  }
 +  return 0;
 +}
 +DISPATCHABLE_COMMAND( session 3 2 0 ){
 +  int rc = 0;
 +  struct AuxDb *pAuxDb = p->pAuxDb;
 +  OpenSession *pSession = &pAuxDb->aSession[0];
 +  char **azCmd = &azArg[1];
 +  int iSes = 0;
 +  int nCmd = nArg - 1;
 +  int i;
 +  open_db(p, 0);
 +  if( nArg>=3 ){
 +    for(iSes=0; iSes<pAuxDb->nSession; iSes++){
 +      if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
 +    }
 +    if( iSes<pAuxDb->nSession ){
 +      pSession = &pAuxDb->aSession[iSes];
 +      azCmd++;
 +      nCmd--;
 +    }else{
 +      pSession = &pAuxDb->aSession[0];
 +      iSes = 0;
      }
 +  }
  
 -    /* .session attach TABLE
 -    ** Invoke the sqlite3session_attach() interface to attach a particular
 -    ** table so that it is never filtered.
 -    */
 -    if( strcmp(azCmd[0],"attach")==0 ){
 -      if( nCmd!=2 ) goto session_syntax_error;
 -      if( pSession->p==0 ){
 -        session_not_open:
 -        raw_printf(stderr, "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);
 -          rc = 0;
 -        }
 +  /* .session attach TABLE
 +  ** Invoke the sqlite3session_attach() interface to attach a particular
 +  ** table so that it is never filtered.
 +  */
 +  if( strcmp(azCmd[0],"attach")==0 ){
 +    if( nCmd!=2 ) goto session_syntax_error;
 +    if( pSession->p==0 ){
 +    session_not_open:
 +      raw_printf(stderr, "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);
 +        rc = 0;
        }
 -    }else
 +    }
 +  }else
  
      /* .session changeset FILE
      ** .session patchset FILE