-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmigrate.ts
More file actions
76 lines (66 loc) · 1.81 KB
/
migrate.ts
File metadata and controls
76 lines (66 loc) · 1.81 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { spawnSync } from 'node:child_process';
import { Pool } from 'pg';
import config from '../src/config.js';
const pnpmCommand = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
const directDatabaseUrl = config.directDatabaseUrl;
if (!directDatabaseUrl) {
throw new Error('db:migrate requires DIRECT_DATABASE_URL when DATABASE_URL uses Prisma Accelerate.');
}
function runPrisma(args: string[]) {
const result = spawnSync(
pnpmCommand,
['exec', 'prisma', ...args],
{
env: process.env,
stdio: 'inherit',
},
);
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}
async function bootstrapIfNeeded() {
const pool = new Pool({
connectionString: directDatabaseUrl,
});
try {
const [{ migrationsTableExists, countriesTableExists }] = (
await pool.query<{
migrationsTableExists: string | null;
countriesTableExists: string | null;
}>(
`
SELECT
to_regclass('public._prisma_migrations') AS "migrationsTableExists",
to_regclass('public.countries') AS "countriesTableExists"
`,
)
).rows;
const initApplied = migrationsTableExists
? (
await pool.query<{ exists: boolean }>(
`SELECT EXISTS(
SELECT 1
FROM "_prisma_migrations"
WHERE migration_name = 'init'
) AS "exists"`,
)
).rows[0]?.exists ?? false
: false;
if (!initApplied) {
if (!countriesTableExists) {
runPrisma([
'db',
'execute',
'--file',
'prisma/migrations/init/migration.sql',
]);
}
runPrisma(['migrate', 'resolve', '--applied', 'init']);
}
} finally {
await pool.end();
}
}
await bootstrapIfNeeded();
runPrisma(['migrate', 'deploy']);