Created
August 28, 2024 19:05
-
-
Save Digital39999/d7adc04b39d05fdbd3bb194b989b8092 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client } from 'pg'; | |
import env from 'dotenv'; | |
// Load .env file. | |
env.config(); | |
const connectionURL = process.env.DATABASE_URL; | |
if (!connectionURL) throw new Error('Missing DATABASE_URL environment variable.'); | |
const defaultSchemaUrl = connectionURL.replace(/\/[^/]*$/, '/postgres'); | |
const client = new Client({ connectionString: defaultSchemaUrl }); | |
(async () => { | |
try { | |
await client.connect(); | |
const dbName = connectionURL?.replace(/.*\//, ''); | |
const result = await client.query(`SELECT 1 FROM pg_database WHERE datname = '${dbName}'`); | |
if (result.rows.length !== 0) console.log('Database already exists.'); | |
else { | |
console.log(dbName); | |
await client.query(`CREATE DATABASE "${dbName}"`); | |
console.log('Database created.'); | |
} | |
} catch (error) { | |
console.error('Error:', error); | |
} finally { | |
await client.end(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment