2019-04-18 21:32:38 +00:00
|
|
|
// Copyright IBM Corp. 2014,2019. All Rights Reserved.
|
2016-05-06 04:50:59 +00:00
|
|
|
// Node module: loopback-connector
|
|
|
|
// This file is licensed under the MIT License.
|
|
|
|
// License text available at https://opensource.org/licenses/MIT
|
|
|
|
|
2017-03-06 23:40:47 +00:00
|
|
|
'use strict';
|
2019-08-02 13:50:51 +00:00
|
|
|
const SG = require('strong-globalize');
|
|
|
|
const g = SG();
|
2016-07-25 16:45:38 +00:00
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const util = require('util');
|
|
|
|
const async = require('async');
|
|
|
|
const assert = require('assert');
|
|
|
|
const Connector = require('./connector');
|
|
|
|
const debug = require('debug')('loopback:connector:sql');
|
|
|
|
const ParameterizedSQL = require('./parameterized-sql');
|
|
|
|
const Transaction = require('./transaction');
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
module.exports = SQLConnector;
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2016-01-09 08:23:49 +00:00
|
|
|
function NOOP() {}
|
|
|
|
|
2014-05-23 08:50:23 +00:00
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Base class for connectors that connect to relational databases using SQL
|
2014-05-23 08:50:23 +00:00
|
|
|
* @class
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
function SQLConnector() {
|
|
|
|
// Call the super constructor
|
2014-05-23 08:50:23 +00:00
|
|
|
Connector.apply(this, [].slice.call(arguments));
|
|
|
|
}
|
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
// Inherit from the base Connector
|
|
|
|
util.inherits(SQLConnector, Connector);
|
|
|
|
|
|
|
|
// Export ParameterizedSQL
|
|
|
|
SQLConnector.ParameterizedSQL = ParameterizedSQL;
|
|
|
|
|
|
|
|
// The generic placeholder
|
2019-08-02 13:50:51 +00:00
|
|
|
const PLACEHOLDER = SQLConnector.PLACEHOLDER = ParameterizedSQL.PLACEHOLDER;
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2015-05-15 17:27:08 +00:00
|
|
|
SQLConnector.Transaction = Transaction;
|
|
|
|
|
2014-05-23 08:50:23 +00:00
|
|
|
/**
|
2017-06-22 17:06:24 +00:00
|
|
|
* @private
|
2014-05-23 08:50:23 +00:00
|
|
|
* Set the relational property to indicate the backend is a relational DB
|
|
|
|
* @type {boolean}
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.relational = true;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Invoke a prototype method on the super class
|
|
|
|
* @param {String} methodName Method name
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.invokeSuper = function(methodName) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const args = [].slice.call(arguments, 1);
|
|
|
|
const superMethod = this.constructor.super_.prototype[methodName];
|
2015-05-13 17:14:44 +00:00
|
|
|
return superMethod.apply(this, args);
|
|
|
|
};
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2017-02-23 21:31:04 +00:00
|
|
|
/**
|
|
|
|
* Perform autoupdate for the given models
|
|
|
|
* @param {String[]} [models] A model name or an array of model names.
|
|
|
|
* If not present, apply to all models
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.autoupdate = function(models, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2017-02-23 21:31:04 +00:00
|
|
|
if ((!cb) && ('function' === typeof models)) {
|
|
|
|
cb = models;
|
|
|
|
models = undefined;
|
|
|
|
}
|
|
|
|
// First argument is a model name
|
|
|
|
if ('string' === typeof models) {
|
|
|
|
models = [models];
|
|
|
|
}
|
|
|
|
|
|
|
|
models = models || Object.keys(this._models);
|
|
|
|
|
2020-02-22 14:05:17 +00:00
|
|
|
async.eachSeries(models, function(model, done) {
|
2017-02-23 21:31:04 +00:00
|
|
|
if (!(model in self._models)) {
|
|
|
|
return process.nextTick(function() {
|
|
|
|
done(new Error(g.f('Model not found: %s', model)));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
self.getTableStatus(model, function(err, fields, indexes, FKs) {
|
|
|
|
if (!err && fields.length) {
|
|
|
|
self.alterTable(model, fields, indexes, done);
|
|
|
|
} else {
|
|
|
|
self.createTable(model, done);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}, cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Check if the models exist
|
|
|
|
* @param {String[]} [models] A model name or an array of model names.
|
|
|
|
* If not present, apply to all models
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.isActual = function(models, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2017-02-23 21:31:04 +00:00
|
|
|
|
|
|
|
if ((!cb) && ('function' === typeof models)) {
|
|
|
|
cb = models;
|
|
|
|
models = undefined;
|
|
|
|
}
|
|
|
|
// First argument is a model name
|
|
|
|
if ('string' === typeof models) {
|
|
|
|
models = [models];
|
|
|
|
}
|
|
|
|
|
|
|
|
models = models || Object.keys(this._models);
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
let changes = [];
|
2017-02-23 21:31:04 +00:00
|
|
|
async.each(models, function(model, done) {
|
|
|
|
self.getTableStatus(model, function(err, fields) {
|
|
|
|
changes = changes.concat(self.getAddModifyColumns(model, fields));
|
|
|
|
changes = changes.concat(self.getDropColumns(model, fields));
|
|
|
|
done(err);
|
|
|
|
});
|
|
|
|
}, function done(err) {
|
|
|
|
if (err) {
|
|
|
|
return cb && cb(err);
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const actual = (changes.length === 0);
|
2017-03-06 23:40:47 +00:00
|
|
|
if (cb) cb(null, actual);
|
2017-02-23 21:31:04 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.getAddModifyColumns = function(model, fields) {
|
2019-08-02 13:50:51 +00:00
|
|
|
let sql = [];
|
|
|
|
const self = this;
|
2017-03-20 15:15:27 +00:00
|
|
|
sql = sql.concat(self.getColumnsToAdd(model, fields));
|
|
|
|
return sql;
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.getColumnsToAdd = function(model, fields) {
|
|
|
|
throw new Error(g.f('{{getColumnsToAdd()}} must be implemented by the connector'));
|
2017-02-23 21:31:04 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.getDropColumns = function(model, fields) {
|
2019-08-02 13:50:51 +00:00
|
|
|
let sql = [];
|
|
|
|
const self = this;
|
2017-02-23 21:31:04 +00:00
|
|
|
sql = sql.concat(self.getColumnsToDrop(model, fields));
|
|
|
|
return sql;
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.getColumnsToDrop = function(model, fields) {
|
|
|
|
throw new Error(g.f('{{getColumnsToDrop()}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.searchForPropertyInActual = function(model, propName,
|
|
|
|
actualFields) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
let found = false;
|
2017-02-23 21:31:04 +00:00
|
|
|
actualFields.forEach(function(f) {
|
|
|
|
if (f.column === self.column(model, propName)) {
|
|
|
|
found = f;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return found;
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.addPropertyToActual = function(model, propName) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const sqlCommand = self.columnEscaped(model, propName) +
|
2017-02-23 21:31:04 +00:00
|
|
|
' ' + self.columnDataType(model, propName) +
|
|
|
|
(self.isNullable(self.getPropertyDefinition(model, propName)) ?
|
2018-06-12 14:33:52 +00:00
|
|
|
'' : ' NOT NULL');
|
2017-02-23 21:31:04 +00:00
|
|
|
return sqlCommand;
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.columnDataType = function(model, property) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const columnMetadata = this.columnMetadata(model, property);
|
|
|
|
let colType = columnMetadata && columnMetadata.dataType;
|
2017-02-23 21:31:04 +00:00
|
|
|
if (colType) {
|
|
|
|
colType = colType.toUpperCase();
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const prop = this.getModelDefinition(model).properties[property];
|
2017-02-23 21:31:04 +00:00
|
|
|
if (!prop) {
|
|
|
|
return null;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const colLength = columnMetadata && columnMetadata.dataLength ||
|
2017-02-23 21:31:04 +00:00
|
|
|
prop.length || prop.limit;
|
|
|
|
if (colType && colLength) {
|
|
|
|
return colType + '(' + colLength + ')';
|
|
|
|
}
|
|
|
|
return this.buildColumnType(prop);
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.buildColumnType = function(property) {
|
|
|
|
throw new Error(g.f('{{buildColumnType()}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.propertyHasNotBeenDeleted = function(model, propName) {
|
|
|
|
return !!this.getModelDefinition(model).properties[propName];
|
|
|
|
};
|
|
|
|
|
|
|
|
SQLConnector.prototype.applySqlChanges = function(model, pendingChanges, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2017-02-23 21:31:04 +00:00
|
|
|
if (pendingChanges.length) {
|
2019-08-02 13:50:51 +00:00
|
|
|
let thisQuery = 'ALTER TABLE ' + self.tableEscaped(model);
|
|
|
|
let ranOnce = false;
|
2017-02-23 21:31:04 +00:00
|
|
|
pendingChanges.forEach(function(change) {
|
|
|
|
if (ranOnce) {
|
|
|
|
thisQuery = thisQuery + ' ';
|
|
|
|
}
|
|
|
|
thisQuery = thisQuery + ' ' + change;
|
|
|
|
ranOnce = true;
|
|
|
|
});
|
|
|
|
self.execute(thisQuery, cb);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Alters a table
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} fields Fields of the table
|
|
|
|
* @param {Object} indexes Indexes of the table
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.alterTable = function(model, fields, indexes, cb) {
|
|
|
|
throw new Error(g.f('{{alterTable()}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
2017-03-04 01:22:08 +00:00
|
|
|
SQLConnector.prototype.checkFieldAndIndex = function(fields, indexes) {
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
2017-02-23 21:31:04 +00:00
|
|
|
/**
|
|
|
|
* Get the status of a table
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getTableStatus = function(model, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
let fields, indexes;
|
|
|
|
const self = this;
|
2017-02-23 21:31:04 +00:00
|
|
|
|
|
|
|
this.showFields(model, function(err, data) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
fields = data;
|
|
|
|
|
|
|
|
self.showIndexes(model, function(err, data) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
indexes = data;
|
|
|
|
|
2017-03-04 01:22:08 +00:00
|
|
|
if (self.checkFieldAndIndex(fields, indexes))
|
2017-02-23 21:31:04 +00:00
|
|
|
return cb(null, fields, indexes);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get fields from a table
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.showFields = function(model, cb) {
|
|
|
|
throw new Error(g.f('{{showFields()}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get indexes from a table
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.showIndexes = function(model, cb) {
|
|
|
|
throw new Error(g.f('{{showIndexes()}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
2014-05-23 08:50:23 +00:00
|
|
|
/**
|
|
|
|
* Get types associated with the connector
|
|
|
|
* Returns {String[]} The types for the connector
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.getTypes = function() {
|
2014-05-23 08:50:23 +00:00
|
|
|
return ['db', 'rdbms', 'sql'];
|
|
|
|
};
|
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
2014-05-23 08:50:23 +00:00
|
|
|
* Get the default data type for ID
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param prop Property definition
|
2014-05-23 08:50:23 +00:00
|
|
|
* Returns {Function}
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.getDefaultIdType = function(prop) {
|
2014-05-23 08:50:23 +00:00
|
|
|
return Number;
|
|
|
|
};
|
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Get the default database schema name
|
|
|
|
* @returns {string} The default schema name, such as 'public' or 'dbo'
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getDefaultSchemaName = function() {
|
|
|
|
return '';
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Get the database schema name for the given model. The schema name can be
|
|
|
|
* customized at model settings or connector configuration level as `schema` or
|
|
|
|
* `schemaName`. For example,
|
|
|
|
*
|
|
|
|
* ```json
|
|
|
|
* "Customer": {
|
|
|
|
* "name": "Customer",
|
|
|
|
* "mysql": {
|
|
|
|
* "schema": "MYDB",
|
|
|
|
* "table": "CUSTOMER"
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @returns {String} The database schema name
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.schema = function(model) {
|
|
|
|
// Check if there is a 'schema' property for connector
|
2019-08-02 13:50:51 +00:00
|
|
|
const dbMeta = this.getConnectorSpecificSettings(model);
|
|
|
|
const schemaName = (dbMeta && (dbMeta.schema || dbMeta.schemaName)) ||
|
2015-05-13 17:14:44 +00:00
|
|
|
(this.settings.schema || this.settings.schemaName) ||
|
|
|
|
this.getDefaultSchemaName();
|
|
|
|
return schemaName;
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Get the table name for the given model. The table name can be customized
|
|
|
|
* at model settings as `table` or `tableName`. For example,
|
|
|
|
*
|
|
|
|
* ```json
|
|
|
|
* "Customer": {
|
|
|
|
* "name": "Customer",
|
|
|
|
* "mysql": {
|
|
|
|
* "table": "CUSTOMER"
|
|
|
|
* }
|
|
|
|
* }
|
|
|
|
* ```
|
|
|
|
*
|
2014-05-23 08:50:23 +00:00
|
|
|
* Returns the table name (String).
|
|
|
|
* @param {String} model The model name
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.table = function(model) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const dbMeta = this.getConnectorSpecificSettings(model);
|
|
|
|
let tableName;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (dbMeta) {
|
|
|
|
tableName = dbMeta.table || dbMeta.tableName;
|
|
|
|
if (tableName) {
|
|
|
|
// Explicit table name, return as-is
|
|
|
|
return tableName;
|
|
|
|
}
|
2014-05-23 08:50:23 +00:00
|
|
|
}
|
2015-05-13 17:14:44 +00:00
|
|
|
tableName = model;
|
|
|
|
if (typeof this.dbName === 'function') {
|
|
|
|
tableName = this.dbName(tableName);
|
|
|
|
}
|
|
|
|
return tableName;
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Get the column metadata for the given model property
|
2014-05-23 08:50:23 +00:00
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {String} property The property name
|
|
|
|
* @returns {Object} The column metadata
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.columnMetadata = function(model, property) {
|
2014-05-23 08:50:23 +00:00
|
|
|
return this.getDataSource(model).columnMetadata(model, property);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Get the corresponding property name for the given column name
|
2014-05-23 08:50:23 +00:00
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {String} column The column name
|
|
|
|
* @returns {String} The property name for a given column
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.propertyName = function(model, column) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const props = this.getModelDefinition(model).properties;
|
|
|
|
for (const p in props) {
|
2014-05-23 08:50:23 +00:00
|
|
|
if (this.column(model, p) === column) {
|
|
|
|
return p;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the escaped id column name
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @returns {String} the escaped id column name
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.idColumnEscaped = function(model) {
|
|
|
|
return this.escapeName(this.idColumn(model));
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the escaped table name
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @returns {String} the escaped table name
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.tableEscaped = function(model) {
|
2014-05-23 08:50:23 +00:00
|
|
|
return this.escapeName(this.table(model));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the escaped column name for a given model property
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {String} property The property name
|
|
|
|
* @returns {String} The escaped column name
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.columnEscaped = function(model, property) {
|
2014-05-23 08:50:23 +00:00
|
|
|
return this.escapeName(this.column(model, property));
|
|
|
|
};
|
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/*!
|
|
|
|
* Check if id value is set
|
|
|
|
* @param idValue
|
|
|
|
* @param cb
|
|
|
|
* @param returningNull
|
|
|
|
* @returns {boolean}
|
|
|
|
*/
|
|
|
|
function isIdValuePresent(idValue, cb, returningNull) {
|
2014-05-23 08:50:23 +00:00
|
|
|
try {
|
|
|
|
assert(idValue !== null && idValue !== undefined, 'id value is required');
|
|
|
|
return true;
|
|
|
|
} catch (err) {
|
2015-05-13 17:14:44 +00:00
|
|
|
process.nextTick(function() {
|
|
|
|
if (cb) cb(returningNull ? null : err);
|
2014-05-23 08:50:23 +00:00
|
|
|
});
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2015-05-13 17:14:44 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert the id value to the form required by database column
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {*} idValue The id property value
|
|
|
|
* @returns {*} The escaped id column value
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.idColumnValue = function(model, idValue) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const idProp = this.getDataSource(model).idProperty(model);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (typeof this.toColumnValue === 'function') {
|
|
|
|
return this.toColumnValue(idProp, idValue);
|
|
|
|
} else {
|
|
|
|
return idValue;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Replace `?` with connector specific placeholders. For example,
|
|
|
|
*
|
|
|
|
* ```
|
|
|
|
* {sql: 'SELECT * FROM CUSTOMER WHERE NAME=?', params: ['John']}
|
|
|
|
* ==>
|
|
|
|
* {sql: 'SELECT * FROM CUSTOMER WHERE NAME=:1', params: ['John']}
|
|
|
|
* ```
|
|
|
|
* *LIMITATION*: We don't handle the ? inside escaped values, for example,
|
|
|
|
* `SELECT * FROM CUSTOMER WHERE NAME='J?hn'` will not be parameterized
|
|
|
|
* correctly.
|
|
|
|
*
|
|
|
|
* @param {ParameterizedSQL|Object} ps Parameterized SQL
|
|
|
|
* @returns {ParameterizedSQL} Parameterized SQL with the connector specific
|
|
|
|
* placeholders
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.parameterize = function(ps) {
|
|
|
|
ps = new ParameterizedSQL(ps);
|
|
|
|
|
|
|
|
// The value is parameterized, for example
|
|
|
|
// {sql: 'to_point(?,?)', values: [1, 2]}
|
2019-08-02 13:50:51 +00:00
|
|
|
const parts = ps.sql.split(PLACEHOLDER);
|
|
|
|
const clause = [];
|
|
|
|
for (let j = 0, m = parts.length; j < m; j++) {
|
2015-05-13 17:14:44 +00:00
|
|
|
// Replace ? with the keyed placeholder, such as :5
|
|
|
|
clause.push(parts[j]);
|
|
|
|
if (j !== parts.length - 1) {
|
|
|
|
clause.push(this.getPlaceholderForValue(j + 1));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ps.sql = clause.join('');
|
|
|
|
return ps;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build the the `INSERT INTO` statement
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} fields Fields to be inserted
|
|
|
|
* @param {Object} options Options object
|
|
|
|
* @returns {ParameterizedSQL}
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildInsertInto = function(model, fields, options) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const stmt = new ParameterizedSQL('INSERT INTO ' + this.tableEscaped(model));
|
|
|
|
const columnNames = fields.names.join(',');
|
2015-05-13 17:14:44 +00:00
|
|
|
if (columnNames) {
|
|
|
|
stmt.merge('(' + columnNames + ')', '');
|
|
|
|
}
|
|
|
|
return stmt;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build the clause to return id values after insert
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} data The model data object
|
|
|
|
* @param {Object} options Options object
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildInsertReturning = function(model, data, options) {
|
|
|
|
return '';
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build the clause for default values if the fields is empty
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} data The model data object
|
|
|
|
* @param {Object} options Options object
|
|
|
|
* @returns {string} 'DEFAULT VALUES'
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildInsertDefaultValues = function(model, data, options) {
|
|
|
|
return 'VALUES()';
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build INSERT SQL statement
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} data The model data object
|
|
|
|
* @param {Object} options The options object
|
|
|
|
* @returns {string} The INSERT SQL statement
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildInsert = function(model, data, options) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const fields = this.buildFields(model, data);
|
|
|
|
const insertStmt = this.buildInsertInto(model, fields, options);
|
|
|
|
const columnValues = fields.columnValues;
|
|
|
|
const fieldNames = fields.names;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (fieldNames.length) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const values = ParameterizedSQL.join(columnValues, ',');
|
2015-05-13 17:14:44 +00:00
|
|
|
values.sql = 'VALUES(' + values.sql + ')';
|
|
|
|
insertStmt.merge(values);
|
|
|
|
} else {
|
|
|
|
insertStmt.merge(this.buildInsertDefaultValues(model, data, options));
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const returning = this.buildInsertReturning(model, data, options);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (returning) {
|
|
|
|
insertStmt.merge(returning);
|
|
|
|
}
|
|
|
|
return this.parameterize(insertStmt);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Execute a SQL statement with given parameters.
|
|
|
|
*
|
|
|
|
* @param {String} sql The SQL statement
|
2017-06-22 17:06:24 +00:00
|
|
|
* @param {Array} An array of parameter values
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} [options] Options object
|
|
|
|
* @param {Function} [callback] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.execute = function(sql, params, options, callback) {
|
|
|
|
assert(typeof sql === 'string', 'sql must be a string');
|
|
|
|
if (typeof params === 'function' && options === undefined &&
|
|
|
|
callback === undefined) {
|
|
|
|
// execute(sql, callback)
|
|
|
|
options = {};
|
|
|
|
callback = params;
|
|
|
|
params = [];
|
|
|
|
} else if (typeof options === 'function' && callback === undefined) {
|
|
|
|
// execute(sql, params, callback)
|
|
|
|
callback = options;
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
params = params || [];
|
|
|
|
options = options || {};
|
|
|
|
assert(Array.isArray(params), 'params must be an array');
|
|
|
|
assert(typeof options === 'object', 'options must be an object');
|
|
|
|
assert(typeof callback === 'function', 'callback must be a function');
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (!this.dataSource.connected) {
|
2019-08-01 20:32:39 +00:00
|
|
|
// Prevent adding too many listeners to the 'connected' event on the datasource.
|
|
|
|
if (this.dataSource.listenerCount('connected') <
|
|
|
|
this.dataSource.getMaxOfflineRequests()) {
|
|
|
|
// allow this listener to be added to this event
|
|
|
|
return this.dataSource.once('connected', function() {
|
|
|
|
self.execute(sql, params, options, callback);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
const limitReachedError = new Error(
|
|
|
|
g.f(
|
|
|
|
'Event listener limit reached. ' +
|
|
|
|
'Increase maxOfflineRequests value in datasources.json.',
|
|
|
|
),
|
|
|
|
);
|
|
|
|
callback(limitReachedError);
|
|
|
|
}
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const context = {
|
2015-05-22 16:03:27 +00:00
|
|
|
req: {
|
|
|
|
sql: sql,
|
2016-04-09 18:35:52 +00:00
|
|
|
params: params,
|
2015-05-22 16:03:27 +00:00
|
|
|
},
|
2016-04-09 18:35:52 +00:00
|
|
|
options: options,
|
2015-05-22 16:03:27 +00:00
|
|
|
};
|
|
|
|
this.notifyObserversAround('execute', context, function(context, done) {
|
2016-04-09 19:00:28 +00:00
|
|
|
self.executeSQL(context.req.sql, context.req.params, context.options,
|
2018-06-12 14:33:52 +00:00
|
|
|
function(err, info) {
|
|
|
|
if (err) {
|
|
|
|
debug('Error: %j %j %j', err, context.req.sql, context.req.params);
|
|
|
|
}
|
2015-11-10 22:48:52 +00:00
|
|
|
|
2018-06-12 14:33:52 +00:00
|
|
|
if (!err && info != null) {
|
|
|
|
context.res = info;
|
|
|
|
}
|
|
|
|
// Don't pass more than one args as it will confuse async.waterfall
|
|
|
|
done(err, info);
|
|
|
|
});
|
2015-05-22 16:03:27 +00:00
|
|
|
}, callback);
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
|
|
|
|
2014-05-23 08:50:23 +00:00
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Create the data model in MySQL
|
|
|
|
*
|
2014-05-23 08:50:23 +00:00
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} data The model instance data
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} options Options object
|
|
|
|
* @param {Function} [callback] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.create = function(model, data, options, callback) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const stmt = this.buildInsert(model, data, options);
|
2015-05-13 17:14:44 +00:00
|
|
|
this.execute(stmt.sql, stmt.params, options, function(err, info) {
|
|
|
|
if (err) {
|
|
|
|
callback(err);
|
|
|
|
} else {
|
2019-08-02 13:50:51 +00:00
|
|
|
const insertedId = self.getInsertedId(model, info);
|
2015-05-13 17:14:44 +00:00
|
|
|
callback(err, insertedId);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Save the model instance into the database
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} data The model instance data
|
|
|
|
* @param {Object} options Options object
|
|
|
|
* @param {Function} cb The callback function
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.save = function(model, data, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const idName = this.idName(model);
|
|
|
|
const idValue = data[idName];
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
if (!isIdValuePresent(idValue, cb)) {
|
2014-05-23 08:50:23 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const where = {};
|
2015-05-13 17:14:44 +00:00
|
|
|
where[idName] = idValue;
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
let updateStmt = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model));
|
2015-05-13 17:14:44 +00:00
|
|
|
updateStmt.merge(this.buildFieldsForUpdate(model, data));
|
2019-08-02 13:50:51 +00:00
|
|
|
const whereStmt = this.buildWhere(model, where);
|
2015-05-13 17:14:44 +00:00
|
|
|
updateStmt.merge(whereStmt);
|
|
|
|
updateStmt = this.parameterize(updateStmt);
|
|
|
|
this.execute(updateStmt.sql, updateStmt.params, options,
|
|
|
|
function(err, result) {
|
|
|
|
if (cb) cb(err, result);
|
|
|
|
});
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Check if a model instance exists for the given id value
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {*} id The id value
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} options Options object
|
|
|
|
* @param {Function} cb The callback function
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.exists = function(model, id, options, cb) {
|
|
|
|
if (!isIdValuePresent(id, cb, true)) {
|
2014-05-23 08:50:23 +00:00
|
|
|
return;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const idName = this.idName(model);
|
|
|
|
const where = {};
|
2015-05-13 17:14:44 +00:00
|
|
|
where[idName] = id;
|
2019-08-02 13:50:51 +00:00
|
|
|
let selectStmt = new ParameterizedSQL(
|
2015-05-13 17:14:44 +00:00
|
|
|
'SELECT 1 FROM ' + this.tableEscaped(model) +
|
2019-11-01 12:45:20 +00:00
|
|
|
' WHERE ' + this.idColumnEscaped(model),
|
2015-05-13 17:14:44 +00:00
|
|
|
);
|
|
|
|
selectStmt.merge(this.buildWhere(model, where));
|
|
|
|
selectStmt = this.applyPagination(model, selectStmt, {
|
|
|
|
limit: 1,
|
|
|
|
offset: 0,
|
2016-04-09 18:35:52 +00:00
|
|
|
order: [idName],
|
2015-05-13 17:14:44 +00:00
|
|
|
});
|
|
|
|
selectStmt = this.parameterize(selectStmt);
|
|
|
|
|
|
|
|
this.execute(selectStmt.sql, selectStmt.params, options, function(err, data) {
|
|
|
|
if (!cb) return;
|
2014-05-23 08:50:23 +00:00
|
|
|
if (err) {
|
2015-05-13 17:14:44 +00:00
|
|
|
cb(err);
|
2014-05-23 08:50:23 +00:00
|
|
|
} else {
|
2015-05-13 17:14:44 +00:00
|
|
|
cb(null, data.length >= 1);
|
2014-05-23 08:50:23 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* ATM, this method is not used by loopback-datasource-juggler dao, which
|
|
|
|
* maps `destroy` to `destroyAll` with a `where` filter that includes the `id`
|
|
|
|
* instead.
|
|
|
|
*
|
|
|
|
* Delete a model instance by id value
|
2014-05-23 08:50:23 +00:00
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {*} id The id value
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} options Options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
* @private
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.destroy = function(model, id, options, cb) {
|
|
|
|
if (!isIdValuePresent(id, cb, true)) {
|
2014-05-23 08:50:23 +00:00
|
|
|
return;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const idName = this.idName(model);
|
|
|
|
const where = {};
|
2015-05-13 17:14:44 +00:00
|
|
|
where[idName] = id;
|
|
|
|
this.destroyAll(model, where, options, cb);
|
|
|
|
};
|
2015-05-15 17:27:08 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
// Alias to `destroy`. Juggler checks `destroy` only.
|
|
|
|
Connector.defineAliases(SQLConnector.prototype, 'destroy',
|
|
|
|
['delete', 'deleteById', 'destroyById']);
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Build the `DELETE FROM` SQL statement
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} where The where object
|
|
|
|
* @param {Object} options Options object
|
|
|
|
* @returns {ParameterizedSQL} The SQL DELETE FROM statement
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildDelete = function(model, where, options) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const deleteStmt = new ParameterizedSQL('DELETE FROM ' +
|
2015-05-13 17:14:44 +00:00
|
|
|
this.tableEscaped(model));
|
|
|
|
deleteStmt.merge(this.buildWhere(model, where));
|
|
|
|
return this.parameterize(deleteStmt);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Delete all matching model instances
|
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} where The where object
|
|
|
|
* @param {Object} options The options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.destroyAll = function(model, where, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const stmt = this.buildDelete(model, where, options);
|
2016-01-09 08:23:49 +00:00
|
|
|
this._executeAlteringQuery(model, stmt.sql, stmt.params, options, cb || NOOP);
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
2015-05-15 17:27:08 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
// Alias to `destroyAll`. Juggler checks `destroyAll` only.
|
|
|
|
Connector.defineAliases(SQLConnector.prototype, 'destroyAll', ['deleteAll']);
|
2014-05-23 08:50:23 +00:00
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* ATM, this method is not used by loopback-datasource-juggler dao, which
|
|
|
|
* maps `updateAttributes` to `update` with a `where` filter that includes the
|
|
|
|
* `id` instead.
|
|
|
|
*
|
|
|
|
* Update attributes for a given model instance
|
2014-05-23 08:50:23 +00:00
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {*} id The id value
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} data The model data instance containing all properties to
|
|
|
|
* be updated
|
|
|
|
* @param {Object} options Options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
* @private
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.updateAttributes = function(model, id, data, options, cb) {
|
2015-12-04 18:51:07 +00:00
|
|
|
if (!isIdValuePresent(id, cb)) return;
|
2019-08-02 13:50:51 +00:00
|
|
|
const where = this._buildWhereObjById(model, id, data);
|
2017-04-14 05:51:31 +00:00
|
|
|
this.updateAll(model, where, data, options, function(err, info) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
if (info.count === 0) {
|
|
|
|
return cb(errorIdNotFoundForUpdate(where.id));
|
|
|
|
} else {
|
|
|
|
return cb(null, info);
|
2019-08-02 13:50:51 +00:00
|
|
|
}
|
2017-04-14 05:51:31 +00:00
|
|
|
});
|
2015-12-04 18:51:07 +00:00
|
|
|
};
|
|
|
|
|
2017-04-14 05:51:31 +00:00
|
|
|
function errorIdNotFoundForUpdate(idValue) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const msg = g.f(
|
2019-11-01 12:45:20 +00:00
|
|
|
'Could not update attributes. {{Object}} with {{id}} %s does not exist!', idValue,
|
2019-08-02 13:50:51 +00:00
|
|
|
);
|
|
|
|
const error = new Error(msg);
|
2017-04-14 05:51:31 +00:00
|
|
|
error.statusCode = error.status = 404;
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
|
2015-12-04 18:51:07 +00:00
|
|
|
/**
|
|
|
|
* Replace attributes for a given model instance
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {*} id The id value
|
|
|
|
* @param {Object} data The model data instance containing all properties to
|
|
|
|
* be replaced
|
|
|
|
* @param {Object} options Options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
* @private
|
|
|
|
*/
|
2016-01-27 14:46:35 +00:00
|
|
|
SQLConnector.prototype.replaceById = function(model, id, data, options, cb) {
|
2015-12-04 18:51:07 +00:00
|
|
|
if (!isIdValuePresent(id, cb)) return;
|
2019-08-02 13:50:51 +00:00
|
|
|
const where = this._buildWhereObjById(model, id, data);
|
2015-12-04 18:51:07 +00:00
|
|
|
this._replace(model, where, data, options, cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
/*
|
|
|
|
* @param model The model name.
|
|
|
|
* @param id The instance ID.
|
|
|
|
* @param {Object} data The data Object.
|
|
|
|
* @returns {Object} where The where object for a spcific instance.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype._buildWhereObjById = function(model, id, data) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const idName = this.idName(model);
|
2015-05-13 17:14:44 +00:00
|
|
|
delete data[idName];
|
2019-08-02 13:50:51 +00:00
|
|
|
const where = {};
|
2015-05-13 17:14:44 +00:00
|
|
|
where[idName] = id;
|
2015-12-04 18:51:07 +00:00
|
|
|
return where;
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Build the UPDATE statement
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} where The where object
|
|
|
|
* @param {Object} data The data to be changed
|
|
|
|
* @param {Object} options The options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
* @returns {ParameterizedSQL} The UPDATE SQL statement
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildUpdate = function(model, where, data, options) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const fields = this.buildFieldsForUpdate(model, data);
|
2015-12-04 18:51:07 +00:00
|
|
|
return this._constructUpdateQuery(model, where, fields);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build the UPDATE statement for replacing
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} where The where object
|
|
|
|
* @param {Object} data The data to be changed
|
|
|
|
* @param {Object} options The options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
* @returns {ParameterizedSQL} The UPDATE SQL statement for replacing fields
|
|
|
|
*/
|
2016-01-12 22:27:55 +00:00
|
|
|
SQLConnector.prototype.buildReplace = function(model, where, data, options) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const fields = this.buildFieldsForReplace(model, data);
|
2015-12-04 18:51:07 +00:00
|
|
|
return this._constructUpdateQuery(model, where, fields);
|
|
|
|
};
|
|
|
|
|
|
|
|
/*
|
|
|
|
* @param model The model name.
|
|
|
|
* @param {} where The where object.
|
|
|
|
* @param {Object} field The parameterizedSQL fileds.
|
|
|
|
* @returns {Object} update query Constructed update query.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype._constructUpdateQuery = function(model, where, fields) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const updateClause = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model));
|
|
|
|
const whereClause = this.buildWhere(model, where);
|
2015-05-13 17:14:44 +00:00
|
|
|
updateClause.merge([fields, whereClause]);
|
|
|
|
return this.parameterize(updateClause);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update all instances that match the where clause with the given data
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} where The where object
|
|
|
|
* @param {Object} data The property/value object representing changes
|
|
|
|
* to be made
|
|
|
|
* @param {Object} options The options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.update = function(model, where, data, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const stmt = this.buildUpdate(model, where, data, options);
|
2016-01-09 08:23:49 +00:00
|
|
|
this._executeAlteringQuery(model, stmt.sql, stmt.params, options, cb || NOOP);
|
2015-12-04 18:51:07 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Replace all instances that match the where clause with the given data
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} where The where object
|
|
|
|
* @param {Object} data The property/value object representing changes
|
|
|
|
* to be made
|
|
|
|
* @param {Object} options The options object
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype._replace = function(model, where, data, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const stmt = this.buildReplace(model, where, data, options);
|
2017-01-13 22:45:04 +00:00
|
|
|
this.execute(stmt.sql, stmt.params, options, function(err, info) {
|
|
|
|
if (err) return cb(err);
|
2019-08-02 13:50:51 +00:00
|
|
|
const affectedRows = self.getCountForAffectedRows(model, info);
|
|
|
|
const rowCount = typeof (affectedRows) === 'number' ?
|
2017-02-22 16:32:43 +00:00
|
|
|
affectedRows : info.affectedRows;
|
|
|
|
if (rowCount === 0) {
|
2017-01-13 22:45:04 +00:00
|
|
|
return cb(errorIdNotFoundForReplace(where.id));
|
|
|
|
} else {
|
|
|
|
return cb(null, info);
|
|
|
|
}
|
|
|
|
});
|
2015-12-04 18:51:07 +00:00
|
|
|
};
|
|
|
|
|
2017-01-13 22:45:04 +00:00
|
|
|
function errorIdNotFoundForReplace(idValue) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const msg = g.f('Could not replace. Object with id %s does not exist!', idValue);
|
|
|
|
const error = new Error(msg);
|
2017-01-13 22:45:04 +00:00
|
|
|
error.statusCode = error.status = 404;
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
|
2015-12-04 18:51:07 +00:00
|
|
|
SQLConnector.prototype._executeAlteringQuery = function(model, sql, params, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2015-12-04 18:51:07 +00:00
|
|
|
this.execute(sql, params, options, function(err, info) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const affectedRows = self.getCountForAffectedRows(model, info);
|
2017-03-06 23:40:47 +00:00
|
|
|
cb(err, {count: affectedRows});
|
2014-05-23 08:50:23 +00:00
|
|
|
});
|
|
|
|
};
|
2015-05-15 17:27:08 +00:00
|
|
|
|
2015-12-04 18:51:07 +00:00
|
|
|
// Alias to `update` and `replace`. Juggler checks `update` and `replace` only.
|
2015-05-13 17:14:44 +00:00
|
|
|
Connector.defineAliases(SQLConnector.prototype, 'update', ['updateAll']);
|
2015-12-04 18:51:07 +00:00
|
|
|
Connector.defineAliases(SQLConnector.prototype, 'replace', ['replaceAll']);
|
2014-05-23 08:50:23 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Build the SQL WHERE clause for the where object
|
|
|
|
* @param {string} model Model name
|
|
|
|
* @param {object} where An object for the where conditions
|
|
|
|
* @returns {ParameterizedSQL} The SQL WHERE clause
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildWhere = function(model, where) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const whereClause = this._buildWhere(model, where);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (whereClause.sql) {
|
|
|
|
whereClause.sql = 'WHERE ' + whereClause.sql;
|
|
|
|
}
|
|
|
|
return whereClause;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build SQL expression
|
|
|
|
* @param {String} columnName Escaped column name
|
|
|
|
* @param {String} operator SQL operator
|
|
|
|
* @param {*} columnValue Column value
|
|
|
|
* @param {*} propertyValue Property value
|
|
|
|
* @returns {ParameterizedSQL} The SQL expression
|
|
|
|
*/
|
2016-04-09 19:00:28 +00:00
|
|
|
SQLConnector.prototype.buildExpression =
|
|
|
|
function(columnName, operator, columnValue, propertyValue) {
|
2015-05-13 17:14:44 +00:00
|
|
|
function buildClause(columnValue, separator, grouping) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const values = [];
|
|
|
|
for (let i = 0, n = columnValue.length; i < n; i++) {
|
2015-05-20 16:20:35 +00:00
|
|
|
if (columnValue[i] instanceof ParameterizedSQL) {
|
2015-05-13 17:14:44 +00:00
|
|
|
values.push(columnValue[i]);
|
|
|
|
} else {
|
|
|
|
values.push(new ParameterizedSQL(PLACEHOLDER, [columnValue[i]]));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
separator = separator || ',';
|
2019-08-02 13:50:51 +00:00
|
|
|
const clause = ParameterizedSQL.join(values, separator);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (grouping) {
|
|
|
|
clause.sql = '(' + clause.sql + ')';
|
|
|
|
}
|
|
|
|
return clause;
|
|
|
|
}
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
let sqlExp = columnName;
|
|
|
|
let clause;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (columnValue instanceof ParameterizedSQL) {
|
|
|
|
clause = columnValue;
|
2014-05-23 08:50:23 +00:00
|
|
|
} else {
|
2015-05-13 17:14:44 +00:00
|
|
|
clause = new ParameterizedSQL(PLACEHOLDER, [columnValue]);
|
|
|
|
}
|
|
|
|
switch (operator) {
|
|
|
|
case 'gt':
|
|
|
|
sqlExp += '>';
|
|
|
|
break;
|
|
|
|
case 'gte':
|
|
|
|
sqlExp += '>=';
|
|
|
|
break;
|
|
|
|
case 'lt':
|
|
|
|
sqlExp += '<';
|
|
|
|
break;
|
|
|
|
case 'lte':
|
|
|
|
sqlExp += '<=';
|
|
|
|
break;
|
|
|
|
case 'between':
|
|
|
|
sqlExp += ' BETWEEN ';
|
|
|
|
clause = buildClause(columnValue, ' AND ', false);
|
|
|
|
break;
|
|
|
|
case 'inq':
|
|
|
|
sqlExp += ' IN ';
|
|
|
|
clause = buildClause(columnValue, ',', true);
|
|
|
|
break;
|
|
|
|
case 'nin':
|
|
|
|
sqlExp += ' NOT IN ';
|
|
|
|
clause = buildClause(columnValue, ',', true);
|
|
|
|
break;
|
|
|
|
case 'neq':
|
|
|
|
if (columnValue == null) {
|
|
|
|
return new ParameterizedSQL(sqlExp + ' IS NOT NULL');
|
|
|
|
}
|
|
|
|
sqlExp += '!=';
|
|
|
|
break;
|
|
|
|
case 'like':
|
|
|
|
sqlExp += ' LIKE ';
|
|
|
|
break;
|
|
|
|
case 'nlike':
|
|
|
|
sqlExp += ' NOT LIKE ';
|
|
|
|
break;
|
2015-07-28 09:02:59 +00:00
|
|
|
// this case not needed since each database has its own regex syntax, but
|
|
|
|
// we leave the MySQL syntax here as a placeholder
|
2015-07-21 00:06:46 +00:00
|
|
|
case 'regexp':
|
|
|
|
sqlExp += ' REGEXP ';
|
|
|
|
break;
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const stmt = ParameterizedSQL.join([sqlExp, clause], '');
|
2015-05-13 17:14:44 +00:00
|
|
|
return stmt;
|
|
|
|
};
|
|
|
|
|
2017-06-22 17:06:24 +00:00
|
|
|
/**
|
|
|
|
* @private
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param model
|
|
|
|
* @param where
|
|
|
|
* @returns {ParameterizedSQL}
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype._buildWhere = function(model, where) {
|
2019-08-02 13:50:51 +00:00
|
|
|
let columnValue, sqlExp;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (!where) {
|
|
|
|
return new ParameterizedSQL('');
|
|
|
|
}
|
|
|
|
if (typeof where !== 'object' || Array.isArray(where)) {
|
|
|
|
debug('Invalid value for where: %j', where);
|
|
|
|
return new ParameterizedSQL('');
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const props = self.getModelDefinition(model).properties;
|
2015-05-13 17:14:44 +00:00
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const whereStmts = [];
|
|
|
|
for (const key in where) {
|
|
|
|
const stmt = new ParameterizedSQL('', []);
|
2015-05-13 17:14:44 +00:00
|
|
|
// Handle and/or operators
|
|
|
|
if (key === 'and' || key === 'or') {
|
2019-08-02 13:50:51 +00:00
|
|
|
const branches = [];
|
|
|
|
let branchParams = [];
|
|
|
|
const clauses = where[key];
|
2015-05-13 17:14:44 +00:00
|
|
|
if (Array.isArray(clauses)) {
|
2019-08-02 13:50:51 +00:00
|
|
|
for (let i = 0, n = clauses.length; i < n; i++) {
|
|
|
|
const stmtForClause = self._buildWhere(model, clauses[i]);
|
2016-02-06 17:07:49 +00:00
|
|
|
if (stmtForClause.sql) {
|
|
|
|
stmtForClause.sql = '(' + stmtForClause.sql + ')';
|
|
|
|
branchParams = branchParams.concat(stmtForClause.params);
|
|
|
|
branches.push(stmtForClause.sql);
|
|
|
|
}
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
|
|
|
stmt.merge({
|
2020-11-06 17:47:25 +00:00
|
|
|
sql: '(' + branches.join(' ' + key.toUpperCase() + ' ') + ')',
|
2016-04-09 18:35:52 +00:00
|
|
|
params: branchParams,
|
2015-05-13 17:14:44 +00:00
|
|
|
});
|
|
|
|
whereStmts.push(stmt);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// The value is not an array, fall back to regular fields
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const p = props[key];
|
2016-02-06 17:07:49 +00:00
|
|
|
if (p == null) {
|
|
|
|
// Unknown property, ignore it
|
|
|
|
debug('Unknown property %s is skipped for model %s', key, model);
|
|
|
|
continue;
|
|
|
|
}
|
2017-06-22 17:06:24 +00:00
|
|
|
// eslint-disable one-var
|
2019-08-02 13:50:51 +00:00
|
|
|
let expression = where[key];
|
|
|
|
const columnName = self.columnEscaped(model, key);
|
2017-06-22 17:06:24 +00:00
|
|
|
// eslint-enable one-var
|
2015-05-13 17:14:44 +00:00
|
|
|
if (expression === null || expression === undefined) {
|
|
|
|
stmt.merge(columnName + ' IS NULL');
|
2015-05-20 16:20:35 +00:00
|
|
|
} else if (expression && expression.constructor === Object) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const operator = Object.keys(expression)[0];
|
2015-05-13 17:14:44 +00:00
|
|
|
// Get the expression without the operator
|
|
|
|
expression = expression[operator];
|
|
|
|
if (operator === 'inq' || operator === 'nin' || operator === 'between') {
|
|
|
|
columnValue = [];
|
|
|
|
if (Array.isArray(expression)) {
|
|
|
|
// Column value is a list
|
2019-08-02 13:50:51 +00:00
|
|
|
for (let j = 0, m = expression.length; j < m; j++) {
|
2016-02-06 17:07:49 +00:00
|
|
|
columnValue.push(this.toColumnValue(p, expression[j]));
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
|
|
|
} else {
|
2016-02-06 17:07:49 +00:00
|
|
|
columnValue.push(this.toColumnValue(p, expression));
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
|
|
|
if (operator === 'between') {
|
|
|
|
// BETWEEN v1 AND v2
|
2019-08-02 13:50:51 +00:00
|
|
|
const v1 = columnValue[0] === undefined ? null : columnValue[0];
|
|
|
|
const v2 = columnValue[1] === undefined ? null : columnValue[1];
|
2015-05-13 17:14:44 +00:00
|
|
|
columnValue = [v1, v2];
|
|
|
|
} else {
|
|
|
|
// IN (v1,v2,v3) or NOT IN (v1,v2,v3)
|
|
|
|
if (columnValue.length === 0) {
|
|
|
|
if (operator === 'inq') {
|
|
|
|
columnValue = [null];
|
|
|
|
} else {
|
|
|
|
// nin () is true
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-07-28 09:02:59 +00:00
|
|
|
} else if (operator === 'regexp' && expression instanceof RegExp) {
|
|
|
|
// do not coerce RegExp based on property definitions
|
|
|
|
columnValue = expression;
|
2015-05-13 17:14:44 +00:00
|
|
|
} else {
|
2016-02-06 17:07:49 +00:00
|
|
|
columnValue = this.toColumnValue(p, expression);
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
2017-06-22 17:06:24 +00:00
|
|
|
sqlExp = self.buildExpression(columnName, operator, columnValue, p);
|
2015-05-13 17:14:44 +00:00
|
|
|
stmt.merge(sqlExp);
|
2014-05-23 08:50:23 +00:00
|
|
|
} else {
|
2015-05-13 17:14:44 +00:00
|
|
|
// The expression is the field value, not a condition
|
2016-02-06 17:07:49 +00:00
|
|
|
columnValue = self.toColumnValue(p, expression);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (columnValue === null) {
|
|
|
|
stmt.merge(columnName + ' IS NULL');
|
|
|
|
} else {
|
|
|
|
if (columnValue instanceof ParameterizedSQL) {
|
|
|
|
stmt.merge(columnName + '=').merge(columnValue);
|
|
|
|
} else {
|
|
|
|
stmt.merge({
|
|
|
|
sql: columnName + '=?',
|
2016-04-09 18:35:52 +00:00
|
|
|
params: [columnValue],
|
2015-05-13 17:14:44 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2014-05-23 08:50:23 +00:00
|
|
|
}
|
2015-05-13 17:14:44 +00:00
|
|
|
whereStmts.push(stmt);
|
2014-05-23 08:50:23 +00:00
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
let params = [];
|
|
|
|
const sqls = [];
|
|
|
|
for (let k = 0, s = whereStmts.length; k < s; k++) {
|
2018-11-21 21:23:11 +00:00
|
|
|
if (!whereStmts[k].sql) continue;
|
2015-05-13 17:14:44 +00:00
|
|
|
sqls.push(whereStmts[k].sql);
|
|
|
|
params = params.concat(whereStmts[k].params);
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const whereStmt = new ParameterizedSQL({
|
2015-05-13 17:14:44 +00:00
|
|
|
sql: sqls.join(' AND '),
|
2016-04-09 18:35:52 +00:00
|
|
|
params: params,
|
2015-05-13 17:14:44 +00:00
|
|
|
});
|
|
|
|
return whereStmt;
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Build the ORDER BY clause
|
|
|
|
* @param {string} model Model name
|
|
|
|
* @param {string[]} order An array of sorting criteria
|
|
|
|
* @returns {string} The ORDER BY clause
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildOrderBy = function(model, order) {
|
|
|
|
if (!order) {
|
|
|
|
return '';
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (typeof order === 'string') {
|
|
|
|
order = [order];
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const clauses = [];
|
|
|
|
for (let i = 0, n = order.length; i < n; i++) {
|
|
|
|
const t = order[i].split(/[\s,]+/);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (t.length === 1) {
|
|
|
|
clauses.push(self.columnEscaped(model, order[i]));
|
|
|
|
} else {
|
|
|
|
clauses.push(self.columnEscaped(model, t[0]) + ' ' + t[1]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return 'ORDER BY ' + clauses.join(',');
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build an array of fields for the database operation
|
|
|
|
* @param {String} model Model name
|
|
|
|
* @param {Object} data Model data object
|
|
|
|
* @param {Boolean} excludeIds Exclude id properties or not, default to false
|
|
|
|
* @returns {{names: Array, values: Array, properties: Array}}
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildFields = function(model, data, excludeIds) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const keys = Object.keys(data);
|
2016-01-09 08:23:49 +00:00
|
|
|
return this._buildFieldsForKeys(model, data, keys, excludeIds);
|
2015-12-04 18:51:07 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build an array of fields for the replace database operation
|
|
|
|
* @param {String} model Model name
|
|
|
|
* @param {Object} data Model data object
|
|
|
|
* @param {Boolean} excludeIds Exclude id properties or not, default to false
|
|
|
|
* @returns {{names: Array, values: Array, properties: Array}}
|
|
|
|
*/
|
2016-01-14 17:46:14 +00:00
|
|
|
SQLConnector.prototype.buildReplaceFields = function(model, data, excludeIds) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const props = this.getModelDefinition(model).properties;
|
|
|
|
const keys = Object.keys(props);
|
2016-01-09 08:23:49 +00:00
|
|
|
return this._buildFieldsForKeys(model, data, keys, excludeIds);
|
2015-12-04 18:51:07 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/*
|
|
|
|
* @param {String} model The model name.
|
|
|
|
* @returns {Object} data The model data object.
|
|
|
|
* @returns {Array} keys The key fields for which need to be built.
|
|
|
|
* @param {Boolean} excludeIds Exclude id properties or not, default to false
|
|
|
|
* @private
|
|
|
|
*/
|
2016-01-09 08:23:49 +00:00
|
|
|
SQLConnector.prototype._buildFieldsForKeys = function(model, data, keys, excludeIds) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const props = this.getModelDefinition(model).properties;
|
|
|
|
const fields = {
|
2015-05-13 17:14:44 +00:00
|
|
|
names: [], // field names
|
|
|
|
columnValues: [], // an array of ParameterizedSQL
|
2016-04-09 18:35:52 +00:00
|
|
|
properties: [], // model properties
|
|
|
|
};
|
2019-08-02 13:50:51 +00:00
|
|
|
for (let i = 0, n = keys.length; i < n; i++) {
|
|
|
|
const key = keys[i];
|
|
|
|
const p = props[key];
|
2015-05-22 15:52:40 +00:00
|
|
|
if (p == null) {
|
|
|
|
// Unknown property, ignore it
|
|
|
|
debug('Unknown property %s is skipped for model %s', key, model);
|
|
|
|
continue;
|
|
|
|
}
|
2015-12-04 18:51:07 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
if (excludeIds && p.id) {
|
|
|
|
continue;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const k = this.columnEscaped(model, key);
|
|
|
|
const v = this.toColumnValue(p, data[key]);
|
2015-05-22 15:52:40 +00:00
|
|
|
if (v !== undefined) {
|
|
|
|
fields.names.push(k);
|
|
|
|
if (v instanceof ParameterizedSQL) {
|
|
|
|
fields.columnValues.push(v);
|
|
|
|
} else {
|
|
|
|
fields.columnValues.push(new ParameterizedSQL(PLACEHOLDER, [v]));
|
2014-06-19 05:24:55 +00:00
|
|
|
}
|
2015-05-22 15:52:40 +00:00
|
|
|
fields.properties.push(p);
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
2014-06-19 05:24:55 +00:00
|
|
|
}
|
2015-05-13 17:14:44 +00:00
|
|
|
return fields;
|
|
|
|
};
|
2014-06-19 05:24:55 +00:00
|
|
|
|
2014-05-23 08:50:23 +00:00
|
|
|
/**
|
2015-12-04 18:51:07 +00:00
|
|
|
* Build the SET clause for database update.
|
|
|
|
* @param {String} model Model name.
|
|
|
|
* @param {Object} data The model data object.
|
|
|
|
* @param {Boolean} excludeIds Exclude id properties or not, default to true.
|
|
|
|
* @returns {string} The list of fields for update query.
|
2015-05-13 17:14:44 +00:00
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildFieldsForUpdate = function(model, data, excludeIds) {
|
|
|
|
if (excludeIds === undefined) {
|
|
|
|
excludeIds = true;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const fields = this.buildFields(model, data, excludeIds);
|
2015-12-04 18:51:07 +00:00
|
|
|
return this._constructUpdateParameterizedSQL(fields);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build the SET clause for database replace through update query.
|
|
|
|
* @param {String} model Model name.
|
|
|
|
* @param {Object} data The model data object.
|
|
|
|
* @param {Boolean} excludeIds Exclude id properties or not, default to true.
|
|
|
|
* @returns {string} The list of fields for update query.
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildFieldsForReplace = function(model, data, excludeIds) {
|
|
|
|
if (excludeIds === undefined) {
|
|
|
|
excludeIds = true;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const fields = this.buildReplaceFields(model, data, excludeIds);
|
2015-12-04 18:51:07 +00:00
|
|
|
return this._constructUpdateParameterizedSQL(fields);
|
|
|
|
};
|
|
|
|
|
|
|
|
/*
|
|
|
|
* @param {Object} field The fileds.
|
|
|
|
* @returns {Object} parameterizedSQL.
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype._constructUpdateParameterizedSQL = function(fields) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const columns = new ParameterizedSQL('');
|
|
|
|
for (let i = 0, n = fields.names.length; i < n; i++) {
|
|
|
|
const clause = ParameterizedSQL.append(fields.names[i],
|
2015-05-13 17:14:44 +00:00
|
|
|
fields.columnValues[i], '=');
|
|
|
|
columns.merge(clause, ',');
|
|
|
|
}
|
|
|
|
columns.sql = 'SET ' + columns.sql;
|
|
|
|
return columns;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build a list of escaped column names for the given model and fields filter
|
|
|
|
* @param {string} model Model name
|
|
|
|
* @param {object} filter The filter object
|
|
|
|
* @returns {string} Comma separated string of escaped column names
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildColumnNames = function(model, filter) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const fieldsFilter = filter && filter.fields;
|
|
|
|
const cols = this.getModelDefinition(model).properties;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (!cols) {
|
|
|
|
return '*';
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
let keys = Object.keys(cols);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (Array.isArray(fieldsFilter) && fieldsFilter.length > 0) {
|
2015-05-13 22:03:49 +00:00
|
|
|
// Not empty array, including all the fields that are valid properties
|
|
|
|
keys = fieldsFilter.filter(function(f) {
|
|
|
|
return cols[f];
|
|
|
|
});
|
2015-05-13 17:14:44 +00:00
|
|
|
} else if ('object' === typeof fieldsFilter &&
|
|
|
|
Object.keys(fieldsFilter).length > 0) {
|
|
|
|
// { field1: boolean, field2: boolean ... }
|
2019-08-02 13:50:51 +00:00
|
|
|
const included = [];
|
|
|
|
const excluded = [];
|
2015-05-13 17:14:44 +00:00
|
|
|
keys.forEach(function(k) {
|
|
|
|
if (fieldsFilter[k]) {
|
|
|
|
included.push(k);
|
|
|
|
} else if ((k in fieldsFilter) && !fieldsFilter[k]) {
|
|
|
|
excluded.push(k);
|
2014-06-19 05:24:55 +00:00
|
|
|
}
|
|
|
|
});
|
2015-05-13 17:14:44 +00:00
|
|
|
if (included.length > 0) {
|
|
|
|
keys = included;
|
|
|
|
} else if (excluded.length > 0) {
|
|
|
|
excluded.forEach(function(e) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const index = keys.indexOf(e);
|
2015-05-13 17:14:44 +00:00
|
|
|
keys.splice(index, 1);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const names = keys.map(function(c) {
|
2015-05-13 17:14:44 +00:00
|
|
|
return self.columnEscaped(model, c);
|
|
|
|
});
|
|
|
|
return names.join(',');
|
|
|
|
};
|
2014-05-23 08:50:23 +00:00
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Build a SQL SELECT statement
|
|
|
|
* @param {String} model Model name
|
|
|
|
* @param {Object} filter Filter object
|
|
|
|
* @param {Object} options Options object
|
2017-06-22 17:06:24 +00:00
|
|
|
* @returns {ParameterizedSQL} Statement object {sql: ..., params: ...}
|
2015-05-13 17:14:44 +00:00
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildSelect = function(model, filter, options) {
|
|
|
|
if (!filter.order) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const idNames = this.idNames(model);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (idNames && idNames.length) {
|
|
|
|
filter.order = idNames;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
let selectStmt = new ParameterizedSQL('SELECT ' +
|
2015-05-13 17:14:44 +00:00
|
|
|
this.buildColumnNames(model, filter) +
|
2019-08-02 13:50:51 +00:00
|
|
|
' FROM ' + this.tableEscaped(model));
|
2015-05-13 17:14:44 +00:00
|
|
|
|
|
|
|
if (filter) {
|
|
|
|
if (filter.where) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const whereStmt = this.buildWhere(model, filter.where);
|
2015-05-13 17:14:44 +00:00
|
|
|
selectStmt.merge(whereStmt);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (filter.order) {
|
|
|
|
selectStmt.merge(this.buildOrderBy(model, filter.order));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (filter.limit || filter.skip || filter.offset) {
|
|
|
|
selectStmt = this.applyPagination(
|
2019-11-01 12:45:20 +00:00
|
|
|
model, selectStmt, filter,
|
2019-08-02 13:50:51 +00:00
|
|
|
);
|
2015-05-13 17:14:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return this.parameterize(selectStmt);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Transform the row data into a model data object
|
|
|
|
* @param {string} model Model name
|
|
|
|
* @param {object} rowData An object representing the row data from DB
|
|
|
|
* @returns {object} Model data object
|
|
|
|
*/
|
2016-04-09 19:00:28 +00:00
|
|
|
SQLConnector.prototype.fromRow = SQLConnector.prototype.fromDatabase =
|
|
|
|
function(model, rowData) {
|
2015-05-13 17:14:44 +00:00
|
|
|
if (rowData == null) {
|
|
|
|
return rowData;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const props = this.getModelDefinition(model).properties;
|
|
|
|
const data = {};
|
|
|
|
for (const p in props) {
|
|
|
|
const columnName = this.column(model, p);
|
2015-05-13 17:14:44 +00:00
|
|
|
// Load properties from the row
|
2019-08-02 13:50:51 +00:00
|
|
|
const columnValue = this.fromColumnValue(props[p], rowData[columnName]);
|
2015-05-13 17:14:44 +00:00
|
|
|
if (columnValue !== undefined) {
|
|
|
|
data[p] = columnValue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return data;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Find matching model instances by the filter
|
|
|
|
*
|
|
|
|
* Please also note the name `all` is confusing. `Model.find` is to find all
|
|
|
|
* matching instances while `Model.findById` is to find an instance by id. On
|
|
|
|
* the other hand, `Connector.prototype.all` implements `Model.find` while
|
|
|
|
* `Connector.prototype.find` implements `Model.findById` due to the `bad`
|
|
|
|
* naming convention we inherited from juggling-db.
|
2014-05-23 08:50:23 +00:00
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} filter The filter
|
|
|
|
* @param {Function} [cb] The cb function
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.all = function find(model, filter, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2015-05-13 17:14:44 +00:00
|
|
|
// Order by id if no order is specified
|
|
|
|
filter = filter || {};
|
2019-08-02 13:50:51 +00:00
|
|
|
const stmt = this.buildSelect(model, filter, options);
|
2015-05-13 17:14:44 +00:00
|
|
|
this.execute(stmt.sql, stmt.params, options, function(err, data) {
|
2014-05-23 08:50:23 +00:00
|
|
|
if (err) {
|
2015-05-13 17:14:44 +00:00
|
|
|
return cb(err, []);
|
|
|
|
}
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const objs = data.map(function(obj) {
|
2015-05-13 17:14:44 +00:00
|
|
|
return self.fromRow(model, obj);
|
|
|
|
});
|
|
|
|
if (filter && filter.include) {
|
2015-05-15 23:59:59 +00:00
|
|
|
self.getModelDefinition(model).model.include(
|
2019-11-01 12:45:20 +00:00
|
|
|
objs, filter.include, options, cb,
|
2019-08-02 13:50:51 +00:00
|
|
|
);
|
2015-05-13 17:14:44 +00:00
|
|
|
} else {
|
|
|
|
cb(null, objs);
|
2014-05-23 08:50:23 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
2015-05-15 17:27:08 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
// Alias to `all`. Juggler checks `all` only.
|
|
|
|
Connector.defineAliases(SQLConnector.prototype, 'all', ['findAll']);
|
2014-05-23 08:50:23 +00:00
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* ATM, this method is not used by loopback-datasource-juggler dao, which
|
|
|
|
* maps `findById` to `find` with a `where` filter that includes the `id`
|
|
|
|
* instead.
|
|
|
|
*
|
|
|
|
* Please also note the name `find` is confusing. `Model.find` is to find all
|
|
|
|
* matching instances while `Model.findById` is to find an instance by id. On
|
|
|
|
* the other hand, `Connector.prototype.find` is for `findById` and
|
|
|
|
* `Connector.prototype.all` is for `find` due the `bad` convention used by
|
|
|
|
* juggling-db.
|
|
|
|
*
|
|
|
|
* Find by id
|
|
|
|
* @param {String} model The Model name
|
2014-05-23 08:50:23 +00:00
|
|
|
* @param {*} id The id value
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} options The options object
|
2014-05-23 08:50:23 +00:00
|
|
|
* @param {Function} cb The callback function
|
2015-05-13 17:14:44 +00:00
|
|
|
* @private
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.find = function(model, id, options, cb) {
|
|
|
|
if (id == null) {
|
|
|
|
process.nextTick(function() {
|
2019-08-02 13:50:51 +00:00
|
|
|
const err = new Error(g.f('id value is required'));
|
2015-05-13 17:14:44 +00:00
|
|
|
if (cb) {
|
|
|
|
cb(err);
|
|
|
|
}
|
|
|
|
});
|
2014-05-23 08:50:23 +00:00
|
|
|
return;
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const where = {};
|
|
|
|
const idName = this.idName(model);
|
2014-06-21 04:13:10 +00:00
|
|
|
where[idName] = id;
|
2015-05-13 17:14:44 +00:00
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const filter = {limit: 1, offset: 0, order: idName, where: where};
|
2015-05-13 17:14:44 +00:00
|
|
|
return this.all(model, filter, options, function(err, results) {
|
|
|
|
cb(err, (results && results[0]) || null);
|
|
|
|
});
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
2015-05-13 17:14:44 +00:00
|
|
|
// Alias to `find`. Juggler checks `findById` only.
|
|
|
|
Connector.defineAliases(SQLConnector.prototype, 'find', ['findById']);
|
2014-05-23 08:50:23 +00:00
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Count all model instances by the where filter
|
|
|
|
*
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Object} where The where object
|
|
|
|
* @param {Object} options The options object
|
|
|
|
* @param {Function} cb The callback function
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.count = function(model, where, options, cb) {
|
|
|
|
if (typeof where === 'function') {
|
|
|
|
// Backward compatibility for 1.x style signature:
|
|
|
|
// count(model, cb, where)
|
2019-08-02 13:50:51 +00:00
|
|
|
const tmp = options;
|
2015-05-13 17:14:44 +00:00
|
|
|
cb = where;
|
|
|
|
where = tmp;
|
|
|
|
}
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
let stmt = new ParameterizedSQL('SELECT count(*) as "cnt" FROM ' +
|
2015-05-13 17:14:44 +00:00
|
|
|
this.tableEscaped(model));
|
|
|
|
stmt = stmt.merge(this.buildWhere(model, where));
|
|
|
|
stmt = this.parameterize(stmt);
|
2017-08-23 14:35:19 +00:00
|
|
|
this.execute(stmt.sql, stmt.params, options,
|
2015-05-13 17:14:44 +00:00
|
|
|
function(err, res) {
|
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
2019-08-02 13:50:51 +00:00
|
|
|
const c = (res && res[0] && res[0].cnt) || 0;
|
2015-05-13 17:14:44 +00:00
|
|
|
// Some drivers return count as a string to contain bigint
|
|
|
|
// See https://github.com/brianc/node-postgres/pull/427
|
|
|
|
cb(err, Number(c));
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Drop the table for the given model from the database
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.dropTable = function(model, cb) {
|
|
|
|
this.execute('DROP TABLE IF EXISTS ' + this.tableEscaped(model), cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create the table for the given model
|
|
|
|
* @param {String} model The model name
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.createTable = function(model, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const sql = 'CREATE TABLE ' + this.tableEscaped(model) +
|
2015-05-13 17:14:44 +00:00
|
|
|
' (\n ' + this.buildColumnDefinitions(model) + '\n)';
|
|
|
|
this.execute(sql, cb);
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Recreate the tables for the given models
|
2017-06-22 17:06:24 +00:00
|
|
|
* @param {String|String[]} [models] A model name or an array of model names,
|
2014-05-23 08:50:23 +00:00
|
|
|
* if not present, apply to all models defined in the connector
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.automigrate = function(models, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2014-05-23 08:50:23 +00:00
|
|
|
|
|
|
|
if ((!cb) && ('function' === typeof models)) {
|
|
|
|
cb = models;
|
|
|
|
models = undefined;
|
|
|
|
}
|
|
|
|
// First argument is a model name
|
|
|
|
if ('string' === typeof models) {
|
|
|
|
models = [models];
|
|
|
|
}
|
|
|
|
|
|
|
|
models = models || Object.keys(self._models);
|
2014-10-13 16:47:11 +00:00
|
|
|
if (models.length === 0) {
|
|
|
|
return process.nextTick(cb);
|
|
|
|
}
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const invalidModels = models.filter(function(m) {
|
2015-05-13 17:14:44 +00:00
|
|
|
return !(m in self._models);
|
|
|
|
});
|
2014-10-13 16:47:11 +00:00
|
|
|
if (invalidModels.length) {
|
|
|
|
return process.nextTick(function() {
|
2016-07-25 16:45:38 +00:00
|
|
|
cb(new Error(g.f('Cannot migrate models not attached to this datasource: %s',
|
|
|
|
invalidModels.join(' '))));
|
2014-10-13 16:47:11 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-02-22 14:05:17 +00:00
|
|
|
async.eachSeries(models, function(model, done) {
|
2014-10-13 16:47:11 +00:00
|
|
|
self.dropTable(model, function(err) {
|
|
|
|
if (err) {
|
|
|
|
// TODO(bajtos) should we abort here and call cb(err)?
|
|
|
|
// The original code in juggler ignored the error completely
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
self.createTable(model, function(err, result) {
|
2014-05-23 08:50:23 +00:00
|
|
|
if (err) {
|
|
|
|
console.error(err);
|
|
|
|
}
|
2014-10-13 16:47:11 +00:00
|
|
|
done(err, result);
|
2014-05-23 08:50:23 +00:00
|
|
|
});
|
2014-10-13 16:47:11 +00:00
|
|
|
});
|
2014-05-23 08:50:23 +00:00
|
|
|
}, cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Serialize an object into JSON string or other primitive types so that it
|
|
|
|
* can be saved into a RDB column
|
|
|
|
* @param {Object} obj The object value
|
|
|
|
* @returns {*}
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.serializeObject = function(obj) {
|
2019-08-02 13:50:51 +00:00
|
|
|
let val;
|
2015-05-13 17:14:44 +00:00
|
|
|
if (obj && typeof obj.toJSON === 'function') {
|
|
|
|
obj = obj.toJSON();
|
|
|
|
}
|
|
|
|
if (typeof obj !== 'string') {
|
|
|
|
val = JSON.stringify(obj);
|
|
|
|
} else {
|
|
|
|
val = obj;
|
|
|
|
}
|
|
|
|
return val;
|
|
|
|
};
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* @param obj
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.escapeObject = function(obj) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const val = this.serializeObject(obj);
|
2015-05-13 17:14:44 +00:00
|
|
|
return this.escapeValue(val);
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* The following _abstract_ methods have to be implemented by connectors that
|
|
|
|
* extend from SQLConnector to reuse the base implementations of CRUD methods
|
|
|
|
* from SQLConnector
|
2014-05-23 08:50:23 +00:00
|
|
|
*/
|
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Converts a model property value into the form required by the
|
|
|
|
* database column. The result should be one of following forms:
|
|
|
|
*
|
|
|
|
* - {sql: "point(?,?)", params:[10,20]}
|
|
|
|
* - {sql: "'John'", params: []}
|
|
|
|
* - "John"
|
|
|
|
*
|
|
|
|
* @param {Object} propertyDef Model property definition
|
|
|
|
* @param {*} value Model property value
|
|
|
|
* @returns {ParameterizedSQL|*} Database column value.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.toColumnValue = function(propertyDef, value) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{toColumnValue()}} must be implemented by the connector'));
|
2014-05-23 08:50:23 +00:00
|
|
|
};
|
|
|
|
|
2014-06-19 05:24:55 +00:00
|
|
|
/**
|
2015-05-13 17:14:44 +00:00
|
|
|
* Convert the data from database column to model property
|
|
|
|
* @param {object} propertyDef Model property definition
|
|
|
|
* @param {*) value Column value
|
|
|
|
* @returns {*} Model property value
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.fromColumnValue = function(propertyDef, value) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{fromColumnValue()}} must be implemented by the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Escape the name for the underlying database
|
|
|
|
* @param {String} name The name
|
|
|
|
* @returns {String} An escaped name for SQL
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.escapeName = function(name) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{escapeName()}} must be implemented by the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Escape the name for the underlying database
|
|
|
|
* @param {String} value The value to be escaped
|
|
|
|
* @returns {*} An escaped value for SQL
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.escapeValue = function(value) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{escapeValue()}} must be implemented by the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the place holder in SQL for identifiers, such as ??
|
|
|
|
* @param {String} key Optional key, such as 1 or id
|
|
|
|
* @returns {String} The place holder
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getPlaceholderForIdentifier = function(key) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{getPlaceholderForIdentifier()}} must be implemented by ' +
|
|
|
|
'the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the place holder in SQL for values, such as :1 or ?
|
|
|
|
* @param {String} key Optional key, such as 1 or id
|
|
|
|
* @returns {String} The place holder
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getPlaceholderForValue = function(key) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{getPlaceholderForValue()}} must be implemented by ' +
|
|
|
|
'the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build a new SQL statement with pagination support by wrapping the given sql
|
2014-06-19 05:24:55 +00:00
|
|
|
* @param {String} model The model name
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {ParameterizedSQL} stmt The sql statement
|
2015-05-21 00:20:55 +00:00
|
|
|
* @param {Object} filter The filter object from the query
|
2014-06-19 05:24:55 +00:00
|
|
|
*/
|
2015-05-13 17:14:44 +00:00
|
|
|
SQLConnector.prototype.applyPagination = function(model, stmt, filter) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{applyPagination()}} must be implemented by the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
2014-06-19 05:24:55 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Parse the result for SQL UPDATE/DELETE/INSERT for the number of rows
|
|
|
|
* affected
|
|
|
|
* @param {String} model Model name
|
|
|
|
* @param {Object} info Status object
|
|
|
|
* @returns {Number} Number of rows affected
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getCountForAffectedRows = function(model, info) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{getCountForAffectedRows()}} must be implemented by ' +
|
|
|
|
'the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
2014-06-19 05:24:55 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Parse the result for SQL INSERT for newly inserted id
|
|
|
|
* @param {String} model Model name
|
|
|
|
* @param {Object} info The status object from driver
|
|
|
|
* @returns {*} The inserted id value
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getInsertedId = function(model, info) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{getInsertedId()}} must be implemented by the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
2014-06-19 05:24:55 +00:00
|
|
|
|
2015-05-13 17:14:44 +00:00
|
|
|
/**
|
|
|
|
* Execute a SQL statement with given parameters
|
|
|
|
* @param {String} sql The SQL statement
|
2017-06-22 17:06:24 +00:00
|
|
|
* @param {Array} [params] An array of parameter values
|
2015-05-13 17:14:44 +00:00
|
|
|
* @param {Object} [options] Options object
|
|
|
|
* @param {Function} [callback] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.executeSQL = function(sql, params, options, callback) {
|
2016-07-25 16:45:38 +00:00
|
|
|
throw new Error(g.f('{{executeSQL()}} must be implemented by the connector'));
|
2015-05-13 17:14:44 +00:00
|
|
|
};
|
2017-02-13 20:28:59 +00:00
|
|
|
|
|
|
|
// Refactored Discovery methods
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build sql for listing schemas
|
|
|
|
* @param {Object} options Options for discoverDatabaseSchemas
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildQuerySchemas = function(options) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const sql = 'SELECT catalog_name as "catalog",' +
|
2017-02-13 20:28:59 +00:00
|
|
|
' schema_name as "schema"' +
|
|
|
|
' FROM information_schema.schemata';
|
|
|
|
return this.paginateSQL(sql, 'schema_name', options);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Paginate the results returned from database
|
|
|
|
* @param {String} sql The sql to execute
|
|
|
|
* @param {Object} orderBy The property name by which results are ordered
|
|
|
|
* @param {Object} options Options for discoverDatabaseSchemas
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.paginateSQL = function(sql, orderBy, options) {
|
|
|
|
throw new Error(g.f('{{paginateSQL}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
/**
|
|
|
|
* Discover database schemas
|
|
|
|
*
|
2017-04-07 20:00:13 +00:00
|
|
|
* @param {Object} options Options for discovery
|
2017-02-13 20:28:59 +00:00
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.discoverDatabaseSchemas = function(options, cb) {
|
|
|
|
if (!cb && typeof options === 'function') {
|
|
|
|
cb = options;
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
options = options || {};
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
2017-02-13 20:28:59 +00:00
|
|
|
this.execute(self.buildQuerySchemas(options), cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Build sql for listing tables
|
|
|
|
* @param options {all: for all owners, owner: for a given owner}
|
|
|
|
* @returns {string} The sql statement
|
|
|
|
*/
|
2018-06-12 14:33:52 +00:00
|
|
|
// Due to the different implementation structure of information_schema across
|
|
|
|
// connectors, each connector will have to generate its own query
|
2017-02-13 20:28:59 +00:00
|
|
|
SQLConnector.prototype.buildQueryTables = function(options) {
|
|
|
|
throw new Error(g.f('{{buildQueryTables}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Build sql for listing views
|
|
|
|
* @param options {all: for all owners, owner: for a given owner}
|
|
|
|
* @returns {string} The sql statement
|
|
|
|
*/
|
2018-06-12 14:33:52 +00:00
|
|
|
// Due to the different implementation structure of information_schema across
|
|
|
|
// connectors, each connector will have to generate its own query
|
2017-02-13 20:28:59 +00:00
|
|
|
SQLConnector.prototype.buildQueryViews = function(options) {
|
|
|
|
throw new Error(g.f('{{buildQueryViews}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Discover model definitions
|
|
|
|
*
|
|
|
|
* @param {Object} options Options for discovery
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.discoverModelDefinitions = function(options, cb) {
|
|
|
|
if (!cb && typeof options === 'function') {
|
|
|
|
cb = options;
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
options = options || {};
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const calls = [function(callback) {
|
2017-02-13 20:28:59 +00:00
|
|
|
self.execute(self.buildQueryTables(options), callback);
|
|
|
|
}];
|
|
|
|
|
|
|
|
if (options.views) {
|
|
|
|
calls.push(function(callback) {
|
|
|
|
self.execute(self.buildQueryViews(options), callback);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
async.parallel(calls, function(err, data) {
|
|
|
|
if (err) {
|
|
|
|
cb(err, data);
|
|
|
|
} else {
|
2019-08-02 13:50:51 +00:00
|
|
|
let merged = [];
|
2017-02-13 20:28:59 +00:00
|
|
|
merged = merged.concat(data.shift());
|
|
|
|
if (data.length) {
|
|
|
|
merged = merged.concat(data.shift());
|
|
|
|
}
|
|
|
|
cb(err, merged);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build sql for listing columns
|
|
|
|
* @param {String} schema The schema name
|
|
|
|
* @param {String} table The table name
|
|
|
|
*/
|
|
|
|
// Due to the different implementation structure of information_schema across
|
|
|
|
// connectors, each connector will have to generate its own query
|
|
|
|
SQLConnector.prototype.buildQueryColumns = function(schema, table) {
|
|
|
|
throw new Error(g.f('{{buildQueryColumns}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Map the property type from database to loopback
|
|
|
|
* @param {Object} columnDefinition The columnDefinition of the table/schema
|
|
|
|
* @param {Object} options The options for the connector
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.buildPropertyType = function(columnDefinition, options) {
|
|
|
|
throw new Error(g.f('{{buildPropertyType}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Normalize the arguments
|
|
|
|
* @param table string, required
|
|
|
|
* @param options object, optional
|
|
|
|
* @param cb function, optional
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getArgs = function(table, options, cb) {
|
|
|
|
throw new Error(g.f('{{getArgs}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Discover model properties from a table
|
|
|
|
* @param {String} table The table name
|
|
|
|
* @param {Object} options The options for discovery
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.discoverModelProperties = function(table, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const args = self.getArgs(table, options, cb);
|
|
|
|
let schema = args.schema || args.owner;
|
2017-02-13 20:28:59 +00:00
|
|
|
|
|
|
|
table = args.table;
|
|
|
|
options = args.options;
|
|
|
|
|
|
|
|
if (!schema) {
|
|
|
|
schema = self.getDefaultSchema();
|
|
|
|
}
|
|
|
|
|
|
|
|
self.setDefaultOptions(options);
|
|
|
|
cb = args.cb;
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const sql = self.buildQueryColumns(schema, table);
|
|
|
|
const callback = function(err, results) {
|
2017-02-13 20:28:59 +00:00
|
|
|
if (err) {
|
|
|
|
cb(err, results);
|
|
|
|
} else {
|
|
|
|
results.map(function(r) {
|
|
|
|
r.type = self.buildPropertyType(r, options);
|
|
|
|
self.setNullableProperty(r);
|
|
|
|
});
|
|
|
|
cb(err, results);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
this.execute(sql, callback);
|
|
|
|
};
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Build the sql statement for querying primary keys of a given table
|
|
|
|
* @param schema
|
|
|
|
* @param table
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
|
|
|
// http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html
|
|
|
|
// #getPrimaryKeys(java.lang.String, java.lang.String, java.lang.String)
|
|
|
|
// Due to the different implementation structure of information_schema across
|
|
|
|
// connectors, each connector will have to generate its own query
|
|
|
|
SQLConnector.prototype.buildQueryPrimaryKeys = function(schema, table) {
|
|
|
|
throw new Error(g.f('{{buildQueryPrimaryKeys}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Discover primary keys for a given table
|
|
|
|
* @param {String} table The table name
|
|
|
|
* @param {Object} options The options for discovery
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.discoverPrimaryKeys = function(table, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const args = self.getArgs(table, options, cb);
|
|
|
|
let schema = args.schema || args.owner;
|
2017-02-13 20:28:59 +00:00
|
|
|
|
|
|
|
if (typeof(self.getDefaultSchema) === 'function' && !schema) {
|
|
|
|
schema = self.getDefaultSchema();
|
|
|
|
}
|
|
|
|
table = args.table;
|
|
|
|
options = args.options;
|
|
|
|
cb = args.cb;
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const sql = self.buildQueryPrimaryKeys(schema, table);
|
2017-02-13 20:28:59 +00:00
|
|
|
this.execute(sql, cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Build the sql statement for querying foreign keys of a given table
|
|
|
|
* @param schema
|
|
|
|
* @param table
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
2018-06-12 14:33:52 +00:00
|
|
|
// Due to the different implementation structure of information_schema across
|
|
|
|
// connectors, each connector will have to generate its own query
|
2017-02-13 20:28:59 +00:00
|
|
|
SQLConnector.prototype.buildQueryForeignKeys = function(schema, table) {
|
|
|
|
throw new Error(g.f('{{buildQueryForeignKeys}} must be implemented by the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Discover foreign keys for a given table
|
|
|
|
* @param {String} table The table name
|
|
|
|
* @param {Object} options The options for discovery
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.discoverForeignKeys = function(table, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const args = self.getArgs(table, options, cb);
|
|
|
|
let schema = args.schema || args.owner;
|
2017-02-13 20:28:59 +00:00
|
|
|
|
|
|
|
if (typeof(self.getDefaultSchema) === 'function' && !schema) {
|
|
|
|
schema = self.getDefaultSchema();
|
|
|
|
}
|
|
|
|
table = args.table;
|
|
|
|
options = args.options;
|
|
|
|
cb = args.cb;
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const sql = self.buildQueryForeignKeys(schema, table);
|
2017-02-13 20:28:59 +00:00
|
|
|
this.execute(sql, cb);
|
|
|
|
};
|
|
|
|
|
2017-04-07 20:00:13 +00:00
|
|
|
/**
|
2017-02-13 20:28:59 +00:00
|
|
|
* Retrieves a description of the foreign key columns that reference the
|
|
|
|
* given table's primary key columns (the foreign keys exported by a table).
|
|
|
|
* They are ordered by fkTableOwner, fkTableName, and keySeq.
|
|
|
|
* @param schema
|
|
|
|
* @param table
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
2018-06-12 14:33:52 +00:00
|
|
|
// Due to the different implementation structure of information_schema across
|
|
|
|
// connectors, each connector will have to generate its own query
|
2017-02-13 20:28:59 +00:00
|
|
|
SQLConnector.prototype.buildQueryExportedForeignKeys = function(schema, table) {
|
|
|
|
throw new Error(g.f('{{buildQueryExportedForeignKeys}} must be implemented by' +
|
|
|
|
'the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Discover foreign keys that reference to the primary key of this table
|
|
|
|
* @param {String} table The table name
|
|
|
|
* @param {Object} options The options for discovery
|
|
|
|
* @param {Function} [cb] The callback function
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.discoverExportedForeignKeys = function(table, options, cb) {
|
2019-08-02 13:50:51 +00:00
|
|
|
const self = this;
|
|
|
|
const args = self.getArgs(table, options, cb);
|
|
|
|
let schema = args.schema || args.owner;
|
2017-02-13 20:28:59 +00:00
|
|
|
|
|
|
|
if (typeof(self.getDefaultSchema) === 'function' && !schema) {
|
|
|
|
schema = self.getDefaultSchema();
|
|
|
|
}
|
|
|
|
table = args.table;
|
|
|
|
options = args.options;
|
|
|
|
cb = args.cb;
|
|
|
|
|
2019-08-02 13:50:51 +00:00
|
|
|
const sql = self.buildQueryExportedForeignKeys(schema, table);
|
2017-02-13 20:28:59 +00:00
|
|
|
this.execute(sql, cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Discover default schema of a database
|
|
|
|
* @param {Object} options The options for discovery
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.getDefaultSchema = function(options) {
|
|
|
|
throw new Error(g.f('{{getDefaultSchema}} must be implemented by' +
|
|
|
|
'the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Set default options for the connector
|
|
|
|
* @param {Object} options The options for discovery
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.setDefaultOptions = function(options) {
|
|
|
|
throw new Error(g.f('{{setDefaultOptions}} must be implemented by' +
|
|
|
|
'the connector'));
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Set the nullable value for the property
|
|
|
|
* @param {Object} property The property to set nullable
|
|
|
|
*/
|
|
|
|
SQLConnector.prototype.setNullableProperty = function(property) {
|
|
|
|
throw new Error(g.f('{{setNullableProperty}} must be implemented by' +
|
|
|
|
'the connector'));
|
|
|
|
};
|