Safe Bank Transfer 使用事务
你将构建什么
SQL script 那个创建 accounts 表 and 执行 safe money transfer 之间 two accounts using 事务使用 proper 错误 handling.
学习目标
- 创建 accounts 表使用 balance tracking
- Use BEGIN and COMMIT 到 wrap transfer
- Use ROLLBACK 到撤销 on 失败
- 添加 CHECK constraint 到 prevent 负 balances
前置要求
- INSERT and UPDATE 基础
- 理解的 事务
- ACID 属性
步骤
- 1
创建 accounts 表
创建 accounts 表使用 balance 列那个 cannot go 负 (CHECK constraint).
代码CREATE TABLE accounts ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, balance NUMERIC(10,2) NOT NULL DEFAULT 0 CHECK (balance >= 0) );预期结果
accounts 表是 创建使用非-负 balance constraint.
- 2
Insert accounts
Insert two accounts: one 使用 $1000 and one 使用 $500.
代码INSERT INTO accounts (name, balance) VALUES ('Alice', 1000.00), ('Bob', 500.00);预期结果
Two accounts 是创建使用开始 balances.
- 3
执行 safe transfer
Transfer $300 从 Alice 到 Bob in 事务. 如果要么更新失败, 整个事务 rolls 后面.
代码BEGIN; -- Deduct from Alice UPDATE accounts SET balance = balance - 300.00 WHERE name = 'Alice'; -- Add to Bob UPDATE accounts SET balance = balance + 300.00 WHERE name = 'Bob'; -- Verify: total should be unchanged SELECT SUM(balance) AS total FROM accounts; COMMIT;预期结果
Alice's balance 是 $700, Bob's 是 $800, 总计是 still $1500.
- 4
Handle 失败 transfer
Try 到 transfer $2000 从 Alice (谁仅 有 $700 现在). CHECK constraint prevents 负 balance, 所以我们 roll 后面.
代码BEGIN; UPDATE accounts SET balance = balance - 2000.00 WHERE name = 'Alice'; -- This fails: CHECK (balance >= 0) violated! -- Roll back to undo any changes ROLLBACK; -- Verify balances are unchanged SELECT name, balance FROM accounts;预期结果
事务是 rolled 后面. Balances remain $700 and $800.
- 5
添加索引优化查询
为频繁查询的列创建索引,提升查询性能。索引是数据库性能优化的首要手段,但需注意写操作的开销。
代码-- Create indexes on frequently filtered columns CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_orders_user_id ON orders(user_id); CREATE INDEX idx_orders_created_at ON orders(created_at DESC); -- Verify the index is used EXPLAIN SELECT * FROM orders WHERE user_id = 42;预期结果
EXPLAIN 输出显示使用 idx_orders_user_id 索引扫描而非全表扫描。
自己动手试试
你学到了什么
你 implemented safe financial 事务 using BEGIN, COMMIT, and ROLLBACK, and saw 如何 CHECK constraints protect 数据 integrity — 基础的 ACID-compliant 系统.
相关资源
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。