Skip to main content

gen_models/
db.rs

1use std::{ops::Deref, path::Path, rc::Rc, sync::Arc};
2
3use gen_core::{config::Workspace, errors::ConfigError};
4use rusqlite::{Connection, limits::Limit};
5
6use crate::{
7    history::dolt::{active_branch, checkout, connect_branch},
8    migrations::{run_config_migrations, run_migrations},
9    operations::Defaults,
10};
11
12/// Returns the SQLite variable parameter limit for the provided connection.
13pub fn sqlite_parameter_limit(conn: &Connection) -> usize {
14    let limit = conn
15        .limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER)
16        .expect("SQLite parameter limit should be readable");
17    usize::try_from(limit).expect("SQLite parameter limit should be positive")
18}
19
20/// Computes how many rows can be inserted per batch given a parameter count.
21pub fn max_rows_per_batch(conn: &Connection, params_per_row: usize) -> usize {
22    let params_per_row = params_per_row.max(1);
23    let max_params = sqlite_parameter_limit(conn);
24    (max_params / params_per_row).max(1)
25}
26
27#[derive(Debug)]
28pub struct GraphConnection(pub Connection);
29
30/// The Deref lets us use GraphConnection any place a &Connection is expected, such as the generic traits for query
31impl Deref for GraphConnection {
32    type Target = Connection;
33
34    fn deref(&self) -> &Self::Target {
35        &self.0
36    }
37}
38
39impl GraphConnection {
40    /// Starts a plain SQL transaction unless one is already active.
41    ///
42    /// The returned flag is true when the caller already owned the transaction. Pass it to
43    /// [`Self::end_transaction`] so only the transaction started by this method is finalized.
44    pub fn start_transaction(&self) -> rusqlite::Result<bool> {
45        let in_transaction = !self.is_autocommit();
46        if !in_transaction {
47            self.execute("BEGIN;", [])?;
48        }
49        Ok(in_transaction)
50    }
51
52    /// Finishes a transaction started by [`Self::start_transaction`].
53    ///
54    /// An existing transaction remains owned by its caller. Dolt version-control statements can
55    /// seal a transaction opened by this helper themselves, so commit and rollback are
56    /// conditional on the connection still being in a transaction after the operation returns.
57    pub fn end_transaction<T>(
58        &self,
59        in_transaction: bool,
60        result: rusqlite::Result<T>,
61    ) -> rusqlite::Result<T> {
62        if in_transaction || self.is_autocommit() {
63            return result;
64        }
65
66        match result {
67            Ok(value) => {
68                self.execute("COMMIT;", [])?;
69                Ok(value)
70            }
71            Err(error) => {
72                self.execute("ROLLBACK;", [])?;
73                Err(error)
74            }
75        }
76    }
77
78    /// Runs an operation in a plain SQL transaction owned by this helper when needed.
79    ///
80    /// An existing transaction remains owned by its caller. Dolt version-control statements can
81    /// seal a transaction opened by this helper themselves, so commit and rollback are
82    /// conditional on the connection still being in a transaction after the operation returns.
83    pub fn with_transaction<T>(
84        &self,
85        operation: impl FnOnce() -> rusqlite::Result<T>,
86    ) -> rusqlite::Result<T> {
87        let in_transaction = self.start_transaction()?;
88        let result = operation();
89        self.end_transaction(in_transaction, result)
90    }
91}
92
93pub fn get_connection(path: impl AsRef<Path>) -> Result<GraphConnection, rusqlite::Error> {
94    let mut conn = Connection::open(path)?;
95    rusqlite::vtab::array::load_module(&conn)?;
96    run_migrations(&mut conn);
97    Ok(GraphConnection(conn))
98}
99
100#[derive(Debug)]
101pub struct ConfigConnection(pub Connection);
102
103impl Deref for ConfigConnection {
104    type Target = Connection;
105
106    fn deref(&self) -> &Self::Target {
107        &self.0
108    }
109}
110
111pub fn get_config_connection(path: impl AsRef<Path>) -> Result<ConfigConnection, rusqlite::Error> {
112    let mut conn = Connection::open(path)?;
113    rusqlite::vtab::array::load_module(&conn)?;
114    run_config_migrations(&mut conn);
115    Ok(ConfigConnection(conn))
116}
117
118pub struct DbHandle<C> {
119    workspace: Arc<Workspace>,
120    conn: Rc<C>,
121}
122
123impl<C> Clone for DbHandle<C> {
124    fn clone(&self) -> Self {
125        Self {
126            workspace: self.workspace.clone(),
127            conn: self.conn.clone(),
128        }
129    }
130}
131
132impl<C> DbHandle<C> {
133    pub fn new(workspace: Arc<Workspace>, conn: Rc<C>) -> Self {
134        Self { workspace, conn }
135    }
136
137    pub fn workspace(&self) -> &Workspace {
138        &self.workspace
139    }
140
141    pub fn conn(&self) -> &C {
142        // We don't use &self.conn here to get rid of the Rc
143        self.conn.as_ref()
144    }
145}
146
147pub type GraphHandle = DbHandle<GraphConnection>;
148pub type ConfigHandle = DbHandle<ConfigConnection>;
149
150#[derive(Clone)]
151pub struct DbContext {
152    workspace: Arc<Workspace>,
153    graph: GraphHandle,
154    config: ConfigHandle,
155}
156
157impl DbContext {
158    fn build(
159        workspace: Workspace,
160        graph_conn: GraphConnection,
161        config_conn: ConfigConnection,
162    ) -> Self {
163        let workspace = Arc::new(workspace);
164        let graph = DbHandle::new(workspace.clone(), graph_conn.into());
165        let config = DbHandle::new(workspace.clone(), config_conn.into());
166        Self {
167            workspace,
168            graph,
169            config,
170        }
171    }
172
173    pub fn new(
174        workspace: Workspace,
175        graph_conn: GraphConnection,
176        config_conn: ConfigConnection,
177    ) -> Result<Self, rusqlite::Error> {
178        let context = Self::build(workspace, graph_conn, config_conn);
179        if let Some(intended_branch) = Defaults::get_current_branch(context.config().conn()) {
180            let branch_name = active_branch(context.graph().conn())?;
181            if branch_name != intended_branch {
182                connect_branch(context.graph().conn(), &intended_branch)?;
183            }
184        }
185        Ok(context)
186    }
187
188    pub fn new_with_ref(
189        workspace: Workspace,
190        graph_conn: GraphConnection,
191        config_conn: ConfigConnection,
192        history_ref: &str,
193    ) -> Result<Self, rusqlite::Error> {
194        let context = Self::build(workspace, graph_conn, config_conn);
195        let branch_exists = context.graph().conn().query_row(
196            "SELECT EXISTS(SELECT 1 FROM dolt_branches WHERE name = ?1)",
197            [history_ref],
198            |row| row.get::<_, bool>(0),
199        )?;
200        if branch_exists {
201            let branch_name = active_branch(context.graph().conn())?;
202            if branch_name != history_ref {
203                connect_branch(context.graph().conn(), history_ref)?;
204            }
205        } else {
206            checkout(context.graph().conn(), history_ref)?;
207        }
208        Ok(context)
209    }
210
211    pub fn new_raw(
212        workspace: Workspace,
213        graph_conn: GraphConnection,
214        config_conn: ConfigConnection,
215    ) -> Self {
216        Self::build(workspace, graph_conn, config_conn)
217    }
218
219    pub fn set_graph(&mut self, graph_conn: GraphConnection) {
220        self.graph = DbHandle::new(self.workspace.clone(), graph_conn.into());
221    }
222
223    pub fn workspace(&self) -> &Workspace {
224        &self.workspace
225    }
226
227    pub fn graph(&self) -> &GraphHandle {
228        &self.graph
229    }
230
231    pub fn config(&self) -> &ConfigHandle {
232        &self.config
233    }
234
235    pub fn repo_root(&self) -> Result<std::path::PathBuf, ConfigError> {
236        self.workspace.repo_root()
237    }
238
239    pub fn gen_db_path(&self) -> Result<std::path::PathBuf, ConfigError> {
240        self.workspace.gen_db_path()
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use gen_core::config::Workspace;
247    use tempfile::tempdir;
248
249    use super::{DbContext, get_config_connection, get_connection};
250    use crate::{
251        collection::Collection,
252        history::dolt::{active_branch, commit_all, connect_branch, create_branch},
253        operations::Defaults,
254        sample::{NewSample, Sample},
255        test_helpers::get_connection as test_graph_connection,
256    };
257
258    fn branch_has_sample(context: &DbContext, sample_name: &str) -> bool {
259        context
260            .graph()
261            .conn()
262            .query_row(
263                "SELECT EXISTS(SELECT 1 FROM samples WHERE name = ?1)",
264                [sample_name],
265                |row| row.get::<_, bool>(0),
266            )
267            .expect("should query sample existence")
268    }
269
270    fn setup_branch_restore_repo() -> Workspace {
271        let temp_dir = tempdir().expect("should create temp repo");
272        let workspace = Workspace::new(temp_dir.keep());
273        workspace.ensure_gen_dir();
274        let graph_path = workspace
275            .graph_db_path()
276            .expect("should resolve graph database path");
277        let config_path = workspace
278            .gen_db_path()
279            .expect("should resolve config database path");
280
281        let graph_conn = get_connection(&graph_path).expect("should open graph connection");
282        let config_conn =
283            get_config_connection(&config_path).expect("should open config connection");
284
285        Collection::create(&graph_conn, "main-collection").expect("should create main collection");
286        commit_all(&graph_conn, "initial commit").expect("should commit initial graph state");
287        create_branch(&graph_conn, "feature").expect("should create feature branch");
288        connect_branch(&graph_conn, "feature").expect("should connect feature branch");
289        Sample::create(
290            &graph_conn,
291            NewSample {
292                name: "feature-sample",
293                is_reference: false,
294            },
295        )
296        .expect("should create feature sample");
297        commit_all(&graph_conn, "feature commit").expect("should commit feature branch change");
298        Defaults::set_current_branch(&config_conn, Some("feature"))
299            .expect("should persist current branch intent");
300
301        workspace
302    }
303
304    #[test]
305    fn test_new_restores_saved_current_branch() {
306        let workspace = setup_branch_restore_repo();
307        let graph_path = workspace
308            .graph_db_path()
309            .expect("should resolve graph database path");
310        let config_path = workspace
311            .gen_db_path()
312            .expect("should resolve config database path");
313        let graph_conn = get_connection(&graph_path).expect("should reopen graph connection");
314        let config_conn =
315            get_config_connection(&config_path).expect("should reopen config connection");
316
317        let context = DbContext::new(workspace, graph_conn, config_conn)
318            .expect("should restore current branch when opening context");
319
320        assert_eq!(
321            active_branch(context.graph().conn()).expect("should resolve active branch"),
322            "feature"
323        );
324        assert!(
325            branch_has_sample(&context, "feature-sample"),
326            "default DbContext construction should restore the saved branch contents"
327        );
328    }
329
330    #[test]
331    fn test_new_with_ref_overrides_saved_current_branch() {
332        let workspace = setup_branch_restore_repo();
333        let graph_path = workspace
334            .graph_db_path()
335            .expect("should resolve graph database path");
336        let config_path = workspace
337            .gen_db_path()
338            .expect("should resolve config database path");
339        let graph_conn = get_connection(&graph_path).expect("should reopen graph connection");
340        let config_conn =
341            get_config_connection(&config_path).expect("should reopen config connection");
342
343        let context = DbContext::new_with_ref(workspace, graph_conn, config_conn, "main")
344            .expect("should open context on explicit ref");
345
346        assert_eq!(
347            active_branch(context.graph().conn()).expect("should resolve active branch"),
348            "main"
349        );
350        assert!(
351            !branch_has_sample(&context, "feature-sample"),
352            "explicit ref checkout should override the saved branch intent"
353        );
354    }
355
356    #[test]
357    fn test_with_transaction_commits_successful_operation() {
358        let conn = test_graph_connection(None).expect("should create graph database");
359        conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
360            .expect("should create transaction fixture table");
361
362        conn.with_transaction(|| {
363            conn.execute(
364                "INSERT INTO transaction_rows (value) VALUES ('committed')",
365                [],
366            )?;
367            Ok(())
368        })
369        .expect("should commit successful transaction operation");
370
371        assert_eq!(
372            conn.query_row("SELECT value FROM transaction_rows", [], |row| row
373                .get::<_, String>(0))
374                .expect("should query committed transaction row"),
375            "committed",
376            "successful transaction should commit its inserted row"
377        );
378    }
379
380    #[test]
381    fn test_with_transaction_rolls_back_sql_error() {
382        let conn = test_graph_connection(None).expect("should create graph database");
383        conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
384            .expect("should create transaction fixture table");
385
386        let error = conn.with_transaction(|| {
387            conn.execute(
388                "INSERT INTO transaction_rows (value) VALUES ('rolled back')",
389                [],
390            )?;
391            conn.execute("INSERT INTO transaction_rows (value) VALUES (NULL)", [])?;
392            Ok(())
393        });
394        let sqlite_error = error.expect_err("constraint violation should fail transaction");
395        assert!(
396            matches!(
397                sqlite_error,
398                rusqlite::Error::SqliteFailure(error, _)
399                    if error.code == rusqlite::ErrorCode::ConstraintViolation
400            ),
401            "transaction should return the SQL constraint violation"
402        );
403        assert_eq!(
404            conn.query_row("SELECT COUNT(*) FROM transaction_rows", [], |row| row
405                .get::<_, i64>(0))
406                .expect("should query rolled-back transaction rows"),
407            0,
408            "SQL-error transaction should roll back its valid inserted row"
409        );
410    }
411
412    #[test]
413    fn test_start_and_end_transaction_commits_successful_operation() {
414        let conn = test_graph_connection(None).expect("should create graph database");
415        conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
416            .expect("should create transaction fixture table");
417
418        let in_transaction = conn
419            .start_transaction()
420            .expect("should start transaction explicitly");
421        assert!(
422            !in_transaction,
423            "start_transaction should own a newly opened transaction"
424        );
425        let result = conn
426            .execute(
427                "INSERT INTO transaction_rows (value) VALUES ('explicit commit')",
428                [],
429            )
430            .map(|_| ());
431        conn.end_transaction(in_transaction, result)
432            .expect("should commit explicit transaction");
433
434        assert_eq!(
435            conn.query_row("SELECT value FROM transaction_rows", [], |row| row
436                .get::<_, String>(0))
437                .expect("should query explicitly committed row"),
438            "explicit commit",
439            "end_transaction should commit a successful explicit transaction"
440        );
441    }
442
443    #[test]
444    fn test_end_transaction_rolls_back_explicit_error() {
445        let conn = test_graph_connection(None).expect("should create graph database");
446        conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
447            .expect("should create transaction fixture table");
448
449        let in_transaction = conn
450            .start_transaction()
451            .expect("should start transaction explicitly");
452        let result: rusqlite::Result<()> = (|| {
453            conn.execute(
454                "INSERT INTO transaction_rows (value) VALUES ('explicit rollback')",
455                [],
456            )?;
457            Err(rusqlite::Error::InvalidParameterName(
458                "expected explicit transaction failure".to_string(),
459            ))
460        })();
461        let error = conn.end_transaction(in_transaction, result);
462        assert!(error.is_err(), "explicit failure should return its error");
463        assert_eq!(
464            conn.query_row("SELECT COUNT(*) FROM transaction_rows", [], |row| row
465                .get::<_, i64>(0))
466                .expect("should query explicitly rolled-back rows"),
467            0,
468            "end_transaction should roll back an explicit transaction error"
469        );
470    }
471
472    #[test]
473    fn test_start_transaction_preserves_outer_transaction() {
474        let conn = test_graph_connection(None).expect("should create graph database");
475        conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
476            .expect("should create transaction fixture table");
477        conn.execute("BEGIN;", [])
478            .expect("should begin outer transaction");
479
480        let in_transaction = conn
481            .start_transaction()
482            .expect("should inspect outer transaction");
483        assert!(
484            in_transaction,
485            "start_transaction should report an existing outer transaction"
486        );
487        let result = conn
488            .execute("INSERT INTO transaction_rows (value) VALUES ('outer')", [])
489            .map(|_| ());
490        conn.end_transaction(in_transaction, result)
491            .expect("should leave outer transaction active");
492
493        assert!(
494            !conn.is_autocommit(),
495            "end_transaction should leave an outer transaction active"
496        );
497        conn.execute("ROLLBACK;", [])
498            .expect("should roll back outer transaction");
499        let row_count: i64 = conn
500            .query_row("SELECT COUNT(*) FROM transaction_rows", [], |row| {
501                row.get(0)
502            })
503            .expect("should count transaction rows");
504        assert_eq!(
505            row_count, 0,
506            "rolling back the outer transaction should discard its inserted row"
507        );
508    }
509
510    #[test]
511    fn test_end_transaction_accepts_dolt_commit_sealing_transaction() {
512        let conn = test_graph_connection(None).expect("should create graph database");
513        Collection::create(&conn, "transaction-commit")
514            .expect("should create Dolt transaction fixture row");
515
516        let in_transaction = conn
517            .start_transaction()
518            .expect("should start transaction explicitly");
519        let result = commit_all(&conn, "transaction commit");
520        let commit_hash = conn
521            .end_transaction(in_transaction, result)
522            .expect("should preserve a Dolt commit that seals its transaction");
523
524        assert_eq!(
525            conn.query_row("SELECT dolt_hashof('HEAD')", [], |row| row
526                .get::<_, gen_core::DoltHashId>(
527                0
528            ))
529            .expect("should query Dolt head after transaction commit"),
530            commit_hash,
531            "end_transaction should preserve a Dolt commit that sealed its transaction"
532        );
533    }
534}