From d71aa310fabb65cdfb5ad81994e2378e034f3c90 Mon Sep 17 00:00:00 2001 From: Jack Bridger Date: Wed, 21 Aug 2019 18:05:12 +0100 Subject: [PATCH] first draft of db build --- src/model/database/build.js | 11 +++++++++++ src/model/database/build.sql | 30 +++++++++++++++++++++++++++++ src/model/database/db_connection.js | 27 ++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) diff --git a/src/model/database/build.js b/src/model/database/build.js index e69de29..137fe3a 100644 --- a/src/model/database/build.js +++ b/src/model/database/build.js @@ -0,0 +1,11 @@ +const fs = require("fs"); +const path = require("path"); +const dbConnection = require("./db_connection"); + +const sqlPath = path.join(__dirname, "build.sql"); +const sql = fs.readFileSync(sqlPath).toString(); +const runDbBuild = cb => { + dbConnection.query(sql, cb); +}; + +module.exports = runDbBuild; diff --git a/src/model/database/build.sql b/src/model/database/build.sql index e69de29..ea32024 100644 --- a/src/model/database/build.sql +++ b/src/model/database/build.sql @@ -0,0 +1,30 @@ +BEGIN; + +DROP TABLE IF EXISTS users CASCADE; +DROP TABLE IF EXISTS animals CASCADE; +DROP TABLE IF EXISTS adoption CASCADE; + +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + name VARCHAR(30) NOT NULL +); + +CREATE TABLE animals ( + id SERIAL PRIMARY KEY, + name VARCHAR(30) NOT NULL +); + +CREATE TABLE adoption ( + id SERIAL PRIMARY KEY, + user_id INTEGER REFERENCES users(id), + animal_id INTEGER REFERENCES animals(id) +); + +INSERT INTO users (name) +VALUES ('Gregor'), ('Andy'), ('Francesca'), ('Jack'); + +INSERT INTO animals (name) +VALUES ('Pig'), ('Goat'), ('Tiger'), ('Monkey'); + +INSERT INTO adoption (name) +VALUES (1,2), (2,1), (2,4), (3,3), (3,1), (4,1); \ No newline at end of file diff --git a/src/model/database/db_connection.js b/src/model/database/db_connection.js index e69de29..84e8dd9 100644 --- a/src/model/database/db_connection.js +++ b/src/model/database/db_connection.js @@ -0,0 +1,27 @@ +const { Pool } = require("pg"); +const url = require("url"); +require("env2")("./config.env"); + +let DB_URL = process.env.DB_URL; + +if (process.env.NODE_env === "test") { + DB_URL = process.env.TEST_DB_URL; +} + +if (!DB_URL) throw new Error("env var db url does not exist"); + +const params = url.parse(DB_URL); +const [user, password] = params.auth.split(":"); + +const options = { + host: params.hostname, + port: params.port, + database: params.pathname.split("/")[1], + max: process.env.DB_MAX_CONNECTIONS || 2, + user, + password +}; + +options.ssl = options.host !== "localhost"; + +module.exports = new Pool(options);