diff --git a/src/Database/index.js b/src/Database/index.js index 52fe9f76..196e798c 100644 --- a/src/Database/index.js +++ b/src/Database/index.js @@ -162,6 +162,19 @@ class Database { }) } + /** + * Run a callback inside a transaction + * + * @param {Function} callback + * + * @method transaction + * + * @returns Object + */ + transaction (callback) { + return this.knex.transaction(callback) + } + /** * Starts a global transaction, where all query builder * methods will be part of transaction automatically. diff --git a/test/unit/database.spec.js b/test/unit/database.spec.js index 1523600d..0426db70 100644 --- a/test/unit/database.spec.js +++ b/test/unit/database.spec.js @@ -184,6 +184,15 @@ test.group('Database | QueryBuilder', (group) => { const fn = () => this.database.foo() assert.throw(fn, 'Database.foo is not a function') }) + + test('database.transaction should work', async (assert) => { + await this.database.transaction(function (trx) { + return trx.table('users').insert({ username: 'virk' }) + }) + const firstUser = await this.database.table('users').first() + assert.equal(firstUser.username, 'virk') + await this.database.truncate('users') + }) }) test.group('Database | Manager', () => {