Edit Page

.transaction()

Fetch a preconfigured, deferred object hooked up to the sails-mysql or sails-postgresql adapter (and consequently the appropriate driver).

await datastore.transaction(during);

or

  • var result = await datastore.transaction(during);

Usage

Argument Type Details
1 during See parameters in the "during usage" table below.
During
Argument Type Details
1 db The leased (transactional) database connection. (See .usingConnection() for more information on what to do with this.)

Note that prior to Sails 1.1.0, the recommended usage of .transaction() expected your "during" code to call a callback (proceed) when it finished. This is no longer necessary as long as you do not actually include a second argument in the function signature of your "during" code.

Result
Type Details
The optional result data sent back from during. In other words, if in your during function you did return 'foo';, then this will be 'foo'.
Errors
Name Type When?
UsageError Thrown if something invalid was passed in.
AdapterError Thrown if something went wrong in the database adapter.
Error Thrown if anything else unexpected happens.

See Concepts > Models and ORM > Errors for examples of negotiating errors in Sails and Waterline.

Example

Subtract the specified amount from one user's balance and add it to another's.

// e.g. in an action:

var flaverr = require('flaverr');

await sails.getDatastore()
.transaction(async (db)=> {

  var myAccount = await BankAccount.findOne({ owner: this.req.session.userId })
  .usingConnection(db);
  if (!myAccount) {
    throw new Error('Consistency violation: Database is corrupted-- logged in user record has gone missing');
  }

  var recipientAccount = await BankAccount.findOne({ owner: inputs.recipientId }).usingConnection(db)
  if (!recipientAccount) {
    throw flaverr('E_NO_SUCH_RECIPIENT', new Error('There is no recipient with that id'));
  }

  // Do the math to subtract from the logged-in user's account balance,
  // and add to the recipient's bank account balance.
  var myNewBalance = myAccount.balance - inputs.amount;

  // If this would put the logged-in user's account balance below zero,
  // then abort.  (The transaction will be rolled back automatically.)
  if (myNewBalance < 0) {
    throw flaverr('E_INSUFFICIENT_FUNDS', new Error('Insufficient funds'));
  }

  // Update the current user's bank account
  await BankAccount.update({ owner: this.req.session.userId })
  .set({
    balance: myNewBalance
  })
  .usingConnection(db);

  // Update the recipient's bank account
  await BankAccount.update({ owner: inputs.recipientId })
  .set({
    balance: recipientAccount.balance + inputs.amount
  })
  .usingConnection(db);
})
.intercept('E_INSUFFICIENT_FUNDS', ()=>'badRequest')
.intercept('E_NO_SUCH_RECIPIENT', ()=>'notFound');

Note that the example above is just a demonstration; in practice, this kind of increment/decrement logic should also include row-level locking. Unsure?.

Is something missing?

If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.

Sails logo
  • Home
  • Get started
  • Support
  • Documentation
  • Documentation

For a better experience on sailsjs.com, update your browser.

Check out the full Sailsconf 2022 playlist on Youtube

Tweet Follow @sailsjs

Documentation

Reference Concepts App structure | Upgrading Contribution guide | Tutorials More

Reference

  • Application
    • Advanced usage
      • Lifecycle
      • sails.LOOKS_LIKE_ASSET_RX
      • sails.getActions()
      • sails.getRouteFor()
      • sails.lift()
      • sails.load()
      • sails.lower()
      • sails.registerAction()
      • sails.registerActionMiddleware()
      • sails.reloadActions()
      • sails.renderView()
      • sails.request()
      • sails.getBaseUrl()
    • sails.config.custom
    • sails.getDatastore()
    • sails.getUrlFor()
    • sails.log()
  • Blueprint API
    • add to
    • create
    • destroy
    • find one
    • find where
    • populate where
    • remove from
    • replace
    • update
  • Command-line interface
    • sails --version
    • sails console
    • sails debug
    • sails generate
    • sails inspect
    • sails lift
    • sails new
  • Configuration
    • sails.config.*
    • sails.config.blueprints
    • sails.config.bootstrap()
    • sails.config.custom
    • sails.config.datastores
    • sails.config.globals
    • sails.config.http
    • sails.config.i18n
    • sails.config.log
    • sails.config.models
    • sails.config.policies
    • sails.config.routes
    • sails.config.security
    • sails.config.session
    • sails.config.sockets
    • sails.config.views
  • Request (`req`)
    • req._startTime
    • req.body
    • req.cookies
    • req.fresh
    • req.headers
    • req.hostname
    • req.ip
    • req.ips
    • req.isSocket
    • req.method
    • req.options
    • req.originalUrl
    • req.params
    • req.path
    • req.protocol
    • req.query
    • req.secure
    • req.signedCookies
    • req.socket
    • req.subdomains
    • req.url
    • req.wantsJSON
    • req.xhr
    • req.accepts()
    • req.acceptsCharsets()
    • req.acceptsLanguages()
    • req.allParams()
    • req.file()
    • req.get()
    • req.is()
    • req.param()
    • req.setLocale()
    • req.setTimeout()
    • req.host
  • Response (`res`)
    • res.attachment()
    • res.badRequest()
    • res.clearCookie()
    • res.cookie()
    • res.forbidden()
    • res.get()
    • res.json()
    • res.jsonp()
    • res.location()
    • res.notFound()
    • res.ok()
    • res.redirect()
    • res.send()
    • res.serverError()
    • res.set()
    • res.status()
    • res.type()
    • res.view()
    • res.negotiate()
  • Waterline (ORM)
    • Datastores
      • .driver
      • .manager
      • .leaseConnection()
      • .sendNativeQuery()
      • .transaction()
    • Models
      • .addToCollection()
      • .archive()
      • .archiveOne()
      • .avg()
      • .count()
      • .create()
      • .createEach()
      • .destroy()
      • .destroyOne()
      • .find()
      • .findOne()
      • .findOrCreate()
      • .getDatastore()
      • .removeFromCollection()
      • .replaceCollection()
      • .stream()
      • .sum()
      • .update()
      • .updateOne()
      • .validate()
      • .native()
      • .query()
    • Queries
      • .catch()
      • .decrypt()
      • .exec()
      • .fetch()
      • .intercept()
      • .limit()
      • .meta()
      • .populate()
      • .skip()
      • .sort()
      • .then()
      • .tolerate()
      • .toPromise()
      • .usingConnection()
      • .where()
    • Records
      • .toJSON()
  • WebSockets
    • Resourceful PubSub
      • .getRoomName()
      • .publish()
      • .subscribe()
      • .unsubscribe()
    • sails.sockets
      • .addRoomMembersToRooms()
      • .blast()
      • .broadcast()
      • .getId()
      • .join()
      • .leave()
      • .leaveAll()
      • .removeRoomMembersFromRooms()
      • sails.sockets.id()
    • Socket client
      • io.sails
      • io.socket
      • SailsSocket
        • Methods
        • Properties
      • io.socket.delete()
      • io.socket.get()
      • io.socket.off()
      • io.socket.on()
      • io.socket.patch()
      • io.socket.post()
      • io.socket.put()
      • io.socket.request()

Built with Love

The Sails framework is built by a web & mobile shop in Austin, TX, with the help of our contributors. We created Sails in 2012 to assist us on Node.js projects. Naturally we open-sourced it. We hope it makes your life a little bit easier!

Sails:
  • What is Sails?
  • Community
  • News
  • For business
About:
  • Our company
  • Security
  • Legal
  • Logos/artwork
Help:
  • Get started
  • Documentation
  • Docs
  • Contribute
  • Take a class

© 2012-2023 The Sails Company. 
The Sails framework is free and open-source under the MIT License. 
Illustrations by Edamame.