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
12pub 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
20pub 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
30impl Deref for GraphConnection {
32 type Target = Connection;
33
34 fn deref(&self) -> &Self::Target {
35 &self.0
36 }
37}
38
39impl GraphConnection {
40 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 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 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 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, tempfile::TempDir) {
271 let temp_dir = tempdir().expect("should create temp repo");
272 let workspace = Workspace::new(temp_dir.path());
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, temp_dir)
302 }
303
304 #[test]
305 fn test_new_restores_saved_current_branch() {
306 let (workspace, temp_dir) = setup_branch_restore_repo();
307 let base_dir = workspace.base_dir().to_path_buf();
308 let graph_path = workspace
309 .graph_db_path()
310 .expect("should resolve graph database path");
311 let config_path = workspace
312 .gen_db_path()
313 .expect("should resolve config database path");
314 let graph_conn = get_connection(&graph_path).expect("should reopen graph connection");
315 let config_conn =
316 get_config_connection(&config_path).expect("should reopen config connection");
317
318 let context = DbContext::new(workspace, graph_conn, config_conn)
319 .expect("should restore current branch when opening context");
320
321 assert_eq!(
322 active_branch(context.graph().conn()).expect("should resolve active branch"),
323 "feature"
324 );
325 assert!(
326 branch_has_sample(&context, "feature-sample"),
327 "default DbContext construction should restore the saved branch contents"
328 );
329 drop(context);
330 drop(temp_dir);
331 assert!(
332 !base_dir.exists(),
333 "workspace should be removed after context drops"
334 );
335 }
336
337 #[test]
338 fn test_new_with_ref_overrides_saved_current_branch() {
339 let (workspace, temp_dir) = setup_branch_restore_repo();
340 let base_dir = workspace.base_dir().to_path_buf();
341 let graph_path = workspace
342 .graph_db_path()
343 .expect("should resolve graph database path");
344 let config_path = workspace
345 .gen_db_path()
346 .expect("should resolve config database path");
347 let graph_conn = get_connection(&graph_path).expect("should reopen graph connection");
348 let config_conn =
349 get_config_connection(&config_path).expect("should reopen config connection");
350
351 let context = DbContext::new_with_ref(workspace, graph_conn, config_conn, "main")
352 .expect("should open context on explicit ref");
353
354 assert_eq!(
355 active_branch(context.graph().conn()).expect("should resolve active branch"),
356 "main"
357 );
358 assert!(
359 !branch_has_sample(&context, "feature-sample"),
360 "explicit ref checkout should override the saved branch intent"
361 );
362 drop(context);
363 drop(temp_dir);
364 assert!(
365 !base_dir.exists(),
366 "workspace should be removed after context drops"
367 );
368 }
369
370 #[test]
371 fn test_with_transaction_commits_successful_operation() {
372 let conn = test_graph_connection(None).expect("should create graph database");
373 conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
374 .expect("should create transaction fixture table");
375
376 conn.with_transaction(|| {
377 conn.execute(
378 "INSERT INTO transaction_rows (value) VALUES ('committed')",
379 [],
380 )?;
381 Ok(())
382 })
383 .expect("should commit successful transaction operation");
384
385 assert_eq!(
386 conn.query_row("SELECT value FROM transaction_rows", [], |row| row
387 .get::<_, String>(0))
388 .expect("should query committed transaction row"),
389 "committed",
390 "successful transaction should commit its inserted row"
391 );
392 }
393
394 #[test]
395 fn test_with_transaction_rolls_back_sql_error() {
396 let conn = test_graph_connection(None).expect("should create graph database");
397 conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
398 .expect("should create transaction fixture table");
399
400 let error = conn.with_transaction(|| {
401 conn.execute(
402 "INSERT INTO transaction_rows (value) VALUES ('rolled back')",
403 [],
404 )?;
405 conn.execute("INSERT INTO transaction_rows (value) VALUES (NULL)", [])?;
406 Ok(())
407 });
408 let sqlite_error = error.expect_err("constraint violation should fail transaction");
409 assert!(
410 matches!(
411 sqlite_error,
412 rusqlite::Error::SqliteFailure(error, _)
413 if error.code == rusqlite::ErrorCode::ConstraintViolation
414 ),
415 "transaction should return the SQL constraint violation"
416 );
417 assert_eq!(
418 conn.query_row("SELECT COUNT(*) FROM transaction_rows", [], |row| row
419 .get::<_, i64>(0))
420 .expect("should query rolled-back transaction rows"),
421 0,
422 "SQL-error transaction should roll back its valid inserted row"
423 );
424 }
425
426 #[test]
427 fn test_start_and_end_transaction_commits_successful_operation() {
428 let conn = test_graph_connection(None).expect("should create graph database");
429 conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
430 .expect("should create transaction fixture table");
431
432 let in_transaction = conn
433 .start_transaction()
434 .expect("should start transaction explicitly");
435 assert!(
436 !in_transaction,
437 "start_transaction should own a newly opened transaction"
438 );
439 let result = conn
440 .execute(
441 "INSERT INTO transaction_rows (value) VALUES ('explicit commit')",
442 [],
443 )
444 .map(|_| ());
445 conn.end_transaction(in_transaction, result)
446 .expect("should commit explicit transaction");
447
448 assert_eq!(
449 conn.query_row("SELECT value FROM transaction_rows", [], |row| row
450 .get::<_, String>(0))
451 .expect("should query explicitly committed row"),
452 "explicit commit",
453 "end_transaction should commit a successful explicit transaction"
454 );
455 }
456
457 #[test]
458 fn test_end_transaction_rolls_back_explicit_error() {
459 let conn = test_graph_connection(None).expect("should create graph database");
460 conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
461 .expect("should create transaction fixture table");
462
463 let in_transaction = conn
464 .start_transaction()
465 .expect("should start transaction explicitly");
466 let result: rusqlite::Result<()> = (|| {
467 conn.execute(
468 "INSERT INTO transaction_rows (value) VALUES ('explicit rollback')",
469 [],
470 )?;
471 Err(rusqlite::Error::InvalidParameterName(
472 "expected explicit transaction failure".to_string(),
473 ))
474 })();
475 let error = conn.end_transaction(in_transaction, result);
476 assert!(error.is_err(), "explicit failure should return its error");
477 assert_eq!(
478 conn.query_row("SELECT COUNT(*) FROM transaction_rows", [], |row| row
479 .get::<_, i64>(0))
480 .expect("should query explicitly rolled-back rows"),
481 0,
482 "end_transaction should roll back an explicit transaction error"
483 );
484 }
485
486 #[test]
487 fn test_start_transaction_preserves_outer_transaction() {
488 let conn = test_graph_connection(None).expect("should create graph database");
489 conn.execute("CREATE TABLE transaction_rows (value TEXT NOT NULL)", [])
490 .expect("should create transaction fixture table");
491 conn.execute("BEGIN;", [])
492 .expect("should begin outer transaction");
493
494 let in_transaction = conn
495 .start_transaction()
496 .expect("should inspect outer transaction");
497 assert!(
498 in_transaction,
499 "start_transaction should report an existing outer transaction"
500 );
501 let result = conn
502 .execute("INSERT INTO transaction_rows (value) VALUES ('outer')", [])
503 .map(|_| ());
504 conn.end_transaction(in_transaction, result)
505 .expect("should leave outer transaction active");
506
507 assert!(
508 !conn.is_autocommit(),
509 "end_transaction should leave an outer transaction active"
510 );
511 conn.execute("ROLLBACK;", [])
512 .expect("should roll back outer transaction");
513 let row_count: i64 = conn
514 .query_row("SELECT COUNT(*) FROM transaction_rows", [], |row| {
515 row.get(0)
516 })
517 .expect("should count transaction rows");
518 assert_eq!(
519 row_count, 0,
520 "rolling back the outer transaction should discard its inserted row"
521 );
522 }
523
524 #[test]
525 fn test_end_transaction_accepts_dolt_commit_sealing_transaction() {
526 let conn = test_graph_connection(None).expect("should create graph database");
527 Collection::create(&conn, "transaction-commit")
528 .expect("should create Dolt transaction fixture row");
529
530 let in_transaction = conn
531 .start_transaction()
532 .expect("should start transaction explicitly");
533 let result = commit_all(&conn, "transaction commit");
534 let commit_hash = conn
535 .end_transaction(in_transaction, result)
536 .expect("should preserve a Dolt commit that seals its transaction");
537
538 assert_eq!(
539 conn.query_row("SELECT dolt_hashof('HEAD')", [], |row| row
540 .get::<_, gen_core::DoltHashId>(
541 0
542 ))
543 .expect("should query Dolt head after transaction commit"),
544 commit_hash,
545 "end_transaction should preserve a Dolt commit that sealed its transaction"
546 );
547 }
548}