[英]Postgres sql script to manage database in nodejs
我正在嘗試從 node.js 自動創建數據庫並刪除 postgres sql 上的表。 我編寫了一個運行良好的腳本,但它的行為方式很奇怪。 讓我先在這里發布代碼然后解釋這個問題。
db.js 文件
require('dotenv').config()
const { Pool } = require('pg')
const isProduction = process.env.NODE_ENV === 'production'
// don't try to load .env file on Heroku
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
// get the current environment
var env = process.env.NODE_ENV
console.log(env);
// convert to uppercase
var envString = env.toUpperCase()
// access the environment variables for this environment
var DB_USER = process.env['DB_USER_' + envString]
var DB_PASSWORD = process.env['DB_PASSWORD_' + envString]
var DB_HOST = process.env['DB_HOST_' + envString]
var DB_PORT = process.env['DB_PORT_' + envString]
var DB_DATABASE = process.env['DB_DATABASE_' + envString]
const connectionString = `postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_DATABASE}`
const pool = new Pool({
connectionString: connectionString
});
pool.on('connect', () => {
console.log('connected to the database');
});
/**
* Create Users Table
*/
const createUsersTable = () => {
const queryText =
`CREATE TABLE IF NOT EXISTS users (
userId SERIAL PRIMARY KEY,
firstName VARCHAR (50) NOT NULL,
lastName VARCHAR (50) NOT NULL,
email VARCHAR (50) NOT NULL,
password VARCHAR (255) NOT NULL,
gender VARCHAR(10) check (gender in ('Male', 'Female')),
jobRole VARCHAR(10) check (jobRole in ('Admin', 'User')),
department VARCHAR (100) NOT NULL,
address VARCHAR (100) NOT NULL,
createdOn TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
UNIQUE (email)
)`;
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Create GIFs Table
*/
const createGifsTable = () => {
const queryText =
`CREATE TABLE IF NOT EXISTS Gifs (
gifId SERIAL PRIMARY KEY,
image VARCHAR (50) NOT NULL,
title VARCHAR (50) NOT NULL,
flags INTEGER DEFAULT 0,
userId INTEGER REFERENCES Users(userId) ON DELETE CASCADE,
createdOn TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)`;
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Create Articles Table
*/
const createArticlesTable = () => {
const queryText =
`CREATE TABLE IF NOT EXISTS Articles (
articleId SERIAL PRIMARY KEY,
title VARCHAR (100) NOT NULL,
article TEXT NOT NULL,
flags INTEGER DEFAULT 0,
userId INTEGER REFERENCES Users(userId) ON DELETE CASCADE,
createdOn TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)`;
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Create Category Table
*/
const createCategoryTable = () => {
const queryText =
`CREATE TABLE IF NOT EXISTS Category (
categoryId SERIAL PRIMARY KEY,
category VARCHAR (50) NOT NULL,
articleId INTEGER REFERENCES Articles(articleId) ON DELETE CASCADE,
createdOn TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)`;
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Create ArticleComments Table
*/
const createArticleCommentsTable = () => {
const queryText =
`CREATE TABLE IF NOT EXISTS ArticleComments (
commentId SERIAL PRIMARY KEY,
comment TEXT NOT NULL,
flags INTEGER DEFAULT 0,
articleId INTEGER REFERENCES Articles(articleId) ON DELETE CASCADE,
createdOn TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)`;
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Create GifComments Table
*/
const createGifCommentsTable = () => {
const queryText =
`CREATE TABLE IF NOT EXISTS GifComments (
commentId SERIAL PRIMARY KEY,
comment TEXT NOT NULL,
flags INTEGER DEFAULT 0,
gifId INTEGER REFERENCES Gifs(gifId) ON DELETE CASCADE,
createdOn TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)`;
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Drop Users Table
*/
const dropUsersTable = () => {
const queryText = 'DROP TABLE IF EXISTS Users';
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Drop Gifs Table
*/
const dropGifsTable = () => {
const queryText = 'DROP TABLE IF EXISTS Gifs';
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Drop Articles Table
*/
const dropArticlesTable = () => {
const queryText = 'DROP TABLE IF EXISTS Articles';
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Drop Category Table
*/
const dropCategoryTable = () => {
const queryText = 'DROP TABLE IF EXISTS Category';
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Drop ArticleComments Table
*/
const dropArticleCommentsTable = () => {
const queryText = 'DROP TABLE IF EXISTS ArticleComments';
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Drop GifComments Table
*/
const dropGifCommentsTable = () => {
const queryText = 'DROP TABLE IF EXISTS GifComments';
pool.query(queryText)
.then((res) => {
console.log(res);
pool.end();
})
.catch((err) => {
console.log(err);
pool.end();
});
}
/**
* Create All Tables
*/
const createAllTables = () => {
createUsersTable();
createGifsTable();
createArticlesTable();
createCategoryTable();
createArticleCommentsTable();
createGifCommentsTable();
}
/**
* Drop All Tables
*/
const dropAllTables = () => {
dropArticleCommentsTable();
dropGifCommentsTable();
dropCategoryTable();
dropGifsTable();
dropArticlesTable();
dropUsersTable();
}
pool.on('remove', () => {
console.log('client removed');
process.exit(0);
});
module.exports = {
createUsersTable,
createGifsTable,
createArticlesTable,
createCategoryTable,
createArticleCommentsTable,
createGifCommentsTable,
createAllTables,
dropUsersTable,
dropGifsTable,
dropArticlesTable,
dropCategoryTable,
dropArticleCommentsTable,
dropGifCommentsTable,
dropAllTables
};
require('make-runnable');
在這個文件中,我創建了單獨的函數來創建和刪除數據庫表。 我在 package.js 上的腳本如下所示:
"scripts": {
"start": "NODE_ENV=dev nodemon server.js",
"test": "NODE_ENV=test mocha --exit",
"dbCreate": "NODE_ENV=dev node -e 'require(\"./db\").createAllTables()'"
}
最后,由於我已將 db.js 中的所有單獨的創建表命令添加到db.js
createAllTables
並將其添加到腳本中,因此我希望在我運行命令npm run dbCreate
時創建表。
當我執行命令npm run dbCreate
時,它會創建總共 1 個或 2 個表。 當我再次執行時,它會另外創建一個或兩個表。 因此,對於要創建的所有表,我必須重復執行命令,但我希望在一個 go 上完成。 當我用 dropAllTables 替換createAllTables
function 時, dropAllTables
發生同樣的事情。 有什么我做錯了嗎? 我想在運行自動化測試時使用這個腳本。
盡量不要在回調中調用pool.end()
。 我目前沒有時間進行測試,但看起來正在發生的事情是您正在關閉連接然后沒有重新打開它,因此由於它們是異步的,您可能能夠在第一個解決之前關閉兩個命令,但是一旦第一個查詢完成,它總是會停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.