-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
seed-local.ts
59 lines (56 loc) · 1.97 KB
/
seed-local.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { LibsqlError } from '@libsql/client';
import { type SQL, sql } from 'drizzle-orm';
import type { LibSQLDatabase } from 'drizzle-orm/libsql';
import { SQLiteAsyncDialect } from 'drizzle-orm/sqlite-core';
import { type DBTables } from '../core/types.js';
import { SEED_DEFAULT_EXPORT_ERROR } from './errors.js';
import { getCreateIndexQueries, getCreateTableQuery } from './queries.js';
import { AstroDbError } from './utils.js';
const sqlite = new SQLiteAsyncDialect();
export async function seedLocal({
db,
tables,
// Glob all potential seed files to catch renames and deletions.
userSeedGlob,
integrationSeedFunctions,
}: {
db: LibSQLDatabase;
tables: DBTables;
userSeedGlob: Record<string, { default?: () => Promise<void> }>;
integrationSeedFunctions: Array<() => Promise<void>>;
}) {
await recreateTables({ db, tables });
const seedFunctions: Array<() => Promise<void>> = [];
const seedFilePath = Object.keys(userSeedGlob)[0];
if (seedFilePath) {
const mod = userSeedGlob[seedFilePath];
if (!mod.default) throw new AstroDbError(SEED_DEFAULT_EXPORT_ERROR(seedFilePath));
seedFunctions.push(mod.default);
}
for (const seedFn of integrationSeedFunctions) {
seedFunctions.push(seedFn);
}
for (const seed of seedFunctions) {
try {
await seed();
} catch (e) {
if (e instanceof LibsqlError) {
throw new AstroDbError(`Failed to seed database:\n${e.message}`);
}
throw e;
}
}
}
export async function recreateTables({ db, tables }: { db: LibSQLDatabase; tables: DBTables }) {
const setupQueries: SQL[] = [];
for (const [name, table] of Object.entries(tables)) {
const dropQuery = sql.raw(`DROP TABLE IF EXISTS ${sqlite.escapeName(name)}`);
const createQuery = sql.raw(getCreateTableQuery(name, table));
const indexQueries = getCreateIndexQueries(name, table);
setupQueries.push(dropQuery, createQuery, ...indexQueries.map((s) => sql.raw(s)));
}
await db.batch([
db.run(sql`pragma defer_foreign_keys=true;`),
...setupQueries.map((q) => db.run(q)),
]);
}