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

Commit 2fa8a6e4 by sdepold

refactored query-generator

1 parent 40911a89
var Utils = require("../../utils") var Utils = require("../../utils")
, util = require("util") , util = require("util")
var QueryGenerator = module.exports = { module.exports = (function() {
/* var QueryGenerator = {
Returns a query for creating a table. /*
Attributes should have the format: {attributeName: type, attr2: type2} --> {title: 'VARCHAR(255)'} Returns a query for creating a table.
*/ Attributes should have the format: {attributeName: type, attr2: type2} --> {title: 'VARCHAR(255)'}
createTableQuery: function(tableName, attributes, options) { */
options = options || {} createTableQuery: function(tableName, attributes, options) {
options = options || {}
var query = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>) ENGINE=<%= engine %> <%= charset %>"
, primaryKeys = [] var query = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>) ENGINE=<%= engine %> <%= charset %>"
, attrStr = Utils._.map(attributes, function(dataType, attr) { , primaryKeys = []
var dt = dataType , attrStr = Utils._.map(attributes, function(dataType, attr) {
if (Utils._.includes(dt, 'PRIMARY KEY')) { var dt = dataType
primaryKeys.push(attr) if (Utils._.includes(dt, 'PRIMARY KEY')) {
return Utils.addTicks(attr) + " " + dt.replace(/PRIMARY KEY/, '') primaryKeys.push(attr)
} else { return Utils.addTicks(attr) + " " + dt.replace(/PRIMARY KEY/, '')
return Utils.addTicks(attr) + " " + dt } else {
return Utils.addTicks(attr) + " " + dt
}
}).join(", ")
, values = {
table: Utils.addTicks(tableName),
attributes: attrStr,
engine: options.engine || 'InnoDB',
charset: (options.charset ? "DEFAULT CHARSET=" + options.charset : "")
} }
}).join(", ") , pkString = primaryKeys.map(function(pk) {return Utils.addTicks(pk)}).join(", ")
, values = {
table: Utils.addTicks(tableName), if(pkString.length > 0) values.attributes += ", PRIMARY KEY (" + pkString + ")"
attributes: attrStr,
engine: options.engine || 'InnoDB', return Utils._.template(query)(values).trim() + ";"
charset: (options.charset ? "DEFAULT CHARSET=" + options.charset : "") },
}
, pkString = primaryKeys.map(function(pk) {return Utils.addTicks(pk)}).join(", ") dropTableQuery: function(tableName, options) {
options = options || {}
var query = "DROP TABLE IF EXISTS <%= table %>;"
return Utils._.template(query)({table: Utils.addTicks(tableName)})
},
renameTableQuery: function(before, after) {
var query = "RENAME TABLE `<%= before %>` TO `<%= after %>`;"
return Utils._.template(query)({ before: before, after: after })
},
addColumnQuery: function(tableName, attributes) {
var query = "ALTER TABLE `<%= tableName %>` ADD <%= attributes %>;"
, attrString = Utils._.map(attributes, function(definition, attributeName) {
return Utils._.template('`<%= attributeName %>` <%= definition %>')({
attributeName: attributeName,
definition: definition
})
}).join(', ')
return Utils._.template(query)({ tableName: tableName, attributes: attrString })
},
removeColumnQuery: function(tableName, attributeName) {
var query = "ALTER TABLE `<%= tableName %>` DROP `<%= attributeName %>`;"
return Utils._.template(query)({ tableName: tableName, attributeName: attributeName })
},
changeColumnQuery: function(tableName, attributes) {
var query = "ALTER TABLE `<%= tableName %>` CHANGE <%= attributes %>;"
var attrString = Utils._.map(attributes, function(definition, attributeName) {
return Utils._.template('`<%= attributeName %>` `<%= attributeName %>` <%= definition %>')({
attributeName: attributeName,
definition: definition
})
}).join(', ')
return Utils._.template(query)({ tableName: tableName, attributes: attrString })
},
renameColumnQuery: function(tableName, attrBefore, attributes) {
var query = "ALTER TABLE `<%= tableName %>` CHANGE <%= attributes %>;"
var attrString = Utils._.map(attributes, function(definition, attributeName) {
return Utils._.template('`<%= before %>` `<%= after %>` <%= definition %>')({
before: attrBefore,
after: attributeName,
definition: definition
})
}).join(', ')
return Utils._.template(query)({ tableName: tableName, attributes: attrString })
},
selectQuery: function(tableName, options) {
options = options || {}
options.table = Utils.addTicks(tableName)
options.attributes = options.attributes && options.attributes.map(function(attr){
if(Array.isArray(attr) && attr.length == 2)
return [attr[0], Utils.addTicks(attr[1])].join(' as ')
else
return Utils.addTicks(attr)
}).join(", ")
options.attributes = options.attributes || '*'
var query = "SELECT <%= attributes %> FROM <%= table %>"
if(options.where) {
options.where = QueryGenerator.getWhereConditions(options.where)
query += " WHERE <%= where %>"
}
if(options.order) query += " ORDER BY <%= order %>"
if(options.group) {
options.group = Utils.addTicks(options.group)
query += " GROUP BY <%= group %>"
}
if(options.limit) {
if(options.offset) query += " LIMIT <%= offset %>, <%= limit %>"
else query += " LIMIT <%= limit %>"
}
if(pkString.length > 0) values.attributes += ", PRIMARY KEY (" + pkString + ")" query += ";"
return Utils._.template(query)(values).trim() + ";" return Utils._.template(query)(options)
}, },
dropTableQuery: function(tableName, options) { /*
options = options || {} Returns an insert into command. Parameters: table name + hash of attribute-value-pairs.
*/
insertQuery: function(tableName, attrValueHash) {
var query = "INSERT INTO <%= table %> (<%= attributes %>) VALUES (<%= values %>);"
var query = "DROP TABLE IF EXISTS <%= table %>;" 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)({table: Utils.addTicks(tableName)}) return Utils._.template(query)(replacements)
}, },
/*
Returns an update query.
Parameters:
- tableName -> Name of the table
- values -> A hash with attribute-value-pairs
- where -> A hash with conditions (e.g. {name: 'foo'})
OR an ID as integer
OR a string with conditions (e.g. 'name="foo"').
If you use a string, you have to escape it on your own.
*/
updateQuery: function(tableName, values, where) {
var query = "UPDATE <%= table %> SET <%= values %> WHERE <%= where %>"
var replacements = {
table: Utils.addTicks(tableName),
values: Utils._.map(values, function(value, key){
return Utils.addTicks(key) + "=" + Utils.escape((value instanceof Date) ? Utils.toSqlDate(value) : value)
}).join(","),
where: QueryGenerator.getWhereConditions(where)
}
renameTableQuery: function(before, after) { return Utils._.template(query)(replacements)
var query = "RENAME TABLE `<%= before %>` TO `<%= after %>`;" },
return Utils._.template(query)({ before: before, after: after })
}, /*
Returns a deletion query.
Parameters:
- tableName -> Name of the table
- where -> A hash with conditions (e.g. {name: 'foo'})
OR an ID as integer
OR a string with conditions (e.g. 'name="foo"').
If you use a string, you have to escape it on your own.
Options:
- limit -> Maximaum count of lines to delete
*/
deleteQuery: function(tableName, where, options) {
options = options || {}
options.limit = options.limit || 1
var query = "DELETE FROM <%= table %> WHERE <%= where %> LIMIT <%= limit %>"
var replacements = {
table: Utils.addTicks(tableName),
where: QueryGenerator.getWhereConditions(where),
limit: Utils.escape(options.limit)
}
addColumnQuery: function(tableName, attributes) { return Utils._.template(query)(replacements)
var query = "ALTER TABLE `<%= tableName %>` ADD <%= attributes %>;" },
, attrString = Utils._.map(attributes, function(definition, attributeName) {
return Utils._.template('`<%= attributeName %>` <%= definition %>')({
attributeName: attributeName,
definition: definition
})
}).join(', ')
return Utils._.template(query)({ tableName: tableName, attributes: attrString }) addIndexQuery: function(tableName, attributes, options) {
}, var transformedAttributes = attributes.map(function(attribute) {
if(typeof attribute == 'string')
return attribute
else {
var result = ""
removeColumnQuery: function(tableName, attributeName) { if(!attribute.attribute)
var query = "ALTER TABLE `<%= tableName %>` DROP `<%= attributeName %>`;" throw new Error('The following index attribute has no attribute: ' + util.inspect(attribute))
return Utils._.template(query)({ tableName: tableName, attributeName: attributeName })
},
changeColumnQuery: function(tableName, attributes) { result += attribute.attribute
var query = "ALTER TABLE `<%= tableName %>` CHANGE <%= attributes %>;"
var attrString = Utils._.map(attributes, function(definition, attributeName) {
return Utils._.template('`<%= attributeName %>` `<%= attributeName %>` <%= definition %>')({
attributeName: attributeName,
definition: definition
})
}).join(', ')
return Utils._.template(query)({ tableName: tableName, attributes: attrString })
},
renameColumnQuery: function(tableName, attrBefore, attributes) {
var query = "ALTER TABLE `<%= tableName %>` CHANGE <%= attributes %>;"
var attrString = Utils._.map(attributes, function(definition, attributeName) {
return Utils._.template('`<%= before %>` `<%= after %>` <%= definition %>')({
before: attrBefore,
after: attributeName,
definition: definition
})
}).join(', ')
return Utils._.template(query)({ tableName: tableName, attributes: attrString })
},
selectQuery: function(tableName, options) {
options = options || {}
options.table = Utils.addTicks(tableName)
options.attributes = options.attributes && options.attributes.map(function(attr){
if(Array.isArray(attr) && attr.length == 2)
return [attr[0], Utils.addTicks(attr[1])].join(' as ')
else
return Utils.addTicks(attr)
}).join(", ")
options.attributes = options.attributes || '*'
var query = "SELECT <%= attributes %> FROM <%= table %>"
if(options.where) {
options.where = QueryGenerator.getWhereConditions(options.where)
query += " WHERE <%= where %>"
}
if(options.order) query += " ORDER BY <%= order %>"
if(options.group) {
options.group = Utils.addTicks(options.group)
query += " GROUP BY <%= group %>"
}
if(options.limit) {
if(options.offset) query += " LIMIT <%= offset %>, <%= limit %>"
else query += " LIMIT <%= limit %>"
}
query += ";" if(attribute.length)
result += '(' + attribute.length + ')'
return Utils._.template(query)(options) if(attribute.order)
}, result += ' ' + attribute.order
/* return result
Returns an insert into command. Parameters: table name + hash of attribute-value-pairs. }
*/ })
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) var onlyAttributeNames = attributes.map(function(attribute) {
}, return (typeof attribute == 'string') ? attribute : attribute.attribute
})
/*
Returns an update query.
Parameters:
- tableName -> Name of the table
- values -> A hash with attribute-value-pairs
- where -> A hash with conditions (e.g. {name: 'foo'})
OR an ID as integer
OR a string with conditions (e.g. 'name="foo"').
If you use a string, you have to escape it on your own.
*/
updateQuery: function(tableName, values, where) {
var query = "UPDATE <%= table %> SET <%= values %> WHERE <%= where %>"
var replacements = {
table: Utils.addTicks(tableName),
values: Utils._.map(values, function(value, key){
return Utils.addTicks(key) + "=" + Utils.escape((value instanceof Date) ? Utils.toSqlDate(value) : value)
}).join(","),
where: QueryGenerator.getWhereConditions(where)
}
return Utils._.template(query)(replacements) options = Utils._.extend({
}, indicesType: null,
indexName: Utils._.underscored(tableName + '_' + onlyAttributeNames.join('_')),
/* parser: null
Returns a deletion query. }, options || {})
Parameters:
- tableName -> Name of the table return Utils._.compact([
- where -> A hash with conditions (e.g. {name: 'foo'}) "CREATE", options.indicesType, "INDEX", options.indexName,
OR an ID as integer (options.indexType ? ('USING ' + options.indexType) : undefined),
OR a string with conditions (e.g. 'name="foo"'). "ON", tableName, '(' + transformedAttributes.join(', ') + ')',
If you use a string, you have to escape it on your own. (options.parser ? "WITH PARSER " + options.parser : undefined)
Options: ]).join(' ')
- limit -> Maximaum count of lines to delete },
*/
deleteQuery: function(tableName, where, options) { /*
options = options || {} Takes something and transforms it into values of a where condition.
options.limit = options.limit || 1 */
getWhereConditions: function(smth) {
var query = "DELETE FROM <%= table %> WHERE <%= where %> LIMIT <%= limit %>" var result = null
var replacements = {
table: Utils.addTicks(tableName), if(Utils.isHash(smth))
where: QueryGenerator.getWhereConditions(where), result = QueryGenerator.hashToWhereConditions(smth)
limit: Utils.escape(options.limit) else if(typeof smth == 'number')
result = Utils.addTicks('id') + "=" + Utils.escape(smth)
else if(typeof smth == "string")
result = smth
else if(Array.isArray(smth))
result = Utils.format(smth)
return result
},
/*
Takes a hash and transforms it into a mysql where condition: {key: value, key2: value2} ==> key=value AND key2=value2
The values are transformed by the relevant datatype.
*/
hashToWhereConditions: function(hash) {
return Utils._.map(hash, function(value, key) {
var _key = Utils.addTicks(key)
, _value = null
if(Array.isArray(value)) {
_value = "(" + Utils._.map(value, function(subvalue) {
return Utils.escape(subvalue);
}).join(',') + ")"
return [_key, _value].join(" IN ")
} else {
_value = Utils.escape(value)
return (_value == 'NULL') ? _key + " IS NULL" : [_key, _value].join("=")
}
}).join(" AND ")
} }
return Utils._.template(query)(replacements)
},
addIndexQuery: function(tableName, attributes, options) {
var transformedAttributes = attributes.map(function(attribute) {
if(typeof attribute == 'string')
return attribute
else {
var result = ""
if(!attribute.attribute)
throw new Error('The following index attribute has no attribute: ' + util.inspect(attribute))
result += attribute.attribute
if(attribute.length)
result += '(' + attribute.length + ')'
if(attribute.order)
result += ' ' + attribute.order
return result
}
})
var onlyAttributeNames = attributes.map(function(attribute) {
return (typeof attribute == 'string') ? attribute : attribute.attribute
})
options = Utils._.extend({
indicesType: null,
indexName: Utils._.underscored(tableName + '_' + onlyAttributeNames.join('_')),
parser: null
}, options || {})
return Utils._.compact([
"CREATE", options.indicesType, "INDEX", options.indexName,
(options.indexType ? ('USING ' + options.indexType) : undefined),
"ON", tableName, '(' + transformedAttributes.join(', ') + ')',
(options.parser ? "WITH PARSER " + options.parser : undefined)
]).join(' ')
},
/*
Takes something and transforms it into values of a where condition.
*/
getWhereConditions: function(smth) {
var result = null
if(Utils.isHash(smth))
result = QueryGenerator.hashToWhereConditions(smth)
else if(typeof smth == 'number')
result = Utils.addTicks('id') + "=" + Utils.escape(smth)
else if(typeof smth == "string")
result = smth
else if(Array.isArray(smth))
result = Utils.format(smth)
return result
},
/*
Takes a hash and transforms it into a mysql where condition: {key: value, key2: value2} ==> key=value AND key2=value2
The values are transformed by the relevant datatype.
*/
hashToWhereConditions: function(hash) {
return Utils._.map(hash, function(value, key) {
var _key = Utils.addTicks(key)
, _value = null
if(Array.isArray(value)) {
_value = "(" + Utils._.map(value, function(subvalue) {
return Utils.escape(subvalue);
}).join(',') + ")"
return [_key, _value].join(" IN ")
} else {
_value = Utils.escape(value)
return (_value == 'NULL') ? _key + " IS NULL" : [_key, _value].join("=")
}
}).join(" AND ")
} }
}
QueryGenerator = Utils._.extend(Utils._.clone(require("../query-generator")), QueryGenerator) return Utils._.extend(Utils._.clone(require("../query-generator")), QueryGenerator)
})()
...@@ -5,14 +5,14 @@ module.exports = (function() { ...@@ -5,14 +5,14 @@ module.exports = (function() {
Attributes should have the format: {attributeName: type, attr2: type2} --> {title: 'VARCHAR(255)'} Attributes should have the format: {attributeName: type, attr2: type2} --> {title: 'VARCHAR(255)'}
*/ */
createTableQuery: function(tableName, attributes, options) { createTableQuery: function(tableName, attributes, options) {
throwMethodUndefined.call('createTableQuery') throwMethodUndefined('createTableQuery')
}, },
/* /*
Returns a query for dropping a table. Returns a query for dropping a table.
*/ */
dropTableQuery: function(tableName, options) { dropTableQuery: function(tableName, options) {
throwMethodUndefined.call('dropTableQuery') throwMethodUndefined('dropTableQuery')
}, },
/* /*
...@@ -22,7 +22,7 @@ module.exports = (function() { ...@@ -22,7 +22,7 @@ module.exports = (function() {
- futureTableName: Name of the table after execution. - futureTableName: Name of the table after execution.
*/ */
renameTableQuery: function(originalTableName, futureTableName) { renameTableQuery: function(originalTableName, futureTableName) {
throwMethodUndefined.call('renameTableQuery') throwMethodUndefined('renameTableQuery')
}, },
/* /*
...@@ -37,7 +37,7 @@ module.exports = (function() { ...@@ -37,7 +37,7 @@ module.exports = (function() {
- allowNull: Boolean - allowNull: Boolean
*/ */
addColumnQuery: function(tableName, attributes) { addColumnQuery: function(tableName, attributes) {
throwMethodUndefined.call('addColumnQuery') throwMethodUndefined('addColumnQuery')
}, },
/* /*
...@@ -47,7 +47,7 @@ module.exports = (function() { ...@@ -47,7 +47,7 @@ module.exports = (function() {
- attributeName: Name of the obsolete attribute. - attributeName: Name of the obsolete attribute.
*/ */
removeColumnQuery: function(tableName, attributeName) { removeColumnQuery: function(tableName, attributeName) {
throwMethodUndefined.call('removeColumnQuery') throwMethodUndefined('removeColumnQuery')
}, },
/* /*
...@@ -62,7 +62,7 @@ module.exports = (function() { ...@@ -62,7 +62,7 @@ module.exports = (function() {
- allowNull: Boolean - allowNull: Boolean
*/ */
changeColumnQuery: function(tableName, attribute) { changeColumnQuery: function(tableName, attribute) {
throwMethodUndefined.call('changeColumnQuery') throwMethodUndefined('changeColumnQuery')
}, },
/* /*
...@@ -73,7 +73,7 @@ module.exports = (function() { ...@@ -73,7 +73,7 @@ module.exports = (function() {
- attrNameAfter: The name of the attribute, after renaming. - attrNameAfter: The name of the attribute, after renaming.
*/ */
renameColumnQuery: function(tableName, attrNameBefore, attrNameAfter) { renameColumnQuery: function(tableName, attrNameBefore, attrNameAfter) {
throwMethodUndefined.call('renameColumnQuery') throwMethodUndefined('renameColumnQuery')
}, },
/* /*
...@@ -90,14 +90,14 @@ module.exports = (function() { ...@@ -90,14 +90,14 @@ module.exports = (function() {
- offset -> An offset value to start from. Only useable with limit! - offset -> An offset value to start from. Only useable with limit!
*/ */
selectQuery: function(tableName, options) { selectQuery: function(tableName, options) {
throwMethodUndefined.call('selectQuery') throwMethodUndefined('selectQuery')
}, },
/* /*
Returns an insert into command. Parameters: table name + hash of attribute-value-pairs. Returns an insert into command. Parameters: table name + hash of attribute-value-pairs.
*/ */
insertQuery: function(tableName, attrValueHash) { insertQuery: function(tableName, attrValueHash) {
throwMethodUndefined.call('insertQuery') throwMethodUndefined('insertQuery')
}, },
/* /*
...@@ -111,7 +111,7 @@ module.exports = (function() { ...@@ -111,7 +111,7 @@ module.exports = (function() {
If you use a string, you have to escape it on your own. If you use a string, you have to escape it on your own.
*/ */
updateQuery: function(tableName, values, where) { updateQuery: function(tableName, values, where) {
throwMethodUndefined.call('updateQuery') throwMethodUndefined('updateQuery')
}, },
/* /*
...@@ -126,7 +126,7 @@ module.exports = (function() { ...@@ -126,7 +126,7 @@ module.exports = (function() {
- limit -> Maximaum count of lines to delete - limit -> Maximaum count of lines to delete
*/ */
deleteQuery: function(tableName, where, options) { deleteQuery: function(tableName, where, options) {
throwMethodUndefined.call('deleteQuery') throwMethodUndefined('deleteQuery')
}, },
/* /*
...@@ -145,22 +145,29 @@ module.exports = (function() { ...@@ -145,22 +145,29 @@ module.exports = (function() {
- parser - parser
*/ */
addIndexQuery: function(tableName, attributes, options) { addIndexQuery: function(tableName, attributes, options) {
throwMethodUndefined.call('addIndexQuery') throwMethodUndefined('addIndexQuery')
}, },
/*
Returns an show index query.
Parameters:
- tableName: Name of an existing table.
- options:
- databaseName: Name of the database.
*/
showIndexQuery: function(tableName, options) { showIndexQuery: function(tableName, options) {
throwMethodUndefined.call('showIndexQuery') throwMethodUndefined('showIndexQuery')
}, },
removeIndexQuery: function(tableName, options) { removeIndexQuery: function(tableName, options) {
throwMethodUndefined.call('removeIndexQuery') throwMethodUndefined('removeIndexQuery')
}, },
/* /*
Takes something and transforms it into values of a where condition. Takes something and transforms it into values of a where condition.
*/ */
getWhereConditions: function(smth) { getWhereConditions: function(smth) {
throwMethodUndefined.call('getWhereConditions') throwMethodUndefined('getWhereConditions')
}, },
/* /*
...@@ -168,7 +175,7 @@ module.exports = (function() { ...@@ -168,7 +175,7 @@ module.exports = (function() {
The values are transformed by the relevant datatype. The values are transformed by the relevant datatype.
*/ */
hashToWhereConditions: function(hash) { hashToWhereConditions: function(hash) {
throwMethodUndefined.call('hashToWhereConditions') throwMethodUndefined('hashToWhereConditions')
} }
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!