Skip to main content

cozo/runtime/db/
backup.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
9#![allow(unused_imports)]
10
11use std::path::Path;
12use std::sync::atomic::Ordering;
13
14use itertools::Itertools;
15use miette::{bail, Diagnostic, Result};
16use smartstring::SmartString;
17use thiserror::Error;
18
19use crate::data::tuple::{Tuple, TupleT};
20use crate::runtime::relation::{AccessLevel, InsufficientAccessLevel};
21use crate::storage::Storage;
22
23use super::{Db, ImportIntoIndex};
24
25impl<'s, S: Storage<'s>> Db<S> {
26    /// Backup the running database into an Sqlite file
27    #[allow(unused_variables)]
28    pub fn backup_db(&'s self, out_file: impl AsRef<Path>) -> Result<()> {
29        #[cfg(feature = "storage-sqlite")]
30        {
31            let sqlite_db = crate::new_cozo_sqlite(out_file)?;
32            if sqlite_db.relation_store_id.load(Ordering::SeqCst) != 0 {
33                bail!("Cannot create backup: data exists in the target database.");
34            }
35            let mut tx = self.transact()?;
36            let iter = tx.store_tx.range_scan(&[], &[0xFF]);
37            sqlite_db.db.batch_put(iter)?;
38            tx.commit_tx()?;
39            Ok(())
40        }
41        #[cfg(not(feature = "storage-sqlite"))]
42        bail!("backup requires the 'storage-sqlite' feature to be enabled")
43    }
44
45    /// Restore from an Sqlite backup
46    #[allow(unused_variables)]
47    pub fn restore_backup(&'s self, in_file: impl AsRef<Path>) -> Result<()> {
48        #[cfg(feature = "storage-sqlite")]
49        {
50            let sqlite_db = crate::new_cozo_sqlite(in_file)?;
51            let mut s_tx = sqlite_db.transact()?;
52            {
53                let mut tx = self.transact()?;
54                let store_id = tx.relation_store_id.load(Ordering::SeqCst);
55                if store_id != 0 {
56                    bail!(
57                        "Cannot restore backup: data exists in the current database. \
58                You can only restore into a new database (store id: {}).",
59                        store_id
60                    );
61                }
62                tx.commit_tx()?;
63            }
64            let iter = s_tx.store_tx.total_scan();
65            self.db.batch_put(iter)?;
66            s_tx.commit_tx()?;
67            Ok(())
68        }
69        #[cfg(not(feature = "storage-sqlite"))]
70        bail!("backup requires the 'storage-sqlite' feature to be enabled")
71    }
72
73    /// Import data from relations in a backup file.
74    /// The target stored relations must already exist in the database, and it must not
75    /// have any associated indices. If you want to import into relations with indices,
76    /// use [Db::import_relations].
77    ///
78    /// Note that triggers and callbacks are _not_ run for the relations, if any exists.
79    /// If you need to activate triggers or callbacks, use queries with parameters.
80    #[allow(unused_variables)]
81    pub fn import_from_backup(
82        &'s self,
83        in_file: impl AsRef<Path>,
84        relations: &[String],
85    ) -> Result<()> {
86        #[cfg(not(feature = "storage-sqlite"))]
87        bail!("backup requires the 'storage-sqlite' feature to be enabled");
88
89        #[cfg(feature = "storage-sqlite")]
90        {
91            let rel_names = relations.iter().map(SmartString::from).collect_vec();
92            let locks = self.obtain_relation_locks(rel_names.iter());
93            let _guards = locks.iter().map(|l| l.read().unwrap()).collect_vec();
94
95            let source_db = crate::new_cozo_sqlite(in_file)?;
96            let mut src_tx = source_db.transact()?;
97            let mut dst_tx = self.transact_write()?;
98
99            for relation in relations {
100                if relation.contains(':') {
101                    bail!(ImportIntoIndex(relation.to_string()))
102                }
103                let src_handle = src_tx.get_relation(relation, false)?;
104                let dst_handle = dst_tx.get_relation(relation, false)?;
105
106                if !dst_handle.indices.is_empty() {
107                    #[derive(Debug, Error, Diagnostic)]
108                    #[error("Cannot import data into relation {0} from backup as the relation has indices")]
109                    #[diagnostic(code(tx::bare_import_with_indices))]
110                    #[diagnostic(help("Use `import_relations()` instead"))]
111                    pub(crate) struct RestoreIntoRelWithIndices(pub(crate) String);
112
113                    bail!(RestoreIntoRelWithIndices(dst_handle.name.to_string()))
114                }
115
116                if dst_handle.access_level < AccessLevel::Protected {
117                    bail!(InsufficientAccessLevel(
118                        dst_handle.name.to_string(),
119                        "data import".to_string(),
120                        dst_handle.access_level
121                    ));
122                }
123
124                let src_lower = Tuple::default().encode_as_key(src_handle.id);
125                let src_upper = Tuple::default().encode_as_key(src_handle.id.next());
126
127                let data_it = src_tx.store_tx.range_scan(&src_lower, &src_upper).map(
128                    |src_pair| -> Result<(Vec<u8>, Vec<u8>)> {
129                        let (mut src_k, mut src_v) = src_pair?;
130                        dst_handle.amend_key_prefix(&mut src_k);
131                        dst_handle.amend_key_prefix(&mut src_v);
132                        Ok((src_k, src_v))
133                    },
134                );
135                for result in data_it {
136                    let (key, val) = result?;
137                    dst_tx.store_tx.put(&key, &val)?;
138                }
139            }
140
141            src_tx.commit_tx()?;
142            dst_tx.commit_tx()
143        }
144    }
145}