@davoodmehraban89 / LifeMate / commits / 049c273
Fork 0

LifeMate — Personal, Family & Learning Companion

build: add portable PostgreSQL migration runner

davoodmehraban89 committed Oct 5, 2026 at 07:46 UTC 049c273f480b320718432418487e45ec1fe22496
1 file changed +52
backend/scripts/migrate.js new
+52
@@ -0,0 +1,52 @@
1 +import fs from 'node:fs/promises';
2 +import path from 'node:path';
3 +import pg from 'pg';
4 +
5 +const { Client } = pg;
6 +const databaseUrl = process.env.DATABASE_URL;
7 +if (!databaseUrl) throw new Error('DATABASE_URL is required');
8 +
9 +const client = new Client({
10 + connectionString: databaseUrl,
11 + ssl: databaseUrl.includes('localhost') ? false : { rejectUnauthorized: false },
12 +});
13 +
14 +await client.connect();
15 +try {
16 + await client.query(`
17 + create table if not exists schema_migration (
18 + filename text primary key,
19 + applied_at timestamptz not null default now()
20 + )
21 + `);
22 +
23 + const dir = path.resolve('migrations');
24 + const files = (await fs.readdir(dir))
25 + .filter((name) => /^\d+_.*\.sql$/.test(name))
26 + .sort();
27 +
28 + for (const filename of files) {
29 + const exists = await client.query(
30 + 'select 1 from schema_migration where filename=$1',
31 + [filename],
32 + );
33 + if (exists.rowCount) continue;
34 +
35 + const sql = await fs.readFile(path.join(dir, filename), 'utf8');
36 + await client.query('begin');
37 + try {
38 + await client.query(sql);
39 + await client.query(
40 + 'insert into schema_migration(filename) values($1)',
41 + [filename],
42 + );
43 + await client.query('commit');
44 + console.log('applied', filename);
45 + } catch (error) {
46 + await client.query('rollback');
47 + throw error;
48 + }
49 + }
50 +} finally {
51 + await client.end();
52 +}