-
Notifications
You must be signed in to change notification settings - Fork 483
Expand file tree
/
Copy pathdb.init.js
More file actions
81 lines (64 loc) · 2.17 KB
/
db.init.js
File metadata and controls
81 lines (64 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
Initialization script for database setup.
Usage:
Run this file once to create the database (and optionally the tables):
$ node ./app/config/db.init.js
By default, this script runs immediately when executed.
It does NOT export any functions since it’s meant to be a one-time setup.
If you prefer to import and call the functions manually elsewhere,
just uncomment the last line, and paste the following script in the desired file:
const { createDatabase, createTables } = require('./app/config/db.init');
createDatabase();
createTables();
*/
const { Sequelize } = require("sequelize");
const dbConfig = require("../config/db.config.js");
async function createDatabase() {
const sequelize = new Sequelize("", dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.DIALECT,
});
try {
await sequelize.query(`CREATE DATABASE IF NOT EXISTS \`${dbConfig.DB}\`;`);
console.log(`Database "${dbConfig.DB}" created successfully!`);
} catch (err) {
console.error("Error creating database:", err);
} finally {
await sequelize.close();
}
}
async function createTables() {
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.DIALECT,
});
// every table should be imported as it follows:
const { TutorialModel } = require("../models/tutorial.model.js");
// the model should be added to "modelNameList":
const modelNameList = [TutorialModel];
for (const modelDef of modelNameList) {
const attributes = modelDef.getAttributes();
sequelize.define(
modelDef.name,
attributes,
{
...(modelDef.options || {}),
tableName: modelDef.options?.tableName ?? modelDef.tableName
}
);
}
try {
await sequelize.sync({ force: true });
console.log(`All tables created/updated successfully in database "${dbConfig.DB}"!`);
} catch (err) {
console.error(`Failed to create tables:`, err);
} finally {
await sequelize.close();
}
}
async function init() {
await createDatabase();
await createTables();
}
init();
// module.exports = { createDatabase, createTables }; // uncomment line to export function