不要怂,就是干,撸起袖子干!

Commit f18ddbd1 by sdepold

first working things in sqlite

1 parent 4d5f7f0e
var Utils = require("../../utils") var Utils = require("../../utils")
, sqlite3 = require('sqlite3').verbose() , sqlite3 = require('sqlite3').verbose()
, Query = require("./query")
module.exports = (function() { module.exports = (function() {
var ConnectorManager = function(sequelize, config) { var ConnectorManager = function(sequelize, config) {
this.sequelize = sequelize this.sequelize = sequelize
this.database = new sqlite3.Database(':memory:')
} }
Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype) Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype)
ConnectorManager.prototype.query = function(sql, callee, options) { ConnectorManager.prototype.query = function(sql, callee, options) {
return new Utils.CustomEventEmitter(function(emitter) { return new Query(this.database, callee, options).run(sql)
var db = new sqlite3.Database(':memory:')
db.serialize(function() {
db.run(sql, function(err, foo) {
if(err)
emitter.emit('failure', err)
else
emitter.emit('success', foo)
})
})
db.close()
}).run()
} }
return ConnectorManager return ConnectorManager
......
...@@ -6,15 +6,14 @@ module.exports = (function() { ...@@ -6,15 +6,14 @@ module.exports = (function() {
createTableQuery: function(tableName, attributes, options) { createTableQuery: function(tableName, attributes, options) {
options = options || {} options = options || {}
var query = "CREATE TABLE IF NOT EXISTS <%= table %>(<%= attributes%>)" var query = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>)"
, primaryKeys = [] , primaryKeys = []
, attrStr = Utils._.map(attributes, function(dataType, attr) { , attrStr = Utils._.map(attributes, function(dataType, attr) {
var dt = dataType if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (Utils._.includes(dt, 'PRIMARY KEY')) {
primaryKeys.push(attr) primaryKeys.push(attr)
return Utils.addTicks(attr) + " " + dt.replace(/PRIMARY KEY/, '') return Utils.addTicks(attr) + " " + dataType
} else { } else {
return Utils.addTicks(attr) + " " + dt return Utils.addTicks(attr) + " " + dataType
} }
}).join(", ") }).join(", ")
, values = { , values = {
...@@ -23,9 +22,61 @@ module.exports = (function() { ...@@ -23,9 +22,61 @@ module.exports = (function() {
charset: (options.charset ? "DEFAULT CHARSET=" + options.charset : "") charset: (options.charset ? "DEFAULT CHARSET=" + options.charset : "")
} }
var sql = Utils._.template(query)(values).trim() + ";" return Utils._.template(query)(values).trim() + ";"
console.log(sql) },
return sql
dropTableQuery: function(tableName, options) {
options = options || {}
var query = "DROP TABLE IF EXISTS <%= table %>;"
return Utils._.template(query)({table: Utils.addTicks(tableName)})
},
showTablesQuery: function() {
return "SELECT name FROM sqlite_master WHERE type='table';"
},
insertQuery: function(tableName, attrValueHash) {
var query = "INSERT INTO <%= table %> (<%= attributes %>) VALUES (<%= values %>);"
var replacements = {
table: Utils.addTicks(tableName),
attributes: Utils._.keys(attrValueHash).map(function(attr){return Utils.addTicks(attr)}).join(","),
values: Utils._.values(attrValueHash).map(function(value){
return Utils.escape((value instanceof Date) ? Utils.toSqlDate(value) : value)
}).join(",")
}
return Utils._.template(query)(replacements)
},
attributesToSQL: function(attributes) {
var result = {}
Utils._.map(attributes, function(dataType, name) {
if(Utils.isHash(dataType)) {
var template = "<%= type %>"
, replacements = { type: dataType.type }
if(dataType.hasOwnProperty('allowNull') && !dataType.allowNull && !dataType.primaryKey)
template += " NOT NULL"
if(dataType.defaultValue != undefined) {
template += " DEFAULT <%= defaultValue %>"
replacements.defaultValue = Utils.escape(dataType.defaultValue)
}
if(dataType.unique) template += " UNIQUE"
if(dataType.primaryKey) template += " PRIMARY KEY"
result[name] = Utils._.template(template)(replacements)
} else {
result[name] = dataType
}
})
return result
} }
} }
......
var Utils = require("../../utils")
module.exports = (function() {
var Query = function(database, callee, options) {
var self = this
this.database = database
this.callee = callee
this.options = Utils._.extend({
logging: true,
plain: false,
raw: false
}, options || {})
}
Utils.addEventEmitter(Query)
Query.prototype.run = function(sql) {
var self = this
this.sql = sql
if(this.options.logging)
console.log('Executing: ' + this.sql)
this.database.serialize(function() {
self.database.all(self.sql, function(err, results) {
err ? onFailure.call(self, err) : onSuccess.call(self, results)
})
})
return this
}
Query.prototype.success = Query.prototype.ok = function(fct) {
this.on('success', fct)
return this
}
Query.prototype.failure = Query.prototype.fail = Query.prototype.error = function(fct) {
this.on('failure', fct)
return this
}
//private
var onSuccess = function(results) {
var result = this.callee
, self = this
// add the inserted row id to the instance
if (this.callee && (this.sql.indexOf('INSERT INTO') == 0) && (results.hasOwnProperty('insertId')))
this.callee[this.callee.__definition.autoIncrementField] = results.insertId
if (this.sql.indexOf('sqlite_master') != -1) {
result = results.map(function(resultSet){ return resultSet.name })
} else if (this.sql.indexOf('SELECT') == 0) {
// transform results into real model instances
// return the first real model instance if options.plain is set (e.g. Model.find)
if(this.options.raw) {
result = results
} else {
result = results.map(function(result) {
return self.callee.build(result, { isNewRecord: false })
})
}
if(this.options.plain)
result = (result.length == 0) ? null : result[0]
} else if((this.sql.indexOf('SHOW') == 0) || (this.sql.indexOf('DESCRIBE') == 0))
result = results
this.emit('success', result)
}
var onFailure = function(err) {
this.emit('failure', err, this.callee)
}
return Query
})()
...@@ -23,13 +23,17 @@ describe('ModelFactory', function() { ...@@ -23,13 +23,17 @@ describe('ModelFactory', function() {
Helpers.async(function(done) { Helpers.async(function(done) {
User User
.create({ age: 21, name: 'John Wayne', bio: 'noot noot' }) .create({ age: 21, name: 'John Wayne', bio: 'noot noot' })
.success(function(user) { .success(done)
console.log(user) .error(function(err) { console.log(err) })
done()
}) })
.error(function(err) {
console.log(err) Helpers.async(function(done) {
User.all().success(function(users) {
var usernames = users.map(function(user) {
return user.name
}) })
expect(usernames).toEqual(['John Wayne'])
}).error(function(err){ console.log(err) })
}) })
}) })
}) })
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!