diff --git a/docs/content/docs/guides/transactions.mdx b/docs/content/docs/guides/transactions.mdx index efd3a9d5..21eb0f44 100644 --- a/docs/content/docs/guides/transactions.mdx +++ b/docs/content/docs/guides/transactions.mdx @@ -59,6 +59,6 @@ await db.transaction(async (tx) => { Await every `tx.executeAsync()` and `tx.executeRawAsync()` before the callback returns or before manually finalizing. While an async statement is pending, `tx.execute()`, `tx.executeRaw()`, `tx.commit()`, and `tx.rollback()` throw instead of running out of order. If the callback throws, the wrapper waits for pending async statements before rolling back. A thrown error after an explicit commit or rollback cannot undo that completed transaction. -`tx.commit()` and `tx.rollback()` are synchronous. Their declared return type exposes the native query result fields. The JavaScript helper also adds `rows` at runtime, but that field is not in their declared type. Use them to finalize the transaction, not to retrieve rows. The transaction starts with `BEGIN TRANSACTION`; the global [`NitroSQLite.transaction`](/api/react-native-nitro-sqlite/variables/NitroSQLite) helper also accepts `isExclusive` to use `BEGIN EXCLUSIVE TRANSACTION`. See [transaction modes](/docs/concepts/transactions#transaction-modes) for the SQLite differences. +`tx.commit()` and `tx.rollback()` are synchronous. Their declared return type exposes the native query result fields. The JavaScript helper also adds `rows` at runtime, but that field is not in their declared type. Use them to finalize the transaction, not to retrieve rows. The transaction starts with `BEGIN TRANSACTION`, which runs synchronously like `COMMIT` because a deferred `BEGIN` takes no lock. The global [`NitroSQLite.transaction`](/api/react-native-nitro-sqlite/variables/NitroSQLite) helper also accepts `isExclusive` to use `BEGIN EXCLUSIVE TRANSACTION`, which runs on the connection's background thread because it can wait for another connection's lock. See [transaction modes](/docs/concepts/transactions#transaction-modes) for the SQLite differences. For a fixed list of statements and parameter sets, [batch operations](/docs/guides/batch-operations) need less callback code. See the generated [`Transaction` reference](/api/react-native-nitro-sqlite/interfaces/Transaction) for exact method types. diff --git a/packages/react-native-nitro-sqlite/src/__tests__/session.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/session.test.ts index 788217b8..25091a5f 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/session.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/session.test.ts @@ -133,11 +133,10 @@ describe('open', () => { await expect( db.transaction(async (tx) => tx.execute('SELECT 1').rows.length), ).resolves.toBe(0) - expect(HybridNitroSQLite.executeAsync).toHaveBeenCalledWith( + expect(HybridNitroSQLite.execute).toHaveBeenCalledWith( dbName, 'BEGIN TRANSACTION', undefined, - expect.any(Function), ) expect(HybridNitroSQLite.execute).toHaveBeenCalledWith( dbName, diff --git a/packages/react-native-nitro-sqlite/src/__tests__/transaction.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/transaction.test.ts index 6553dd1e..3f092400 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/transaction.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/transaction.test.ts @@ -18,6 +18,15 @@ beforeEach(() => { afterEach(() => closeDatabaseQueue(dbName)) +/** Native execute mock that fails the listed statements, e.g. "rollback failed" for ROLLBACK. */ +const failOn = + (...queries: string[]) => + (_name: string, query: string) => { + if (queries.includes(query)) + throw new Error(`${query.toLowerCase()} failed`) + return nativeResult() + } + describe('transaction', () => { it('requires an open database', async () => { closeDatabaseQueue(dbName) @@ -35,21 +44,20 @@ describe('transaction', () => { }) expect(result).toBe('finished') - expect(HybridNitroSQLite.executeAsync).toHaveBeenNthCalledWith( + expect(HybridNitroSQLite.execute).toHaveBeenNthCalledWith( 1, dbName, 'BEGIN TRANSACTION', undefined, - expect.any(Function), ) expect(HybridNitroSQLite.execute).toHaveBeenNthCalledWith( - 1, + 2, dbName, 'SELECT ?', [1], ) - expect(HybridNitroSQLite.executeAsync).toHaveBeenNthCalledWith( - 2, + expect(HybridNitroSQLite.executeAsync).toHaveBeenCalledTimes(1) + expect(HybridNitroSQLite.executeAsync).toHaveBeenCalledWith( dbName, 'SELECT ?', [2], @@ -62,6 +70,20 @@ describe('transaction', () => { ) }) + it('starts the callback after transaction() returns', async () => { + const callback = jest.fn(async () => {}) + const pending = transaction(dbName, callback) + + expect(HybridNitroSQLite.execute).toHaveBeenCalledWith( + dbName, + 'BEGIN TRANSACTION', + undefined, + ) + expect(callback).not.toHaveBeenCalled() + await pending + expect(callback).toHaveBeenCalledTimes(1) + }) + it('runs raw queries inside the transaction with the same guards', async () => { const raw = nativeRawResult(['value'], [[1]]) const pendingQuery = deferred() @@ -146,14 +168,14 @@ describe('transaction', () => { queryStarted.resolve() }) await queryStarted.promise - expect(HybridNitroSQLite.execute).not.toHaveBeenCalled() + expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(1) pendingQuery.resolve(nativeResult()) await expect(pendingTransaction).rejects.toThrow( 'Await all tx.executeAsync', ) - expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(1) - expect(HybridNitroSQLite.execute).toHaveBeenCalledWith( + expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(2) + expect(HybridNitroSQLite.execute).toHaveBeenLastCalledWith( dbName, 'ROLLBACK', undefined, @@ -216,8 +238,8 @@ describe('transaction', () => { expect(() => tx.rollback()).toThrow('finalized transaction') }) - expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(1) - expect(HybridNitroSQLite.execute).toHaveBeenCalledWith( + expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(2) + expect(HybridNitroSQLite.execute).toHaveBeenLastCalledWith( dbName, 'ROLLBACK', undefined, @@ -241,9 +263,9 @@ describe('transaction', () => { }) it('converts a rollback failure when handling a callback error', async () => { - jest.mocked(HybridNitroSQLite.execute).mockImplementation(() => { - throw new Error('rollback failed') - }) + jest + .mocked(HybridNitroSQLite.execute) + .mockImplementation(failOn('ROLLBACK')) await expect( transaction(dbName, async () => { @@ -263,7 +285,7 @@ describe('transaction', () => { throw new Error('after commit') }), ).rejects.toThrow('after commit') - expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(1) + expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(2) }) it('serializes transactions behind the same queue', async () => { @@ -362,9 +384,9 @@ describe('transaction', () => { it.each([false, true])( 'rejects a failed manual rollback even when caught: %s', async (caught) => { - jest.mocked(HybridNitroSQLite.execute).mockImplementation(() => { - throw new Error('rollback failed') - }) + jest + .mocked(HybridNitroSQLite.execute) + .mockImplementation(failOn('ROLLBACK')) await expect( transaction(dbName, async (tx) => { if (caught) { @@ -374,18 +396,14 @@ describe('transaction', () => { tx.rollback() }), ).rejects.toThrow('rollback failed') - expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(1) + expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(2) }, ) it('preserves commit and rollback errors in order', async () => { jest .mocked(HybridNitroSQLite.execute) - .mockImplementation((_name, query) => { - throw new Error( - query === 'COMMIT' ? 'commit failed' : 'rollback failed', - ) - }) + .mockImplementation(failOn('COMMIT', 'ROLLBACK')) await expect(transaction(dbName, async () => {})).rejects.toMatchObject({ message: 'commit failed\nRollback failed: rollback failed', cause: { @@ -400,11 +418,7 @@ describe('transaction', () => { it('preserves both errors when manual rollback after a failed commit also fails', async () => { jest .mocked(HybridNitroSQLite.execute) - .mockImplementation((_name, query) => { - throw new Error( - query === 'COMMIT' ? 'commit failed' : 'rollback failed', - ) - }) + .mockImplementation(failOn('COMMIT', 'ROLLBACK')) await expect( transaction(dbName, async (tx) => { expect(() => tx.commit()).toThrow('commit failed') @@ -419,15 +433,29 @@ describe('transaction', () => { ], }, }) - expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(2) + expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(3) }) it('does not roll back when BEGIN fails', async () => { + jest + .mocked(HybridNitroSQLite.execute) + .mockImplementation(failOn('BEGIN TRANSACTION')) + const callback = jest.fn() + await expect(transaction(dbName, callback)).rejects.toThrow( + 'begin transaction failed', + ) + expect(callback).not.toHaveBeenCalled() + expect(HybridNitroSQLite.execute).toHaveBeenCalledTimes(1) + }) + + it('does not roll back when BEGIN EXCLUSIVE fails', async () => { jest .mocked(HybridNitroSQLite.executeAsync) .mockRejectedValue(new Error('begin failed')) const callback = jest.fn() - await expect(transaction(dbName, callback)).rejects.toThrow('begin failed') + await expect(transaction(dbName, callback, true)).rejects.toThrow( + 'begin failed', + ) expect(callback).not.toHaveBeenCalled() expect(HybridNitroSQLite.execute).not.toHaveBeenCalled() }) diff --git a/packages/react-native-nitro-sqlite/src/operations/transaction.ts b/packages/react-native-nitro-sqlite/src/operations/transaction.ts index c299a8bc..09b3742d 100644 --- a/packages/react-native-nitro-sqlite/src/operations/transaction.ts +++ b/packages/react-native-nitro-sqlite/src/operations/transaction.ts @@ -145,10 +145,16 @@ export const transaction = ( // The queue rejects when the database is not open. return queueOperationAsync(queueKey, async () => { try { - await executeAsyncNative( - dbName, - isExclusive ? 'BEGIN EXCLUSIVE TRANSACTION' : 'BEGIN TRANSACTION', - ) + if (isExclusive) { + // BEGIN EXCLUSIVE can wait for other connections' locks, so it stays off the JS thread. + await executeAsyncNative(dbName, 'BEGIN EXCLUSIVE TRANSACTION') + } else { + // A deferred BEGIN takes no lock and returns at once, so it runs synchronously + // like COMMIT instead of making a round trip to the native worker thread. + executeNative(dbName, 'BEGIN TRANSACTION') + // The callback still starts after transaction() returns, as it did with an async BEGIN. + await Promise.resolve() + } state.current = { kind: 'active' }