|
| 1 | +import { PGlite } from '@electric-sql/pglite' |
| 2 | +import fs from 'node:fs/promises' |
| 3 | +import path from 'node:path' |
| 4 | +import { fileURLToPath } from 'node:url' |
| 5 | +import { extract as tarExtract } from 'tar' |
| 6 | + |
| 7 | +const SCHEMA_URL = |
| 8 | + 'https://raw.githubusercontent.com/devrimgunduz/pagila/refs/heads/master/pagila-schema.sql' |
| 9 | +const DATA_URL = |
| 10 | + 'https://raw.githubusercontent.com/devrimgunduz/pagila/refs/heads/master/pagila-insert-data.sql' |
| 11 | +const THIS_DIR = path.dirname(fileURLToPath(import.meta.url)) |
| 12 | + |
| 13 | +// Download the schema and data from the internet |
| 14 | +console.log('Downloading schema...') |
| 15 | +const schema = await fetch(SCHEMA_URL).then((r) => r.text()) |
| 16 | +console.log('Downloading data...') |
| 17 | +const data = await fetch(DATA_URL).then((r) => r.text()) |
| 18 | + |
| 19 | +// Create a new PGlite instance |
| 20 | +console.log('Creating database...') |
| 21 | +const pg = await PGlite.create() |
| 22 | + |
| 23 | +// Initialize the schema |
| 24 | +console.log('Initializing database schema...') |
| 25 | +await pg.exec(schema) |
| 26 | + |
| 27 | +// Split the data into lines and execute each line so as to not run out of memory |
| 28 | +console.log('Inserting database data...') |
| 29 | +const dataLines = data.split('\n').filter((line) => line.trim().length > 0 && !line.startsWith('--')) |
| 30 | +for (const line of dataLines) { |
| 31 | + try { |
| 32 | + await pg.exec(line) |
| 33 | + } catch (e) { |
| 34 | + console.error(line) |
| 35 | + console.error(e) |
| 36 | + process.exit(1) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +console.log('Vacuuming database...') |
| 41 | +await pg.exec('VACUUM ANALYZE') |
| 42 | +await pg.exec('CHECKPOINT') |
| 43 | + |
| 44 | +console.log('Dumping database...') |
| 45 | +const file = await pg.dumpDataDir() |
| 46 | + |
| 47 | +console.log('Writing database...') |
| 48 | +await fs.writeFile( |
| 49 | + path.join(THIS_DIR, '..', 'public', 'pagila.tar.gz'), |
| 50 | + Buffer.from(await file.arrayBuffer()), |
| 51 | +) |
| 52 | + |
| 53 | +console.log('Extracting database...') |
| 54 | +await fs.mkdir(path.join(THIS_DIR, '..', 'public', 'pagila')) |
| 55 | +await tarExtract({ |
| 56 | + file: path.join(THIS_DIR, '..', 'public', 'pagila.tar.gz'), |
| 57 | + cwd: path.join(THIS_DIR, '..', 'public', 'pagila'), |
| 58 | +}) |
| 59 | + |
| 60 | +console.log('Done!') |
0 commit comments