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

Commit f50469b6 by Felix Becker Committed by Mick Hansen

ES6 refactor: dialects / SQLite (#6051)

* ES6 refactor of SQLite ConnectionManager

* ES6 refactor of SQLiteDialect

* Make sqlite Query an ES6 class

* ES6 refactor of SQLite Query

* ES6 refactor of SQLite QueryGenerator

* ES6 refactor of SQLite QueryInterface
1 parent 3107396d
'use strict';
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, Utils = require('../../utils')
, Promise = require('../../promise')
, dataTypes = require('../../data-types').sqlite
, sequelizeErrors = require('../../errors')
, parserStore = require('../parserStore')('sqlite');
const AbstractConnectionManager = require('../abstract/connection-manager');
const Promise = require('../../promise');
const dataTypes = require('../../data-types').sqlite;
const sequelizeErrors = require('../../errors');
const parserStore = require('../parserStore')('sqlite');
ConnectionManager = function(dialect, sequelize) {
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
super(dialect, sequelize);
this.sequelize = sequelize;
this.config = sequelize.config;
this.dialect = dialect;
......@@ -28,60 +28,61 @@ ConnectionManager = function(dialect, sequelize) {
}
this.refreshTypeParser(dataTypes);
};
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
}
// Expose this as a method so that the parsing may be updated when the user has added additional, custom types
ConnectionManager.prototype.$refreshTypeParser = function (dataType) {
// Expose this as a method so that the parsing may be updated when the user has added additional, custom types
$refreshTypeParser(dataType) {
parserStore.refresh(dataType);
};
}
ConnectionManager.prototype.$clearTypeParser = function () {
$clearTypeParser() {
parserStore.clear();
};
}
ConnectionManager.prototype.getConnection = function(options) {
var self = this;
getConnection(options) {
options = options || {};
options.uuid = options.uuid || 'default';
options.inMemory = ((self.sequelize.options.storage || self.sequelize.options.host || ':memory:') === ':memory:') ? 1 : 0;
options.inMemory = ((this.sequelize.options.storage || this.sequelize.options.host || ':memory:') === ':memory:') ? 1 : 0;
var dialectOptions = self.sequelize.options.dialectOptions;
const dialectOptions = this.sequelize.options.dialectOptions;
options.readWriteMode = dialectOptions && dialectOptions.mode;
if (self.connections[options.inMemory || options.uuid]) {
return Promise.resolve(self.connections[options.inMemory || options.uuid]);
if (this.connections[options.inMemory || options.uuid]) {
return Promise.resolve(this.connections[options.inMemory || options.uuid]);
}
return new Promise(function (resolve, reject) {
self.connections[options.inMemory || options.uuid] = new self.lib.Database(
self.sequelize.options.storage || self.sequelize.options.host || ':memory:',
options.readWriteMode || (self.lib.OPEN_READWRITE | self.lib.OPEN_CREATE), // default mode
function(err) {
return new Promise((resolve, reject) => {
this.connections[options.inMemory || options.uuid] = new this.lib.Database(
this.sequelize.options.storage || this.sequelize.options.host || ':memory:',
options.readWriteMode || (this.lib.OPEN_READWRITE | this.lib.OPEN_CREATE), // default mode
err => {
if (err) {
if (err.code === 'SQLITE_CANTOPEN') return reject(new sequelizeErrors.ConnectionError(err));
return reject(new sequelizeErrors.ConnectionError(err));
}
resolve(self.connections[options.inMemory || options.uuid]);
resolve(this.connections[options.inMemory || options.uuid]);
}
);
}).tap(function (connection) {
if (self.sequelize.options.foreignKeys !== false) {
}).tap(connection => {
if (this.sequelize.options.foreignKeys !== false) {
// Make it possible to define and use foreign key constraints unless
// explicitly disallowed. It's still opt-in per relation
connection.run('PRAGMA FOREIGN_KEYS=ON');
}
});
};
}
ConnectionManager.prototype.releaseConnection = function(connection, force) {
releaseConnection(connection, force) {
if (connection.filename === ':memory:' && force !== true) return;
if (connection.uuid) {
connection.close();
delete this.connections[connection.uuid];
}
};
}
}
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
'use strict';
var _ = require('lodash')
, Abstract = require('../abstract')
, ConnectionManager = require('./connection-manager')
, Query = require('./query')
, QueryGenerator = require('./query-generator')
, DataTypes = require('../../data-types').sqlite;
const _ = require('lodash');
const AbstractDialect = require('../abstract');
const ConnectionManager = require('./connection-manager');
const Query = require('./query');
const QueryGenerator = require('./query-generator');
const DataTypes = require('../../data-types').sqlite;
var SqliteDialect = function(sequelize) {
class SqliteDialect extends AbstractDialect {
constructor(sequelize) {
super();
this.sequelize = sequelize;
this.connectionManager = new ConnectionManager(this, sequelize);
this.QueryGenerator = _.extend({}, QueryGenerator, {
options: sequelize.options,
_dialect: this,
sequelize: sequelize
sequelize
});
};
}
}
SqliteDialect.prototype.supports = _.merge(_.cloneDeep(Abstract.prototype.supports), {
SqliteDialect.prototype.supports = _.merge(_.cloneDeep(AbstractDialect.prototype.supports), {
'DEFAULT': false,
'DEFAULT VALUES': true,
'UNION ALL': false,
......@@ -43,3 +46,5 @@ SqliteDialect.prototype.TICK_CHAR_LEFT = SqliteDialect.prototype.TICK_CHAR;
SqliteDialect.prototype.TICK_CHAR_RIGHT = SqliteDialect.prototype.TICK_CHAR;
module.exports = SqliteDialect;
module.exports.SqliteDialect = SqliteDialect;
module.exports.default = SqliteDialect;
'use strict';
/* jshint -W110 */
var Utils = require('../../utils')
, Transaction = require('../../transaction')
, _ = require('lodash');
const Utils = require('../../utils');
const Transaction = require('../../transaction');
const _ = require('lodash');
var MySqlQueryGenerator = Utils._.extend(
const MySqlQueryGenerator = Utils._.extend(
Utils._.clone(require('../abstract/query-generator')),
Utils._.clone(require('../mysql/query-generator'))
);
var QueryGenerator = {
const QueryGenerator = {
options: {},
dialect: 'sqlite',
createSchema: function() {
var query = "SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';";
return Utils._.template(query)({});
createSchema() {
return "SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';";
},
showSchemasQuery: function() {
showSchemasQuery() {
return "SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';";
},
versionQuery: function() {
versionQuery() {
return 'SELECT sqlite_version() as `version`';
},
createTableQuery: function(tableName, attributes, options) {
createTableQuery(tableName, attributes, options) {
options = options || {};
var query = 'CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>)'
, primaryKeys = []
, needsMultiplePrimaryKeys = (Utils._.values(attributes).filter(function(definition) {
return Utils._.includes(definition, 'PRIMARY KEY');
}).length > 1)
, attrStr = [];
const primaryKeys = [];
const needsMultiplePrimaryKeys = (Utils._.values(attributes).filter(definition => _.includes(definition, 'PRIMARY KEY')).length > 1);
const attrArray = [];
for (var attr in attributes) {
for (const attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
var dataType = attributes[attr];
var containsAutoIncrement = Utils._.includes(dataType, 'AUTOINCREMENT');
let dataType = attributes[attr];
const containsAutoIncrement = Utils._.includes(dataType, 'AUTOINCREMENT');
if (containsAutoIncrement) {
dataType = dataType.replace(/BIGINT/, 'INTEGER');
}
var dataTypeString = dataType;
let dataTypeString = dataType;
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (Utils._.includes(dataType, 'INTEGER')) { // Only INTEGER is allowed for primary key, see https://github.com/sequelize/sequelize/issues/969 (no lenght, unsigned etc)
dataTypeString = containsAutoIncrement ? 'INTEGER PRIMARY KEY AUTOINCREMENT' : 'INTEGER PRIMARY KEY';
......@@ -57,82 +53,69 @@ var QueryGenerator = {
dataTypeString = dataType.replace(/PRIMARY KEY/, 'NOT NULL');
}
}
attrStr.push(this.quoteIdentifier(attr) + ' ' + dataTypeString);
attrArray.push(this.quoteIdentifier(attr) + ' ' + dataTypeString);
}
}
var values = {
table: this.quoteTable(tableName),
attributes: attrStr.join(', '),
charset: (options.charset ? 'DEFAULT CHARSET=' + options.charset : '')
}
, pkString = primaryKeys.map(function(pk) { return this.quoteIdentifier(pk); }.bind(this)).join(', ');
const table = this.quoteTable(tableName);
let attrStr = attrArray.join(', ');
const pkString = primaryKeys.map(pk => this.quoteIdentifier(pk)).join(', ');
if (!!options.uniqueKeys) {
Utils._.each(options.uniqueKeys, function(columns) {
Utils._.each(options.uniqueKeys, columns => {
if (!columns.singleField) { // If it's a single field its handled in column def, not as an index
values.attributes += ', UNIQUE (' + columns.fields.join(', ') + ')';
attrStr += ', UNIQUE (' + columns.fields.join(', ') + ')';
}
});
}
if (pkString.length > 0) {
values.attributes += ', PRIMARY KEY (' + pkString + ')';
attrStr += ', PRIMARY KEY (' + pkString + ')';
}
var sql = Utils._.template(query)(values).trim() + ';';
const sql = `CREATE TABLE IF NOT EXISTS ${table} (${attrStr});`;
return this.replaceBooleanDefaults(sql);
},
booleanValue: function(value){
booleanValue(value){
return !!value ? 1 : 0;
},
addColumnQuery: function(table, key, dataType) {
var query = 'ALTER TABLE <%= table %> ADD <%= attribute %>;'
, attributes = {};
addColumnQuery(table, key, dataType) {
const attributes = {};
attributes[key] = dataType;
var fields = this.attributesToSQL(attributes, {
context: 'addColumn'
});
var attribute = Utils._.template('<%= key %> <%= definition %>')({
key: this.quoteIdentifier(key),
definition: fields[key]
});
const fields = this.attributesToSQL(attributes, {context: 'addColumn'});
const attribute = this.quoteIdentifier(key) + ' ' + fields[key];
var sql = Utils._.template(query)({
table: this.quoteTable(table),
attribute: attribute
});
const sql = `ALTER TABLE ${this.quoteTable(table)} ADD ${attribute};`;
return this.replaceBooleanDefaults(sql);
},
showTablesQuery: function() {
showTablesQuery() {
return "SELECT name FROM `sqlite_master` WHERE type='table' and name!='sqlite_sequence';";
},
upsertQuery: function (tableName, insertValues, updateValues, where, rawAttributes, options) {
upsertQuery(tableName, insertValues, updateValues, where, rawAttributes, options) {
options.ignore = true;
var sql = this.insertQuery(tableName, insertValues, rawAttributes, options) + ' ' + this.updateQuery(tableName, updateValues, where, options, rawAttributes);
const sql = this.insertQuery(tableName, insertValues, rawAttributes, options) + ' ' + this.updateQuery(tableName, updateValues, where, options, rawAttributes);
return sql;
},
updateQuery: function(tableName, attrValueHash, where, options, attributes) {
updateQuery(tableName, attrValueHash, where, options, attributes) {
options = options || {};
_.defaults(options, this.options);
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, options.omitNull, options);
var query = 'UPDATE <%= table %> SET <%= values %> <%= where %>'
, modelAttributeMap = {}
, values = [];
const modelAttributeMap = {};
const values = [];
if (attributes) {
_.each(attributes, function(attribute, key) {
_.each(attributes, (attribute, key) => {
modelAttributeMap[key] = attribute;
if (attribute.field) {
modelAttributeMap[attribute.field] = attribute;
......@@ -140,94 +123,81 @@ var QueryGenerator = {
});
}
for (var key in attrValueHash) {
var value = attrValueHash[key];
for (const key in attrValueHash) {
const value = attrValueHash[key];
values.push(this.quoteIdentifier(key) + '=' + this.escape(value, (modelAttributeMap && modelAttributeMap[key] || undefined), { context: 'UPDATE' }));
}
var replacements = {
table: this.quoteTable(tableName),
values: values.join(','),
where: this.whereQuery(where)
};
return Utils._.template(query)(replacements).trim();
return `UPDATE ${this.quoteTable(tableName)} SET ${values.join(',')} ${this.whereQuery(where)}`;
},
deleteQuery: function(tableName, where, options) {
deleteQuery(tableName, where, options) {
options = options || {};
var query = 'DELETE FROM <%= table %><%= where %>';
var replacements = {
table: this.quoteTable(tableName),
where: this.getWhereConditions(where)
};
if (replacements.where) {
replacements.where = ' WHERE ' + replacements.where;
let whereClause = this.getWhereConditions(where);
if (whereClause) {
whereClause = ' WHERE ' + whereClause;
}
return Utils._.template(query)(replacements);
return `DELETE FROM ${this.quoteTable(tableName)}${whereClause}`;
},
attributesToSQL: function(attributes) {
var result = {};
attributesToSQL(attributes) {
const result = {};
for (var name in attributes) {
var dataType = attributes[name];
var fieldName = dataType.field || name;
for (const name in attributes) {
const dataType = attributes[name];
const fieldName = dataType.field || name;
if (Utils._.isObject(dataType)) {
var template = '<%= type %>'
, replacements = { type: dataType.type.toString() };
let sql = dataType.type.toString();
if (dataType.hasOwnProperty('allowNull') && !dataType.allowNull) {
template += ' NOT NULL';
sql += ' NOT NULL';
}
if (Utils.defaultValueSchemable(dataType.defaultValue)) {
// TODO thoroughly check that DataTypes.NOW will properly
// get populated on all databases as DEFAULT value
// i.e. mysql requires: DEFAULT CURRENT_TIMESTAMP
template += ' DEFAULT <%= defaultValue %>';
replacements.defaultValue = this.escape(dataType.defaultValue, dataType);
sql += ' DEFAULT ' + this.escape(dataType.defaultValue, dataType);
}
if (dataType.unique === true) {
template += ' UNIQUE';
sql += ' UNIQUE';
}
if (dataType.primaryKey) {
template += ' PRIMARY KEY';
sql += ' PRIMARY KEY';
if (dataType.autoIncrement) {
template += ' AUTOINCREMENT';
sql += ' AUTOINCREMENT';
}
}
if(dataType.references) {
template += ' REFERENCES <%= referencesTable %> (<%= referencesKey %>)';
replacements.referencesTable = this.quoteTable(dataType.references.model);
const referencesTable = this.quoteTable(dataType.references.model);
let referencesKey;
if(dataType.references.key) {
replacements.referencesKey = this.quoteIdentifier(dataType.references.key);
referencesKey = this.quoteIdentifier(dataType.references.key);
} else {
replacements.referencesKey = this.quoteIdentifier('id');
referencesKey = this.quoteIdentifier('id');
}
sql += ` REFERENCES ${referencesTable} (${referencesKey})`;
if(dataType.onDelete) {
template += ' ON DELETE <%= onDeleteAction %>';
replacements.onDeleteAction = dataType.onDelete.toUpperCase();
sql += ' ON DELETE ' + dataType.onDelete.toUpperCase();
}
if(dataType.onUpdate) {
template += ' ON UPDATE <%= onUpdateAction %>';
replacements.onUpdateAction = dataType.onUpdate.toUpperCase();
sql += ' ON UPDATE ' + dataType.onUpdate.toUpperCase();
}
}
result[fieldName] = Utils._.template(template)(replacements);
result[fieldName] = sql;
} else {
result[fieldName] = dataType;
}
......@@ -236,12 +206,12 @@ var QueryGenerator = {
return result;
},
findAutoIncrementField: function(factory) {
var fields = [];
findAutoIncrementField(factory) {
const fields = [];
for (var name in factory.attributes) {
for (const name in factory.attributes) {
if (factory.attributes.hasOwnProperty(name)) {
var definition = factory.attributes[name];
const definition = factory.attributes[name];
if (definition && definition.autoIncrement) {
fields.push(name);
}
......@@ -251,38 +221,34 @@ var QueryGenerator = {
return fields;
},
showIndexesQuery: function(tableName) {
var sql = 'PRAGMA INDEX_LIST(<%= tableName %>)';
return Utils._.template(sql)({ tableName: this.quoteTable(tableName) });
showIndexesQuery(tableName) {
return `PRAGMA INDEX_LIST(${this.quoteTable(tableName)})`;
},
removeIndexQuery: function(tableName, indexNameOrAttributes) {
var sql = 'DROP INDEX IF EXISTS <%= indexName %>'
, indexName = indexNameOrAttributes;
removeIndexQuery(tableName, indexNameOrAttributes) {
let indexName = indexNameOrAttributes;
if (typeof indexName !== 'string') {
indexName = Utils.inflection.underscore(tableName + '_' + indexNameOrAttributes.join('_'));
}
return Utils._.template(sql)( { tableName: this.quoteIdentifiers(tableName), indexName: indexName });
return 'DROP INDEX IF EXISTS ' + indexName;
},
describeTableQuery: function(tableName, schema, schemaDelimiter) {
var table = {};
table.$schema = schema;
table.$schemaDelimiter = schemaDelimiter;
table.tableName = tableName;
var sql = 'PRAGMA TABLE_INFO(<%= tableName %>);';
return Utils._.template(sql)({tableName: this.quoteTable(this.addSchema(table))});
describeTableQuery(tableName, schema, schemaDelimiter) {
const table = {
$schema: schema,
$schemaDelimiter: schemaDelimiter,
tableName
};
return `PRAGMA TABLE_INFO(${this.quoteTable(this.addSchema(table))});`;
},
removeColumnQuery: function(tableName, attributes) {
var backupTableName
, query;
removeColumnQuery(tableName, attributes) {
attributes = this.attributesToSQL(attributes);
let backupTableName;
if (typeof tableName === 'object') {
backupTableName = {
tableName: tableName.tableName + '_backup',
......@@ -292,25 +258,21 @@ var QueryGenerator = {
backupTableName = tableName + '_backup';
}
query = [
this.createTableQuery(backupTableName, attributes).replace('CREATE TABLE', 'CREATE TEMPORARY TABLE'),
'INSERT INTO <%= backupTableName %> SELECT <%= attributeNames %> FROM <%= tableName %>;',
'DROP TABLE <%= tableName %>;',
this.createTableQuery(tableName, attributes),
'INSERT INTO <%= tableName %> SELECT <%= attributeNames %> FROM <%= backupTableName %>;',
'DROP TABLE <%= backupTableName %>;'
].join('');
const quotedTableName = this.quoteTable(tableName);
const quotedBackupTableName = this.quoteTable(backupTableName);
const attributeNames = Object.keys(attributes).join(', ');
return Utils._.template(query)({
tableName: this.quoteTable(tableName),
backupTableName: this.quoteTable(backupTableName),
attributeNames: Utils._.keys(attributes).join(', ')
});
return this.createTableQuery(backupTableName, attributes).replace('CREATE TABLE', 'CREATE TEMPORARY TABLE')
+ `INSERT INTO ${quotedBackupTableName} SELECT ${attributeNames} FROM ${quotedTableName};`
+ `DROP TABLE ${quotedTableName};`
+ this.createTableQuery(tableName, attributes)
+ `INSERT INTO ${quotedTableName} SELECT ${attributeNames} FROM ${quotedBackupTableName};`
+ `DROP TABLE ${quotedBackupTableName};`;
},
renameColumnQuery: function(tableName, attrNameBefore, attrNameAfter, attributes) {
var backupTableName
, query;
renameColumnQuery(tableName, attrNameBefore, attrNameAfter, attributes) {
let backupTableName;
attributes = this.attributesToSQL(attributes);
......@@ -323,28 +285,22 @@ var QueryGenerator = {
backupTableName = tableName + '_backup';
}
query = [
this.createTableQuery(backupTableName, attributes).replace('CREATE TABLE', 'CREATE TEMPORARY TABLE'),
'INSERT INTO <%= backupTableName %> SELECT <%= attributeNamesImport %> FROM <%= tableName %>;',
'DROP TABLE <%= tableName %>;',
this.createTableQuery(tableName, attributes),
'INSERT INTO <%= tableName %> SELECT <%= attributeNamesExport %> FROM <%= backupTableName %>;',
'DROP TABLE <%= backupTableName %>;'
].join('');
return Utils._.template(query)({
tableName: this.quoteTable(tableName),
backupTableName: this.quoteTable(backupTableName),
attributeNamesImport: Utils._.keys(attributes).map(function(attr) {
return (attrNameAfter === attr) ? this.quoteIdentifier(attrNameBefore) + ' AS ' + this.quoteIdentifier(attr) : this.quoteIdentifier(attr);
}.bind(this)).join(', '),
attributeNamesExport: Utils._.keys(attributes).map(function(attr) {
return this.quoteIdentifier(attr);
}.bind(this)).join(', ')
});
const quotedTableName = this.quoteTable(tableName);
const quotedBackupTableName = this.quoteTable(backupTableName);
const attributeNamesImport = Object.keys(attributes).map(attr =>
(attrNameAfter === attr) ? this.quoteIdentifier(attrNameBefore) + ' AS ' + this.quoteIdentifier(attr) : this.quoteIdentifier(attr)
).join(', ');
const attributeNamesExport = Object.keys(attributes).map(attr => this.quoteIdentifier(attr)).join(', ');
return this.createTableQuery(backupTableName, attributes).replace('CREATE TABLE', 'CREATE TEMPORARY TABLE')
+ `INSERT INTO ${quotedBackupTableName} SELECT ${attributeNamesImport} FROM ${quotedTableName};`
+ `DROP TABLE ${quotedTableName};`
+ this.createTableQuery(tableName, attributes)
+ `INSERT INTO ${quotedTableName} SELECT ${attributeNamesExport} FROM ${quotedBackupTableName};`
+ `DROP TABLE ${quotedBackupTableName};`;
},
startTransactionQuery: function(transaction, options) {
startTransactionQuery(transaction, options) {
if (transaction.parent) {
return 'SAVEPOINT ' + this.quoteIdentifier(transaction.name) + ';';
}
......@@ -352,12 +308,12 @@ var QueryGenerator = {
return 'BEGIN ' + transaction.options.type + ' TRANSACTION;';
},
setAutocommitQuery: function() {
setAutocommitQuery() {
// SQLite does not support SET autocommit
return null;
},
setIsolationLevelQuery: function(value) {
setIsolationLevelQuery(value) {
switch (value) {
case Transaction.ISOLATION_LEVELS.REPEATABLE_READ:
return '-- SQLite is not able to choose the isolation level REPEATABLE READ.';
......@@ -372,11 +328,11 @@ var QueryGenerator = {
}
},
replaceBooleanDefaults: function(sql) {
replaceBooleanDefaults(sql) {
return sql.replace(/DEFAULT '?false'?/g, 'DEFAULT 0').replace(/DEFAULT '?true'?/g, 'DEFAULT 1');
},
quoteIdentifier: function(identifier) {
quoteIdentifier(identifier) {
if (identifier === '*') return identifier;
return Utils.addTicks(identifier, '`');
},
......@@ -388,9 +344,8 @@ var QueryGenerator = {
* @param {String} schemaName The name of the schema.
* @return {String} The generated sql query.
*/
getForeignKeysQuery: function(tableName, schemaName) {
var sql = 'PRAGMA foreign_key_list(<%= tableName %>)';
return Utils._.template(sql)({ tableName: tableName });
getForeignKeysQuery(tableName, schemaName) {
return `PRAGMA foreign_key_list(${tableName})`;
}
};
......
'use strict';
var Utils = require('../../utils')
, Promise = require('../../promise');
const Utils = require('../../utils');
const Promise = require('../../promise');
/**
Returns an object that treats SQLite's inabilities to do certain queries.
......@@ -25,21 +25,20 @@ var Utils = require('../../utils')
@since 1.6.0
*/
var removeColumn = function(tableName, attributeName, options) {
var self = this;
function removeColumn(tableName, attributeName, options) {
options = options || {};
return this.describeTable(tableName, options).then(function(fields) {
/* jshint validthis:true */
return this.describeTable(tableName, options).then(fields => {
delete fields[attributeName];
var sql = self.QueryGenerator.removeColumnQuery(tableName, fields)
, subQueries = sql.split(';').filter(function(q) { return q !== ''; });
const sql = this.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, function(subQuery) {
return self.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options));
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
});
});
};
}
exports.removeColumn = removeColumn;
/**
A wrapper that fixes SQLite's inability to change columns from existing tables.
......@@ -56,22 +55,21 @@ var removeColumn = function(tableName, attributeName, options) {
@since 1.6.0
*/
var changeColumn = function(tableName, attributes, options) {
var attributeName = Utils._.keys(attributes)[0]
, self = this;
function changeColumn(tableName, attributes, options) {
const attributeName = Object.keys(attributes)[0];
options = options || {};
return this.describeTable(tableName, options).then(function(fields) {
/* jshint validthis:true */
return this.describeTable(tableName, options).then(fields => {
fields[attributeName] = attributes[attributeName];
var sql = self.QueryGenerator.removeColumnQuery(tableName, fields)
, subQueries = sql.split(';').filter(function(q) { return q !== ''; });
const sql = this.QueryGenerator.removeColumnQuery(tableName, fields);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, function(subQuery) {
return self.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options));
});
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
});
};
}
exports.changeColumn = changeColumn;
/**
A wrapper that fixes SQLite's inability to rename columns from existing tables.
......@@ -89,25 +87,18 @@ var changeColumn = function(tableName, attributes, options) {
@since 1.6.0
*/
var renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) {
var self = this;
function renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
return this.describeTable(tableName, options).then(function(fields) {
/* jshint validthis:true */
return this.describeTable(tableName, options).then(fields => {
fields[attrNameAfter] = Utils._.clone(fields[attrNameBefore]);
delete fields[attrNameBefore];
var sql = self.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields)
, subQueries = sql.split(';').filter(function(q) { return q !== ''; });
const sql = this.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields);
const subQueries = sql.split(';').filter(q => q !== '');
return Promise.each(subQueries, function(subQuery) {
return self.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options));
return Promise.each(subQueries, subQuery => this.sequelize.query(subQuery + ';', Utils._.assign({raw: true}, options)));
});
});
};
module.exports = {
removeColumn: removeColumn,
changeColumn: changeColumn,
renameColumn: renameColumn
};
}
exports.renameColumn = renameColumn;
'use strict';
var Utils = require('../../utils')
, _ = require('lodash')
, Promise = require('../../promise')
, AbstractQuery = require('../abstract/query')
, QueryTypes = require('../../query-types')
, sequelizeErrors = require('../../errors.js')
, parserStore = require('../parserStore')('sqlite');
var Query = function(database, sequelize, options) {
const _ = require('lodash');
const Promise = require('../../promise');
const AbstractQuery = require('../abstract/query');
const QueryTypes = require('../../query-types');
const sequelizeErrors = require('../../errors.js');
const parserStore = require('../parserStore')('sqlite');
class Query extends AbstractQuery {
constructor(database, sequelize, options) {
super();
this.database = database;
this.sequelize = sequelize;
this.instance = options.instance;
......@@ -20,135 +22,134 @@ var Query = function(database, sequelize, options) {
}, options || {});
this.checkLoggingOption();
};
Utils.inherit(Query, AbstractQuery);
}
Query.prototype.getInsertIdField = function() {
getInsertIdField() {
return 'lastID';
};
}
/**
/**
* rewrite query with parameters
*/
Query.formatBindParameters = function(sql, values, dialect) {
var bindParam = [];
static formatBindParameters(sql, values, dialect) {
let bindParam;
if (Array.isArray(values)) {
bindParam = {};
values.forEach(function(v, i) {
values.forEach((v, i) => {
bindParam['$'+(i+1)] = v;
});
sql = AbstractQuery.formatBindParameters(sql, values, dialect, { skipValueReplace: true })[0];
} else {
bindParam = {};
if (typeof values === 'object') {
Object.keys(values).forEach(function(k) {
for (const k of Object.keys(values)) {
bindParam['$'+k] = values[k];
});
}
}
sql = AbstractQuery.formatBindParameters(sql, values, dialect, { skipValueReplace: true })[0];
}
return [sql, bindParam];
};
}
Query.prototype.$collectModels = function(include, prefix) {
var ret = {};
$collectModels(include, prefix) {
const ret = {};
if (include) {
include.forEach(function (include) {
var key;
for (const _include of include) {
let key;
if (!prefix) {
key = include.as;
key = _include.as;
} else {
key = prefix + '.' + include.as;
key = prefix + '.' + _include.as;
}
ret[key] = include.model;
ret[key] = _include.model;
if (include.include) {
_.merge(ret, this.$collectModels(include.include, key));
if (_include.include) {
_.merge(ret, this.$collectModels(_include.include, key));
}
}
}, this);
}
return ret;
};
Query.prototype.run = function(sql, parameters) {
var self = this
, promise;
}
run(sql, parameters) {
this.sql = sql;
var method = self.getDatabaseMethod();
const method = this.getDatabaseMethod();
if (method === 'exec') {
// exec does not support bind parameter
sql = AbstractQuery.formatBindParameters(sql, self.options.bind, self.options.dialect, { skipUnescape: true })[0];
sql = AbstractQuery.formatBindParameters(sql, this.options.bind, this.options.dialect, { skipUnescape: true })[0];
this.sql = sql;
}
//do we need benchmark for this query execution
var benchmark = this.sequelize.options.benchmark || this.options.benchmark;
const benchmark = this.sequelize.options.benchmark || this.options.benchmark;
let queryBegin;
if (benchmark) {
var queryBegin = Date.now();
queryBegin = Date.now();
} else {
this.sequelize.log('Executing (' + (this.database.uuid || 'default') + '): ' + this.sql, this.options);
}
promise = new Promise(function(resolve) {
var columnTypes = {};
self.database.serialize(function() {
var executeSql = function() {
if (self.sql.indexOf('-- ') === 0) {
return new Promise(resolve => {
const columnTypes = {};
this.database.serialize(() => {
const executeSql = () => {
if (this.sql.indexOf('-- ') === 0) {
return resolve();
} else {
resolve(new Promise(function(resolve, reject) {
var afterExecute = function(err, results) {
resolve(new Promise((resolve, reject) => {
const query = this;
// cannot use arrow function here because the function is bound to the statement
function afterExecute(err, results) {
/* jshint validthis:true */
if (benchmark) {
self.sequelize.log('Executed (' + (self.database.uuid || 'default') + '): ' + self.sql, (Date.now() - queryBegin), self.options);
query.sequelize.log('Executed (' + (query.database.uuid || 'default') + '): ' + query.sql, (Date.now() - queryBegin), query.options);
}
if (err) {
err.sql = self.sql;
reject(self.formatError(err));
err.sql = query.sql;
reject(query.formatError(err));
} else {
var metaData = this
, result = self.instance;
const metaData = this;
let result = query.instance;
// add the inserted row id to the instance
if (self.isInsertQuery(results, metaData)) {
self.handleInsertQuery(results, metaData);
if (query.isInsertQuery(results, metaData)) {
query.handleInsertQuery(results, metaData);
if (!self.instance) {
result = metaData[self.getInsertIdField()];
if (!query.instance) {
result = metaData[query.getInsertIdField()];
}
}
if (self.sql.indexOf('sqlite_master') !== -1) {
result = results.map(function(resultSet) { return resultSet.name; });
} else if (self.isSelectQuery()) {
if (!self.options.raw) {
if (query.sql.indexOf('sqlite_master') !== -1) {
result = results.map(resultSet => resultSet.name);
} else if (query.isSelectQuery()) {
if (!query.options.raw) {
// This is a map of prefix strings to models, e.g. user.projects -> Project model
var prefixes = self.$collectModels(self.options.include);
const prefixes = query.$collectModels(query.options.include);
results = results.map(function(result) {
return _.mapValues(result, function (value, name) {
var model;
results = results.map(result => {
return _.mapValues(result, (value, name) => {
let model;
if (name.indexOf('.') !== -1) {
var lastind = name.lastIndexOf('.');
const lastind = name.lastIndexOf('.');
model = prefixes[name.substr(0, lastind)];
name = name.substr(lastind + 1);
} else {
model = self.options.model;
model = query.options.model;
}
var tableName = model.getTableName().toString().replace(/`/g, '')
, tableTypes = columnTypes[tableName] || {};
const tableName = model.getTableName().toString().replace(/`/g, '');
const tableTypes = columnTypes[tableName] || {};
if (tableTypes && !(name in tableTypes)) {
// The column is aliased
_.forOwn(model.rawAttributes, function (attribute, key) {
_.forOwn(model.rawAttributes, (attribute, key) => {
if (name === key && attribute.field) {
name = attribute.field;
return false;
......@@ -156,7 +157,7 @@ Query.prototype.run = function(sql, parameters) {
});
}
var type = tableTypes[name];
let type = tableTypes[name];
if (type) {
if (type.indexOf('(') !== -1) {
// Remove the lenght part
......@@ -164,10 +165,10 @@ Query.prototype.run = function(sql, parameters) {
}
type = type.replace('UNSIGNED', '').replace('ZEROFILL', '');
type = type.trim().toUpperCase();
var parse = parserStore.get(type);
const parse = parserStore.get(type);
if (value !== null && parse) {
return parse(value, { timezone: self.sequelize.options.timezone});
return parse(value, { timezone: query.sequelize.options.timezone});
}
}
return value;
......@@ -175,19 +176,19 @@ Query.prototype.run = function(sql, parameters) {
});
}
result = self.handleSelectQuery(results);
} else if (self.isShowOrDescribeQuery()) {
result = query.handleSelectQuery(results);
} else if (query.isShowOrDescribeQuery()) {
result = results;
} else if (self.sql.indexOf('PRAGMA INDEX_LIST') !== -1) {
result = self.handleShowIndexesQuery(results);
} else if (self.sql.indexOf('PRAGMA INDEX_INFO') !== -1) {
} else if (query.sql.indexOf('PRAGMA INDEX_LIST') !== -1) {
result = query.handleShowIndexesQuery(results);
} else if (query.sql.indexOf('PRAGMA INDEX_INFO') !== -1) {
result = results;
} else if (self.sql.indexOf('PRAGMA TABLE_INFO') !== -1) {
} else if (query.sql.indexOf('PRAGMA TABLE_INFO') !== -1) {
// this is the sqlite way of getting the metadata of a table
result = {};
var defaultValue;
results.forEach(function(_result) {
let defaultValue;
for (const _result of results) {
if (_result.dflt_value === null) {
// Column schema omits any "DEFAULT ..."
defaultValue = undefined;
......@@ -201,7 +202,7 @@ Query.prototype.run = function(sql, parameters) {
result[_result.name] = {
type: _result.type,
allowNull: (_result.notnull === 0),
defaultValue: defaultValue,
defaultValue,
primaryKey : (_result.pk === 1)
};
......@@ -212,93 +213,88 @@ Query.prototype.run = function(sql, parameters) {
if (typeof result[_result.name].defaultValue === 'string') {
result[_result.name].defaultValue = result[_result.name].defaultValue.replace(/'/g, '');
}
});
} else if (self.sql.indexOf('PRAGMA foreign_keys;') !== -1) {
}
} else if (query.sql.indexOf('PRAGMA foreign_keys;') !== -1) {
result = results[0];
} else if (self.sql.indexOf('PRAGMA foreign_keys') !== -1) {
} else if (query.sql.indexOf('PRAGMA foreign_keys') !== -1) {
result = results;
} else if (self.sql.indexOf('PRAGMA foreign_key_list') !== -1) {
} else if (query.sql.indexOf('PRAGMA foreign_key_list') !== -1) {
result = results;
} else if ([QueryTypes.BULKUPDATE, QueryTypes.BULKDELETE].indexOf(self.options.type) !== -1) {
} else if ([QueryTypes.BULKUPDATE, QueryTypes.BULKDELETE].indexOf(query.options.type) !== -1) {
result = metaData.changes;
} else if (self.options.type === QueryTypes.UPSERT) {
} else if (query.options.type === QueryTypes.UPSERT) {
result = undefined;
} else if (self.options.type === QueryTypes.VERSION) {
} else if (query.options.type === QueryTypes.VERSION) {
result = results[0].version;
} else if (self.options.type === QueryTypes.RAW) {
} else if (query.options.type === QueryTypes.RAW) {
result = [results, metaData];
}
resolve(result);
}
};
}
if (method === 'exec') {
// exec does not support bind parameter
self.database[method](self.sql, afterExecute);
this.database[method](this.sql, afterExecute);
} else {
if (!parameters) parameters = [];
self.database[method](self.sql, parameters, afterExecute);
this.database[method](this.sql, parameters, afterExecute);
}
}));
return null;
}
};
if ((self.getDatabaseMethod() === 'all')) {
var tableNames = [];
if (self.options && self.options.tableNames) {
tableNames = self.options.tableNames;
} else if (/FROM `(.*?)`/i.exec(self.sql)) {
tableNames.push(/FROM `(.*?)`/i.exec(self.sql)[1]);
if ((this.getDatabaseMethod() === 'all')) {
let tableNames = [];
if (this.options && this.options.tableNames) {
tableNames = this.options.tableNames;
} else if (/FROM `(.*?)`/i.exec(this.sql)) {
tableNames.push(/FROM `(.*?)`/i.exec(this.sql)[1]);
}
// If we already have the metadata for the table, there's no need to ask for it again
tableNames = _.filter(tableNames, function (tableName) {
return !(tableName in columnTypes) && tableName !== 'sqlite_master';
});
tableNames = _.filter(tableNames, tableName => !(tableName in columnTypes) && tableName !== 'sqlite_master');
if (!tableNames.length) {
return executeSql();
} else {
return Promise.map(tableNames, function(tableName) {
return new Promise(function(resolve) {
return Promise.map(tableNames, tableName =>
new Promise(resolve => {
tableName = tableName.replace(/`/g, '');
columnTypes[tableName] = {};
self.database.all('PRAGMA table_info(`' + tableName + '`)', function(err, results) {
this.database.all('PRAGMA table_info(`' + tableName + '`)', (err, results) => {
if (!err) {
results.forEach(function (result) {
for (const result of results) {
columnTypes[tableName][result.name] = result.type;
});
}
}
resolve();
});
});
}).then(executeSql);
})
).then(executeSql);
}
} else {
return executeSql();
}
});
});
}
return promise;
};
Query.prototype.formatError = function (err) {
var match;
formatError(err) {
switch (err.code) {
case 'SQLITE_CONSTRAINT':
match = err.message.match(/FOREIGN KEY constraint failed/);
case 'SQLITE_CONSTRAINT': {
let match = err.message.match(/FOREIGN KEY constraint failed/);
if (match !== null) {
return new sequelizeErrors.ForeignKeyConstraintError({
parent :err
});
}
var fields = [];
let fields = [];
// Sqlite pre 2.2 behavior - Error: SQLITE_CONSTRAINT: columns x, y are not unique
match = err.message.match(/columns (.*?) are/);
......@@ -309,24 +305,21 @@ Query.prototype.formatError = function (err) {
// Sqlite post 2.2 behavior - Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: table.x, table.y
match = err.message.match(/UNIQUE constraint failed: (.*)/);
if (match !== null && match.length >= 2) {
fields = match[1].split(', ').map(function (columnWithTable) {
return columnWithTable.split('.')[1];
});
fields = match[1].split(', ').map(columnWithTable => columnWithTable.split('.')[1]);
}
}
var errors = []
, self = this
, message = 'Validation error';
const errors = [];
let message = 'Validation error';
fields.forEach(function(field) {
for (const field of fields) {
errors.push(new sequelizeErrors.ValidationErrorItem(
self.getUniqueConstraintErrorMessage(field),
'unique violation', field, self.instance && self.instance[field]));
});
this.getUniqueConstraintErrorMessage(field),
'unique violation', field, this.instance && this.instance[field]));
}
if (this.model) {
_.forOwn(this.model.uniqueKeys, function(constraint) {
_.forOwn(this.model.uniqueKeys, constraint => {
if (_.isEqual(constraint.fields, fields) && !!constraint.msg) {
message = constraint.msg;
return false;
......@@ -334,45 +327,39 @@ Query.prototype.formatError = function (err) {
});
}
return new sequelizeErrors.UniqueConstraintError({
message: message,
errors: errors,
parent: err,
fields: fields
});
return new sequelizeErrors.UniqueConstraintError({message, errors, parent: err, fields});
}
case 'SQLITE_BUSY':
return new sequelizeErrors.TimeoutError(err);
default:
return new sequelizeErrors.DatabaseError(err);
}
};
}
Query.prototype.handleShowIndexesQuery = function (data) {
var self = this;
handleShowIndexesQuery(data) {
// Sqlite returns indexes so the one that was defined last is returned first. Lets reverse that!
return this.sequelize.Promise.map(data.reverse(), function (item) {
return this.sequelize.Promise.map(data.reverse(), item => {
item.fields = [];
item.primary = false;
item.unique = !!item.unique;
return self.run('PRAGMA INDEX_INFO(`' + item.name + '`)').then(function (columns) {
columns.forEach(function (column) {
return this.run('PRAGMA INDEX_INFO(`' + item.name + '`)').then(columns => {
for (const column of columns) {
item.fields[column.seqno] = {
attribute: column.name,
length: undefined,
order: undefined,
};
});
}
return item;
});
});
};
}
Query.prototype.getDatabaseMethod = function() {
getDatabaseMethod() {
if (this.isUpsertQuery()) {
return 'exec'; // Needed to run multiple queries in one
} else if (this.isInsertQuery() || this.isUpdateQuery() || this.isBulkUpdateQuery() || (this.sql.toLowerCase().indexOf('CREATE TEMPORARY TABLE'.toLowerCase()) !== -1) || this.options.type === QueryTypes.BULKDELETE) {
......@@ -380,6 +367,9 @@ Query.prototype.getDatabaseMethod = function() {
} else {
return 'all';
}
};
}
}
module.exports = Query;
module.exports.Query = Query;
module.exports.default = Query;
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!