Skip to content
This repository has been archived by the owner on Apr 3, 2022. It is now read-only.

Add info on transaction handling in hooks. #168

Merged
merged 1 commit into from
Oct 21, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion views/docs/latest/hooks.jade
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ block documentation
|
| Model.destroy({username: 'Tom'} /*whereClause argument*/)

h2#associations Associations
h3#associations Associations
p
| For the most part hooks will work the same for instances when being associated except a few things

Expand Down Expand Up @@ -237,3 +237,48 @@ block documentation
code SELECT
|on the associated objects and destroy each instance one by one in order to be able to call the hooks with the right parameters.

h3#transactions A Note About Transactions
p
| Note that many model operations in Sequelize allow you to specify a transaction in the options parameter of the method. If a transaction <em>is</em> specified in the original call, it will be present in the options parameter passed to the hook function. For example, consider the following snippet:

pre.dark-blue
code.javascript
| // Here we use the promise-style of async hooks rather than
| // the callback.
| User.hook('afterCreate', function(user, options) {
| // 'trans' will be available in options.transaction
|
| // This operation will be part of the same transaction as the
| // original User.create call.
| return User.update({
| mood: 'sad'
| }, {
| where: {
| id: user.id
| },
| transaction: options.transaction
| });
| });
|
|
| sequelize.transaction(function(trans) {
| User.create({
| username: 'someguy',
| mood: 'happy'
| }, {
| transaction: trans
| });
| });
|

p
| If we had not included the transaction option in our call to
code User.update
| in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.

h4#internal-transactions Internal Transactions
p
| It is very important to recognize that sequelize may make use of transactions internally for certain operations such as <code> Model.findOrCreate </code>. If your hook functions execute read or write operations that rely on the object's presence in the database, or modify the object's stored values like the example in the preceding section, you should always specify <code>{ transaction: options.transaction }</code>.

p
| If the hook has been called in the process of a transacted operation, this makes sure that your dependent read/write is a part of that same transaction. If the hook is not transacted, you have simply specified <code>{ transaction: null } </code> and can expect the default behaviour.