const EventEmitter = require('events');
const SqlLite = require('sqlite3');
const { Sequelize } = require('sequelize');
const Umzug = require('umzug');
const { finished } = require('stream');
class database extends EventEmitter {
constructor() {
super();
this.db = null;
}
/**
* Starts / initializes database connection to core database
* @param {function} callback true or false
*/
startDatabase(callback) {
console.log('MODELS-DATABASE | Starting check for database existence');
this.checkIfCoreDatabaseExists((successDB) => {
if (successDB) {
console.log('MODELS-DATABASE | Starting database migrations');
this.runMigrations((successMigrations) => {
if (successMigrations) {
this.openCoreDatabase((successConnection) => {
if (successConnection) {
console.log('MODELS-DATABASE | Initialization of Core Database: ' + successConnection);
callback(true);
} else {
callback(false);
}
})
} else {
callback(false);
}
})
} else {
callback(false);
}
})
}
/**
* Runs database migration steps
* @param {function} callback true or false
*/
runMigrations(callback) {
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: './store/coredatabase.db',
logging: msg => {
console.log("SEQUELIZE | " + msg);
}
});
const umzug = new Umzug({
migrations: {
path: './migrations',
params: [
sequelize.getQueryInterface()
]
},
storage: 'sequelize',
storageOptions: {
sequelize: sequelize
}
});
(async () => {
// Checks migrations and run them if they are not already applied. To keep
// track of the executed migrations, a table (and sequelize model) called SequelizeMeta
// will be automatically created (if it doesn't exist already) and parsed.
await umzug.up();
// HIER MUSS DER CALLBACK SEIN
callback(true);
})();
}
/**
* Checks if coredatabase exists. if not -> copy template for initial start.
* @param {function} callback success (true or false)
*/
checkIfCoreDatabaseExists(callback) {
const fs = require('fs');
try {
if (fs.existsSync(global.appRoot + '/store/coredatabase.db')) {
console.log("MODELS | DATABASE | coredatabase exists. Ready to open.");
} else {
console.log('MODELS | DATABASE | coredatabase does not exist. Copying initial template to store.');
fs.copyFileSync(global.appRoot + '/store/templates/coredatabase.db', global.appRoot + '/store/coredatabase.db');
}
/* So funktionierts .... */
callback(true);
// Aber callback wird aufgerufen, bevor dbmigrate durchläuft
} catch (err) {
console.error(err);
callback(false);
}
}
/**
* initializes connection to core database
* @param {function} callback success (true or false)
*/
openCoreDatabase(callback) {
this.db = new SqlLite.Database(global.appRoot + '/store/coredatabase.db', (err) => {
if (err) {
console.log('DATABASEMANAGER | Could not connect to database', err);
callback(false);
} else {
console.log('DATABASEMANAGER | Connected');
callback(true);
}
})
}
}
module.exports = database;