@@ -1144,6 +1144,23 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
11441144 var destination = NULL ;
11451145 var backup = NULL ;
11461146 try {
1147+ var file = FS . lookupPath ( filename ) . node ;
1148+ var binaryDb = null ;
1149+ var write = file . stream_ops . write ;
1150+ file . stream_ops = Object . create ( file . stream_ops ) ;
1151+ file . stream_ops . write = function writeExport (
1152+ stream , buffer , offset , length , position
1153+ ) {
1154+ if ( binaryDb === null ) {
1155+ return write ( stream , buffer , offset , length , position ) ;
1156+ }
1157+ // Write directly into the final JS-owned result buffer.
1158+ // MEMFS would otherwise replace it on the first write.
1159+ file . contents . set ( buffer . subarray ( offset , offset + length ) ,
1160+ position ) ;
1161+ file . usedBytes = Math . max ( file . usedBytes , position + length ) ;
1162+ return length ;
1163+ } ;
11471164 var rc = sqlite3_open ( filename , apiTemp ) ;
11481165 destination = getValue ( apiTemp , "i32" ) ;
11491166 if ( rc !== SQLITE_OK ) {
@@ -1153,7 +1170,18 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
11531170 if ( backup === NULL ) {
11541171 throw new Error ( sqlite3_errmsg ( destination ) ) ;
11551172 }
1156- rc = sqlite3_backup_step ( backup , - 1 ) ;
1173+ // Initialize the backup and reject writers before allocating.
1174+ rc = sqlite3_backup_step ( backup , 0 ) ;
1175+ if ( rc === SQLITE_OK ) {
1176+ var sizes = this . exec (
1177+ "PRAGMA main.page_count; PRAGMA main.page_size"
1178+ ) ;
1179+ binaryDb = new Uint8Array (
1180+ sizes [ 0 ] . values [ 0 ] [ 0 ] * sizes [ 1 ] . values [ 0 ] [ 0 ]
1181+ ) ;
1182+ file . contents = binaryDb ;
1183+ rc = sqlite3_backup_step ( backup , - 1 ) ;
1184+ }
11571185 // Do not retry: this synchronous call cannot let a writer progress.
11581186 if ( rc === SQLITE_BUSY || rc === SQLITE_LOCKED ) {
11591187 throw new Error ( "Unable to export: SQLite is busy or locked. "
@@ -1172,7 +1200,9 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
11721200 throw new Error ( sqlite3_errmsg ( destination ) ) ;
11731201 }
11741202 destination = NULL ;
1175- var binaryDb = FS . readFile ( filename , { encoding : "binary" } ) ;
1203+ // The private file is closed and unlinked below; hand its buffer
1204+ // to the caller rather than making a full-size FS.readFile copy.
1205+ binaryDb = file . contents . subarray ( 0 , file . usedBytes ) ;
11761206 if ( binaryDb . length > 0 ) {
11771207 // All pages, including WAL pages, are in the backup.
11781208 // Make the exported copy independent of WAL support.
0 commit comments