forked from harikrishna0315/uni_map
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_database.js
More file actions
56 lines (47 loc) Β· 2.25 KB
/
setup_database.js
File metadata and controls
56 lines (47 loc) Β· 2.25 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
const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
async function setupDatabase() {
const config = {
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD,
multipleStatements: true // Needed for running SQL files
};
console.log(`π Connecting to MySQL at ${config.host} as ${config.user}...`);
let connection;
try {
connection = await mysql.createConnection(config);
console.log('β
Connected to MySQL server.');
// Create Database
const dbName = process.env.DB_NAME || 'uni';
console.log(`π¨ Recreating database '${dbName}'...`);
await connection.query(`DROP DATABASE IF EXISTS ${dbName}`);
await connection.query(`CREATE DATABASE ${dbName}`);
await connection.query(`USE ${dbName}`);
console.log(`π Selected database '${dbName}'.`);
// Read and Execute Schema
console.log('π Importing schema from university_schema.sql...');
const schemaSql = fs.readFileSync(path.join(__dirname, 'university_schema.sql'), 'utf8').replace(/^\uFEFF/, '');
await connection.query(schemaSql);
console.log('β
Schema imported.');
// Read and Execute Data
console.log('Buildings data from ssn_buildings.sql...');
const dataSql = fs.readFileSync(path.join(__dirname, 'ssn_buildings.sql'), 'utf8');
// ssn_buildings.sql has "USE uni;" which might conflict if db name is different, but we selected it.
// It's safer to remove "USE uni;" from the file content or just run it.
// Mysql2 with multipleStatements should handle it, but let's be safe.
await connection.query(dataSql);
console.log('β
Buildings data imported.');
console.log('\nπ Database setup complete! You can now run "npm start".');
} catch (err) {
console.error('β Error setting up database:', err.message);
if (err.code === 'ER_ACCESS_DENIED_ERROR') {
console.error('\nπ HINT: detailed check your DB_PASSWORD in the .env file.');
}
} finally {
if (connection) await connection.end();
}
}
setupDatabase();