sync/database.js

103 lines
2.8 KiB
JavaScript
Raw Normal View History

2013-08-12 14:34:57 +00:00
var mysql = require("mysql");
2013-06-04 22:26:17 +00:00
2013-08-12 14:34:57 +00:00
var Logger = {
errlog: {
log: function () {
console.log(arguments[0]);
2013-05-26 01:01:32 +00:00
}
}
2013-08-12 14:34:57 +00:00
};
2013-06-03 22:37:30 +00:00
2013-08-12 14:34:57 +00:00
var Database = function (cfg) {
this.cfg = cfg;
this.pool = mysql.createPool({
host: cfg["mysql-server"],
user: cfg["mysql-user"],
password: cfg["mysql-pw"],
database: cfg["mysql-db"]
});
2013-06-03 22:37:30 +00:00
2013-08-12 14:34:57 +00:00
// Test the connection
this.pool.getConnection(function (err, conn) {
if(err) {
Logger.errlog.log("! DB connection failed");
}
conn.end();
});
};
Database.prototype.query = function (query, sub, callback) {
// 2nd argument is optional
if(typeof sub === "function") {
callback = sub;
sub = false;
}
var self = this;
self.pool.getConnection(function (err, conn) {
if(err) {
callback("Database failure", null);
conn.end();
} else {
function cback(err, res) {
if(err) {
callback("Database failure", null);
} else {
callback(null, res);
}
conn.end();
2013-06-03 22:37:30 +00:00
}
2013-08-12 14:34:57 +00:00
if(sub)
conn.query(query, sub, cback);
else {
conn.query(query, cback);
}
}
});
}
2013-04-02 19:39:56 +00:00
2013-08-12 14:34:57 +00:00
Database.prototype.init = function () {
var self = this;
var query;
2013-05-26 01:01:32 +00:00
// Create channel table
2013-08-12 14:34:57 +00:00
query = ["CREATE TABLE IF NOT EXISTS `channels` (",
"`id` INT NOT NULL AUTO_INCREMENT,",
"`name` VARCHAR(255) NOT NULL,",
"`owner` VARCHAR(20) NOT NULL,",
"PRIMARY KEY(`id`))",
"ENGINE = MyISAM;"].join("");
self.query(query, function (err, res) {
if(err) {
Logger.errlog.log("! Failed to create channels table");
} else {
console.log("Created channels table");
}
});
2013-05-26 01:01:32 +00:00
// Create registration table
query = ["CREATE TABLE IF NOT EXISTS `registrations` (",
"`id` INT NOT NULL AUTO_INCREMENT,",
"`uname` VARCHAR(20) NOT NULL,",
"`pw` VARCHAR(64) NOT NULL,",
"`global_rank` INT NOT NULL,",
"`session_hash` VARCHAR(64) NOT NULL,",
"`expire` BIGINT NOT NULL,",
"`profile_image` VARCHAR(255) NOT NULL,",
"`profile_text` TEXT NOT NULL,",
2013-05-30 18:52:00 +00:00
"`email` VARCHAR(255) NOT NULL,",
2013-05-26 01:01:32 +00:00
"PRIMARY KEY (`id`))",
"ENGINE = MyISAM;"].join("");
2013-08-12 14:34:57 +00:00
self.query(query, function (err, res) {
if(err) {
Logger.errlog.log("! Failed to create registration table");
} else if(self.cfg["debug"]) {
console.log("Created registrations table");
2013-05-26 01:01:32 +00:00
}
2013-06-18 03:57:29 +00:00
});
2013-08-12 14:34:57 +00:00
};
2013-06-18 03:57:29 +00:00
2013-08-12 14:34:57 +00:00
module.exports = Database;