]> git.lizzy.rs Git - sqlite3-cmake.git/blobdiff - src/shell.c
upgrade to 3.20.0
[sqlite3-cmake.git] / src / shell.c
index d36f1fdd19beb76e8702d2f8310a42d82456d17a..eaefe62012752ff2098be992e5fd7f23e0cdb56d 100644 (file)
@@ -1,3 +1,21 @@
+/* DO NOT EDIT!
+** This file is automatically generated by the script in the canonical
+** SQLite source tree at tool/mkshellc.tcl.  That script combines source
+** code from various constituent source files of SQLite into this single
+** "shell.c" file used to implement the SQLite command-line shell.
+**
+** Most of the code found below comes from the "src/shell.c.in" file in
+** the canonical SQLite source tree.  That main file contains "INCLUDE"
+** lines that specify other files in the canonical source tree that are
+** inserted to getnerate this complete program source file.
+**
+** The code from multiple files is combined into this single "shell.c"
+** source file to help make the command-line program easier to compile.
+**
+** To modify this program, get a copy of the canonical SQLite source tree,
+** edit the src/shell.c.in" and/or some of the other files that are included
+** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
+*/
 /*
 ** 2001 September 15
 **
 #endif
 
 /*
-** If requested, include the SQLite compiler options file for MSVC.
-*/
-#if defined(INCLUDE_MSVC_H)
-#include "msvc.h"
-#endif
+** Warning pragmas copied from msvc.h in the core.
+*/
+#if defined(_MSC_VER)
+#pragma warning(disable : 4054)
+#pragma warning(disable : 4055)
+#pragma warning(disable : 4100)
+#pragma warning(disable : 4127)
+#pragma warning(disable : 4130)
+#pragma warning(disable : 4152)
+#pragma warning(disable : 4189)
+#pragma warning(disable : 4206)
+#pragma warning(disable : 4210)
+#pragma warning(disable : 4232)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4305)
+#pragma warning(disable : 4306)
+#pragma warning(disable : 4702)
+#pragma warning(disable : 4706)
+#endif /* defined(_MSC_VER) */
 
 /*
 ** No support for loadable extensions in VxWorks.
@@ -495,6 +527,18 @@ static int strlen30(const char *z){
   return 0x3fffffff & (int)(z2 - z);
 }
 
+/*
+** Return the length of a string in characters.  Multibyte UTF8 characters
+** count as a single character.
+*/
+static int strlenChar(const char *z){
+  int n = 0;
+  while( *z ){
+    if( (0xc0&*(z++))!=0x80 ) n++;
+  }
+  return n;
+}
+
 /*
 ** This routine reads a line of text from FILE in, stores
 ** the text in memory obtained from malloc() and returns a pointer
@@ -703,10 +747,108 @@ static char quoteChar(const char *zName){
   return 0;
 }
 
-/******************************************************************************
-** SHA3 hash implementation copied from ../ext/misc/shathree.c
+/*
+** SQL function:  shell_add_schema(S,X)
+**
+** Add the schema name X to the CREATE statement in S and return the result.
+** Examples:
+**
+**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
+**
+** Also works on
+**
+**    CREATE INDEX
+**    CREATE UNIQUE INDEX
+**    CREATE VIEW
+**    CREATE TRIGGER
+**    CREATE VIRTUAL TABLE
+**
+** This UDF is used by the .schema command to insert the schema name of
+** attached databases into the middle of the sqlite_master.sql field.
+*/
+static void shellAddSchemaName(
+  sqlite3_context *pCtx,
+  int nVal,
+  sqlite3_value **apVal
+){
+  static const char *aPrefix[] = {
+     "TABLE",
+     "INDEX",
+     "UNIQUE INDEX",
+     "VIEW",
+     "TRIGGER",
+     "VIRTUAL TABLE"
+  };
+  int i = 0;
+  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
+  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
+  assert( nVal==2 );
+  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
+    for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
+      int n = strlen30(aPrefix[i]);
+      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
+        char cQuote = quoteChar(zSchema);
+        char *z;
+        if( cQuote ){
+         z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
+        }else{
+          z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
+        }
+        sqlite3_result_text(pCtx, z, -1, sqlite3_free);
+        return;
+      }
+    }
+  }
+  sqlite3_result_value(pCtx, apVal[0]);
+}
+
+/*
+** The source code for several run-time loadable extensions is inserted
+** below by the ../tool/mkshellc.tcl script.  Before processing that included
+** code, we need to override some macros to make the included program code
+** work here in the middle of this regular program.
 */
+#define SQLITE_EXTENSION_INIT1
+#define SQLITE_EXTENSION_INIT2(X) (void)(X)
+
+/************************* Begin ../ext/misc/shathree.c ******************/
+/*
+** 2017-03-08
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This SQLite extension implements a functions that compute SHA1 hashes.
+** Two SQL functions are implemented:
+**
+**     sha3(X,SIZE)
+**     sha3_query(Y,SIZE)
+**
+** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
+** X is NULL.
+**
+** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
+** and returns a hash of their results.
+**
+** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
+** is used.  If SIZE is included it must be one of the integers 224, 256,
+** 384, or 512, to determine SHA3 hash variant that is computed.
+*/
+SQLITE_EXTENSION_INIT1
+#include <assert.h>
+#include <string.h>
+#include <stdarg.h>
 typedef sqlite3_uint64 u64;
+
+/******************************************************************************
+** The Hash Engine
+*/
 /*
 ** Macros to determine whether the machine is big or little endian,
 ** and whether or not that determination is run-time or compile-time.
@@ -744,10 +886,6 @@ struct SHA3Context {
   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
 };
 
-/* Allow the following routine to use the B0 variable, which is also
-** a macro in the termios.h header file */
-#undef B0
-
 /*
 ** A single step of the Keccak mixing function for a 1600-bit state
 */
@@ -1158,6 +1296,8 @@ static unsigned char *SHA3Final(SHA3Context *p){
   }
   return &p->u.x[p->nRate];
 }
+/* End of the hashing logic
+*****************************************************************************/
 
 /*
 ** Implementation of the sha3(X,SIZE) function.
@@ -1294,10 +1434,6 @@ static void sha3QueryFunc(
     }
     nCol = sqlite3_column_count(pStmt);
     z = sqlite3_sql(pStmt);
-    if( z==0 ){
-      sqlite3_finalize(pStmt);
-      continue;
-    }
     n = (int)strlen(z);
     hash_step_vformat(&cx,"S%d:",n);
     SHA3Update(&cx,(unsigned char*)z,n);
@@ -1360,8 +1496,666 @@ static void sha3QueryFunc(
   }
   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
 }
-/* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
-********************************************************************************/
+
+
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+int sqlite3_shathree_init(
+  sqlite3 *db,
+  char **pzErrMsg,
+  const sqlite3_api_routines *pApi
+){
+  int rc = SQLITE_OK;
+  SQLITE_EXTENSION_INIT2(pApi);
+  (void)pzErrMsg;  /* Unused parameter */
+  rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
+                               sha3Func, 0, 0);
+  if( rc==SQLITE_OK ){
+    rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
+                                 sha3Func, 0, 0);
+  }
+  if( rc==SQLITE_OK ){
+    rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
+                                 sha3QueryFunc, 0, 0);
+  }
+  if( rc==SQLITE_OK ){
+    rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
+                                 sha3QueryFunc, 0, 0);
+  }
+  return rc;
+}
+
+/************************* End ../ext/misc/shathree.c ********************/
+/************************* Begin ../ext/misc/fileio.c ******************/
+/*
+** 2014-06-13
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This SQLite extension implements SQL functions readfile() and
+** writefile().
+*/
+SQLITE_EXTENSION_INIT1
+#include <stdio.h>
+
+/*
+** Implementation of the "readfile(X)" SQL function.  The entire content
+** of the file named X is read and returned as a BLOB.  NULL is returned
+** if the file does not exist or is unreadable.
+*/
+static void readfileFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  const char *zName;
+  FILE *in;
+  long nIn;
+  void *pBuf;
+
+  (void)(argc);  /* Unused parameter */
+  zName = (const char*)sqlite3_value_text(argv[0]);
+  if( zName==0 ) return;
+  in = fopen(zName, "rb");
+  if( in==0 ) return;
+  fseek(in, 0, SEEK_END);
+  nIn = ftell(in);
+  rewind(in);
+  pBuf = sqlite3_malloc( nIn );
+  if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
+    sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
+  }else{
+    sqlite3_free(pBuf);
+  }
+  fclose(in);
+}
+
+/*
+** Implementation of the "writefile(X,Y)" SQL function.  The argument Y
+** is written into file X.  The number of bytes written is returned.  Or
+** NULL is returned if something goes wrong, such as being unable to open
+** file X for writing.
+*/
+static void writefileFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  FILE *out;
+  const char *z;
+  sqlite3_int64 rc;
+  const char *zFile;
+
+  (void)(argc);  /* Unused parameter */
+  zFile = (const char*)sqlite3_value_text(argv[0]);
+  if( zFile==0 ) return;
+  out = fopen(zFile, "wb");
+  if( out==0 ) return;
+  z = (const char*)sqlite3_value_blob(argv[1]);
+  if( z==0 ){
+    rc = 0;
+  }else{
+    rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
+  }
+  fclose(out);
+  sqlite3_result_int64(context, rc);
+}
+
+
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+int sqlite3_fileio_init(
+  sqlite3 *db, 
+  char **pzErrMsg, 
+  const sqlite3_api_routines *pApi
+){
+  int rc = SQLITE_OK;
+  SQLITE_EXTENSION_INIT2(pApi);
+  (void)pzErrMsg;  /* Unused parameter */
+  rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
+                               readfileFunc, 0, 0);
+  if( rc==SQLITE_OK ){
+    rc = sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
+                                 writefileFunc, 0, 0);
+  }
+  return rc;
+}
+
+/************************* End ../ext/misc/fileio.c ********************/
+/************************* Begin ../ext/misc/completion.c ******************/
+/*
+** 2017-07-10
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file implements an eponymous virtual table that returns suggested
+** completions for a partial SQL input.
+**
+** Suggested usage:
+**
+**     SELECT DISTINCT candidate COLLATE nocase
+**       FROM completion($prefix,$wholeline)
+**      ORDER BY 1;
+**
+** The two query parameters are optional.  $prefix is the text of the
+** current word being typed and that is to be completed.  $wholeline is
+** the complete input line, used for context.
+**
+** The raw completion() table might return the same candidate multiple
+** times, for example if the same column name is used to two or more
+** tables.  And the candidates are returned in an arbitrary order.  Hence,
+** the DISTINCT and ORDER BY are recommended.
+**
+** This virtual table operates at the speed of human typing, and so there
+** is no attempt to make it fast.  Even a slow implementation will be much
+** faster than any human can type.
+**
+*/
+SQLITE_EXTENSION_INIT1
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+
+/* completion_vtab is a subclass of sqlite3_vtab which will
+** serve as the underlying representation of a completion virtual table
+*/
+typedef struct completion_vtab completion_vtab;
+struct completion_vtab {
+  sqlite3_vtab base;  /* Base class - must be first */
+  sqlite3 *db;        /* Database connection for this completion vtab */
+};
+
+/* completion_cursor is a subclass of sqlite3_vtab_cursor which will
+** serve as the underlying representation of a cursor that scans
+** over rows of the result
+*/
+typedef struct completion_cursor completion_cursor;
+struct completion_cursor {
+  sqlite3_vtab_cursor base;  /* Base class - must be first */
+  sqlite3 *db;               /* Database connection for this cursor */
+  int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
+  char *zPrefix;             /* The prefix for the word we want to complete */
+  char *zLine;               /* The whole that we want to complete */
+  const char *zCurrentRow;   /* Current output row */
+  sqlite3_stmt *pStmt;       /* Current statement */
+  sqlite3_int64 iRowid;      /* The rowid */
+  int ePhase;                /* Current phase */
+  int j;                     /* inter-phase counter */
+};
+
+/* Values for ePhase:
+*/
+#define COMPLETION_FIRST_PHASE   1
+#define COMPLETION_KEYWORDS      1
+#define COMPLETION_PRAGMAS       2
+#define COMPLETION_FUNCTIONS     3
+#define COMPLETION_COLLATIONS    4
+#define COMPLETION_INDEXES       5
+#define COMPLETION_TRIGGERS      6
+#define COMPLETION_DATABASES     7
+#define COMPLETION_TABLES        8
+#define COMPLETION_COLUMNS       9
+#define COMPLETION_MODULES       10
+#define COMPLETION_EOF           11
+
+/*
+** The completionConnect() method is invoked to create a new
+** completion_vtab that describes the completion virtual table.
+**
+** Think of this routine as the constructor for completion_vtab objects.
+**
+** All this routine needs to do is:
+**
+**    (1) Allocate the completion_vtab object and initialize all fields.
+**
+**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
+**        result set of queries against completion will look like.
+*/
+static int completionConnect(
+  sqlite3 *db,
+  void *pAux,
+  int argc, const char *const*argv,
+  sqlite3_vtab **ppVtab,
+  char **pzErr
+){
+  completion_vtab *pNew;
+  int rc;
+
+  (void)(pAux);    /* Unused parameter */
+  (void)(argc);    /* Unused parameter */
+  (void)(argv);    /* Unused parameter */
+  (void)(pzErr);   /* Unused parameter */
+
+/* Column numbers */
+#define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
+#define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
+#define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
+#define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
+
+  rc = sqlite3_declare_vtab(db,
+      "CREATE TABLE x("
+      "  candidate TEXT,"
+      "  prefix TEXT HIDDEN,"
+      "  wholeline TEXT HIDDEN,"
+      "  phase INT HIDDEN"        /* Used for debugging only */
+      ")");
+  if( rc==SQLITE_OK ){
+    pNew = sqlite3_malloc( sizeof(*pNew) );
+    *ppVtab = (sqlite3_vtab*)pNew;
+    if( pNew==0 ) return SQLITE_NOMEM;
+    memset(pNew, 0, sizeof(*pNew));
+    pNew->db = db;
+  }
+  return rc;
+}
+
+/*
+** This method is the destructor for completion_cursor objects.
+*/
+static int completionDisconnect(sqlite3_vtab *pVtab){
+  sqlite3_free(pVtab);
+  return SQLITE_OK;
+}
+
+/*
+** Constructor for a new completion_cursor object.
+*/
+static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
+  completion_cursor *pCur;
+  pCur = sqlite3_malloc( sizeof(*pCur) );
+  if( pCur==0 ) return SQLITE_NOMEM;
+  memset(pCur, 0, sizeof(*pCur));
+  pCur->db = ((completion_vtab*)p)->db;
+  *ppCursor = &pCur->base;
+  return SQLITE_OK;
+}
+
+/*
+** Reset the completion_cursor.
+*/
+static void completionCursorReset(completion_cursor *pCur){
+  sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
+  sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
+  sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
+  pCur->j = 0;
+}
+
+/*
+** Destructor for a completion_cursor.
+*/
+static int completionClose(sqlite3_vtab_cursor *cur){
+  completionCursorReset((completion_cursor*)cur);
+  sqlite3_free(cur);
+  return SQLITE_OK;
+}
+
+/*
+** All SQL keywords understood by SQLite
+*/
+static const char *completionKwrds[] = {
+  "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
+  "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
+  "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
+  "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
+  "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
+  "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
+  "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
+  "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
+  "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
+  "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
+  "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
+  "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
+  "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
+  "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
+  "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
+  "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
+  "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
+  "WITH", "WITHOUT",
+};
+#define completionKwCount \
+   (int)(sizeof(completionKwrds)/sizeof(completionKwrds[0]))
+
+/*
+** Advance a completion_cursor to its next row of output.
+**
+** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
+** record the current state of the scan.  This routine sets ->zCurrentRow
+** to the current row of output and then returns.  If no more rows remain,
+** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
+** table that has reached the end of its scan.
+**
+** The current implementation just lists potential identifiers and
+** keywords and filters them by zPrefix.  Future enhancements should
+** take zLine into account to try to restrict the set of identifiers and
+** keywords based on what would be legal at the current point of input.
+*/
+static int completionNext(sqlite3_vtab_cursor *cur){
+  completion_cursor *pCur = (completion_cursor*)cur;
+  int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
+  int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
+  pCur->iRowid++;
+  while( pCur->ePhase!=COMPLETION_EOF ){
+    switch( pCur->ePhase ){
+      case COMPLETION_KEYWORDS: {
+        if( pCur->j >= completionKwCount ){
+          pCur->zCurrentRow = 0;
+          pCur->ePhase = COMPLETION_DATABASES;
+        }else{
+          pCur->zCurrentRow = completionKwrds[pCur->j++];
+        }
+        iCol = -1;
+        break;
+      }
+      case COMPLETION_DATABASES: {
+        if( pCur->pStmt==0 ){
+          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
+                             &pCur->pStmt, 0);
+        }
+        iCol = 1;
+        eNextPhase = COMPLETION_TABLES;
+        break;
+      }
+      case COMPLETION_TABLES: {
+        if( pCur->pStmt==0 ){
+          sqlite3_stmt *pS2;
+          char *zSql = 0;
+          const char *zSep = "";
+          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
+          while( sqlite3_step(pS2)==SQLITE_ROW ){
+            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
+            zSql = sqlite3_mprintf(
+               "%z%s"
+               "SELECT name FROM \"%w\".sqlite_master"
+               " WHERE type='table'",
+               zSql, zSep, zDb
+            );
+            if( zSql==0 ) return SQLITE_NOMEM;
+            zSep = " UNION ";
+          }
+          sqlite3_finalize(pS2);
+          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
+          sqlite3_free(zSql);
+        }
+        iCol = 0;
+        eNextPhase = COMPLETION_COLUMNS;
+        break;
+      }
+      case COMPLETION_COLUMNS: {
+        if( pCur->pStmt==0 ){
+          sqlite3_stmt *pS2;
+          char *zSql = 0;
+          const char *zSep = "";
+          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
+          while( sqlite3_step(pS2)==SQLITE_ROW ){
+            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
+            zSql = sqlite3_mprintf(
+               "%z%s"
+               "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
+                       " JOIN pragma_table_info(sm.name,%Q) AS pti"
+               " WHERE sm.type='table'",
+               zSql, zSep, zDb, zDb
+            );
+            if( zSql==0 ) return SQLITE_NOMEM;
+            zSep = " UNION ";
+          }
+          sqlite3_finalize(pS2);
+          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
+          sqlite3_free(zSql);
+        }
+        iCol = 0;
+        eNextPhase = COMPLETION_EOF;
+        break;
+      }
+    }
+    if( iCol<0 ){
+      /* This case is when the phase presets zCurrentRow */
+      if( pCur->zCurrentRow==0 ) continue;
+    }else{
+      if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
+        /* Extract the next row of content */
+        pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
+      }else{
+        /* When all rows are finished, advance to the next phase */
+        sqlite3_finalize(pCur->pStmt);
+        pCur->pStmt = 0;
+        pCur->ePhase = eNextPhase;
+        continue;
+      }
+    }
+    if( pCur->nPrefix==0 ) break;
+    if( sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 ){
+      break;
+    }
+  }
+
+  return SQLITE_OK;
+}
+
+/*
+** Return values of columns for the row at which the completion_cursor
+** is currently pointing.
+*/
+static int completionColumn(
+  sqlite3_vtab_cursor *cur,   /* The cursor */
+  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
+  int i                       /* Which column to return */
+){
+  completion_cursor *pCur = (completion_cursor*)cur;
+  switch( i ){
+    case COMPLETION_COLUMN_CANDIDATE: {
+      sqlite3_result_text(ctx, pCur->zCurrentRow, -1, SQLITE_TRANSIENT);
+      break;
+    }
+    case COMPLETION_COLUMN_PREFIX: {
+      sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
+      break;
+    }
+    case COMPLETION_COLUMN_WHOLELINE: {
+      sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
+      break;
+    }
+    case COMPLETION_COLUMN_PHASE: {
+      sqlite3_result_int(ctx, pCur->ePhase);
+      break;
+    }
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Return the rowid for the current row.  In this implementation, the
+** rowid is the same as the output value.
+*/
+static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
+  completion_cursor *pCur = (completion_cursor*)cur;
+  *pRowid = pCur->iRowid;
+  return SQLITE_OK;
+}
+
+/*
+** Return TRUE if the cursor has been moved off of the last
+** row of output.
+*/
+static int completionEof(sqlite3_vtab_cursor *cur){
+  completion_cursor *pCur = (completion_cursor*)cur;
+  return pCur->ePhase >= COMPLETION_EOF;
+}
+
+/*
+** This method is called to "rewind" the completion_cursor object back
+** to the first row of output.  This method is always called at least
+** once prior to any call to completionColumn() or completionRowid() or 
+** completionEof().
+*/
+static int completionFilter(
+  sqlite3_vtab_cursor *pVtabCursor, 
+  int idxNum, const char *idxStr,
+  int argc, sqlite3_value **argv
+){
+  completion_cursor *pCur = (completion_cursor *)pVtabCursor;
+  int iArg = 0;
+  (void)(idxStr);   /* Unused parameter */
+  (void)(argc);     /* Unused parameter */
+  completionCursorReset(pCur);
+  if( idxNum & 1 ){
+    pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
+    if( pCur->nPrefix>0 ){
+      pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
+      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
+    }
+    iArg++;
+  }
+  if( idxNum & 2 ){
+    pCur->nLine = sqlite3_value_bytes(argv[iArg]);
+    if( pCur->nLine>0 ){
+      pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
+      if( pCur->zLine==0 ) return SQLITE_NOMEM;
+    }
+    iArg++;
+  }
+  if( pCur->zLine!=0 && pCur->zPrefix==0 ){
+    int i = pCur->nLine;
+    while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
+      i--;
+    }
+    pCur->nPrefix = pCur->nLine - i;
+    if( pCur->nPrefix>0 ){
+      pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
+      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
+    }
+  }
+  pCur->iRowid = 0;
+  pCur->ePhase = COMPLETION_FIRST_PHASE;
+  return completionNext(pVtabCursor);
+}
+
+/*
+** SQLite will invoke this method one or more times while planning a query
+** that uses the completion virtual table.  This routine needs to create
+** a query plan for each invocation and compute an estimated cost for that
+** plan.
+**
+** There are two hidden parameters that act as arguments to the table-valued
+** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
+** is available and bit 1 is set if "wholeline" is available.
+*/
+static int completionBestIndex(
+  sqlite3_vtab *tab,
+  sqlite3_index_info *pIdxInfo
+){
+  int i;                 /* Loop over constraints */
+  int idxNum = 0;        /* The query plan bitmask */
+  int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
+  int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
+  int nArg = 0;          /* Number of arguments that completeFilter() expects */
+  const struct sqlite3_index_constraint *pConstraint;
+
+  (void)(tab);    /* Unused parameter */
+  pConstraint = pIdxInfo->aConstraint;
+  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
+    if( pConstraint->usable==0 ) continue;
+    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
+    switch( pConstraint->iColumn ){
+      case COMPLETION_COLUMN_PREFIX:
+        prefixIdx = i;
+        idxNum |= 1;
+        break;
+      case COMPLETION_COLUMN_WHOLELINE:
+        wholelineIdx = i;
+        idxNum |= 2;
+        break;
+    }
+  }
+  if( prefixIdx>=0 ){
+    pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
+    pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
+  }
+  if( wholelineIdx>=0 ){
+    pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
+    pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
+  }
+  pIdxInfo->idxNum = idxNum;
+  pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
+  pIdxInfo->estimatedRows = 500 - 100*nArg;
+  return SQLITE_OK;
+}
+
+/*
+** This following structure defines all the methods for the 
+** completion virtual table.
+*/
+static sqlite3_module completionModule = {
+  0,                         /* iVersion */
+  0,                         /* xCreate */
+  completionConnect,         /* xConnect */
+  completionBestIndex,       /* xBestIndex */
+  completionDisconnect,      /* xDisconnect */
+  0,                         /* xDestroy */
+  completionOpen,            /* xOpen - open a cursor */
+  completionClose,           /* xClose - close a cursor */
+  completionFilter,          /* xFilter - configure scan constraints */
+  completionNext,            /* xNext - advance a cursor */
+  completionEof,             /* xEof - check for end of scan */
+  completionColumn,          /* xColumn - read data */
+  completionRowid,           /* xRowid - read data */
+  0,                         /* xUpdate */
+  0,                         /* xBegin */
+  0,                         /* xSync */
+  0,                         /* xCommit */
+  0,                         /* xRollback */
+  0,                         /* xFindMethod */
+  0,                         /* xRename */
+  0,                         /* xSavepoint */
+  0,                         /* xRelease */
+  0                          /* xRollbackTo */
+};
+
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
+
+int sqlite3CompletionVtabInit(sqlite3 *db){
+  int rc = SQLITE_OK;
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+  rc = sqlite3_create_module(db, "completion", &completionModule, 0);
+#endif
+  return rc;
+}
+
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+int sqlite3_completion_init(
+  sqlite3 *db, 
+  char **pzErrMsg, 
+  const sqlite3_api_routines *pApi
+){
+  int rc = SQLITE_OK;
+  SQLITE_EXTENSION_INIT2(pApi);
+  (void)(pzErrMsg);  /* Unused parameter */
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+  rc = sqlite3CompletionVtabInit(db);
+#endif
+  return rc;
+}
+
+/************************* End ../ext/misc/completion.c ********************/
 
 #if defined(SQLITE_ENABLE_SESSION)
 /*
@@ -1442,8 +2236,9 @@ struct ShellState {
 #define SHFLG_Lookaside      0x00000004 /* Lookaside memory is used */
 #define SHFLG_Backslash      0x00000008 /* The --backslash option is used */
 #define SHFLG_PreserveRowid  0x00000010 /* .dump preserves rowid values */
-#define SHFLG_CountChanges   0x00000020 /* .changes setting */
-#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
+#define SHFLG_Newlines       0x00000020 /* .dump --newline flag */
+#define SHFLG_CountChanges   0x00000040 /* .changes setting */
+#define SHFLG_Echo           0x00000080 /* .echo or --echo setting */
 
 /*
 ** Macros for testing and setting shellFlgs
@@ -1903,9 +2698,9 @@ static int shell_callback(
             w = 0;
           }
           if( w==0 ){
-            w = strlen30(azCol[i] ? azCol[i] : "");
+            w = strlenChar(azCol[i] ? azCol[i] : "");
             if( w<10 ) w = 10;
-            n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
+            n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
             if( w<n ) w = n;
           }
           if( i<ArraySize(p->actualWidth) ){
@@ -1940,8 +2735,8 @@ static int shell_callback(
         }else{
            w = 10;
         }
-        if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
-          w = strlen30(azArg[i]);
+        if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
+          w = strlenChar(azArg[i]);
         }
         if( i==1 && p->aiIndent && p->pStmt ){
           if( p->iIndent<p->nIndent ){
@@ -2114,7 +2909,11 @@ static int shell_callback(
         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
           utf8_printf(p->out,"NULL");
         }else if( aiType && aiType[i]==SQLITE_TEXT ){
-          output_quoted_escaped_string(p->out, azArg[i]);
+          if( ShellHasFlag(p, SHFLG_Newlines) ){
+            output_quoted_string(p->out, azArg[i]);
+          }else{
+            output_quoted_escaped_string(p->out, azArg[i]);
+          }
         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
           utf8_printf(p->out,"%s", azArg[i]);
         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
@@ -2128,6 +2927,8 @@ static int shell_callback(
           output_hex_blob(p->out, pBlob, nBlob);
         }else if( isNumber(azArg[i], 0) ){
           utf8_printf(p->out,"%s", azArg[i]);
+        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
+          output_quoted_string(p->out, azArg[i]);
         }else{
           output_quoted_escaped_string(p->out, azArg[i]);
         }
@@ -2282,7 +3083,7 @@ static void set_table_name(ShellState *p, const char *zName){
   if( zName==0 ) return;
   cQuote = quoteChar(zName);
   n = strlen30(zName);
-  if( cQuote ) n += 2;
+  if( cQuote ) n += n+2;
   z = p->zDestTable = malloc( n+1 );
   if( z==0 ){
     raw_printf(stderr,"Error: out of memory\n");
@@ -2997,7 +3798,7 @@ static char **tableColumnList(ShellState *p, const char *zTab){
       nPK++;
       if( nPK==1
        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
-                          "INTEGER")==0 
+                          "INTEGER")==0
       ){
         isIPK = 1;
       }else{
@@ -3234,6 +4035,7 @@ static char zHelp[] =
   ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
   ".bail on|off           Stop after hitting an error.  Default OFF\n"
   ".binary on|off         Turn binary output on or off.  Default OFF\n"
+  ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
   ".changes on|off        Show number of rows changed by SQL\n"
   ".check GLOB            Fail if output since .testcase does not match\n"
   ".clone NEWDB           Clone data into NEWDB from the existing database\n"
@@ -3245,7 +4047,9 @@ static char zHelp[] =
   ".echo on|off           Turn command echo on or off\n"
   ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
   ".exit                  Exit this program\n"
-  ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
+/* Because explain mode comes on automatically now, the ".explain" mode
+** is removed from the help screen.  It is still supported for legacy, however */
+/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
   ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
   ".headers on|off        Turn display of headers on or off\n"
   ".help                  Show this message\n"
@@ -3279,8 +4083,8 @@ static char zHelp[] =
   "                         tcl      TCL list elements\n"
   ".nullvalue STRING      Use STRING in place of NULL values\n"
   ".once FILENAME         Output for the next SQL command only to FILENAME\n"
-  ".open ?--new? ?FILE?   Close existing database and reopen FILE\n"
-  "                         The --new starts with an empty file\n"
+  ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
+  "                         The --new option starts with an empty file\n"
   ".output ?FILENAME?     Send output to FILENAME or stdout\n"
   ".print STRING...       Print literal STRING\n"
   ".prompt MAIN CONTINUE  Replace the standard prompts\n"
@@ -3345,8 +4149,8 @@ static int process_input(ShellState *p, FILE *in);
 
 /*
 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
-** and return a pointer to the buffer. The caller is responsible for freeing 
-** the memory. 
+** and return a pointer to the buffer. The caller is responsible for freeing
+** the memory.
 **
 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
 ** read.
@@ -3380,58 +4184,6 @@ static char *readFile(const char *zName, int *pnByte){
   return pBuf;
 }
 
-/*
-** Implementation of the "readfile(X)" SQL function.  The entire content
-** of the file named X is read and returned as a BLOB.  NULL is returned
-** if the file does not exist or is unreadable.
-*/
-static void readfileFunc(
-  sqlite3_context *context,
-  int argc,
-  sqlite3_value **argv
-){
-  const char *zName;
-  void *pBuf;
-  int nBuf;
-
-  UNUSED_PARAMETER(argc);
-  zName = (const char*)sqlite3_value_text(argv[0]);
-  if( zName==0 ) return;
-  pBuf = readFile(zName, &nBuf);
-  if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
-}
-
-/*
-** Implementation of the "writefile(X,Y)" SQL function.  The argument Y
-** is written into file X.  The number of bytes written is returned.  Or
-** NULL is returned if something goes wrong, such as being unable to open
-** file X for writing.
-*/
-static void writefileFunc(
-  sqlite3_context *context,
-  int argc,
-  sqlite3_value **argv
-){
-  FILE *out;
-  const char *z;
-  sqlite3_int64 rc;
-  const char *zFile;
-
-  UNUSED_PARAMETER(argc);
-  zFile = (const char*)sqlite3_value_text(argv[0]);
-  if( zFile==0 ) return;
-  out = fopen(zFile, "wb");
-  if( out==0 ) return;
-  z = (const char*)sqlite3_value_blob(argv[1]);
-  if( z==0 ){
-    rc = 0;
-  }else{
-    rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
-  }
-  fclose(out);
-  sqlite3_result_int64(context, rc);
-}
-
 #if defined(SQLITE_ENABLE_SESSION)
 /*
 ** Close a single OpenSession object and release all of its associated
@@ -3497,21 +4249,78 @@ static void open_db(ShellState *p, int keepAlive){
 #ifndef SQLITE_OMIT_LOAD_EXTENSION
     sqlite3_enable_load_extension(p->db, 1);
 #endif
-    sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
-                            readfileFunc, 0, 0);
-    sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
-                            writefileFunc, 0, 0);
-    sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
-                            sha3Func, 0, 0);
-    sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
-                            sha3Func, 0, 0);
-    sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
-                            sha3QueryFunc, 0, 0);
-    sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
-                            sha3QueryFunc, 0, 0);
+    sqlite3_fileio_init(p->db, 0, 0);
+    sqlite3_shathree_init(p->db, 0, 0);
+    sqlite3_completion_init(p->db, 0, 0);
+    sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
+                            shellAddSchemaName, 0, 0);
   }
 }
 
+#if HAVE_READLINE || HAVE_EDITLINE
+/*
+** Readline completion callbacks
+*/
+static char *readline_completion_generator(const char *text, int state){
+  static sqlite3_stmt *pStmt = 0;
+  char *zRet;
+  if( state==0 ){
+    char *zSql;
+    sqlite3_finalize(pStmt);
+    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
+                           "  FROM completion(%Q) ORDER BY 1", text);
+    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
+    sqlite3_free(zSql);
+  }
+  if( sqlite3_step(pStmt)==SQLITE_ROW ){
+    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
+  }else{
+    sqlite3_finalize(pStmt);
+    pStmt = 0;
+    zRet = 0;
+  }
+  return zRet;
+}
+static char **readline_completion(const char *zText, int iStart, int iEnd){
+  rl_attempted_completion_over = 1;
+  return rl_completion_matches(zText, readline_completion_generator);
+}
+
+#elif HAVE_LINENOISE
+/*
+** Linenoise completion callback
+*/
+static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
+  int nLine = (int)strlen(zLine);
+  int i, iStart;
+  sqlite3_stmt *pStmt = 0;
+  char *zSql;
+  char zBuf[1000];
+
+  if( nLine>sizeof(zBuf)-30 ) return;
+  if( zLine[0]=='.' ) return;
+  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
+  if( i==nLine-1 ) return;
+  iStart = i+1;
+  memcpy(zBuf, zLine, iStart);
+  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
+                         "  FROM completion(%Q,%Q) ORDER BY 1",
+                         &zLine[iStart], zLine);
+  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
+  sqlite3_free(zSql);
+  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
+  while( sqlite3_step(pStmt)==SQLITE_ROW ){
+    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
+    int nCompletion = sqlite3_column_bytes(pStmt, 0);
+    if( iStart+nCompletion < sizeof(zBuf)-1 ){
+      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
+      linenoiseAddCompletion(lc, zBuf);
+    }
+  }
+  sqlite3_finalize(pStmt);
+}
+#endif
+
 /*
 ** Do C-language style dequoting.
 **
@@ -3737,6 +4546,7 @@ struct ImportCtx {
   int n;              /* Number of bytes in z */
   int nAlloc;         /* Space allocated for z[] */
   int nLine;          /* Current line number */
+  int bNotFirst;      /* True if one or more bytes already read */
   int cTerm;          /* Character that terminated the most recent field */
   int cColSep;        /* The column separator character.  (Usually ",") */
   int cRowSep;        /* The row separator character.  (Usually "\n") */
@@ -3816,6 +4626,21 @@ static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
       pc = c;
     }
   }else{
+    /* If this is the first field being parsed and it begins with the
+    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
+    if( (c&0xff)==0xef && p->bNotFirst==0 ){
+      import_append_char(p, c);
+      c = fgetc(p->in);
+      if( (c&0xff)==0xbb ){
+        import_append_char(p, c);
+        c = fgetc(p->in);
+        if( (c&0xff)==0xbf ){
+          p->bNotFirst = 1;
+          p->n = 0;
+          return csv_read_one_field(p);
+        }
+      }
+    }
     while( c!=EOF && c!=cSep && c!=rSep ){
       import_append_char(p, c);
       c = fgetc(p->in);
@@ -3827,6 +4652,7 @@ static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
     p->cTerm = c;
   }
   if( p->z ) p->z[p->n] = 0;
+  p->bNotFirst = 1;
   return p->z;
 }
 
@@ -4353,15 +5179,15 @@ int shellDeleteFile(const char *zFilename){
 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
 **
 ** If either of the named tables or columns do not exist, this function
-** returns an empty string. An empty string is also returned if both tables 
+** returns an empty string. An empty string is also returned if both tables
 ** and columns exist but have the same default collation sequence. Or,
 ** if both exist but the default collation sequences are different, this
 ** function returns the string " COLLATE <parent-collation>", where
 ** <parent-collation> is the default collation sequence of the parent column.
 */
 static void shellFkeyCollateClause(
-  sqlite3_context *pCtx, 
-  int nVal, 
+  sqlite3_context *pCtx,
+  int nVal,
   sqlite3_value **apVal
 ){
   sqlite3 *db = sqlite3_context_db_handle(pCtx);
@@ -4372,7 +5198,7 @@ static void shellFkeyCollateClause(
   const char *zChildCol;
   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
   int rc;
-  
+
   assert( nVal==4 );
   zParent = (const char*)sqlite3_value_text(apVal[0]);
   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
@@ -4494,7 +5320,7 @@ static int lintFkeyIndexes(
       return SQLITE_ERROR;
     }
   }
-  
+
   /* Register the fkey_collate_clause() SQL function */
   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
       0, shellFkeyCollateClause, 0, 0
@@ -4537,9 +5363,9 @@ static int lintFkeyIndexes(
         raw_printf(stderr, "Error: internal error");
         break;
       }else{
-        if( bGroupByParent 
+        if( bGroupByParent
         && (bVerbose || res==0)
-        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 
+        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
         ){
           raw_printf(out, "-- Parent table %s\n", zParent);
           sqlite3_free(zPrev);
@@ -4549,7 +5375,7 @@ static int lintFkeyIndexes(
         if( res==0 ){
           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
         }else if( bVerbose ){
-          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 
+          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
               zIndent, zFrom, zTarget
           );
         }
@@ -4731,6 +5557,25 @@ static int do_meta_command(char *zLine, ShellState *p){
     }
   }else
 
+  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
+    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{
+      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
+      rc = 1;
+    }
+  }else
+
   /* The undocumented ".breakpoint" command causes a call to the no-op
   ** routine named test_breakpoint().
   */
@@ -4807,7 +5652,7 @@ static int do_meta_command(char *zLine, ShellState *p){
     const char *zLike = 0;
     int i;
     int savedShowHeader = p->showHeader;
-    ShellClearFlag(p, SHFLG_PreserveRowid);
+    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
     for(i=1; i<nArg; i++){
       if( azArg[i][0]=='-' ){
         const char *z = azArg[i]+1;
@@ -4822,13 +5667,17 @@ static int do_meta_command(char *zLine, ShellState *p){
           ShellSetFlag(p, SHFLG_PreserveRowid);
 #endif
         }else
+        if( strcmp(z,"newlines")==0 ){
+          ShellSetFlag(p, SHFLG_Newlines);
+        }else
         {
           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
           rc = 1;
           goto meta_command_exit;
         }
       }else if( zLike ){
-        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
+        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
+                           "?--newlines? ?LIKE-PATTERN?\n");
         rc = 1;
         goto meta_command_exit;
       }else{
@@ -4914,6 +5763,8 @@ static int do_meta_command(char *zLine, ShellState *p){
     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 ){
@@ -5430,7 +6281,9 @@ static int do_meta_command(char *zLine, ShellState *p){
       p->mode = MODE_Ascii;
       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
-    }else {
+    }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 column csv html insert line list quote tabs tcl\n");
       rc = 1;
@@ -5643,12 +6496,17 @@ static int do_meta_command(char *zLine, ShellState *p){
   }else
 
   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
+    ShellText sSelect;
     ShellState data;
     char *zErrMsg = 0;
+    const char *zDiv = 0;
+    int iSchema = 0;
+
     open_db(p, 0);
     memcpy(&data, p, sizeof(data));
     data.showHeader = 0;
     data.cMode = data.mode = MODE_Semi;
+    initText(&sSelect);
     if( nArg>=2 && optionMatch(azArg[1], "indent") ){
       data.cMode = data.mode = MODE_Pretty;
       nArg--;
@@ -5686,33 +6544,68 @@ static int do_meta_command(char *zLine, ShellState *p){
         callback(&data, 1, new_argv, new_colv);
         rc = SQLITE_OK;
       }else{
-        char *zSql;
-        zSql = sqlite3_mprintf(
-          "SELECT sql FROM "
-          "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
-          "     FROM sqlite_master UNION ALL"
-          "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
-          "WHERE lower(tbl_name) LIKE %Q"
-          "  AND type!='meta' AND sql NOTNULL "
-          "ORDER BY rowid", azArg[1]);
-        rc = sqlite3_exec(p->db, zSql, callback, &data, &zErrMsg);
-        sqlite3_free(zSql);
+        zDiv = "(";
       }
     }else if( nArg==1 ){
-      rc = sqlite3_exec(p->db,
-         "SELECT sql FROM "
-         "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
-         "     FROM sqlite_master UNION ALL"
-         "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
-         "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
-         "ORDER BY rowid",
-         callback, &data, &zErrMsg
-      );
+      zDiv = "(";
     }else{
       raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
       rc = 1;
       goto meta_command_exit;
     }
+    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 ";
+        if( strcmp(zDb, "main")!=0 ){
+          appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
+          appendText(&sSelect, zDb, '"');
+          appendText(&sSelect, ") 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, '"');
+          appendText(&sSelect, ".sqlite_master", 0);
+        }else{
+          appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
+          appendText(&sSelect, zScNum, 0);
+          appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
+        }
+      }
+      sqlite3_finalize(pStmt);
+      appendText(&sSelect, ") WHERE ", 0);
+      if( nArg>1 ){
+        char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
+        if( strchr(azArg[1], '.') ){
+          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
+        }else{
+          appendText(&sSelect, "lower(tbl_name)", 0);
+        }
+        appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
+        appendText(&sSelect, zQarg, 0);
+        appendText(&sSelect, " AND ", 0);
+        sqlite3_free(zQarg);
+      }
+      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
+                           " ORDER BY snum, rowid", 0);
+      rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
+      freeText(&sSelect);
+    }
     if( zErrMsg ){
       utf8_printf(stderr,"Error: %s\n", zErrMsg);
       sqlite3_free(zErrMsg);
@@ -5954,19 +6847,11 @@ static int do_meta_command(char *zLine, ShellState *p){
     int bIsInit = 0;         /* True to initialize the SELFTEST table */
     int bVerbose = 0;        /* Verbose output */
     int bSelftestExists;     /* True if SELFTEST already exists */
-    char **azTest = 0;       /* Content of the SELFTEST table */
-    int nRow = 0;            /* Number of rows in the SELFTEST table */
-    int nCol = 4;            /* Number of columns in the SELFTEST table */
-    int i;                   /* Loop counter */
+    int i, k;                /* Loop counters */
     int nTest = 0;           /* Number of tests runs */
     int nErr = 0;            /* Number of errors seen */
     ShellText str;           /* Answer for a query */
-    static char *azDefaultTest[] = {
-       0, 0, 0, 0,
-       "0", "memo", "Missing SELFTEST table - default checks only", "",
-       "1", "run", "PRAGMA integrity_check", "ok"
-    };
-    static const int nDefaultRow = 2;
+    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
 
     open_db(p,0);
     for(i=1; i<nArg; i++){
@@ -5996,70 +6881,71 @@ static int do_meta_command(char *zLine, ShellState *p){
       createSelftestTable(p);
       bSelftestExists = 1;
     }
-    if( bSelftestExists ){
-      rc = sqlite3_get_table(p->db, 
-          "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
-          &azTest, &nRow, &nCol, 0);
+    initText(&str);
+    appendText(&str, "x", 0);
+    for(k=bSelftestExists; k>=0; k--){
+      if( k==1 ){
+        rc = sqlite3_prepare_v2(p->db,
+            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
+            -1, &pStmt, 0);
+      }else{
+        rc = sqlite3_prepare_v2(p->db,
+          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
+          "      (1,'run','PRAGMA integrity_check','ok')",
+          -1, &pStmt, 0);
+      }
       if( rc ){
         raw_printf(stderr, "Error querying the selftest table\n");
         rc = 1;
-        sqlite3_free_table(azTest);
+        sqlite3_finalize(pStmt);
         goto meta_command_exit;
-      }else if( nRow==0 ){
-        sqlite3_free_table(azTest);
-        azTest = azDefaultTest;
-        nRow = nDefaultRow;
       }
-    }else{
-      azTest = azDefaultTest;
-      nRow = nDefaultRow;
-    }
-    initText(&str);
-    appendText(&str, "x", 0);
-    for(i=1; i<=nRow; i++){
-      int tno = atoi(azTest[i*nCol]);
-      const char *zOp = azTest[i*nCol+1];
-      const char *zSql = azTest[i*nCol+2];
-      const char *zAns = azTest[i*nCol+3];
-  
-      if( bVerbose>0 ){
-        char *zQuote = sqlite3_mprintf("%q", zSql);
-        printf("%d: %s %s\n", tno, zOp, zSql);
-        sqlite3_free(zQuote);
-      }
-      if( strcmp(zOp,"memo")==0 ){
-        utf8_printf(p->out, "%s\n", zSql);
-      }else
-      if( strcmp(zOp,"run")==0 ){
-        char *zErrMsg = 0;
-        str.n = 0;
-        str.z[0] = 0;
-        rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
-        nTest++;
-        if( bVerbose ){
-          utf8_printf(p->out, "Result: %s\n", str.z);
+      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
+        int tno = sqlite3_column_int(pStmt, 0);
+        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
+        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
+        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
+
+        k = 0;
+        if( bVerbose>0 ){
+          char *zQuote = sqlite3_mprintf("%q", zSql);
+          printf("%d: %s %s\n", tno, zOp, zSql);
+          sqlite3_free(zQuote);
         }
-        if( rc || zErrMsg ){
-          nErr++;
-          rc = 1;
-          utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
-          sqlite3_free(zErrMsg);
-        }else if( strcmp(zAns,str.z)!=0 ){
-          nErr++;
+        if( strcmp(zOp,"memo")==0 ){
+          utf8_printf(p->out, "%s\n", zSql);
+        }else
+        if( strcmp(zOp,"run")==0 ){
+          char *zErrMsg = 0;
+          str.n = 0;
+          str.z[0] = 0;
+          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
+          nTest++;
+          if( bVerbose ){
+            utf8_printf(p->out, "Result: %s\n", str.z);
+          }
+          if( rc || zErrMsg ){
+            nErr++;
+            rc = 1;
+            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
+            sqlite3_free(zErrMsg);
+          }else if( strcmp(zAns,str.z)!=0 ){
+            nErr++;
+            rc = 1;
+            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
+            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
+          }
+        }else
+        {
+          utf8_printf(stderr,
+            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
           rc = 1;
-          utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
-          utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
+          break;
         }
-      }else
-      {
-        utf8_printf(stderr,
-          "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
-        rc = 1;
-        break;
-      }
-    }
+      } /* End loop over rows of content from SELFTEST */
+      sqlite3_finalize(pStmt);
+    } /* End loop over k */
     freeText(&str);
-    if( azTest!=azDefaultTest ) sqlite3_free_table(azTest);
     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
   }else
 
@@ -6099,8 +6985,8 @@ static int do_meta_command(char *zLine, ShellState *p){
         if( strcmp(z,"schema")==0 ){
           bSchema = 1;
         }else
-        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 
-         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 
+        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
+         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
         ){
           iSize = atoi(&z[5]);
         }else
@@ -6268,59 +7154,47 @@ static int do_meta_command(char *zLine, ShellState *p){
     sqlite3_stmt *pStmt;
     char **azResult;
     int nRow, nAlloc;
-    char *zSql = 0;
     int ii;
+    ShellText s;
+    initText(&s);
     open_db(p, 0);
     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
     if( rc ) return shellDatabaseError(p->db);
 
-    /* Create an SQL statement to query for the list of tables in the
-    ** main and all attached databases where the table name matches the
-    ** LIKE pattern bound to variable "?1". */
-    if( c=='t' ){
-      zSql = sqlite3_mprintf(
-          "SELECT name FROM sqlite_master"
-          " WHERE type IN ('table','view')"
-          "   AND name NOT LIKE 'sqlite_%%'"
-          "   AND name LIKE ?1");
-    }else if( nArg>2 ){
+    if( nArg>2 && c=='i' ){
       /* It is an historical accident that the .indexes command shows an error
       ** when called with the wrong number of arguments whereas the .tables
       ** command does not. */
       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
       rc = 1;
       goto meta_command_exit;
-    }else{
-      zSql = sqlite3_mprintf(
-          "SELECT name FROM sqlite_master"
-          " WHERE type='index'"
-          "   AND tbl_name LIKE ?1");
     }
-    for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
+    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
-      if( zDbName==0 || ii==0 ) continue;
+      if( zDbName==0 ) continue;
+      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
+      if( sqlite3_stricmp(zDbName, "main")==0 ){
+        appendText(&s, "SELECT name FROM ", 0);
+      }else{
+        appendText(&s, "SELECT ", 0);
+        appendText(&s, zDbName, '\'');
+        appendText(&s, "||'.'||name FROM ", 0);
+      }
+      appendText(&s, zDbName, '"');
+      appendText(&s, ".sqlite_master ", 0);
       if( c=='t' ){
-        zSql = sqlite3_mprintf(
-                 "%z UNION ALL "
-                 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
-                 " WHERE type IN ('table','view')"
-                 "   AND name NOT LIKE 'sqlite_%%'"
-                 "   AND name LIKE ?1", zSql, zDbName, zDbName);
+        appendText(&s," WHERE type IN ('table','view')"
+                      "   AND name NOT LIKE 'sqlite_%'"
+                      "   AND name LIKE ?1", 0);
       }else{
-        zSql = sqlite3_mprintf(
-                 "%z UNION ALL "
-                 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
-                 " WHERE type='index'"
-                 "   AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
+        appendText(&s," WHERE type='index'"
+                      "   AND tbl_name LIKE ?1", 0);
       }
     }
     rc = sqlite3_finalize(pStmt);
-    if( zSql && rc==SQLITE_OK ){
-      zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
-      if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
-    }
-    sqlite3_free(zSql);
-    if( !zSql ) return shellNomemError();
+    appendText(&s, " ORDER BY 1", 0);
+    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
+    freeText(&s);
     if( rc ) return shellDatabaseError(p->db);
 
     /* Run the SQL statement prepared by the above block. Store the results
@@ -7045,6 +7919,7 @@ static const char zOptions[] =
   "   -newline SEP         set output row separator. Default: '\\n'\n"
   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
+  "   -quote               set output mode to 'quote'\n"
   "   -scratch SIZE N      use N slots of SZ bytes each for scratch memory\n"
   "   -separator SEP       set output column separator. Default: '|'\n"
   "   -stats               print memory stats before each finalize\n"
@@ -7340,6 +8215,8 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
       data.mode = MODE_Html;
     }else if( strcmp(z,"-list")==0 ){
       data.mode = MODE_List;
+    }else if( strcmp(z,"-quote")==0 ){
+      data.mode = MODE_Quote;
     }else if( strcmp(z,"-line")==0 ){
       data.mode = MODE_Line;
     }else if( strcmp(z,"-column")==0 ){
@@ -7491,9 +8368,14 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
         }
       }
       if( zHistory ){ shell_read_history(zHistory); }
+#if HAVE_READLINE || HAVE_EDITLINE
+      rl_attempted_completion_function = readline_completion;
+#elif HAVE_LINENOISE
+      linenoiseSetCompletionCallback(linenoise_completion);
+#endif
       rc = process_input(&data, 0);
       if( zHistory ){
-        shell_stifle_history(100);
+        shell_stifle_history(2000);
         shell_write_history(zHistory);
         free(zHistory);
       }