Transaction hooks and returning()

articles/hooks.jpg

Hooks to transactions

@adonisjs/[email protected] added hooks support to transactions

There are two transaction hooks: commit and rollback. commit runs when transaction is all queries inside transaction run successfully and rollback when one or many queries fail.

Attaching to hook to transaction:

await Database.transaction(async (trx) => {
  // Attach transaction "rollback" hook
  trx.after('rollback', async () => {
    console.log('Something went wrong')
  })

  // Attach "commit" hook
  trx.after('commit', async () => {
    console.log('All queries were OK')
  })
  
  // Queries to run
  await trx
    .insertQuery()
    .table('users')
    .insert({ username: 'Example' })
})

returning()

Same Lucid version update adds support for returning() to query builder

returning() can be used to specify which fields to select when executing some database query. For example when updating user and wanting user email and name in return

Database.table('users')
  .update({ name: 'Example' })
  .where({ id: 1})
  .returning(['email', 'name'])

Same can be done with all the other queries, like insert, delete, etc

The Latest