Transactions

Ensure data consistency with ACID-compliant transactions that automatically commit or rollback.

What are Transactions?

Transactions are a way to group multiple database operations into a single unit of work. Either all operations succeed (commit), or all fail (rollback), ensuring data consistency.

Basic Transaction

Use the adapter's transaction methods to execute queries within a transaction:

1import connection from './db/connection';
2
3const adapter = connection.getAdapter();
4
5try {
6  // Begin transaction
7  await adapter.beginTransaction();
8
9  // Perform multiple operations
10  await adapter.query('INSERT INTO users (name, email) VALUES (?, ?)', 
11    ['John Doe', '[email protected]']
12  );
13  
14  await adapter.query('UPDATE accounts SET balance = balance - 100 WHERE user_id = ?',
15    [1]
16  );
17
18  await adapter.query('UPDATE accounts SET balance = balance + 100 WHERE user_id = ?',
19    [2]
20  );
21
22  // Commit if all operations succeed
23  await adapter.commit();
24  console.log('Transaction completed successfully');
25  
26} catch (error) {
27  // Rollback if any operation fails
28  await adapter.rollback();
29  console.error('Transaction failed:', error);
30  throw error;
31}

Using with Models

Combine transactions with your model operations:

1import { User } from './models/User';
2import connection from './db/connection';
3
4async function transferCredits(fromUserId: number, toUserId: number, amount: number) {
5  const adapter = connection.getAdapter();
6
7  try {
8    await adapter.beginTransaction();
9
10    // Get both users
11    const fromUser = await User.find(fromUserId);
12    const toUser = await User.find(toUserId);
13
14    if (!fromUser || !toUser) {
15      throw new Error('User not found');
16    }
17
18    if (fromUser.credits < amount) {
19      throw new Error('Insufficient credits');
20    }
21
22    // Update credits
23    fromUser.credits -= amount;
24    toUser.credits += amount;
25
26    // Save both users
27    await fromUser.save();
28    await toUser.save();
29
30    // Commit transaction
31    await adapter.commit();
32    
33    return { success: true, message: 'Transfer completed' };
34    
35  } catch (error) {
36    await adapter.rollback();
37    return { success: false, message: error.message };
38  }
39}

Transaction Patterns

Try-Catch-Finally Pattern

1async function performComplexOperation() {
2  const adapter = connection.getAdapter();
3  let transactionStarted = false;
4
5  try {
6    await adapter.beginTransaction();
7    transactionStarted = true;
8
9    // Your operations here
10    await adapter.query('INSERT INTO orders (user_id, total) VALUES (?, ?)', [1, 100]);
11    await adapter.query('UPDATE inventory SET stock = stock - 1 WHERE product_id = ?', [5]);
12
13    await adapter.commit();
14    return { success: true };
15    
16  } catch (error) {
17    if (transactionStarted) {
18      await adapter.rollback();
19    }
20    console.error('Transaction error:', error);
21    return { success: false, error: error.message };
22  }
23}

Helper Function Pattern

utils/transaction.ts
1export async function withTransaction<T>(
2  adapter: any,
3  callback: () => Promise<T>
4): Promise<T> {
5  try {
6    await adapter.beginTransaction();
7    const result = await callback();
8    await adapter.commit();
9    return result;
10  } catch (error) {
11    await adapter.rollback();
12    throw error;
13  }
14}
15
16// Usage
17import { withTransaction } from './utils/transaction';
18
19const result = await withTransaction(adapter, async () => {
20  await adapter.query('INSERT INTO ...', []);
21  await adapter.query('UPDATE ...', []);
22  return { completed: true };
23});

Real-World Examples

E-commerce Order Processing

services/orderService.ts
1import connection from '../db/connection';
2import { Order } from '../models/Order';
3import { Product } from '../models/Product';
4import { User } from '../models/User';
5
6export async function createOrder(
7  userId: number,
8  items: Array<{ productId: number; quantity: number }>
9) {
10  const adapter = connection.getAdapter();
11
12  try {
13    await adapter.beginTransaction();
14
15    // Calculate total and validate stock
16    let total = 0;
17    const orderItems: any[] = [];
18
19    for (const item of items) {
20      const product = await Product.find(item.productId);
21      
22      if (!product) {
23        throw new Error(`Product ${item.productId} not found`);
24      }
25
26      if (product.stock < item.quantity) {
27        throw new Error(`Insufficient stock for ${product.name}`);
28      }
29
30      total += product.price * item.quantity;
31      orderItems.push({
32        productId: product.id,
33        quantity: item.quantity,
34        price: product.price
35      });
36
37      // Reduce stock
38      product.stock -= item.quantity;
39      await product.save();
40    }
41
42    // Create order
43    const order = await Order.create({
44      userId,
45      total,
46      status: 'pending',
47      createdAt: new Date()
48    });
49
50    // Create order items
51    for (const item of orderItems) {
52      await adapter.query(
53        'INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)',
54        [order.id, item.productId, item.quantity, item.price]
55      );
56    }
57
58    // Commit transaction
59    await adapter.commit();
60
61    return { success: true, orderId: order.id };
62
63  } catch (error) {
64    await adapter.rollback();
65    console.error('Order creation failed:', error);
66    return { success: false, error: error.message };
67  }
68}

Bank Transfer

services/bankService.ts
1export async function transferMoney(
2  fromAccountId: number,
3  toAccountId: number,
4  amount: number
5) {
6  const adapter = connection.getAdapter();
7
8  try {
9    await adapter.beginTransaction();
10
11    // Lock accounts for update (prevent concurrent modifications)
12    const fromAccount = await adapter.query(
13      'SELECT * FROM accounts WHERE id = ? FOR UPDATE',
14      [fromAccountId]
15    );
16
17    const toAccount = await adapter.query(
18      'SELECT * FROM accounts WHERE id = ? FOR UPDATE',
19      [toAccountId]
20    );
21
22    if (!fromAccount[0] || !toAccount[0]) {
23      throw new Error('Account not found');
24    }
25
26    if (fromAccount[0].balance < amount) {
27      throw new Error('Insufficient funds');
28    }
29
30    // Debit from source account
31    await adapter.query(
32      'UPDATE accounts SET balance = balance - ? WHERE id = ?',
33      [amount, fromAccountId]
34    );
35
36    // Credit to destination account
37    await adapter.query(
38      'UPDATE accounts SET balance = balance + ? WHERE id = ?',
39      [amount, toAccountId]
40    );
41
42    // Record transaction
43    await adapter.query(
44      `INSERT INTO transactions 
45       (from_account_id, to_account_id, amount, type, created_at) 
46       VALUES (?, ?, ?, 'transfer', NOW())`,
47      [fromAccountId, toAccountId, amount]
48    );
49
50    await adapter.commit();
51
52    return { 
53      success: true, 
54      message: `Transferred $${amount} successfully` 
55    };
56
57  } catch (error) {
58    await adapter.rollback();
59    return { 
60      success: false, 
61      message: error.message 
62    };
63  }
64}

User Registration with Profile

services/authService.ts
1export async function registerUser(userData: {
2  username: string;
3  email: string;
4  password: string;
5  profile: {
6    firstName: string;
7    lastName: string;
8    dateOfBirth: Date;
9  };
10}) {
11  const adapter = connection.getAdapter();
12
13  try {
14    await adapter.beginTransaction();
15
16    // Check if user already exists
17    const existing = await adapter.query(
18      'SELECT id FROM users WHERE email = ? OR username = ?',
19      [userData.email, userData.username]
20    );
21
22    if (existing.length > 0) {
23      throw new Error('User already exists');
24    }
25
26    // Create user
27    const userResult = await adapter.query(
28      'INSERT INTO users (username, email, password_hash, created_at) VALUES (?, ?, ?, NOW())',
29      [userData.username, userData.email, userData.password]
30    );
31
32    const userId = userResult.insertId || userResult.lastID;
33
34    // Create user profile
35    await adapter.query(
36      `INSERT INTO user_profiles 
37       (user_id, first_name, last_name, date_of_birth) 
38       VALUES (?, ?, ?, ?)`,
39      [userId, userData.profile.firstName, userData.profile.lastName, userData.profile.dateOfBirth]
40    );
41
42    // Create default settings
43    await adapter.query(
44      'INSERT INTO user_settings (user_id, theme, notifications) VALUES (?, ?, ?)',
45      [userId, 'light', true]
46    );
47
48    await adapter.commit();
49
50    return { success: true, userId };
51
52  } catch (error) {
53    await adapter.rollback();
54    return { success: false, error: error.message };
55  }
56}

Transaction Isolation Levels

Different databases support different isolation levels. Check your database documentation:

1// PostgreSQL example
2await adapter.query('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
3await adapter.beginTransaction();
4
5// Your queries here...
6
7await adapter.commit();

Nested Transactions (Savepoints)

Some databases support savepoints for nested transactions:

1try {
2  await adapter.beginTransaction();
3
4  // First operation
5  await adapter.query('INSERT INTO table1 ...');
6
7  // Create savepoint
8  await adapter.query('SAVEPOINT sp1');
9
10  try {
11    // Second operation
12    await adapter.query('INSERT INTO table2 ...');
13  } catch (error) {
14    // Rollback to savepoint
15    await adapter.query('ROLLBACK TO SAVEPOINT sp1');
16  }
17
18  // Continue with transaction
19  await adapter.query('INSERT INTO table3 ...');
20
21  await adapter.commit();
22} catch (error) {
23  await adapter.rollback();
24}

Best Practices

✓ Do's

  • Keep transactions as short as possible
  • Always use try-catch to handle errors
  • Always rollback on errors
  • Validate data before starting transaction
  • Use transactions for operations that must be atomic
  • Log transaction failures for debugging

✗ Don'ts

  • Don't forget to commit or rollback
  • Don't perform slow operations inside transactions
  • Don't make external API calls within transactions
  • Don't hold transactions open longer than necessary
  • Don't nest transactions without savepoint support

Next Steps