Skip to content

Commit

Permalink
first draft of db build
Browse files Browse the repository at this point in the history
  • Loading branch information
jackbridger committed Aug 21, 2019
1 parent 66789c7 commit d71aa31
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/model/database/build.js
Original file line number Diff line number Diff line change
@@ -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;
30 changes: 30 additions & 0 deletions src/model/database/build.sql
Original file line number Diff line number Diff line change
@@ -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);
27 changes: 27 additions & 0 deletions src/model/database/db_connection.js
Original file line number Diff line number Diff line change
@@ -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);

0 comments on commit d71aa31

Please sign in to comment.