Skip to content

Instantly share code, notes, and snippets.

@Digital39999
Created August 28, 2024 19:05
Show Gist options
  • Save Digital39999/d7adc04b39d05fdbd3bb194b989b8092 to your computer and use it in GitHub Desktop.
Save Digital39999/d7adc04b39d05fdbd3bb194b989b8092 to your computer and use it in GitHub Desktop.
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