From 54e058c2c503364cd316bf9c73e253dffa5285a4 Mon Sep 17 00:00:00 2001
From: Dan Kennedy <danielk1977@gmail.com>
Date: Tue, 27 Nov 2018 19:47:55 +0000
Subject: [PATCH 0548/1009] Fix a failing assert() in
 sqlite3ResetAllSchemasOfConnection().

https://github.com/mackyle/sqlite/commit/54e058c2c503364cd316bf9c73e253dffa5285a4

---
 src/build.c        | 11 ++++++++---
 test/vtab_err.test | 23 ++++++++++++++++++++++-
 2 files changed, 30 insertions(+), 4 deletions(-)

diff --git a/src/build.c b/src/build.c
index fca5a92..bed8295 100644
--- a/src/build.c
+++ b/src/build.c
@@ -544,17 +544,22 @@ void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
   int i;
   sqlite3BtreeEnterAll(db);
-  assert( db->nSchemaLock==0 );
   for(i=0; i<db->nDb; i++){
     Db *pDb = &db->aDb[i];
     if( pDb->pSchema ){
-      sqlite3SchemaClear(pDb->pSchema);
+      if( db->nSchemaLock==0 ){
+        sqlite3SchemaClear(pDb->pSchema);
+      }else{
+        DbSetProperty(db, i, DB_ResetWanted);
+      }
     }
   }
   db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
   sqlite3VtabUnlockList(db);
   sqlite3BtreeLeaveAll(db);
-  sqlite3CollapseDatabaseArray(db);
+  if( db->nSchemaLock==0 ){
+    sqlite3CollapseDatabaseArray(db);
+  }
 }
 
 /*
diff --git a/test/vtab_err.test b/test/vtab_err.test
index cb40acd..cfc5fc3 100644
--- a/test/vtab_err.test
+++ b/test/vtab_err.test
@@ -20,7 +20,6 @@ ifcapable !vtab {
 }
 
 
-
 unset -nocomplain echo_module_begin_fail
 do_ioerr_test vtab_err-1 -tclprep {
   register_echo_module [sqlite3_connection_pointer db]
@@ -63,4 +62,26 @@ do_malloc_test vtab_err-2 -tclprep {
 
 sqlite3_memdebug_fail -1
 
+reset_db
+register_echo_module [sqlite3_connection_pointer db]
+do_execsql_test vtab_err-3.0 {
+  CREATE TABLE r(a PRIMARY KEY, b, c);
+  CREATE VIRTUAL TABLE e USING echo(r);
+}
+faultsim_save_and_close
+
+do_faultsim_test vtab_err-3 -faults oom-t* -prep {
+  faultsim_restore_and_reopen
+  register_echo_module [sqlite3_connection_pointer db]
+} -body {
+  execsql {
+    BEGIN;
+      CREATE TABLE xyz(x);
+      SELECT a FROM e;
+    COMMIT;
+  }
+} -test {
+  faultsim_test_result {0 {}}
+}
+
 finish_test
-- 
1.8.3.1

