Transaction Management
Transaction:
涉及到数据库变更的动作:Action, or series of actions, carried out by user or application, which reads or updates contents of database.由用户或应用程序执行的、读取或更新数据库内容的操作,或一系列操作。
ACID:
A:Atomicity 要不就全执行要不就不执行
C:Consistency 操作前后必须保证一致,必须valid
I:Isolation transaction中间的步骤不能对其他变量“隐身”
D:Durability transaction之后的效果必须是永久的 只要做了就是永久有效
Concurrency
Concurrency Problems
(破坏isolation)如果要一起进行transactions,必然出现交错的情况。所以我们需要Concurrency去提高数据库的利用效率,使得同一个数据库反复在同一时刻可以被不同的用户操作。
Lost Update Problem:
Transaction A已经上传成功更新了数据库的数值,但另一个Transaction B被read的时候数据还是原始数据(有一个上传成功的,但是其他的数据还未更新,造成一个Transaction对数据库进行的上传失败)
Uncommited Dependency Problem:
Transaction A在commit之前进行了成功的数据库操作,但还在中间值阶段被另一个transaction B使用,然而A又rollback了(关键:对commit之前的中间值进行操作,而要commit的rollback了)
Incorrect Analysis Problem:
Transaction A读取了多个数据库中的数值,但另一个Transaction B在A读取之后中对数据库数值进行了上传,造成了数据库的不一致。(关键在于多个数据读取)
Serialisability
Schedule
A sequence of the operations by a set of concurrent transactions that preserves the order of the operations in each of the individual transactions. 一堆操作+有序进行。
Serial Schedule
一些Transactions需要Concurrently operates,但没有数据交错的情况。
Non-Serial
与Serial Schedule相对,出现数据交错情况,这样很可能出现Transaction的冲突。
Conflict Serialisability
只读不会出现 对不同的数据操作不会出现Conflict,多个Transaction对相同数据操作并且出现write会出现Conflict,有Conflict并且是Serial Schedule就是Conflict Serialisability
Concurrency Control Techniques
通过delay处理冲突
Locking(Shared Lock)
Read:对某变量上锁,不让其他的transaction访问
Write:只允许一个transaction修改
解锁过早:Incorrect Locking Schedule
违背了Isolation和Atomicity两个Transaction的性质,出现Non-Serial Schedule
A transaction continues to hold a lock until it explicitly
TimeStamping
OCC:Optimistic Concurrency Control
2PL:Two-Phase Locking
解决concurrency的三大问题
解决lost update.Growing phase - acquires all locks but cannot release any locks.
2、Shrinking phase - releases locks but cannot acquire any
new locks.
规则:
每个事务必须在访问项目之前锁定(读取或写),,一旦释放锁定,就不能锁定新项目
步骤:
增长阶段-获取所有的锁,但不能释放任何锁。 ,,缩小相释放锁,但无法获得任何新锁。
未解决:
Cascading Rillback
解决方案:延迟所有变量Lock的Release时间
DeadLocks
解决方案:Abort一个或者多个Transaction//Timeouts(有可能误判) 以及 Deadlock Prevention
TimeOut: Transaction that requests lock will only wait for a system-defined period of time. If lock has not been granted within this period, lock request times out.
Deadlock Prevention: DBMS looks ahead to see if the transaction would cause a deadlock and never allows a deadlock to occur.
DeadLock Prevention
Conservative 2PL:Transaction开始的时候begin之后下一步对所有变量全部加锁。
但也有问题:1、用哪一种锁?2、锁的利用率低下造成Concurrency效率低。
Data Recovery 方法:
1、Backup Mechanism 备份
2、Log file 记录每个Transaction的操作,可以回放查看
3、(重点)Checkpoint 设定检查节点(之前commit的Transaction已经进入Secondary Storage所以什么都不用管),Checkpoint过后有的Transaction但操作在Failure前结束就redo,如果在Failure之前没结束就undo)。
4、Recovery Manager 直接恢复到正常状态