Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 68 additions & 46 deletions src/export/dump.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response> {
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',
},
})
}