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

Commit 7275c7c6 by Felix Becker Committed by Jan Aagaard Meier

ES6 refactor: dialects / MSSQL (#6049)

* ES6 refactor of MSSQL ConnectionManager

classes, let, const, arrow functions, export default

* Make Mssql Query an ES6 class

* ES6 refactor of Mssql Query

let, const, arrow functions, property shorthands, for of, export default
1 parent 3ff27d10
'use strict';
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, ResourceLock = require('./resource-lock')
, Utils = require('../../utils')
, Promise = require('../../promise')
, sequelizeErrors = require('../../errors')
, parserStore = require('../parserStore')('mssql')
, _ = require('lodash');
ConnectionManager = function(dialect, sequelize) {
AbstractConnectionManager.call(this, dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 1433;
try {
this.lib = require(sequelize.config.dialectModulePath || 'tedious');
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
throw new Error('Please install tedious package manually');
const AbstractConnectionManager = require('../abstract/connection-manager');
const ResourceLock = require('./resource-lock');
const Promise = require('../../promise');
const sequelizeErrors = require('../../errors');
const parserStore = require('../parserStore')('mssql');
const _ = require('lodash');
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
super(dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 1433;
try {
this.lib = require(sequelize.config.dialectModulePath || 'tedious');
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
throw new Error('Please install tedious package manually');
}
throw err;
}
throw err;
}
};
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) {
parserStore.refresh(dataType);
};
ConnectionManager.prototype.$clearTypeParser = function () {
parserStore.clear();
};
ConnectionManager.prototype.connect = function(config) {
var self = this;
return new Promise(function (resolve, reject) {
var connectionConfig = {
userName: config.username,
password: config.password,
server: config.host,
options: {
port: config.port,
database: config.database
}
};
if (config.dialectOptions) {
// only set port if no instance name was provided
if (config.dialectOptions.instanceName) {
delete connectionConfig.options.port;
}
// 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);
}
// The 'tedious' driver needs domain property to be in the main Connection config object
if(config.dialectOptions.domain) {
connectionConfig.domain = config.dialectOptions.domain;
}
$clearTypeParser() {
parserStore.clear();
}
Object.keys(config.dialectOptions).forEach(function(key) {
connectionConfig.options[key] = config.dialectOptions[key];
});
}
connect(config) {
return new Promise((resolve, reject) => {
const connectionConfig = {
userName: config.username,
password: config.password,
server: config.host,
options: {
port: config.port,
database: config.database
}
};
var connection = new self.lib.Connection(connectionConfig)
, connectionLock = new ResourceLock(connection);
connection.lib = self.lib;
if (config.dialectOptions) {
// only set port if no instance name was provided
if (config.dialectOptions.instanceName) {
delete connectionConfig.options.port;
}
connection.on('connect', function(err) {
if (!err) {
resolve(connectionLock);
return;
}
// The 'tedious' driver needs domain property to be in the main Connection config object
if(config.dialectOptions.domain) {
connectionConfig.domain = config.dialectOptions.domain;
}
if (!err.code) {
reject(new sequelizeErrors.ConnectionError(err));
return;
for (const key of Object.keys(config.dialectOptions)) {
connectionConfig.options[key] = config.dialectOptions[key];
}
}
switch (err.code) {
case 'ESOCKET':
if (_.includes(err.message, 'connect EHOSTUNREACH')) {
reject(new sequelizeErrors.HostNotReachableError(err));
} else if (_.includes(err.message, 'connect ECONNREFUSED')) {
reject(new sequelizeErrors.ConnectionRefusedError(err));
} else {
const connection = new this.lib.Connection(connectionConfig);
const connectionLock = new ResourceLock(connection);
connection.lib = this.lib;
connection.on('connect', err => {
if (!err) {
resolve(connectionLock);
return;
}
if (!err.code) {
reject(new sequelizeErrors.ConnectionError(err));
return;
}
break;
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ER_ACCESS_DENIED_ERROR':
reject(new sequelizeErrors.AccessDeniedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
reject(new sequelizeErrors.ConnectionError(err));
break;
}
});
if (config.pool.handleDisconnects) {
connection.on('error', function (err) {
switch (err.code) {
case 'ESOCKET':
case 'ECONNRESET':
self.pool.destroy(connectionLock);
case 'ESOCKET':
if (_.includes(err.message, 'connect EHOSTUNREACH')) {
reject(new sequelizeErrors.HostNotReachableError(err));
} else if (_.includes(err.message, 'connect ECONNREFUSED')) {
reject(new sequelizeErrors.ConnectionRefusedError(err));
} else {
reject(new sequelizeErrors.ConnectionError(err));
}
break;
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ER_ACCESS_DENIED_ERROR':
reject(new sequelizeErrors.AccessDeniedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
reject(new sequelizeErrors.ConnectionError(err));
break;
}
});
}
});
};
ConnectionManager.prototype.disconnect = function(connectionLock) {
var connection = connectionLock.unwrap();
if (config.pool.handleDisconnects) {
connection.on('error', err => {
switch (err.code) {
case 'ESOCKET':
case 'ECONNRESET':
this.pool.destroy(connectionLock);
}
});
}
// Dont disconnect a connection that is already disconnected
if (!!connection.closed) {
return Promise.resolve();
});
}
return new Promise(function (resolve, reject) {
connection.on('end', resolve);
connection.close();
});
};
disconnect(connectionLock) {
const connection = connectionLock.unwrap();
ConnectionManager.prototype.validate = function(connectionLock) {
var connection = connectionLock.unwrap();
// Dont disconnect a connection that is already disconnected
if (!!connection.closed) {
return Promise.resolve();
}
return connection && connection.loggedIn;
};
return new Promise(resolve => {
connection.on('end', resolve);
connection.close();
});
}
validate(connectionLock) {
const connection = connectionLock.unwrap();
return connection && connection.loggedIn;
}
}
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
'use strict';
var Utils = require('../../utils')
, Promise = require('../../promise')
, AbstractQuery = require('../abstract/query')
, sequelizeErrors = require('../../errors.js')
, parserStore = require('../parserStore')('mssql'),
_ = require('lodash');
var Query = function(connection, sequelize, options) {
this.connection = connection;
this.instance = options.instance;
this.model = options.model;
this.sequelize = sequelize;
this.options = Utils._.extend({
logging: console.log,
plain: false,
raw: false
}, options || {});
this.checkLoggingOption();
};
Utils.inherit(Query, AbstractQuery);
Query.prototype.getInsertIdField = function() {
return 'id';
};
Query.formatBindParameters = AbstractQuery.formatBindParameters;
Query.prototype._run = function(connection, sql, parameters) {
var self = this;
this.sql = sql;
//do we need benchmark for this query execution
var benchmark = this.sequelize.options.benchmark || this.options.benchmark;
if (benchmark) {
var queryBegin = Date.now();
} else {
this.sequelize.log('Executing (' + (connection.uuid || 'default') + '): ' + this.sql, this.options);
const Utils = require('../../utils');
const Promise = require('../../promise');
const AbstractQuery = require('../abstract/query');
const sequelizeErrors = require('../../errors.js');
const parserStore = require('../parserStore')('mssql');
const _ = require('lodash');
class Query extends AbstractQuery {
constructor(connection, sequelize, options) {
super();
this.connection = connection;
this.instance = options.instance;
this.model = options.model;
this.sequelize = sequelize;
this.options = Utils._.extend({
logging: console.log,
plain: false,
raw: false
}, options || {});
this.checkLoggingOption();
}
var promise = new Utils.Promise(function(resolve, reject) {
// TRANSACTION SUPPORT
if (_.includes(self.sql, 'BEGIN TRANSACTION')) {
connection.beginTransaction(function(err) {
if (!!err) {
reject(self.formatError(err));
} else {
resolve(self.formatResults());
}
} /* name, isolation_level */);
} else if (_.includes(self.sql, 'COMMIT TRANSACTION')) {
connection.commitTransaction(function(err) {
if (!!err) {
reject(self.formatError(err));
} else {
resolve(self.formatResults());
}
});
} else if (_.includes(self.sql, 'ROLLBACK TRANSACTION')) {
connection.rollbackTransaction(function(err) {
if (!!err) {
reject(self.formatError(err));
} else {
resolve(self.formatResults());
}
});
} else {
// QUERY SUPPORT
var results = [];
var request = new connection.lib.Request(self.sql, function(err) {
if (benchmark) {
self.sequelize.log('Executed (' + (connection.uuid || 'default') + '): ' + self.sql, (Date.now() - queryBegin), self.options);
}
if (err) {
err.sql = sql;
reject(self.formatError(err));
} else {
resolve(self.formatResults(results));
}
});
getInsertIdField() {
return 'id';
}
request.on('row', function(columns) {
var row = {};
columns.forEach(function(column) {
var typeid = column.metadata.type.id
, value = column.value
, parse = parserStore.get(typeid);
_run(connection, sql, parameters) {
this.sql = sql;
if (value !== null & !!parse) {
value = parse(value);
//do we need benchmark for this query execution
const benchmark = this.sequelize.options.benchmark || this.options.benchmark;
let queryBegin;
if (benchmark) {
queryBegin = Date.now();
} else {
this.sequelize.log('Executing (' + (connection.uuid || 'default') + '): ' + this.sql, this.options);
}
return new Promise((resolve, reject) => {
// TRANSACTION SUPPORT
if (_.includes(this.sql, 'BEGIN TRANSACTION')) {
connection.beginTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
} /* name, isolation_level */);
} else if (_.includes(this.sql, 'COMMIT TRANSACTION')) {
connection.commitTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
row[column.metadata.colName] = value;
});
} else if (_.includes(this.sql, 'ROLLBACK TRANSACTION')) {
connection.rollbackTransaction(err => {
if (!!err) {
reject(this.formatError(err));
} else {
resolve(this.formatResults());
}
});
} else {
// QUERY SUPPORT
const results = [];
results.push(row);
});
const request = new connection.lib.Request(this.sql, err => {
connection.execSql(request);
}
});
return promise;
};
Query.prototype.run = function(sql, parameters) {
var self = this;
return Promise.using(this.connection.lock(), function (connection) {
return self._run(connection, sql, parameters);
});
};
/**
* High level function that handles the results of a query execution.
*
*
* Example:
* query.formatResults([
* {
* id: 1, // this is from the main table
* attr2: 'snafu', // this is from the main table
* Tasks.id: 1, // this is from the associated table
* Tasks.title: 'task' // this is from the associated table
* }
* ])
*
* @param {Array} data - The result of the query execution.
*/
Query.prototype.formatResults = function(data) {
var result = this.instance;
if (this.isInsertQuery(data)) {
this.handleInsertQuery(data);
if (!this.instance) {
if (this.options.plain) {
// NOTE: super contrived. This just passes the newly added query-interface
// test returning only the PK. There isn't a way in MSSQL to identify
// that a given return value is the PK, and we have no schema information
// because there was no calling Model.
var record = data[0];
result = record[Object.keys(record)[0]];
} else {
result = data;
}
}
}
if (benchmark) {
this.sequelize.log('Executed (' + (connection.uuid || 'default') + '): ' + this.sql, (Date.now() - queryBegin), this.options);
}
if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data);
} else if (this.isDescribeQuery()) {
result = {};
data.forEach(function(_result) {
if (_result.Default) {
_result.Default = _result.Default.replace("('",'').replace("')",'').replace(/'/g,''); /* jshint ignore: line */
}
if (err) {
err.sql = sql;
reject(this.formatError(err));
} else {
resolve(this.formatResults(results));
}
});
result[_result.Name] = {
type: _result.Type.toUpperCase(),
allowNull: (_result.IsNull === 'YES' ? true : false),
defaultValue: _result.Default,
primaryKey: _result.Constraint === 'PRIMARY KEY'
};
request.on('row', columns => {
const row = {};
for (const column of columns) {
const typeid = column.metadata.type.id;
const parse = parserStore.get(typeid);
let value = column.value;
if (value !== null & !!parse) {
value = parse(value);
}
row[column.metadata.colName] = value;
}
results.push(row);
});
connection.execSql(request);
}
});
} else if (this.isShowIndexesQuery()) {
result = this.handleShowIndexesQuery(data);
} else if (this.isSelectQuery()) {
result = this.handleSelectQuery(data);
} else if (this.isCallQuery()) {
result = data[0];
} else if (this.isBulkUpdateQuery()) {
result = data.length;
} else if (this.isBulkDeleteQuery()){
result = data[0] && data[0].AFFECTEDROWS;
} else if (this.isVersionQuery()) {
result = data[0].version;
} else if (this.isForeignKeysQuery()) {
result = data;
} else if (this.isRawQuery()) {
// MSSQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta
result = [data, data];
}
return result;
};
Query.prototype.handleShowTablesQuery = function(results) {
return results.map(function(resultSet) {
return {
tableName: resultSet.TABLE_NAME,
schema: resultSet.TABLE_SCHEMA
};
});
};
Query.prototype.formatError = function (err) {
var match;
match = err.message.match(/Violation of UNIQUE KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'.(:? The duplicate key value is \((.*)\).)?/);
match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/);
if (match && match.length > 1) {
var fields = {}
, message = 'Validation error'
, uniqueKey = this.model && this.model.uniqueKeys[match[1]];
if (uniqueKey && !!uniqueKey.msg) {
message = uniqueKey.msg;
}
if (!!match[4]) {
var values = match[4].split(',').map(Function.prototype.call, String.prototype.trim);
if (!!uniqueKey) {
fields = Utils._.zipObject(uniqueKey.fields, values);
} else {
fields[match[1]] = match[4];
}
run(sql, parameters) {
return Promise.using(this.connection.lock(), connection => this._run(connection, sql, parameters));
}
/**
* High level function that handles the results of a query execution.
*
*
* Example:
* query.formatResults([
* {
* id: 1, // this is from the main table
* attr2: 'snafu', // this is from the main table
* Tasks.id: 1, // this is from the associated table
* Tasks.title: 'task' // this is from the associated table
* }
* ])
*
* @param {Array} data - The result of the query execution.
*/
formatResults(data) {
let result = this.instance;
if (this.isInsertQuery(data)) {
this.handleInsertQuery(data);
if (!this.instance) {
if (this.options.plain) {
// NOTE: super contrived. This just passes the newly added query-interface
// test returning only the PK. There isn't a way in MSSQL to identify
// that a given return value is the PK, and we have no schema information
// because there was no calling Model.
const record = data[0];
result = record[Object.keys(record)[0]];
} else {
result = data;
}
}
}
var errors = [];
var self = this;
Utils._.forOwn(fields, function(value, field) {
errors.push(new sequelizeErrors.ValidationErrorItem(
self.getUniqueConstraintErrorMessage(field),
'unique violation', field, value));
});
if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data);
} else if (this.isDescribeQuery()) {
result = {};
for (const _result of data) {
if (_result.Default) {
_result.Default = _result.Default.replace("('",'').replace("')",'').replace(/'/g,''); /* jshint ignore: line */
}
result[_result.Name] = {
type: _result.Type.toUpperCase(),
allowNull: (_result.IsNull === 'YES' ? true : false),
defaultValue: _result.Default,
primaryKey: _result.Constraint === 'PRIMARY KEY'
};
}
} else if (this.isShowIndexesQuery()) {
result = this.handleShowIndexesQuery(data);
} else if (this.isSelectQuery()) {
result = this.handleSelectQuery(data);
} else if (this.isCallQuery()) {
result = data[0];
} else if (this.isBulkUpdateQuery()) {
result = data.length;
} else if (this.isBulkDeleteQuery()){
result = data[0] && data[0].AFFECTEDROWS;
} else if (this.isVersionQuery()) {
result = data[0].version;
} else if (this.isForeignKeysQuery()) {
result = data;
} else if (this.isRawQuery()) {
// MSSQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta
result = [data, data];
}
return new sequelizeErrors.UniqueConstraintError({
message: message,
errors: errors,
parent: err,
fields: fields
});
return result;
}
match = err.message.match(/Failed on step '(.*)'.Could not create constraint. See previous errors./) ||
err.message.match(/The DELETE statement conflicted with the REFERENCE constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) ||
err.message.match(/The INSERT statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) ||
err.message.match(/The UPDATE statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./);
if (match && match.length > 0) {
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match[1],
parent: err
handleShowTablesQuery(results) {
return results.map(resultSet => {
return {
tableName: resultSet.TABLE_NAME,
schema: resultSet.TABLE_SCHEMA
};
});
}
return new sequelizeErrors.DatabaseError(err);
};
formatError(err) {
let match;
match = err.message.match(/Violation of UNIQUE KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'.(:? The duplicate key value is \((.*)\).)?/);
match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/);
if (match && match.length > 1) {
let fields = {};
const uniqueKey = this.model && this.model.uniqueKeys[match[1]];
let message = 'Validation error';
if (uniqueKey && !!uniqueKey.msg) {
message = uniqueKey.msg;
}
if (!!match[4]) {
const values = match[4].split(',').map(part => part.trim());
if (!!uniqueKey) {
fields = Utils._.zipObject(uniqueKey.fields, values);
} else {
fields[match[1]] = match[4];
}
}
Query.prototype.isShowOrDescribeQuery = function() {
var result = false;
const errors = [];
Utils._.forOwn(fields, (value, field) => {
errors.push(new sequelizeErrors.ValidationErrorItem(
this.getUniqueConstraintErrorMessage(field),
'unique violation', field, value
));
});
result = result || (this.sql.toLowerCase().indexOf("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'") === 0); /* jshint ignore: line */
result = result || (this.sql.toLowerCase().indexOf('select tablename = t.name, name = ind.name,') === 0);
result = result || (this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0);
return new sequelizeErrors.UniqueConstraintError({message, errors, parent: err, fields});
}
return result;
};
match = err.message.match(/Failed on step '(.*)'.Could not create constraint. See previous errors./) ||
err.message.match(/The DELETE statement conflicted with the REFERENCE constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) ||
err.message.match(/The INSERT statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) ||
err.message.match(/The UPDATE statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./);
if (match && match.length > 0) {
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match[1],
parent: err
});
}
Query.prototype.isShowIndexesQuery = function () {
return this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0;
};
return new sequelizeErrors.DatabaseError(err);
}
Query.prototype.handleShowIndexesQuery = function (data) {
// Group by index name, and collect all fields
data = _.reduce(data, function (acc, item) {
if (!(item.index_name in acc)) {
acc[item.index_name] = item;
item.fields = [];
}
isShowOrDescribeQuery() {
let result = false;
Utils._.forEach(item.index_keys.split(','), function(column) {
var columnName = column.trim();
if (columnName.indexOf('(-)') !== -1) {
columnName = columnName.replace('(-)','');
result = result || (this.sql.toLowerCase().indexOf("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'") === 0); /* jshint ignore: line */
result = result || (this.sql.toLowerCase().indexOf('select tablename = t.name, name = ind.name,') === 0);
result = result || (this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0);
return result;
}
isShowIndexesQuery() {
return this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0;
}
handleShowIndexesQuery(data) {
// Group by index name, and collect all fields
data = _.reduce(data, (acc, item) => {
if (!(item.index_name in acc)) {
acc[item.index_name] = item;
item.fields = [];
}
acc[item.index_name].fields.push({
attribute: columnName,
length: undefined,
order: (column.indexOf('(-)') !== -1 ? 'DESC' : 'ASC'),
collate: undefined
Utils._.forEach(item.index_keys.split(','), column => {
let columnName = column.trim();
if (columnName.indexOf('(-)') !== -1) {
columnName = columnName.replace('(-)','');
}
acc[item.index_name].fields.push({
attribute: columnName,
length: undefined,
order: (column.indexOf('(-)') !== -1 ? 'DESC' : 'ASC'),
collate: undefined
});
});
});
delete item.index_keys;
return acc;
}, {});
delete item.index_keys;
return acc;
}, {});
return Utils._.map(data, function(item) {
return {
return Utils._.map(data, item => ({
primary: (item.index_name.toLowerCase().indexOf('pk') === 0),
fields: item.fields,
name: item.index_name,
tableName: undefined,
unique: (item.index_description.toLowerCase().indexOf('unique') !== -1),
type: undefined,
};
});
};
Query.prototype.handleInsertQuery = function(results, metaData) {
if (this.instance) {
// add the inserted row id to the instance
var autoIncrementField = this.model.autoIncrementField
, autoIncrementFieldAlias = null
, id = null;
if (this.model.rawAttributes.hasOwnProperty(autoIncrementField) &&
this.model.rawAttributes[autoIncrementField].field !== undefined)
autoIncrementFieldAlias = this.model.rawAttributes[autoIncrementField].field ;
id = id || (results && results[0][this.getInsertIdField()]);
id = id || (metaData && metaData[this.getInsertIdField()]);
id = id || (results && results[0][autoIncrementField]);
id = id || (autoIncrementFieldAlias && results && results[0][autoIncrementFieldAlias]);
this.instance[autoIncrementField] = id;
type: undefined
}));
}
handleInsertQuery(results, metaData) {
if (this.instance) {
// add the inserted row id to the instance
const autoIncrementField = this.model.autoIncrementField;
let id = null;
let autoIncrementFieldAlias = null;
if (this.model.rawAttributes.hasOwnProperty(autoIncrementField) &&
this.model.rawAttributes[autoIncrementField].field !== undefined)
autoIncrementFieldAlias = this.model.rawAttributes[autoIncrementField].field ;
id = id || (results && results[0][this.getInsertIdField()]);
id = id || (metaData && metaData[this.getInsertIdField()]);
id = id || (results && results[0][autoIncrementField]);
id = id || (autoIncrementFieldAlias && results && results[0][autoIncrementFieldAlias]);
this.instance[autoIncrementField] = id;
}
}
};
}
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!