/** * Transaction 测试 */ import { MemoryEngine } from '../../src/engine/memory'; import { TransactionManager, Transaction } from '../../src/transaction/index'; import { createSchema } from '../../src/table/schema'; describe('Transaction', () => { let engine: MemoryEngine; let tm: TransactionManager; const userSchema = createSchema('users', { id: { type: 'string', primaryKey: true }, name: { type: 'string', required: true }, balance: { type: 'number', default: 0 }, }); beforeEach(async () => { engine = new MemoryEngine(); await engine.open('test-tx', 1); await engine.createTable(userSchema); tm = new TransactionManager(engine); }); afterEach(async () => { await engine.close(); }); it('事务中执行插入', async () => { await tm.execute(async (trx) => { await trx.table('users').insert({ id: '1', name: 'Alice', balance: 100 }); await trx.table('users').insert({ id: '2', name: 'Bob', balance: 50 }); }); expect(await engine.count('users')).toBe(2); }); it('事务中执行混合操作', async () => { await engine.insert('users', [{ id: '1', name: 'Alice', balance: 100 }]); await tm.execute(async (trx) => { await trx.table('users').update({ balance: 200 }).where({ id: '1' }).execute(); await trx.table('users').insert({ id: '2', name: 'Bob', balance: 50 }); }); const rows = await engine.find('users', { table: 'users', where: { id: '1' } }); expect(rows[0].balance).toBe(200); expect(await engine.count('users')).toBe(2); }); it('事务中的 table() 返回相同实例', async () => { await tm.execute(async (trx) => { const t1 = trx.table('users'); const t2 = trx.table('users'); expect(t1).toBe(t2); // 相同表名返回同一实例 }); }); it('Transaction.isCompleted', async () => { let trxRef: Transaction | null = null; await tm.execute(async (trx) => { trxRef = trx; expect(trx.isCompleted()).toBe(false); await trx.table('users').insert({ id: '1', name: 'Alice' }); }); expect(trxRef!.isCompleted()).toBe(true); }); it('事务抛出错误', async () => { await expect(tm.execute(async (trx) => { await trx.table('users').insert({ id: '1', name: 'Alice' }); throw new Error('intentional error'); })).rejects.toThrow('Transaction failed'); // 注意:MemoryEngine 没有回滚,所以数据已经写入 // v0.0.1 的 Transaction 只是错误包装 }); });