Transactions |
![]() ![]() ![]() |
A transaction is a group of related database updates to be treated as a unit that must either happen in its entirety or not at all. From a programmer's point of view, the updates are enclosed between two QMBasic statements, BEGIN TRANSACTION and END TRANSACTION. All writes and deletes appearing during the transaction are cached and only take place when the program executes a COMMIT statement. The program can abort the transaction by executing a ROLLBACK statement which causes all updates to be discarded.
An alternative transaction syntax is available using the TRANSACTION START, TRANSACTION COMMIT and TRANSACTION ABORT statements. The two styles may be mixed in a single application.
Transactions affect the operation of file and record locks. Outside a transaction, locks are released when a write or delete occurs. Because transactional database updates are deferred until the transaction is committed, all locks acquired inside the transaction are held until the commit or rollback. Because of this change to the locking mechanism, converting an application to use transactions is usually rather more complex than simply inserting the transaction control statements into existing programs. The retention of locks can give rise to deadlock situations.
There are some restrictions on what a program may do inside a transaction. In general, QM tries not to enforce prohibitive rules but leaves the application designer to consider the potential impact of the operations embedded inside the transaction. Note carefully, that developers should try to avoid user interactions (e.g. INPUT statements) inside a transaction as these can result in locks being held for long periods if the user does not respond quickly.
Example
BEGIN TRANSACTION READU CUST1.REC FROM CUST.F, CUST1.ID ELSE ROLLBACK CUST1.REC<C.BALANCE> -= TRANSFER.VALUE WRITE CUST1.REC TO CUST.F, CUST1.ID
READU CUST2.REC FROM CUST.F, CUST2.ID ELSE ROLLBACK CUST2.REC<C.BALANCE> += TRANSFER.VALUE WRITE CUST2.REC TO CUST.F, CUST2.ID COMMIT END TRANSACTION
The above program fragment transfers money between two customer accounts. The updates are only committed if the entire transaction is successful. |