1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 //! This module is used to implement database transactions.
17 //! Transaction is auto rollback if not commit by RAII.
18 
19 use asset_definition::Result;
20 
21 use crate::database::Database;
22 
23 /// Transaction for sqlite db
24 #[repr(C)]
25 pub struct Transaction<'a> {
26     db: &'a Database,
27 }
28 
29 impl<'a> Transaction<'a> {
30     /// Create a transaction instance.
new(db: &'a Database) -> Transaction<'a>31     pub(crate) fn new(db: &'a Database) -> Transaction<'a> {
32         Transaction { db }
33     }
34 
35     /// Begin a database transaction.
36     /// Once the transaction is begun, the caller must call the rollback or commit function later.
begin(&mut self) -> Result<()>37     pub(crate) fn begin(&mut self) -> Result<()> {
38         self.db.exec("begin transaction")
39     }
40 
41     /// Rollback the database transaction.
rollback(self) -> Result<()>42     pub(crate) fn rollback(self) -> Result<()> {
43         self.db.exec("rollback")
44     }
45 
46     /// Commit the database transaction.
commit(self) -> Result<()>47     pub(crate) fn commit(self) -> Result<()> {
48         self.db.exec("commit")
49     }
50 }
51