From 263f19d0657c4aea1bd2b73f25ff96e437efc09d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yusuf=20=C4=B0pek?= Date: Tue, 11 Nov 2025 18:05:00 +0300 Subject: [PATCH] feat: add database initialization script command --- package.json | 1 + scripts/init-db.js | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 scripts/init-db.js diff --git a/package.json b/package.json index 878ef15..91626f3 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "type-check": "tsc --noEmit", "test:db": "node scripts/test-db.js", "init:backend": "chmod +x scripts/init-backend.sh && ./scripts/init-backend.sh", + "init:db": "node scripts/init-db.js", "sync:arch": "npx tsx scripts/sync-arch.ts" }, "dependencies": { diff --git a/scripts/init-db.js b/scripts/init-db.js new file mode 100644 index 0000000..a71997a --- /dev/null +++ b/scripts/init-db.js @@ -0,0 +1,41 @@ +#!/usr/bin/env node + +const { Pool } = require('pg') + +const DB_HOST = process.env.DB_HOST || 'localhost' +const DB_PORT = parseInt(process.env.DB_PORT || '5432', 10) +const DB_USER = process.env.DB_USER || 'postgres' +const DB_PASSWORD = process.env.DB_PASSWORD || '' +const DB_NAME = process.env.DB_NAME || 'repohub' + +async function main() { + // Connect to default 'postgres' database to create DB if missing + const admin = new Pool({ + host: DB_HOST, + port: DB_PORT, + database: 'postgres', + user: DB_USER, + password: DB_PASSWORD, + }) + + try { + console.log(`🔍 Ensuring database "${DB_NAME}" exists on ${DB_HOST}:${DB_PORT} ...`) + await admin.query(`CREATE DATABASE ${DB_NAME};`) + console.log(`✅ Created database "${DB_NAME}"`) + } catch (err) { + // 42P04 = duplicate_database + if (err && err.code === '42P04') { + console.log(`â„šī¸ Database "${DB_NAME}" already exists`) + } else { + console.error('❌ Failed to create database:', err) + process.exitCode = 1 + } + } finally { + await admin.end().catch(() => {}) + } +} + +main().catch((e) => { + console.error('❌ init:db failed:', e) + process.exit(1) +})