Skip to main content

cozo/runtime/db/
multi_tx.rs

1/*
2 * Copyright 2022, The Cozo Project Authors.
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
5 * If a copy of the MPL was not distributed with this file,
6 * You can obtain one at https://mozilla.org/MPL/2.0/.
7 */
8
9use std::collections::btree_map::Entry;
10use std::collections::BTreeMap;
11use std::iter;
12
13use crossbeam::channel::{Receiver, Sender};
14use miette::Result;
15
16use crate::data::functions::current_validity;
17use crate::parse::parse_script;
18use crate::storage::Storage;
19
20use super::{Db, NamedRows, TransactionPayload};
21
22impl<'s, S: Storage<'s>> Db<S> {
23    /// Run a multi-transaction. A command should be sent to `payloads`, and the result should be
24    /// retrieved from `results`. A transaction ends when it receives a `Commit` or `Abort`,
25    /// or when a query is not successful. After a transaction ends, sending / receiving from
26    /// the channels will fail.
27    ///
28    /// Write transactions _may_ block other reads, but we guarantee that this does not happen
29    /// for the RocksDB backend.
30    pub fn run_multi_transaction(
31        &'s self,
32        is_write: bool,
33        payloads: Receiver<TransactionPayload>,
34        results: Sender<Result<NamedRows>>,
35    ) {
36        let tx = if is_write {
37            self.transact_write()
38        } else {
39            self.transact()
40        };
41        let mut cleanups: Vec<(Vec<u8>, Vec<u8>)> = vec![];
42        let mut tx = match tx {
43            Ok(tx) => tx,
44            Err(err) => {
45                let _ = results.send(Err(err));
46                return;
47            }
48        };
49
50        let ts = current_validity();
51        let callback_targets = self.current_callback_targets();
52        let mut callback_collector = BTreeMap::new();
53        let mut write_locks = BTreeMap::new();
54
55        for payload in payloads {
56            match payload {
57                TransactionPayload::Commit => {
58                    for (lower, upper) in cleanups {
59                        if let Err(err) = tx.store_tx.del_range_from_persisted(&lower, &upper) {
60                            eprintln!("{err:?}")
61                        }
62                    }
63
64                    let _ = results.send(tx.commit_tx().map(|_| NamedRows::default()));
65                    #[cfg(not(target_arch = "wasm32"))]
66                    if !callback_collector.is_empty() {
67                        self.send_callbacks(callback_collector)
68                    }
69
70                    break;
71                }
72                TransactionPayload::Abort => {
73                    let _ = results.send(Ok(NamedRows::default()));
74                    break;
75                }
76                TransactionPayload::Query((script, params)) => {
77                    let p =
78                        match parse_script(&script, &params, &self.fixed_rules.read().unwrap(), ts)
79                        {
80                            Ok(p) => p,
81                            Err(err) => {
82                                if results.send(Err(err)).is_err() {
83                                    break;
84                                } else {
85                                    continue;
86                                }
87                            }
88                        };
89
90                    let p = match p.get_single_program() {
91                        Ok(p) => p,
92                        Err(err) => {
93                            if results.send(Err(err)).is_err() {
94                                break;
95                            } else {
96                                continue;
97                            }
98                        }
99                    };
100                    if let Some(write_lock_name) = p.needs_write_lock() {
101                        match write_locks.entry(write_lock_name) {
102                            Entry::Vacant(e) => {
103                                let lock = self
104                                    .obtain_relation_locks(iter::once(e.key()))
105                                    .pop()
106                                    .unwrap();
107                                e.insert(lock);
108                            }
109                            Entry::Occupied(_) => {}
110                        }
111                    }
112
113                    let res = self.execute_single_program(
114                        p,
115                        &mut tx,
116                        &mut cleanups,
117                        ts,
118                        &callback_targets,
119                        &mut callback_collector,
120                    );
121                    if results.send(res).is_err() {
122                        break;
123                    }
124                }
125            }
126        }
127    }
128}