CI source code analysis (III)-DB transactions, ci source database transactions
(0) Usage
You can use the method provided by the system: $ this-> db-> trans_start (); // start the transaction $ this-> db-> query (); // execute sqls $ this-> db-> trans_complete (); // end the transaction (do not worry about rollback) if! $ This-> db-> trans_status do something; // handle the error
You can also handle commit and rollback: $ this-> db-> trans_begin (); // start the transaction $ this-> db-> query (); // execute sqlsif! $ This-> db-> trans_status $ this-> db-> trans_rollback (); // roll back and handle the error else $ this-> db-> trans_commit (); // submit
(1) handle errors
- Debug mode can be enabled in the development and test environments, and db error messages are displayed directly.
- In the production environment, you need to determine whether to record an error log Based on the tran_staus () method and return an error message to the front-end (I personally think an error should be logged in trans_complete, or the db class provides the error () method to obtain the error information)
(2) multi-layer transactions
- In multi-layer transactions, ci records the transaction level through _ trans_depth and only processes the outermost transaction. That is, when _ trans_depth> 1, trans_start & trans_complete does not work,
- However, _ trans_depth will add and subtract the count only in trans_start and trans_complete. That is, if the transaction is operated manually, the count does not work, and the first trans_commit takes effect (manual execution is indeed difficult to control the transaction level, commit and rollback are difficult to process, so it is best to use the recommended method to process transactions)