Skip to content
This repository has been archived by the owner on Nov 3, 2023. It is now read-only.

Commit

Permalink
Try new way of seeding db
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcusAhlfors committed Aug 22, 2023
1 parent 7f02b28 commit 85c07e8
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 23 deletions.
22 changes: 0 additions & 22 deletions initialProject/lib/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,3 @@ export const query = async (statement: string | SQLStatement) => {
throw new Error(`\DB error: ${error.message}`);
}
};

// Create database if it doesn't exist
// NOTE! Not the ideal place/way of doing this, but works for now
const initDb = async () => {
try {
// await query(sql`DROP TABLE IF EXISTS todo`);
const exists = (await query(sql`SELECT to_regclass('public.todo') as exists`))[0].exists;
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);
}
};

initDb();
35 changes: 35 additions & 0 deletions initialProject/lib/seedDatabase.js
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();
})();
2 changes: 1 addition & 1 deletion initialProject/pages/api/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
import sql from 'sql-template-strings';
import { query } from '../../lib/db';

export type ListResponse = { list: { id: number; name: string; checked: boolean; }[]; };
export type ListResponse = { list: { id: number; name: string; checked: boolean }[] };

export default async (req: NextApiRequest, res: NextApiResponse) => {
const list = await query(sql`
Expand Down
4 changes: 4 additions & 0 deletions runonce.sh
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ update-ca-certificates
# Make all special env variables available in ssh also (ssh will wipe out env by default)
env >> /etc/environment

# Seed database
# NOTE! Not ideal, this assumes postgres starts faster than app container
node /app/lib/seedDatabase.js

# Now that everything is initialized, start all services
supervisorctl start www

Expand Down

0 comments on commit 85c07e8

Please sign in to comment.