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

Commit 7272c603 by Ruben Bridgewater

Use stricter jshint settings

I added
 - unused: "vars" // warns when you define and never use your variables
 - nonbsp: true // warns about "non-breaking whitespace" characters
 - maxdepth: 8 // lets you control how nested do you want your blocks to be
 - quotmark: false // true = all quotation marks have to either be single quotes or double quotes per file
I tried to use this option with true, but I'm not sure how you like it that way. As here are quite a few use cases where single quotes would have to be escaped

I removed:
 - trailing: true // this option no longer exists in jshint
 - expr: true // this option no longer exists in jshint
 - sub: true // suppresses warnings about using [] notation when it can be expressed in dot notation: person['name'] vs. person.name

I also used maxlen: 200 for a while, but I'm not sure how the line breaks work for the docs, since I did not try that. I still think it would be a good option to use

Be aware, that a couple of options are deprecated and will be removed at some point. Instead jscs could be used to enforce styling warnings.
1 parent f4a680d5
{
"bitwise":false,
"boss":true,
"expr":true,
"camelcase":false,
"curly":false,
"eqeqeq":true,
"freeze":true,
"immed":true,
"indent":2,
"latedef":"nofunc",
"laxbreak":true,
"laxcomma":true,
"newcap":true,
"immed":true, // deprecated
"indent":2, // deprecated
"latedef":"true",
"newcap":true, // deprecated
"noarg":true,
"node":true,
"strict":true,
"trailing":true,
"undef":true,
"esnext":false,
"sub":true,
"unused": "vars",
"nonbsp": true,
"maxdepth": 8,
"quotmark": false, // deprecated
// "maxlen": 200, // depcreated
/* relaxing options */
"laxbreak":true,
"laxcomma":true,
/* questionable */
"loopfunc":true,
......@@ -39,4 +42,4 @@
"setup",
"test"
]
}
}
\ No newline at end of file
......@@ -2,7 +2,7 @@
The sequelize documentation is written in a combination of markdown (articles and example based documentation) and [JSDoc](http://usejsdoc.org) (API reference generated from source code comments).
All documentation is located in the `docs` folder.
All documentation is located in the `docs` folder.
The documentation is rendered using [mkdocs](http://mkdocs.org) and hosted at [Read the docs](http://sequelize.readthedocs.org). Mkdocs generates static HTML from markdown files. The files in `articles` and `docs` should be edited directly, and the files in `api` are generated from source code comments (more on that later).
......@@ -19,8 +19,8 @@ To view the docs locally use `mkdocs serve`. This will start a local server at p
Write markdown, and have fun :)
## API docs
The API documentation is generated from source code comments by a custom script, which outputs markdown into the `docs/api` folder. To regenerate the documentation, run:
The API documentation is generated from source code comments by a custom script, which outputs markdown into the `docs/api` folder. To regenerate the documentation, run:
```bash
$ npm run docs
```
By default all generation will be regenerated, but you can run the generation for a single file by specifying `--file`.
By default all generation will be regenerated, but you can run the generation for a single file by specifying `--file`.
......@@ -53,7 +53,7 @@ For MySQL this would look like this:
$ echo "CREATE DATABASE sequelize_test;" | mysql -uroot
```
**CLEVER NOTE:** by default, your local MySQL install must be with username `root` without password. If you want to customize that, you can set the environment variables `SEQ_DB`, `SEQ_USER`, `SEQ_PW`, `SEQ_HOST` and `SEQ_PORT`.
**CLEVER NOTE:** by default, your local MySQL install must be with username `root` without password. If you want to customize that, you can set the environment variables `SEQ_DB`, `SEQ_USER`, `SEQ_PW`, `SEQ_HOST` and `SEQ_PORT`.
For Postgres, creating the database and (optionally) adding the test user this would look like:
......
......@@ -12,7 +12,7 @@ Sequelize is a promise-based Node.js/io.js ORM for Postgres, MySQL, MariaDB, SQL
`npm install sequelize`
Will install the latest version of sequelize (currently 2.0).
Will install the latest version of sequelize (currently 2.0).
[Upgrading to 2.0](https://github.com/sequelize/sequelize/wiki/Upgrading-to-2.0)
......
......@@ -181,7 +181,7 @@ We are working our way to the first 2.0.0 release candidate.
#### Backwards compatibility changes
- We are using a new inflection library, which should make pluralization and singularization in general more robust. However, a couple of pluralizations have changed as a result:
+ Person is now pluralized as people instead of persons
- Accesors for models with underscored names are no longer camel cased automatically. For example, if you have a model with name `my_model`, and `my_other_model.hasMany(my_model)`, the getter will now be `instance_of_my_model.getMy_model` instead of `.getMyModel`.
- Accesors for models with underscored names are no longer camel cased automatically. For example, if you have a model with name `my_model`, and `my_other_model.hasMany(my_model)`, the getter will now be `instance_of_my_model.getMy_model` instead of `.getMyModel`.
- Removed support for setting sequelize.language. If your model names are not in english, use the name option provided by `sequelize.name` to defined singular and plural forms for your model.
- Model names are now used more verbatim in associations. This means that if you have a model named `Task` (plural T), or an association specifying `{ as: 'Task' }`, the tasks will be returned as `relatedModel.Tasks` instead of `relatedModel.tasks`. For more information and how to mitigate this, see https://github.com/sequelize/sequelize/wiki/Upgrading-to-2.0#inflection-replaces-lingo-and-changes-to-naming-conventions
- Removed the freezeAssociations option - use model and assocation names instead to provide the plural form yourself
......@@ -190,11 +190,11 @@ We are working our way to the first 2.0.0 release candidate.
+ All Error classes properly inherit from Error and a common SequelizeBaseError base
+ Instance Validator returns a single instance of a ValidationError which contains an errors array property. This property contains individual error items for each failed validation.
+ ValidationError includes a `get(path)` method to find all broken validations for a path on an instance. To migrate existing error handling, switch from array indexing to using the get method:
Old: `err.validateCustom[0]`
New: `err.get('validateCustom')[0]`
Old: `err.validateCustom[0]`
New: `err.get('validateCustom')[0]`
- The syntax for findOrCreate has changed, to be more in line with the rest of the library. `Model.findOrCreate(where, defaults);` becomes `Model.findOrCreate({ where: where, defaults: defaults });`.
# v2.0.0-dev12
- [FEATURE] You can now return a promise to a hook rather than use a callback
......
......@@ -4,11 +4,8 @@ var Utils = require('./../utils')
, Helpers = require('./helpers')
, _ = require('lodash')
, Association = require('./base')
, Transaction = require('../transaction')
, Model = require('../model')
, CounterCache = require('../plugins/counter-cache')
, util = require('util')
, HasManyDoubleLinked = require('./has-many-double-linked')
, deprecatedSeen = {}
, deprecated = function(message) {
if (deprecatedSeen[message]) return;
......@@ -19,7 +16,6 @@ var Utils = require('./../utils')
module.exports = (function() {
var BelongsToMany = function(source, target, options) {
Association.call(this);
var self = this;
this.associationType = 'BelongsToMany';
this.source = source;
......@@ -222,8 +218,7 @@ module.exports = (function() {
// the id is in the target table
// or in an extra table which connects two tables
BelongsToMany.prototype.injectAttributes = function() {
var doubleLinked = this.doubleLinked
, self = this;
var self = this;
this.identifier = this.foreignKey;
this.foreignIdentifier = this.otherKey;
......@@ -453,7 +448,8 @@ module.exports = (function() {
, promises = []
, unassociatedObjects;
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']); // Don't try to insert the transaction as an attribute in the through table
// Don't try to insert the transaction as an attribute in the through table
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']);
unassociatedObjects = newAssociatedObjects.filter(function(obj) {
return !Utils._.find(oldAssociatedObjects, function(old) {
......@@ -562,8 +558,7 @@ module.exports = (function() {
return newInstance;
});
var self = this
, foreignIdentifier = association.foreignIdentifier
var foreignIdentifier = association.foreignIdentifier
, sourceKeys = Object.keys(association.source.primaryKeys)
, targetKeys = Object.keys(association.target.primaryKeys)
, obsoleteAssociations = []
......@@ -574,7 +569,8 @@ module.exports = (function() {
, oldAssociations = []
, unassociatedObjects;
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']); // Don't try to insert the transaction as an attribute in the through table
// Don't try to insert the transaction as an attribute in the through table
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']);
unassociatedObjects = newInstances.filter(function(obj) {
return !Utils._.find(oldAssociations, function(old) {
......@@ -679,7 +675,8 @@ module.exports = (function() {
var sourceKeys = Object.keys(association.source.primaryKeys);
var targetKeys = Object.keys(association.target.primaryKeys);
additionalAttributes = Utils._.omit(additionalAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']); // Don't try to insert the transaction as an attribute in the through table
// Don't try to insert the transaction as an attribute in the through table
additionalAttributes = Utils._.omit(additionalAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']);
attributes[association.identifier] = ((sourceKeys.length === 1) ? instance[sourceKeys[0]] : instance.id);
attributes[foreignIdentifier] = ((targetKeys.length === 1) ? newInstance[targetKeys[0]] : newInstance.id);
......
'use strict';
var Utils = require('./../utils')
, Transaction = require('./../transaction');
var Utils = require('./../utils');
module.exports = (function() {
var HasManyDoubleLinked = function(association, instance) {
......@@ -73,7 +72,8 @@ module.exports = (function() {
, promises = []
, unassociatedObjects;
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields', 'logging']); // Don't try to insert the transaction as an attribute in the through table
// Don't try to insert the transaction as an attribute in the through table
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields', 'logging']);
unassociatedObjects = newAssociations.filter(function(obj) {
return !Utils._.find(oldAssociations, function(old) {
......@@ -168,7 +168,8 @@ module.exports = (function() {
var sourceKeys = Object.keys(this.association.source.primaryKeys);
var targetKeys = Object.keys(this.association.target.primaryKeys);
additionalAttributes = Utils._.omit(additionalAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']); // Don't try to insert the transaction as an attribute in the through table
// Don't try to insert the transaction as an attribute in the through table
additionalAttributes = Utils._.omit(additionalAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']);
attributes[this.association.identifier] = ((sourceKeys.length === 1) ? this.instance[sourceKeys[0]] : this.instance.id);
attributes[foreignIdentifier] = ((targetKeys.length === 1) ? newAssociation[targetKeys[0]] : newAssociation.id);
......
'use strict';
var Utils = require('./../utils')
, Transaction = require('./../transaction');
var Utils = require('./../utils');
module.exports = (function() {
var HasManySingleLinked = function(association, instance) {
......
......@@ -4,8 +4,6 @@ var Utils = require('./../utils')
, Helpers = require('./helpers')
, _ = require('lodash')
, Association = require('./base')
, Transaction = require('../transaction')
, Model = require('../model')
, CounterCache = require('../plugins/counter-cache')
, util = require('util')
, deprecatedSeen = {}
......
......@@ -2,7 +2,6 @@
var Utils = require('./../utils')
, Helpers = require('./helpers')
, Transaction = require('../transaction')
, Association = require('./base')
, util = require('util');
......
......@@ -5,7 +5,11 @@ var Utils = require('./../utils');
module.exports = {
checkNamingCollision: function (association) {
if (association.source.rawAttributes.hasOwnProperty(association.as)) {
throw new Error("Naming collision between attribute '" + association.as + "' and association '" + association.as + "' on model " + association.source.name + '. To remedy this, change either foreignKey or as in your association definition');
throw new Error(
'Naming collision between attribute \'' + association.as +
'\' and association \'' + association.as + '\' on model ' + association.source.name +
'. To remedy this, change either foreignKey or as in your association definition'
);
}
},
......
......@@ -98,7 +98,7 @@ var Mixin = module.exports = function() {};
var singleLinked = function (Type) {
return function(targetModel, options) {
if (!(targetModel instanceof this.sequelize.Model)) {
throw new Error(this.name + "." + Utils.lowercaseFirst(Type.toString()) + " called with something that's not an instance of Sequelize.Model");
throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model');
}
var sourceModel = this;
......@@ -244,7 +244,7 @@ Mixin.belongsTo = singleLinked(BelongsTo);
*/
Mixin.hasMany = function(targetModel, options) {
if (!(targetModel instanceof this.sequelize.Model)) {
throw new Error(this.name + ".hasMany called with something that's not an instance of Sequelize.Model");
throw new Error(this.name + '.hasMany called with something that\'s not an instance of Sequelize.Model');
}
var sourceModel = this;
......@@ -338,7 +338,7 @@ Mixin.hasMany = function(targetModel, options) {
*/
Mixin.belongsToMany = function(targetModel, options) {
if (!(targetModel instanceof this.sequelize.Model)) {
throw new Error(this.name + ".belongsToMany called with something that's not an instance of Sequelize.Model");
throw new Error(this.name + '.belongsToMany called with something that\'s not an instance of Sequelize.Model');
}
var sourceModel = this;
......
......@@ -13,7 +13,8 @@ var util = require('util')
* When defining a model you can just as easily pass a string as type, but often using the types defined here is beneficial. For example, using `DataTypes.BLOB`, mean
* that that column will be returned as an instance of `Buffer` when being fetched by sequelize.
*
* Some data types have special properties that can be accessed in order to change the data type. For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`.
* Some data types have special properties that can be accessed in order to change the data type.
* For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`.
* The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as well. The available properties are listed under each data type.
*
* To provide a length for the data type, you can invoke it like a function: `INTEGER(2)`
......@@ -52,7 +53,7 @@ ABSTRACT.prototype.toSql = function() {
* @property STRING
*/
var STRING = function(length, binary) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
......@@ -85,7 +86,7 @@ Object.defineProperty(STRING.prototype, 'BINARY', {
* @property CHAR
*/
var CHAR = function(length, binary) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length,
binary: binary
};
......@@ -166,7 +167,7 @@ Object.defineProperty(NUMBER.prototype, 'ZEROFILL', {
* @property INTEGER
*/
var INTEGER = function(length) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
......@@ -185,7 +186,7 @@ INTEGER.prototype.key = INTEGER.key = 'INTEGER';
*/
var BIGINT = function(length) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
......@@ -204,7 +205,7 @@ BIGINT.prototype.key = BIGINT.key = 'BIGINT';
*/
var FLOAT = function(length, decimals) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
......@@ -223,7 +224,7 @@ FLOAT.prototype.key = FLOAT.key = 'FLOAT';
* @property DECIMAL
*/
var DECIMAL = function(precision, scale) {
var options = typeof precision === "object" && precision || {
var options = typeof precision === 'object' && precision || {
precision: precision,
scale: scale
};
......@@ -359,7 +360,7 @@ NOW.prototype.key = NOW.key = 'NOW';
*/
var BLOB = function(length) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BLOB)) return new BLOB(options);
......@@ -492,7 +493,7 @@ VIRTUAL.prototype.key = VIRTUAL.key = 'VIRTUAL';
* @property ENUM
*/
var ENUM = function(value) {
var options = typeof value === "object" && !Array.isArray(value) && value || {
var options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce(function(result, element) {
return result.concat(Array.isArray(element) ? element : [element]);
}, [])
......@@ -513,7 +514,7 @@ var ARRAY = function(type) {
type: type
};
if (!(this instanceof ARRAY)) return new ARRAY(options);
this.type = typeof options.type === "function" ? new options.type() : options.type;
this.type = typeof options.type === 'function' ? new options.type() : options.type;
};
util.inherits(ARRAY, ABSTRACT);
......@@ -539,8 +540,7 @@ Object.keys(helpers).forEach(function (helper) {
Object.defineProperty(DataType, helper, {
get: function() {
var dataType = new DataType();
if (typeof dataType[helper] === "object") {
dataType[helper];
if (typeof dataType[helper] === 'object') {
return dataType;
}
return dataType[helper].apply(dataType, arguments);
......
"use strict";
'use strict';
var Pooling = require('generic-pool')
, Promise = require('../../promise')
......@@ -57,7 +57,7 @@ ConnectionManager.prototype.close = function () {
process.removeListener('exit', this.onProcessExit); // Remove the listener, so all references to this instance can be garbage collected.
this.getConnection = function () {
return Promise.reject(new Error("ConnectionManager.getConnection was called after the connection manager was closed!"));
return Promise.reject(new Error('ConnectionManager.getConnection was called after the connection manager was closed!'));
};
};
......
......@@ -202,7 +202,7 @@ module.exports = (function() {
}
}
if (this._dialect.supports['EXCEPTION'] && options.exception) {
if (this._dialect.supports.EXCEPTION && options.exception) {
// Mostly for internal use, so we expect the user to know what he's doing!
// pg_temp functions are private per connection, so we never risk this function interfering with another one.
......@@ -214,7 +214,9 @@ module.exports = (function() {
var delimiter = '$func_' + Utils.generateUUID().replace(/-/g, '') + '$';
options.exception = 'WHEN unique_violation THEN GET STACKED DIAGNOSTICS sequelize_caught_exception = PG_EXCEPTION_DETAIL;';
valueQuery = 'CREATE OR REPLACE FUNCTION pg_temp.testfunc(OUT response <%= table %>, OUT sequelize_caught_exception text) RETURNS RECORD AS ' + delimiter + ' BEGIN ' + valueQuery + ' INTO response; EXCEPTION ' + options.exception + ' END ' + delimiter + ' LANGUAGE plpgsql; SELECT (testfunc.response).*, testfunc.sequelize_caught_exception FROM pg_temp.testfunc(); DROP FUNCTION IF EXISTS pg_temp.testfunc()';
valueQuery = 'CREATE OR REPLACE FUNCTION pg_temp.testfunc(OUT response <%= table %>, OUT sequelize_caught_exception text) RETURNS RECORD AS ' + delimiter +
' BEGIN ' + valueQuery + ' INTO response; EXCEPTION ' + options.exception + ' END ' + delimiter +
' LANGUAGE plpgsql; SELECT (testfunc.response).*, testfunc.sequelize_caught_exception FROM pg_temp.testfunc(); DROP FUNCTION IF EXISTS pg_temp.testfunc()';
}
if (this._dialect.supports['ON DUPLICATE KEY'] && options.onDuplicate) {
......@@ -233,7 +235,7 @@ module.exports = (function() {
if (modelAttributeMap && modelAttributeMap[key] && modelAttributeMap[key].autoIncrement === true && !value) {
if (!this._dialect.supports.autoIncrement.defaultValue) {
fields.splice(-1,1);
} else if (this._dialect.supports['DEFAULT']) {
} else if (this._dialect.supports.DEFAULT) {
values.push('DEFAULT');
} else {
values.push(this.escape(null));
......@@ -249,7 +251,7 @@ module.exports = (function() {
}
var replacements = {
ignore: options.ignore ? this._dialect.supports['IGNORE'] : '',
ignore: options.ignore ? this._dialect.supports.IGNORE : '',
table: this.quoteTable(table),
attributes: fields.join(','),
output: outputFragment,
......@@ -903,7 +905,6 @@ module.exports = (function() {
, association = include.association
, through = include.through
, joinType = include.required ? ' INNER JOIN ' : ' LEFT OUTER JOIN '
, includeWhere = {}
, whereOptions = Utils._.clone(options)
, targetWhere;
......@@ -941,8 +942,10 @@ module.exports = (function() {
} else if (attr instanceof Utils.cast ||
attr instanceof Utils.fn
) {
throw new Error("Tried to select attributes using Sequelize.cast or Sequelize.fn without specifying an alias for the result, during eager loading. " +
"This means the attribute will not be added to the returned instance");
throw new Error(
'Tried to select attributes using Sequelize.cast or Sequelize.fn without specifying an alias for the result, during eager loading. ' +
'This means the attribute will not be added to the returned instance'
);
}
var prefix;
......@@ -972,8 +975,6 @@ module.exports = (function() {
, tableSource = parentTable
, identSource = association.identifierField
, attrSource = primaryKeysSource[0]
, where
, primaryKeysTarget = association.target.primaryKeyAttributes
, tableTarget = as
, identTarget = association.foreignIdentifierField
......@@ -1094,7 +1095,7 @@ module.exports = (function() {
self.sequelize.asIs([
self.quoteTable(topParent.model.name) + '.' + self.quoteIdentifier(topParent.model.primaryKeyAttributes[0]),
self.quoteIdentifier(topInclude.through.model.name) + '.' + self.quoteIdentifier(topInclude.association.identifierField)
].join(" = ")),
].join(' = ')),
topInclude.through.where
),
limit: 1,
......@@ -1108,7 +1109,7 @@ module.exports = (function() {
$join: self.sequelize.asIs([
self.quoteTable(topParent.model.name) + '.' + self.quoteIdentifier(topParent.model.primaryKeyAttributes[0]),
self.quoteIdentifier(topInclude.model.name) + '.' + self.quoteIdentifier(topInclude.association.identifierField)
].join(" = "))
].join(' = '))
},
limit: 1,
includeIgnoreAttributes: false
......@@ -1117,7 +1118,7 @@ module.exports = (function() {
options.where['__' + throughAs] = self.sequelize.asIs([
'(',
$query.replace(/\;$/, ""),
$query.replace(/\;$/, ''),
')',
'IS NOT NULL'
].join(' '));
......@@ -1183,7 +1184,7 @@ module.exports = (function() {
var subQueryWhere = self.sequelize.asIs([
'(',
$query.replace(/\;$/, ""),
$query.replace(/\;$/, ''),
')',
'IS NOT NULL'
].join(' '));
......@@ -1309,7 +1310,7 @@ module.exports = (function() {
options.order.forEach(function(t) {
if (Array.isArray(t) && _.size(t) > 1) {
if (t[0] instanceof Model || t[0].model instanceof Model) {
if (typeof t[t.length - 2] === "string") {
if (typeof t[t.length - 2] === 'string') {
validateOrder(_.last(t));
}
} else {
......@@ -1324,7 +1325,7 @@ module.exports = (function() {
mainQueryOrder.push(this.quote(t, model));
}.bind(this));
} else {
mainQueryOrder.push(this.quote(typeof options.order === "string" ? new Utils.literal(options.order) : options.order, model));
mainQueryOrder.push(this.quote(typeof options.order === 'string' ? new Utils.literal(options.order) : options.order, model));
}
if (mainQueryOrder.length) {
......@@ -1481,10 +1482,7 @@ module.exports = (function() {
result = result.length && '(' + result + ')' || undefined;
} else if (smth instanceof Utils.where) {
var value = smth.logic
, key
, logic
, _result = []
, _value;
, key;
if (smth.attribute._isSequelizeMethod) {
key = this.getWhereConditions(smth.attribute, tableName, factory, options, prepend);
......@@ -1605,36 +1603,36 @@ module.exports = (function() {
$notILike: 'NOT ILIKE',
$between: 'BETWEEN',
$notBetween: 'NOT BETWEEN',
$overlap: "&&",
$contains: "@>",
$contained: "<@"
$overlap: '&&',
$contains: '@>',
$contained: '<@'
};
// Maintain BC
aliasMap = {
"ne": "$ne",
"in": "$in",
"not": "$not",
"notIn": "$notIn",
"gte": "$gte",
"gt": "$gt",
"lte": "$lte",
"lt": "$lt",
"like": "$like",
"ilike": "$iLike",
"$ilike": "$iLike",
"nlike": "$notLike",
"$notlike": "$notLike",
"notilike": "$notILike",
"..": "$between",
"between": "$between",
"!..": "$notBetween",
"notbetween": "$notBetween",
"nbetween": "$notBetween",
"overlap": "$overlap",
"&&": "$overlap",
"@>": "$contains",
"<@": "$contained"
'ne': '$ne',
'in': '$in',
'not': '$not',
'notIn': '$notIn',
'gte': '$gte',
'gt': '$gt',
'lte': '$lte',
'lt': '$lt',
'like': '$like',
'ilike': '$iLike',
'$ilike': '$iLike',
'nlike': '$notLike',
'$notlike': '$notLike',
'notilike': '$notILike',
'..': '$between',
'between': '$between',
'!..': '$notBetween',
'notbetween': '$notBetween',
'nbetween': '$notBetween',
'overlap': '$overlap',
'&&': '$overlap',
'@>': '$contains',
'<@': '$contained'
};
key = aliasMap[key] || key;
......@@ -1649,9 +1647,9 @@ module.exports = (function() {
if (key === undefined) {
if (value instanceof Utils.or || value instanceof Utils.and) {
key = value instanceof Utils.or ? "$or" : "$and";
key = value instanceof Utils.or ? '$or' : '$and';
value = value.args;
} else if (typeof value === "string") {
} else if (typeof value === 'string') {
return value;
}
}
......@@ -1671,9 +1669,9 @@ module.exports = (function() {
// OR/AND/NOT grouping logic
if (key === '$or' || key === '$and' || key === '$not') {
binding = (key === '$or') ?' OR ' : ' AND ';
outerBinding = '';
if (key === '$not') outerBinding = 'NOT ';
......@@ -1987,7 +1985,6 @@ module.exports = (function() {
if (Utils._.isPlainObject(options.where)) {
Object.keys(options.where).forEach(function(filterStr) {
var associationParts = filterStr.split('.')
, attributePart = associationParts.pop()
, dao = originalDao;
if (self.isAssociationFilter(filterStr, dao, options)) {
......
......@@ -2,9 +2,7 @@
var Utils = require('../../utils')
, CustomEventEmitter = require('../../emitters/custom-event-emitter')
, Promise = require('../../promise')
, Dot = require('dottie')
, _ = require('lodash')
, QueryTypes = require('../../query-types');
module.exports = (function() {
......@@ -26,7 +24,7 @@ module.exports = (function() {
* @api public
*/
AbstractQuery.prototype.run = function(sql) {
throw new Error("The run method wasn't overwritten!");
throw new Error('The run method wasn\'t overwritten!');
};
/**
......@@ -318,7 +316,6 @@ module.exports = (function() {
, values
, topValues
, topExists
, previous
, checkExisting = options.checkExisting
// If we don't have to deduplicate we can pre-allocate the resulting array
, results = checkExisting ? [] : new Array(rowsLength)
......@@ -383,7 +380,7 @@ module.exports = (function() {
if (!keyPrefixMemo[key]) {
var prefixString = keyPrefixString(key, keyPrefixStringMemo);
if (!keyPrefixMemo[prefixString]) {
keyPrefixMemo[prefixString] = prefixString ? prefixString.split(".") : [];
keyPrefixMemo[prefixString] = prefixString ? prefixString.split('.') : [];
}
keyPrefixMemo[key] = keyPrefixMemo[prefixString];
}
......
"use strict";
'use strict';
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, Utils = require('../../utils')
......
......@@ -3,8 +3,6 @@
var Utils = require('../../utils')
, DataTypes = require('../../data-types')
, Model = require('../../model')
, _ = require('lodash')
, util = require('util')
, AbstractQueryGenerator = require('../abstract/query-generator');
module.exports = (function() {
......@@ -19,7 +17,7 @@ module.exports = (function() {
'WHERE schema_name =', wrapSingleQuote(schema), ')',
'BEGIN',
'EXEC sp_executesql N\'CREATE SCHEMA', this.quoteIdentifier(schema),';\'',
"END;"
'END;'
].join(' ');
},
......@@ -27,17 +25,17 @@ module.exports = (function() {
return [
'SELECT "name" as "schema_name" FROM sys.schemas as s',
'WHERE "s"."name" NOT IN (',
"'INFORMATION_SCHEMA', 'dbo', 'guest', 'sys', 'archive'",
")", "AND", '"s"."name" NOT LIKE', "'db_%'"
'\'INFORMATION_SCHEMA\', \'dbo\', \'guest\', \'sys\', \'archive\'',
')', 'AND', '"s"."name" NOT LIKE', '\'db_%\''
].join(' ');
},
versionQuery: function() {
return "SELECT @@VERSION as 'version'";
return 'SELECT @@VERSION as \'version\'';
},
createTableQuery: function(tableName, attributes, options) {
var query = "IF OBJECT_ID('<%= table %>', 'U') IS NULL CREATE TABLE <%= table %> (<%= attributes %>)"
var query = 'IF OBJECT_ID(\'<%= table %>\', \'U\') IS NULL CREATE TABLE <%= table %> (<%= attributes %>)'
, primaryKeys = []
, foreignKeys = {}
, attrStr = []
......@@ -100,20 +98,20 @@ module.exports = (function() {
describeTableQuery: function(tableName, schema, schemaDelimiter) {
var sql = [
"SELECT",
"c.COLUMN_NAME AS 'Name',",
"c.DATA_TYPE AS 'Type',",
"c.IS_NULLABLE as 'IsNull',",
"COLUMN_DEFAULT AS 'Default'",
"FROM",
"INFORMATION_SCHEMA.TABLES t",
"INNER JOIN",
"INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME",
"WHERE t.TABLE_NAME =", wrapSingleQuote(tableName)
].join(" ");
'SELECT',
'c.COLUMN_NAME AS \'Name\',',
'c.DATA_TYPE AS \'Type\',',
'c.IS_NULLABLE as \'IsNull\',',
'COLUMN_DEFAULT AS \'Default\'',
'FROM',
'INFORMATION_SCHEMA.TABLES t',
'INNER JOIN',
'INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME',
'WHERE t.TABLE_NAME =', wrapSingleQuote(tableName)
].join(' ');
if (schema) {
sql += "AND t.TABLE_SCHEMA =" + wrapSingleQuote(schema);
sql += 'AND t.TABLE_SCHEMA =' + wrapSingleQuote(schema);
}
return sql;
......@@ -132,12 +130,12 @@ module.exports = (function() {
},
dropTableQuery: function(tableName, options) {
var query = "IF OBJECT_ID('<%= table %>', 'U') IS NOT NULL DROP TABLE <%= table %>";
var query = 'IF OBJECT_ID(\'<%= table %>\', \'U\') IS NOT NULL DROP TABLE <%= table %>';
var values = {
table: this.quoteTable(tableName)
};
return Utils._.template(query)(values).trim() + ";";
return Utils._.template(query)(values).trim() + ';';
},
addColumnQuery: function(table, key, dataType) {
......@@ -187,7 +185,7 @@ module.exports = (function() {
},
renameColumnQuery: function(tableName, attrBefore, attributes) {
var query = "EXEC sp_rename '<%= tableName %>.<%= before %>', '<%= after %>', 'COLUMN';"
var query = 'EXEC sp_rename \'<%= tableName %>.<%= before %>\', \'<%= after %>\', \'COLUMN\';'
, newName = Object.keys(attributes)[0];
return Utils._.template(query)({
......@@ -302,7 +300,7 @@ module.exports = (function() {
},
showIndexesQuery: function(tableName, options) {
var sql = "EXEC sys.sp_helpindex @objname = N'<%= tableName %>';";
var sql = 'EXEC sys.sp_helpindex @objname = N\'<%= tableName %>\';';
return Utils._.template(sql)({
tableName: this.quoteTable(tableName)
});
......@@ -343,7 +341,7 @@ module.exports = (function() {
if (attribute.type instanceof DataTypes.ENUM) {
if (attribute.type.values && !attribute.values) attribute.values = attribute.type.values;
// enums are a special case
template = 'VARCHAR(10) NULL' /* + (attribute.allowNull ? 'NULL' : 'NOT NULL') */;
template += ' CHECK (' + attribute.field + ' IN(' + Utils._.map(attribute.values, function(value) {
......@@ -483,12 +481,12 @@ module.exports = (function() {
'constraint_name = C.CONSTRAINT_NAME',
'FROM',
'INFORMATION_SCHEMA.TABLE_CONSTRAINTS C',
"WHERE C.CONSTRAINT_TYPE = 'FOREIGN KEY'",
"AND C.TABLE_NAME =", wrapSingleQuote(tableName)
'WHERE C.CONSTRAINT_TYPE = \'FOREIGN KEY\'',
'AND C.TABLE_NAME =', wrapSingleQuote(tableName)
].join(' ');
if (table.schema) {
sql += " AND C.TABLE_SCHEMA =" + wrapSingleQuote(table.schema);
sql += ' AND C.TABLE_SCHEMA =' + wrapSingleQuote(table.schema);
}
return sql;
......@@ -608,7 +606,7 @@ module.exports = (function() {
// private methods
function wrapSingleQuote(identifier){
return Utils.addTicks(identifier, "'");
return Utils.addTicks(identifier, '\'');
}
/* istanbul ignore next */
......
......@@ -15,7 +15,6 @@ module.exports = (function() {
raw: false
}, options || {});
var self = this;
this.checkLoggingOption();
};
......@@ -59,8 +58,7 @@ module.exports = (function() {
});
} else {
// QUERY SUPPORT
var results = []
, columns = {};
var results = [];
var request = new self.connection.lib.Request(self.sql, function(err, rowCount) {
promise.emit('sql', self.sql, self.connection.uuid);
......@@ -219,7 +217,7 @@ module.exports = (function() {
Query.prototype.isShowOrDescribeQuery = function() {
var result = false;
result = result || (this.sql.toLowerCase().indexOf("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'") === 0);
result = result || (this.sql.toLowerCase().indexOf('select c.column_name as \'name\', c.data_type as \'type\', c.is_nullable as \'isnull\'') === 0);
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);
......
"use strict";
'use strict';
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, Utils = require('../../utils')
......@@ -87,7 +88,7 @@ ConnectionManager.prototype.connect = function(config) {
});
}).tap(function (connection) {
connection.query("SET time_zone = '" + self.sequelize.options.timezone + "'");
connection.query('SET time_zone = \'' + self.sequelize.options.timezone + '\'');
});
};
ConnectionManager.prototype.disconnect = function(connection) {
......
'use strict';
var Utils = require('../../utils')
, DataTypes = require('../../data-types')
, util = require('util');
, DataTypes = require('../../data-types');
module.exports = (function() {
var QueryGenerator = {
......@@ -351,7 +350,8 @@ module.exports = (function() {
* @return {String} The generated sql query.
*/
getForeignKeysQuery: function(tableName, schemaName) {
return "SELECT CONSTRAINT_NAME as constraint_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = '" + tableName + "' AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='" + schemaName + "' AND REFERENCED_TABLE_NAME IS NOT NULL;";
return 'SELECT CONSTRAINT_NAME as constraint_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = \'' + tableName +
'\' AND CONSTRAINT_NAME!=\'PRIMARY\' AND CONSTRAINT_SCHEMA=\'' + schemaName + '\' AND REFERENCED_TABLE_NAME IS NOT NULL;';
},
/**
......
......@@ -17,7 +17,6 @@ module.exports = (function() {
raw: false
}, options || {});
var self = this;
this.checkLoggingOption();
};
......
"use strict";
'use strict';
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, Utils = require('../../utils')
......@@ -95,7 +96,7 @@ ConnectionManager.prototype.connect = function(config) {
}).tap(function (connection) {
if (self.sequelize.config.keepDefaultTimezone) return;
return new Promise(function (resolve, reject) {
connection.query("SET client_min_messages TO warning; SET TIME ZONE INTERVAL '" + self.sequelize.options.timezone + "' HOUR TO MINUTE").on('error', function (err) {
connection.query('SET client_min_messages TO warning; SET TIME ZONE INTERVAL \'' + self.sequelize.options.timezone + '\' HOUR TO MINUTE').on('error', function (err) {
reject(err);
}).on('end', function () {
resolve();
......
'use strict';
var hstore = require("pg-hstore")({sanitize : true});
var hstore = require('pg-hstore')({sanitize : true});
module.exports = {
stringify: function(data) {
......
......@@ -25,7 +25,7 @@ module.exports = (function() {
},
showSchemasQuery: function() {
return "SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name != 'public' AND schema_name !~ E'^pg_';";
return 'SELECT schema_name FROM information_schema.schemata WHERE schema_name <> \'information_schema\' AND schema_name != \'public\' AND schema_name !~ E\'^pg_\';';
},
versionQuery: function() {
......@@ -95,7 +95,7 @@ module.exports = (function() {
},
showTablesQuery: function() {
return "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';";
return 'SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\';';
},
describeTableQuery: function(tableName, schema) {
......@@ -103,7 +103,10 @@ module.exports = (function() {
schema = 'public';
}
var query = 'SELECT c.column_name as "Field", c.column_default as "Default", c.is_nullable as "Null", CASE WHEN c.udt_name = \'hstore\' THEN c.udt_name ELSE c.data_type END as "Type", (SELECT array_agg(e.enumlabel) FROM pg_catalog.pg_type t JOIN pg_catalog.pg_enum e ON t.oid=e.enumtypid WHERE t.typname=c.udt_name) AS "special" FROM information_schema.columns c WHERE table_name = <%= table %> AND table_schema = <%= schema %>';
var query = 'SELECT c.column_name as "Field", c.column_default as "Default", c.is_nullable as "Null", ' +
'CASE WHEN c.udt_name = \'hstore\' THEN c.udt_name ELSE c.data_type END as "Type", (SELECT array_agg(e.enumlabel) ' +
'FROM pg_catalog.pg_type t JOIN pg_catalog.pg_enum e ON t.oid=e.enumtypid WHERE t.typname=c.udt_name) AS "special" ' +
'FROM information_schema.columns c WHERE table_name = <%= table %> AND table_schema = <%= schema %>';
return Utils._.template(query)({
table: this.escape(tableName),
......@@ -132,7 +135,7 @@ module.exports = (function() {
// Parse nested object
if (smth.conditions) {
var conditions = _.map(this.parseConditionObject(smth.conditions), function generateSql(condition) {
return util.format("%s#>>'{%s}' = '%s'",
return util.format('%s#>>\'{%s}\' = \'%s\'',
_.first(condition.path),
_.rest(condition.path).join(','),
condition.value);
......@@ -148,13 +151,13 @@ module.exports = (function() {
} else {
// Also support json dot notation
var path = smth.path.split('.');
str = util.format("%s#>>'{%s}'",
str = util.format('%s#>>\'{%s}\'',
_.first(path),
_.rest(path).join(','));
}
if (smth.value) {
str += util.format(" = %s", this.escape(smth.value));
str += util.format(' = %s', this.escape(smth.value));
}
return str;
......@@ -338,8 +341,8 @@ module.exports = (function() {
return this.exceptionFn(
'sequelize_upsert',
tableName,
insert + " RETURN 1;",
update + "; RETURN 2",
insert + ' RETURN 1;',
update + '; RETURN 2',
'unique_violation',
'integer'
);
......@@ -452,7 +455,11 @@ module.exports = (function() {
showIndexesQuery: function(tableName, options) {
// This is ARCANE!
var query = "SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' and t.relname = '<%= tableName %>' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;";
var query = 'SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, ' +
'array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) ' +
'AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a ' +
'WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND '+
't.relkind = \'r\' and t.relname = \'<%= tableName %>\' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;';
return Utils._.template(query)({ tableName: tableName });
},
......@@ -621,7 +628,7 @@ module.exports = (function() {
, 'BEGIN'
, '\t<%= body %>'
, 'END;'
, "$$ language '<%= language %>'<%= options %>;"
, '$$ language \'<%= language %>\'<%= options %>;'
].join('\n');
return Utils._.template(sql)({
......@@ -667,7 +674,7 @@ module.exports = (function() {
},
pgEscapeAndQuote: function(val) {
return this.quoteIdentifier(Utils.removeTicks(this.escape(val), "'"));
return this.quoteIdentifier(Utils.removeTicks(this.escape(val), '\''));
},
expandFunctionParamList: function expandFunctionParamList(params) {
......@@ -766,7 +773,7 @@ module.exports = (function() {
, values;
if (dataType.values) {
values = "ENUM('" + dataType.values.join("', '") + "')";
values = 'ENUM(\'' + dataType.values.join('\', \'') + '\')';
} else {
values = dataType.toString().match(/^ENUM\(.+\)/)[0];
}
......@@ -844,7 +851,6 @@ module.exports = (function() {
},
quoteIdentifier: function(identifier, force) {
var _ = Utils._;
if (identifier === '*') return identifier;
if (!force && this.options && this.options.quoteIdentifiers === false) { // default is `true`
// In Postgres, if tables or attributes are created double-quoted,
......@@ -868,23 +874,23 @@ module.exports = (function() {
if (Utils._.isObject(value) && field && (field.type instanceof DataTypes.HSTORE || DataTypes.ARRAY.is(field.type, DataTypes.HSTORE))) {
if (field.type instanceof DataTypes.HSTORE){
return "'" + hstore.stringify(value) + "'";
return '\'' + hstore.stringify(value) + '\'';
} else if (DataTypes.ARRAY.is(field.type, DataTypes.HSTORE)) {
return "ARRAY[" + Utils._.map(value, function(v){return "'" + hstore.stringify(v) + "'::hstore";}).join(",") + "]::HSTORE[]";
return 'ARRAY[' + Utils._.map(value, function(v){return '\'' + hstore.stringify(v) + '\'::hstore';}).join(',') + ']::HSTORE[]';
}
} else if(Utils._.isArray(value) && field && (field.type instanceof DataTypes.RANGE || DataTypes.ARRAY.is(field.type, DataTypes.RANGE))) {
if(field.type instanceof DataTypes.RANGE) { // escape single value
return "'" + range.stringify(value) + "'";
return '\'' + range.stringify(value) + '\'';
}
else if (DataTypes.ARRAY.is(field.type, DataTypes.RANGE)) { // escape array of ranges
return "ARRAY[" + Utils._.map(value, function(v){return "'" + range.stringify(v) + "'";}).join(",") + "]::" + field.type.toString();
return 'ARRAY[' + Utils._.map(value, function(v){return '\'' + range.stringify(v) + '\'';}).join(',') + ']::' + field.type.toString();
}
} else if (field && (field.type instanceof DataTypes.JSON || field.type instanceof DataTypes.JSONB)) {
value = JSON.stringify(value);
} else if (Array.isArray(value) && field && DataTypes.ARRAY.is(field.type, DataTypes.JSON)) {
return "ARRAY[" + value.map(function (v) {
return 'ARRAY[' + value.map(function (v) {
return SqlString.escape(JSON.stringify(v), false, this.options.timezone, this.dialect, field);
}, this).join(",") + "]::JSON[]";
}, this).join(',') + ']::JSON[]';
}
return SqlString.escape(value, false, this.options.timezone, this.dialect, field);
......@@ -898,7 +904,8 @@ module.exports = (function() {
* @return {String} The generated sql query.
*/
getForeignKeysQuery: function(tableName, schemaName) {
return "SELECT conname as constraint_name, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = (SELECT oid FROM pg_class WHERE relname = '" + tableName + "' LIMIT 1) AND r.contype = 'f' ORDER BY 1;";
return 'SELECT conname as constraint_name, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r ' +
'WHERE r.conrelid = (SELECT oid FROM pg_class WHERE relname = \'' + tableName + '\' LIMIT 1) AND r.contype = \'f\' ORDER BY 1;';
},
/**
......
"use strict";
'use strict';
var AbstractConnectionManager = require('../abstract/connection-manager')
, ConnectionManager
, Utils = require('../../utils')
......@@ -49,7 +50,7 @@ ConnectionManager.prototype.getConnection = function(options) {
};
ConnectionManager.prototype.releaseConnection = function(connection, force) {
if (connection.filename === ":memory:" && force !== true) return;
if (connection.filename === ':memory:' && force !== true) return;
if (connection.uuid) {
connection.close();
......
......@@ -58,7 +58,7 @@ NUMBER.prototype.toSql = function() {
};
var INTEGER = function(length) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof INTEGER)) return new INTEGER(options);
......@@ -71,7 +71,7 @@ INTEGER.prototype.toSql = function() {
};
var BIGINT = function(length) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length
};
if (!(this instanceof BIGINT)) return new BIGINT(options);
......@@ -84,12 +84,12 @@ BIGINT.prototype.toSql = function() {
};
var FLOAT = function(length, decimals) {
var options = typeof length === "object" && length || {
var options = typeof length === 'object' && length || {
length: length,
decimals: decimals
};
if (!(this instanceof FLOAT)) return new FLOAT(options);
NUMBER.call(this, options);
NUMBER.call(this, options);
};
util.inherits(FLOAT, BaseTypes.FLOAT);
FLOAT.prototype.key = FLOAT.key = 'FLOAT';
......
......@@ -8,7 +8,7 @@ var Utils = require('../../utils');
@class QueryInterface
@static
*/
var QueryInterface = module.exports = {
module.exports = {
/**
A wrapper that fixes SQLite's inability to remove columns from existing tables.
It will create a backup of the table, drop the table afterwards and create a
......
......@@ -22,7 +22,8 @@ error.BaseError = function() {
tmp.name = this.name = 'SequelizeBaseError';
this.message = tmp.message;
Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(error.BaseError, Error);
......@@ -41,6 +42,10 @@ error.ValidationError = function(message, errors) {
error.BaseError.apply(this, arguments);
this.name = 'SequelizeValidationError';
this.message = 'Validation Error';
/**
* An array of ValidationErrorItems
* @member errors
*/
this.errors = errors || [];
// Use provided error message if available...
......@@ -72,13 +77,6 @@ error.ValidationError.prototype.get = function(path) {
};
/**
* An array of ValidationErrorItems
* @property errors
* @name errors
*/
error.ValidationError.prototype.errors;
/**
* A base class for all database related errors.
* @extends BaseError
* @constructor
......@@ -87,24 +85,39 @@ error.DatabaseError = function (parent) {
error.BaseError.apply(this, [parent.message]);
this.name = 'SequelizeDatabaseError';
/**
* The database specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
/**
* The SQL that triggered the error
* @member sql
*/
this.sql = parent.sql;
};
util.inherits(error.DatabaseError, error.BaseError);
/**
* The database specific error which triggered this one
* @property parent
* @name parent
* The message from the DB.
* @member message
* @name message
*/
error.DatabaseError.prototype.parent;
/**
* The SQL that triggered the error
* @property sql
* @name sql
* The fields of the unique constraint
* @member fields
* @name fields
*/
error.DatabaseError.prototype.sql;
/**
* The value(s) which triggered the error
* @member value
* @name value
*/
/**
* The name of the index that triggered the error
* @member index
* @name index
*/
};
util.inherits(error.DatabaseError, error.BaseError);
/**
* Thrown when a database query times out because of a deadlock
......@@ -176,31 +189,6 @@ error.ExclusionConstraintError = function (options) {
util.inherits(error.ExclusionConstraintError, error.DatabaseError);
/**
* The message from the DB.
* @property message
* @name message
*/
error.DatabaseError.prototype.message;
/**
* The fields of the unique constraint
* @property fields
* @name fields
*/
error.DatabaseError.prototype.fields;
/**
* The value(s) which triggered the error
* @property value
* @name value
*/
error.DatabaseError.prototype.value;
/**
* The name of the index that triggered the error
* @property index
* @name index
*/
error.DatabaseError.prototype.index;
/**
* Validation Error Item
* Instances of this class are included in the `ValidationError.errors` property.
*
......@@ -225,20 +213,16 @@ error.ValidationErrorItem = function(message, type, path, value) {
error.ConnectionError = function (parent) {
error.BaseError.apply(this, [parent ? parent.message : '']);
this.name = 'SequelizeConnectionError';
/**
* The connection specific error which triggered this one
* @member parent
*/
this.parent = parent;
this.original = parent;
};
util.inherits(error.ConnectionError, error.BaseError);
/**
* The connection specific error which triggered this one
* @property parent
* @name parent
*/
error.ConnectionError.prototype.parent;
/**
* Thrown when a connection to a database is refused
* @extends ConnectionError
* @constructor
......
'use strict';
var Utils = require('./utils')
, Mixin = require('./associations/mixin')
, BelongsTo = require('./associations/belongs-to')
, HasOne = require('./associations/has-one')
, HasMany = require('./associations/has-many')
, BelongsToMany = require('./associations/belongs-to-many')
, InstanceValidator = require('./instance-validator')
, DataTypes = require('./data-types')
, QueryTypes = require('./query-types')
, Promise = require("./promise")
, _ = require('lodash')
......@@ -183,7 +179,7 @@ module.exports = (function() {
* @return {Object|any}
*/
Instance.prototype.get = function(key, options) {
if (options === undefined && typeof key === "object") {
if (options === undefined && typeof key === 'object') {
options = key;
key = undefined;
}
......@@ -250,7 +246,8 @@ module.exports = (function() {
*
* When set is called, the previous value of the field is stored, so that you can later see which fields changed (see `changed`).
*
* Set can also be used to build instances for associations, if you have values for those. TODO - mick should probably write something here about how includes in set works - perhaps also even some tests?
* Set can also be used to build instances for associations, if you have values for those.
* TODO(mick): should probably write something here about how includes in set works - perhaps also even some tests?
*
* @see {Model#find} for more information about includes
* @param {String|Object} key
......@@ -270,8 +267,7 @@ module.exports = (function() {
if (typeof key === 'object') {
values = key;
options = value;
options || (options = {});
options = value || {};
if (options.reset) {
this.dataValues = {};
......@@ -316,7 +312,8 @@ module.exports = (function() {
}
}
} else {
options || (options = {});
if (!options)
options = {};
if (!options.raw) {
originalValue = this.dataValues[key];
}
......@@ -364,7 +361,7 @@ module.exports = (function() {
if (_.isString(value)) {
// Only take action on valid boolean strings.
value = (value === "true") ? true : (value === "false") ? false : value;
value = (value === 'true') ? true : (value === 'false') ? false : value;
} else if (_.isNumber(value)) {
// Only take action on valid boolean integers.
......@@ -846,7 +843,7 @@ module.exports = (function() {
* @return {Promise<undefined>}
*/
Instance.prototype.restore = function(options) {
if (!this.Model._timestampAttributes.deletedAt) throw new Error("Model is not paranoid");
if (!this.Model._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
hooks: true,
......@@ -886,7 +883,8 @@ module.exports = (function() {
* ```
*
* @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given
* @param {String|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column.
* If and object is provided, each column is incremented by the value given.
* @param {Object} [options]
* @param {Integer} [options.by=1] The number to increment by
* @param {Transaction} [options.transaction]
......@@ -897,7 +895,9 @@ module.exports = (function() {
Utils.validateParameter(countOrOptions, Object, {
optional: true,
deprecated: Number,
deprecationWarning: 'Increment expects an object as second parameter. Please pass the incrementor as option! ~> instance.increment(' + JSON.stringify(fields) + ', { by: ' + countOrOptions + ' })'
deprecationWarning:
'Increment expects an object as second parameter. Please pass the incrementor as option! ~> instance.increment(' +
JSON.stringify(fields) + ', { by: ' + countOrOptions + ' })'
});
var identifier = this.primaryKeyValues
......@@ -973,7 +973,8 @@ module.exports = (function() {
* ```
*
* @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given
* @param {String|Array|Object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column.
* If and object is provided, each column is decremented by the value given
* @param {Object} [options]
* @param {Integer} [options.by=1] The number to decrement by
* @param {Transaction} [options.transaction]
......@@ -984,7 +985,9 @@ module.exports = (function() {
Utils.validateParameter(countOrOptions, Object, {
optional: true,
deprecated: Number,
deprecationWarning: 'Decrement expects an object as second parameter. Please pass the decrementor as option! ~> instance.decrement(' + JSON.stringify(fields) + ', { by: ' + countOrOptions + ' })'
deprecationWarning:
'Decrement expects an object as second parameter. Please pass the decrementor as option! ~> instance.decrement(' +
JSON.stringify(fields) + ', { by: ' + countOrOptions + ' })'
});
if (countOrOptions === undefined) {
......
......@@ -98,17 +98,20 @@ module.exports = (function() {
var filterFrom = function(migrations, from, callback, options) {
var result = migrations.filter(function(migration) { return migration.isAfter(from, options); });
callback && callback(null, result);
if (callback)
callback(null, result);
};
var filterTo = function(migrations, to, callback, options) {
var result = migrations.filter(function(migration) { return migration.isBefore(to, options); });
callback && callback(null, result);
if (callback)
callback(null, result);
};
var filterByMigrationId = function(migrations, migrationIds, callback) {
var result = migrations.filter(function(migration) { return migrationIds.indexOf(migration.migrationId) === -1;
});
callback && callback(null, result);
if (callback)
callback(null, result);
};
var migrationFiles = fs.readdirSync(this.options.path).filter(function(file) {
......@@ -123,10 +126,6 @@ module.exports = (function() {
return parseInt(a.filename.split('-')[0]) - parseInt(b.filename.split('-')[0]);
});
var existingMigrationIds = migrations.map(function(migration) {
return migration.migrationId;
});
var getPendingMigrations = function(callback) {
getAllMigrationIdsFromDatabase.call(self).success(function(allMigrationIds) {
allMigrationIds = allMigrationIds.map(function(migration) {
......@@ -144,16 +143,16 @@ module.exports = (function() {
if (self.options.to) {
filterTo(migrations, self.options.to, callback);
} else {
callback && callback(null, migrations);
if (callback)
callback(null, migrations);
}
});
} else {
getPendingMigrations(function(err, pendingMigrations) {
if (self.options.to) {
filterTo(pendingMigrations, self.options.to, callback);
}
else {
callback && callback(err, pendingMigrations);
} else if (callback) {
callback(err, pendingMigrations);
}
});
}
......@@ -180,10 +179,6 @@ module.exports = (function() {
return parseInt(a.filename.split('-')[0]) - parseInt(b.filename.split('-')[0]);
});
var existingMigrationIds = migrations.map(function(migration) {
return migration.migrationId;
});
getAllMigrationIdsFromDatabase.call(self)
.then(function(allMigrationIds) {
allMigrationIds = allMigrationIds.map(function(migration) {
......@@ -323,7 +318,7 @@ module.exports = (function() {
}).run();
};
var getLastMigrationIdFromDatabase = Migrator.prototype.getLastMigrationIdFromDatabase = function() {
Migrator.prototype.getLastMigrationIdFromDatabase = function() {
var self = this;
return new Utils.CustomEventEmitter(function(emitter) {
......@@ -350,7 +345,7 @@ module.exports = (function() {
return result;
};
var stringToDate = Migrator.prototype.stringToDate = function(s) {
Migrator.prototype.stringToDate = function(s) {
return moment(getFormattedDateString(s), 'YYYYMMDDHHmmss');
};
......
"use strict";
'use strict';
var Utils = require('./utils')
, Instance = require('./instance')
, Attribute = require('./model/attribute')
, Association = require('./associations/base')
, DataTypes = require('./data-types')
, Util = require('util')
, SqlString = require('./sql-string')
, Transaction = require('./transaction')
, Promise = require('./promise')
, QueryTypes = require('./query-types')
......@@ -16,7 +14,8 @@ var Utils = require('./utils')
module.exports = (function() {
/**
* A Model represents a table in the database. Sometimes you might also see it refererred to as model, or simply as factory. This class should _not_ be instantiated directly, it is created using `sequelize.define`, and already created models can be loaded using `sequelize.import`
* A Model represents a table in the database. Sometimes you might also see it refererred to as model, or simply as factory.
* This class should _not_ be instantiated directly, it is created using `sequelize.define`, and already created models can be loaded using `sequelize.import`
*
* @class Model
* @mixes Hooks
......@@ -314,7 +313,7 @@ module.exports = (function() {
}
if (definition.hasOwnProperty('defaultValue')) {
if (typeof definition.defaultValue === "function" && (
if (typeof definition.defaultValue === 'function' && (
definition.defaultValue === DataTypes.NOW ||
definition.defaultValue === DataTypes.UUIDV4 ||
definition.defaultValue === DataTypes.UUIDV4
......@@ -464,7 +463,8 @@ module.exports = (function() {
* Get the tablename of the model, taking schema into account. The method will return The name as a string if the model has no schema,
* or an object with `tableName`, `schema` and `delimiter` properties.
*
* @param {Object} options The hash of options from any query. You can use one model to access tables with matching schemas by overriding `getTableName` and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2)
* @param {Object} options The hash of options from any query. You can use one model to access tables with matching schemas by overriding `getTableName` and
* using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2)
* @return {String|Object}
*/
Model.prototype.getTableName = function(options) {
......@@ -507,7 +507,10 @@ module.exports = (function() {
* // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
* ```
*
* @param {Array|Object|String|null} options* The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
* @param {Array|Object|String|null} options* The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments.
* To apply simple scopes, pass them as strings. For scope function, pass an object, with a `method` property.
* The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method,
* and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
* @return {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
*/
Model.prototype.scope = function(option) {
......@@ -1088,7 +1091,10 @@ module.exports = (function() {
*/
Model.prototype.findOrInitialize = Model.prototype.findOrBuild = function(options) {
if (!options || !options.where) {
throw new Error('Missing where attribute in the options parameter passed to findOrCreate. Please note that the API has changed, and is now options (an object with where and defaults keys), queryOptions (transaction etc.)');
throw new Error(
'Missing where attribute in the options parameter passed to findOrCreate. ' +
'Please note that the API has changed, and is now options (an object with where and defaults keys), queryOptions (transaction etc.)'
);
}
var self = this
......@@ -1135,7 +1141,10 @@ module.exports = (function() {
, defaultFields;
if (!options || !options.where) {
throw new Error('Missing where attribute in the options parameter passed to findOrCreate. Please note that the API has changed, and is now options (an object with where and defaults keys), queryOptions (transaction etc.)');
throw new Error(
'Missing where attribute in the options parameter passed to findOrCreate. '+
'Please note that the API has changed, and is now options (an object with where and defaults keys), queryOptions (transaction etc.)'
);
}
queryOptions = queryOptions ? Utils._.clone(queryOptions) : {};
......@@ -1523,7 +1532,7 @@ module.exports = (function() {
* @return {Promise<undefined>}
*/
Model.prototype.restore = function(options) {
if (!this._timestampAttributes.deletedAt) throw new Error("Model is not paranoid");
if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
hooks: true,
......
......@@ -2,8 +2,6 @@
var Utils = require('./../utils')
, Helpers = require('../associations/helpers')
, Transaction = require('../transaction')
, util = require('util')
, DataTypes = require('../data-types')
, Promise = require('bluebird');
......
......@@ -77,7 +77,7 @@ Promise.prototype._settlePromiseAt = function (index) {
if (this.$sql && receiver && receiver.emit) {
this.$sql.forEach(function (sql) {
receiver.emit("sql", sql);
receiver.emit('sql', sql);
});
}
};
......@@ -87,19 +87,18 @@ SequelizePromise.all = function (promises) {
var ret = bluebirdAll.call(this, promises);
// Propagate sql events
var self = this;
if (Array.isArray(promises)) {
promises.forEach(function (promise) {
if (Promise.is(promise)) {
promise.on("sql", function (sql) {
ret.emit("sql", sql);
promise.on('sql', function (sql) {
ret.emit('sql', sql);
});
if (!promise.$sql) {
promise.$sql = [];
}
promise.$sql.forEach(function (sql) {
ret.emit("sql", sql);
ret.emit('sql', sql);
});
}
});
......
......@@ -113,16 +113,19 @@ module.exports = (function() {
if (serial) {
serial.options = serial.options || {};
serial.options.before && serial.options.before(serial.klass);
if (serial.options.before)
serial.options.before(serial.klass);
var onSuccess = function() {
serial.options.after && serial.options.after(serial.klass);
if (serial.options.after)
serial.options.after(serial.klass);
self.finishedEmits++;
exec();
};
var onError = function(err) {
serial.options.after && serial.options.after(serial.klass);
if (serial.options.after)
serial.options.after(serial.klass);
self.finishedEmits++;
self.fails.push(err);
exec();
......
......@@ -80,7 +80,7 @@ module.exports = (function() {
attribute.type = self.sequelize.normalizeDataType(attribute.type);
if (attribute.hasOwnProperty('defaultValue')) {
if (typeof attribute.defaultValue === "function" && (
if (typeof attribute.defaultValue === 'function' && (
attribute.defaultValue === DataTypes.NOW ||
attribute.defaultValue === DataTypes.UUIDV4 ||
attribute.defaultValue === DataTypes.UUIDV4
......@@ -707,8 +707,7 @@ module.exports = (function() {
options.plain = options.plain === undefined ? true : options.plain;
var sql = this.QueryGenerator.selectQuery(tableName, options, Model)
, queryOptions = Utils._.extend({ transaction: options.transaction, plain: options.plain }, { raw: true, type: QueryTypes.SELECT })
, self = this;
, queryOptions = Utils._.extend({ transaction: options.transaction, plain: options.plain }, { raw: true, type: QueryTypes.SELECT });
if (attributeSelector === undefined) {
throw new Error('Please pass an attribute selector!');
......
......@@ -540,8 +540,7 @@ module.exports = (function() {
*/
Sequelize.prototype.define = function(modelName, attributes, options) {
options = options || {};
var self = this
, globalOptions = this.options;
var globalOptions = this.options;
if (globalOptions.define) {
options = Utils._.merge({}, globalOptions.define, options);
......@@ -776,7 +775,7 @@ module.exports = (function() {
throw new Error('sequelize.set is only supported for mysql');
}
if (!options.transaction || !(options.transaction instanceof Transaction) ) {
throw new TypeError("options.transaction is required");
throw new TypeError('options.transaction is required');
}
// Override some options, since this isn't a SELECT
......@@ -1117,7 +1116,7 @@ module.exports = (function() {
* @fires success When the transaction has ended (either comitted or rolled back)
*/
Sequelize.prototype.transaction = function(options, autoCallback) {
if (typeof options === "function") {
if (typeof options === 'function') {
autoCallback = options;
options = undefined;
}
......@@ -1194,7 +1193,7 @@ module.exports = (function() {
};
Sequelize.prototype.normalizeDataType = function(Type) {
var type = typeof Type === "function" ? new Type() : Type
var type = typeof Type === 'function' ? new Type() : Type
, dialectTypes = this.dialect.DataTypes || {};
if (dialectTypes[type.key]) {
......
......@@ -51,7 +51,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) {
// for us. Postgres actually has a boolean type with true/false literals,
// but sequelize doesn't use it yet.
if (dialect === 'mssql') {
return "'" + val + "'";
return '\'' + val + '\'';
}
if (dialect === 'sqlite') {
return +!!val;
......@@ -83,7 +83,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) {
if (dialect === 'postgres' || dialect === 'sqlite' || dialect === 'mssql') {
// http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
// http://stackoverflow.com/q/603572/130598
val = val.replace(/'/g, "''");
val = val.replace(/'/g, '\'\'');
} else {
val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
switch (s) {
......@@ -97,7 +97,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) {
}
});
}
return "'" + val + "'";
return '\'' + val + '\'';
};
SqlString.arrayToList = function(array, timeZone, dialect, field) {
......@@ -179,12 +179,12 @@ SqlString.bufferToString = function(buffer, dialect) {
if (dialect === 'postgres') {
// bytea hex format http://www.postgresql.org/docs/current/static/datatype-binary.html
return "E'\\\\x" + hex + "'";
return 'E\'\\\\x' + hex + '\'';
} else if (dialect === 'mssql') {
return "0x" + hex;
return '0x' + hex;
}
return "X'" + hex + "'";
return 'X\'' + hex + '\'';
};
SqlString.objectToValues = function(object, timeZone) {
......@@ -199,8 +199,4 @@ SqlString.objectToValues = function(object, timeZone) {
}
return values.join(', ');
};
function zeroPad(number) {
return (number < 10) ? '0' + number : number;
}
};
\ No newline at end of file
'use strict';
var Utils = require('./utils')
, util = require('util');
var Utils = require('./utils');
/**
* The transaction object is used to identify a running transaction. It is created by calling `Sequelize.transaction()`.
......
'use strict';
var util = require('util')
, DataTypes = require('./data-types')
var DataTypes = require('./data-types')
, SqlString = require('./sql-string')
, lodash = require('lodash')
, ParameterValidator = require('./utils/parameter-validator')
......@@ -172,7 +171,7 @@ var Utils = module.exports = {
if (options.attributes) {
options.attributes = options.attributes.map(function(attr) {
// Object lookups will force any variable to strings, we don't want that for special objects etc
if (typeof attr !== "string") return attr;
if (typeof attr !== 'string') return attr;
// Map attributes to aliased syntax attributes
if (Model.rawAttributes[attr] && attr !== Model.rawAttributes[attr].field) {
return [Model.rawAttributes[attr].field, attr];
......
......@@ -27,7 +27,7 @@ var validate = function(value, expectation, options) {
throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
};
var ParameterValidator = module.exports = {
module.exports = {
check: function(value, expectation, options) {
options = _.extend({
deprecated: false,
......
......@@ -34,7 +34,7 @@ pages:
- ['api/transaction.md', 'API', 'Transaction']
- ['api/datatypes.md', 'API', 'Datatypes']
- ['api/errors.md', 'API', 'Errors']
- ['changelog.md', 'Misc', 'Changelog']
- ['imprint.md', 'Misc', 'Imprint']
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!