我为我的node-postgres项目提供了一个postgres模式,我只有两个没有创建外键的表(meetups和users表)。如何编写代码以使每个表都使用其外键创建?这是我在下面所做的事情,如何在表创建中始终使用await。预先谢谢你!
import { Pool } from 'pg';
import dotenv from 'dotenv';
dotenv.config();
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
pool.on('connect', () => {
console.log('connected to the db');
});
/**
* create Database Tables
*/
const createTables = () => {
const meetupTable = `CREATE TABLE IF NOT EXISTS
meetups(
id UUID PRIMARY KEY,
topic VARCHAR(128) NOT NULL,
location VARCHAR(128) NOT NULL,
body TEXT NOT NULL,
happeningOn TIMESTAMPTZ NOT NULL,
Tags TEXT[] NOT NULL,
meetupImage bytea,
createdOn TIMESTAMPTZ DEFAULT Now()
)``;
pool.query(meetupTable)
.catch((err) => {
console.log(err);
pool.end();
});
const questionTable = `CREATE TABLE IF NOT EXISTS
questions(
id UUID PRIMARY KEY,
title VARCHAR(128) UNIQUE NOT NULL,
votes INT REFERENCES votes(no_votes) ON DELETE RESTRICT,
body TEXT NOT NULL,
createdOn TIMESTAMPTZ
)`;
pool.query(questionTable)
.catch((err) => {
console.log(err);
pool.end();
});
const rsvpTable = `CREATE TABLE IF NOT EXISTS
rsvps(
id UUID PRIMARY KEY,
meetupId UUID UNIQUE REFERENCES meetups(id) ON DELETE RESTRICT,
userId UUID UNIQUE REFERENCES users(id) ON DELETE RESTRICT
response VARCHAR(128) NOT NULL,
date TIMESTAMPTZ DEFAULT Now()
)`;
pool.query(rsvpTable)
.catch((err) => {
console.log(err);
pool.end();
});
const userTable = `CREATE TABLE IF NOT EXISTS
users(
id UUID PRIMARY KEY,
userImage bytea,
firstName VARCHAR(128) NOT NULL,
lastName VARCHAR(128) NOT NULL,
otherName VARCHAR(128) NOT NULL,
email VARCHAR(128) UNIQUE NOT NULL,
password VARCHAR(128) NOT NULL,
userName VARCHAR(128) NOT NULL,
phoneNumber VARCHAR(128) NOT NULL,
isAdmin VARCHAR(128) NOT NULL,
createdOn TIMESTAMPTZ DEFAULT Now()
)`;
pool.query(userTable)
.catch((err) => {
console.log(err);
pool.end();
});
const votes = `CREATE TABLE IF NOT EXISTS
votes(
id UUID PRIMARY KEY,
questionId UUID REFERENCES questions(id) ON DELETE RESTRICT,
userId UUID UNIQUE REFERENCES users(id) ON DELETE RESTRICT,
no_votes INT PRIMARY KEY,
createdOn TIMESTAMPTZ
)`;
pool.query(votes)
.catch((err) => {
console.log(err);
pool.end();
});
};
pool.on('remove', () => {
console.log('client removed');
process.exit(0);
});
module.exports = {
createTables
};
require('make-runnable');