From 1adeae9f2c09f64120ee10f08a5540f07dcc8018 Mon Sep 17 00:00:00 2001 From: Illya Popov Date: Sun, 29 Nov 2026 07:17:05 +0000 Subject: [PATCH] Fix #59: Database dumps do not work on large databases --- src/export/dump.ts | 114 +++++++++++++++++++++++++++------------------ 1 file changed, 68 insertions(+), 46 deletions(-) diff --git a/src/export/dump.ts b/src/export/dump.ts index 91a2e89..01f056a 100644 --- a/src/export/dump.ts +++ b/src/export/dump.ts @@ -3,69 +3,91 @@ import { StarbaseDBConfiguration } from '../handler' import { DataSource } from '../types' import { createResponse } from '../utils' +const BATCH_SIZE = 1000 + export async function dumpDatabaseRoute( dataSource: DataSource, config: StarbaseDBConfiguration ): Promise { - try { - // Get all table names - const tablesResult = await executeOperation( - [{ sql: "SELECT name FROM sqlite_master WHERE type='table';" }], - dataSource, - config - ) + const { readable, writable } = new TransformStream() + const writer = writable.getWriter() + const encoder = new TextEncoder() - const tables = tablesResult.map((row: any) => row.name) - let dumpContent = 'SQLite format 3\0' // SQLite file header + const streamDump = async () => { + try { + // 1. SQLite Header + await writer.write(encoder.encode('SQLite format 3\0')) - // Iterate through all tables - for (const table of tables) { - // Get table schema - const schemaResult = await executeOperation( - [ - { - sql: `SELECT sql FROM sqlite_master WHERE type='table' AND name='${table}';`, - }, - ], + // 2. Get all table names + const tablesResult = await executeOperation( + [{ sql: "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';" }], dataSource, config ) + const tables = tablesResult.map((row: any) => row.name) - if (schemaResult.length) { - const schema = schemaResult[0].sql - dumpContent += `\n-- Table: ${table}\n${schema};\n\n` - } + for (const table of tables) { + // 3. Get table schema + const schemaResult = await executeOperation( + [{ sql: `SELECT sql FROM sqlite_master WHERE type='table' AND name='${table}';` }], + dataSource, + config + ) - // Get table data - const dataResult = await executeOperation( - [{ sql: `SELECT * FROM ${table};` }], - dataSource, - config - ) + if (schemaResult.length) { + const schema = schemaResult[0].sql + await writer.write(encoder.encode(`\n\n-- Table: ${table}\n${schema};\n`)) + } - for (const row of dataResult) { - const values = Object.values(row).map((value) => - typeof value === 'string' - ? `'${value.replace(/'/g, "''")}'` - : value - ) - dumpContent += `INSERT INTO ${table} VALUES (${values.join(', ')});\n` + // 4. Batch fetch table data (Pagination) + let offset = 0 + while (true) { + const dataResult = await executeOperation( + [{ sql: `SELECT * FROM ${table} LIMIT ${BATCH_SIZE} OFFSET ${offset};` }], + dataSource, + config + ) + + if (dataResult.length === 0) break + + for (const row of dataResult) { + const keys = Object.keys(row) + const values = keys.map((key) => { + const value = row[key] + if (value === null) return 'NULL' + if (typeof value === 'string') return `'${value.replace(/'/g, "''")}'` + if (typeof value === 'boolean') return value ? '1' : '0' + return value + }) + await writer.write( + encoder.encode(`INSERT INTO ${table} (${keys.join(', ')}) VALUES (${values.join(', ')});\n`) + ) + } + + offset += BATCH_SIZE + if (dataResult.length < BATCH_SIZE) break + } } - dumpContent += '\n' + await writer.write(encoder.encode('\n')) + await writer.close() + } catch (error: any) { + console.error('Database Dump Streaming Error:', error) + // Note: In a streaming response, we can't change the status code once headers are sent. + // But we can abort the stream. + await writer.abort(error) } + } - // Create a Blob from the dump content - const blob = new Blob([dumpContent], { type: 'application/x-sqlite3' }) + // Start background streaming + streamDump() - const headers = new Headers({ + return new Response(readable, { + headers: { 'Content-Type': 'application/x-sqlite3', 'Content-Disposition': 'attachment; filename="database_dump.sql"', - }) - - return new Response(blob, { headers }) - } catch (error: any) { - console.error('Database Dump Error:', error) - return createResponse(undefined, 'Failed to create database dump', 500) - } + 'Transfer-Encoding': 'chunked', + 'X-Content-Type-Options': 'nosniff', + }, + }) }