-[BUG] Fixed `field` support for `increment` and `decrement`.
-[FEATURE/BUG] Raw queries always return all results (including affected rows etc). This means you should change all promise listeners on `sequelize.query` to use `.spread` instead of `.then`, unless you are passing a query type.
#### Backwards compatibility changes
- The default query type for `sequelize.query` is now `RAW` - this means that two arguments (results and metadata) will be returned by default and you should use `.spread`
- The 4th argument to `sequelize.query` has been deprecated in favor of `options.replacements`
# 2.0.0-rc8
-[FEATURE] CLS Support. CLS is also used to automatically pass the transaction to any calls within the callback chain when using `sequelize.transaction(function() ...`.
...
...
@@ -23,7 +28,7 @@
-[BUG]`instance.save()` with `fields: []` (as a result of `.changed()` being `[]`) will no result in a noop instead of an empty update query.
-[BUG] Fixed case where `findOrCreate` could return `[null, true]` when given a `defaults` value that triggered a unique constraint error.
#### Backwards compatability changes
#### Backwards compatibility changes
-`instance.update()` using default fields will now automatically also save and validate values provided via `beforeUpdate` hooks
- Sequelize no longer supports case insensitive mysql enums
-`pg-hstore` has been moved to a devDependency, Postgres users will have to install `pg-hstore` manually alongside `pg`: `$ npm install pg pg-hstore`
...
...
@@ -39,7 +44,7 @@
-[BUG] Sequelize will no longer fail on a postgres constraint error not defined by Sequelize
-[FEATURE] It's now possible to pass an association reference to include. `var Owner = Company.belongsTo(User, {as: 'owner'}; Company.findOne({include: [Owner]});`
#### Backwards compatability changes
#### Backwards compatibility changes
- When updating an instance `_previousDataValues` will now be updated after `afterUpdate` hooks have been run rather than before allowing you to use `changed` in `afterUpdate`
# 2.0.0-rc4
...
...
@@ -52,7 +57,7 @@
-[BUG] Fixed crash/bug when using `include.where` together with `association.scope`
-[BUG] Fixed support for `Instance.destroy()` and `field` for postgres.
#### Backwards compatability changes
#### Backwards compatibility changes
- Some of the string error messages for connection errors have been replaced with actual error instances. Checking for connection errors should now be more consistent.
# 2.0.0-rc3
...
...
@@ -72,7 +77,7 @@
-[INTERNALS] Update `inflection` dependency to v1.5.2
-[REMOVED] Remove query generation syntactic sugar provided by `node-sql`, as well as the dependency on that module
#### Backwards compatability changes
#### Backwards compatibility changes
- When eager-loading a many-to-many association, the attributes of the through table are now accessible through an attribute named after the through model rather than the through table name singularized. i.e. `Task.find({include: Worker})` where the table name for through model `TaskWorker` is `TableTaskWorkers` used to produce `{ Worker: { ..., TableTaskWorker: {...} } }`. It now produces `{ Worker: { ..., TaskWorker: {...} } }`. Does not affect models where table name is auto-defined by Sequelize, or where table name is model name pluralized.
- When using `Model#find()` with an `order` clause, the table name is prepended to the `ORDER BY` SQL. e.g. `ORDER BY Task.id` rather than `ORDER BY id`. The change is to avoid ambiguous column names where there are eager-loaded associations with the same column names. A side effect is that code like `Task.findAll( { include: [ User ], order: [ [ 'Users.id', 'ASC' ] ] } )` will now throw an error. This should be achieved with `Task.findAll( { include: [ User ], order: [ [ User, 'id', 'ASC' ] ] } )` instead.
- Nested HSTORE objects are no longer supported. Use DataTypes.JSON instead.
...
...
@@ -99,7 +104,7 @@
-[FEATURE] Hooks need not return a result - undefined return is interpreted as a resolved promise
-[FEATURE] Added `find()` hooks
#### Backwards compatability changes
#### Backwards compatibility changes
- The `fieldName` property, used in associations with a foreign key object `(A.hasMany(B, { foreignKey: { ... }})`, has been renamed to `name` to avoid confusion with `field`.
- The naming of the join table entry for N:M association getters is now singular (like includes)
- Signature of hooks has changed to pass options to all hooks. Any hooks previously defined like `Model.beforeCreate(values)` now need to be `Model.beforeCreate(values, options)` etc.
...
...
@@ -131,7 +136,7 @@ We are working our way to the first 2.0.0 release candidate.
+ sql 0.35.0 -> 0.39.0
-[INTERNALS] Use a transaction inside `findOrCreate`, and handle unique constraint errors if multiple calls are issues concurrently on the same transaction
#### Backwards compatability changes
#### 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`.
...
...
@@ -170,7 +175,7 @@ We are working our way to the first 2.0.0 release candidate.
-[BUG] Create a composite primary key for doubled linked self reference [#1891](https://github.com/sequelize/sequelize/issues/1891)
-[INTERNALS]`bulkDeleteQuery` was removed from the MySQL / abstract query generator, since it was never used internally. Please use `deleteQuery` instead.
#### Backwards compatability changes
#### Backwards compatibility changes
- Sequelize now returns promises instead of its custom event emitter from most calls. This affects methods that return multiple values (like `findOrCreate` or `findOrInitialize`). If your current callbacks do not accept the 2nd success parameter you might be seeing an array as the first param. Either use `.spread()` for these methods or add another argument to your callback: `.success(instance)` -> `.success(instance, created)`.
-`.success()`/`.done()` and any other non promise methods are now deprecated (we will keep the codebase around for a few versions though). on('sql') persists for debugging purposes.
- Model association calls (belongsTo/hasOne/hasMany) are no longer chainable. (this is to support being able to pass association references to include rather than model/as combinations)
...
...
@@ -195,7 +200,7 @@ We are working our way to the first 2.0.0 release candidate.
-[FEATURE/BUG] hstore values are now parsed on find/findAll. Thanks to @nunofgs [#1560](https://github.com/sequelize/sequelize/pull/1560)
-[FEATURE] Read cli options from a file. Thanks to @codeinvain [#1540](https://github.com/sequelize/sequelize/pull/1540)
#### Backwards compatability changes
#### Backwards compatibility changes
- The `notNull` validator has been removed, use the Schema's `allowNull` property.
- All Validation errors now return a sequelize.ValidationError which inherits from Error.
- selectedValues has been removed for performance reasons, if you depend on this, please open an issue and we will help you work around it.
@@ -474,7 +474,7 @@ Task.drop() // will emit success or failure event
Project.[sync|drop]().then(function(){
// ok ... everything is nice!
}).catch(function(error){
// oooh, did you entered wrong database credentials?
// oooh, did you enter wrong database credentials?
})
```
...
...
@@ -584,7 +584,7 @@ Project.find({
### findOrCreate - Search for a specific element or create it if not available
The method `findOrCreate` can be used to check if a certain element is already existing in the database. If that is the case the method will result in a respective instance. If the element does not yet exist, it will be created.
The method `findOrCreate` can be used to check if a certain element already exists in the database. If that is the case the method will result in a respective instance. If the element does not yet exist, it will be created.
Let's assume we have an empty database with a `User` model which has a `username` and a `job`.
...
...
@@ -637,7 +637,7 @@ User
### findAndCountAll - Search for multiple elements in the database, returns both data and total count
This is a convienience method that combines`findAll()`and`count()`(see below), this is useful when dealing with queries related to pagination where you want to retrieve data with a`limit`and`offset`but also need to know the total number of records that match the query.
This is a convienience method that combines`findAll`()and `count`()(see below), this is useful when dealing with queries related to pagination where you want to retrieve data with a `limit` and `offset`but also need to know the total number of records that match the query.
The success handler will always receive an object with two properties:
...
...
@@ -660,7 +660,7 @@ Project
});
```
The options [object] that you pass to`findAndCountAll()`is the same as for`findAll()`(described below).
The options [object] that you pass to`findAndCountAll`()is the same as for`findAll`()(described below).
### findAll - Search for multiple elements in the database
When you are retrieving data from the database there is a fair chance that you also want to get their associations. This is possible since`v1.6.0`and is called eager loading. The basic idea behind that, is the use of the attribute`include`when you are calling`find`or`findAll`. Lets assume the following setup:
When you are retrieving data from the database there is a fair chance that you also want to get their associations. This is possible since`v1.6.0`and is called eager loading. The basic idea behind that, is the use of the attribute`include` when you are calling `find` or `findAll`. Lets assume the following setup:
Notice that the accessor is plural. This is because the association is many-to-something.
If an association is aliased (using the`as`option), you_must_specify this alias when including the model. Notice how the user's`Tool`s are aliased as`Instruments`above. In order to get that right you have to specify the model you want to load, as well as the alias:
If an association is aliased (using the`as`option), you must specify this alias when including the model. Notice how the user's `Tool`s are aliased as `Instruments`above. In order to get that right you have to specify the model you want to load, as well as the alias:
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function `sequelize.query`.
By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
```js
sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread(function(results,metadata){
// Results will be an empty array and metadata will contain the number of affected rows.
})
```
In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:
```js
sequelize.query("SELECT * FROM `users`",{type:sequelize.QueryTypes.SELECT})
.then(function(users){
// We don't need spread here, since only the results will be returned for select queries
})
```
Several other query types are available. [Peek into the source for details](https://github.com/sequelize/sequelize/blob/master/lib/query-types.js)
A second, optional, argument is the _callee_, which is a model. If you pass a model the returned data will be instances of that model.
```js
// Callee is the model definition. This allows you to easily map a query to a predefined model
sequelize.query('SELECT * FROM projects',Projects).then(function(projects){
// Each record will now be a instance of Project
})
```
# Replacements
Replacements in a query can be done in two different ways, either using named parameters (starting with `:`), or unnamed, represented by a `?`. Replacements are passed in the options object.
* If an array is passed, `?` will be replaced in the order that they appear in the array
* If an object is passed, `:key` will be replaced with the keys from that object. If the object contains keys not found in the query or vice verca, an exception will be thrown.
```js
sequelize.query('SELECT * FROM projects WHERE status = ?',
@@ -225,9 +225,9 @@ var sequelize = new Sequelize('database', 'username', 'password', {
## Executing raw SQL queries
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function`sequelize.query`.
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function `sequelize.query`.
Here is how it works:
Here is how it works:
```js
// Arguments for raw queries
...
...
@@ -324,4 +324,4 @@ sequelize.query('select 1 as `foo.bar.baz`').success(function(rows) {
connection.query("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){
* @param {Boolean} [options.individualHooks=false] Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.
* @param {Boolean} [options.ignoreDuplicates=false] Ignore duplicate values for primary keys? (not supported by postgres)
* @param {Array} [options.updateOnDuplicate] Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated.
* Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed both on the instance, and on the constructor.
* Execute a query on the DB, with the posibility to bypass all the sequelize goodness.
*
* If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.
* By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use `.spread` to access the results.
*
* If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results:
* @param {Instance} [callee] If callee is provided, the returned data will be put into the callee
* @param {Object} [options={}] Query options.
* @param {Boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {Transaction} [options.transaction] The transaction that the query should be executed under
* @param {String} [options.type='SELECT'] The type of query you are executing. The query type affects how results are formatted before they are passed back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to SELECT. The type is a string, but `Sequelize.QueryTypes` is provided is convenience shortcuts. Current options are SELECT, BULKUPDATE and BULKDELETE
* @param {Boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}
* @param {Object|Array} [replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
* @param {String} sql
* @param {Instance|Model} [callee] If callee is provided, the returned data will be put into the callee
* @param {Object} [options={}] Query options.
* @param {Boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
* @param {String} [options.type='RAW'] The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
* @param {Boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
* @param {Boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
* @param {Object|Array} [options.replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
*
* @return {Promise}
*
* @see {Model#build} for more information about callee.
self.sequelize.query('SELECT * FROM '+self.sequelize.queryInterface.QueryGenerator.quoteIdentifier('ParanoidUsers')+' WHERE '+self.sequelize.queryInterface.QueryGenerator.quoteIdentifier('deletedAt')+' IS NOT NULL ORDER BY '+self.sequelize.queryInterface.QueryGenerator.quoteIdentifier('id'),null,{raw:true}).success(function(users){
expect(users[0].username).to.equal('Peter');
expect(users[1].username).to.equal('Paul');
returnself.sequelize.query('SELECT * FROM '+qi('ParanoidUsers')+' WHERE '+qi('deletedAt')+' IS NOT NULL ORDER BY '+qi('id'));