This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
forked from diploi/nextjs-postgresql-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7f02b28
commit 85c07e8
Showing
4 changed files
with
40 additions
and
23 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
const { Pool } = require('pg'); | ||
const sql = require('sql-template-strings'); | ||
|
||
const conn = new Pool({ | ||
user: process.env.POSTGRES_USER, | ||
password: process.env.POSTGRES_PASSWORD, | ||
host: process.env.POSTGRES_HOST, | ||
port: parseInt(process.env.POSTGRES_PORT) || 5432, | ||
database: process.env.POSTGRES_DB, | ||
}); | ||
|
||
const query = async (statement) => { | ||
try { | ||
return (await conn.query(statement)).rows; | ||
} catch (error) { | ||
throw new Error(`\DB error: ${error.message}`); | ||
} | ||
}; | ||
|
||
(async () => { | ||
try { | ||
let exists = false; | ||
try { | ||
exists = (await query(sql`SELECT to_regclass('public.todo') as exists`))[0].exists == 'todo'; | ||
} catch (e) {} | ||
if (!exists) { | ||
console.log(new Date().toISOString(), 'Initializing database'); | ||
await query(sql`CREATE TABLE todo (id SERIAL PRIMARY KEY, name TEXT NOT NULL, checked BOOLEAN NOT NULL)`); | ||
await query(sql`INSERT INTO todo (name, checked) VALUES ('Bananas', TRUE), ('Milk', FALSE), ('Noodles', FALSE)`); | ||
} | ||
} catch (createError) { | ||
console.log(new Date().toISOString(), 'Error initializing database', createError); | ||
} | ||
process.exit(); | ||
})(); |
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
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