1use std::{ops::Deref, rc::Rc, sync::Arc};
2
3use gen_core::{config::Workspace, errors::ConfigError};
4use rusqlite::Connection;
5
6#[derive(Debug)]
7pub struct GraphConnection(pub Connection);
8
9impl Deref for GraphConnection {
11 type Target = Connection;
12
13 fn deref(&self) -> &Self::Target {
14 &self.0
15 }
16}
17
18#[derive(Debug)]
19pub struct OperationsConnection(pub Connection);
20
21impl Deref for OperationsConnection {
22 type Target = Connection;
23
24 fn deref(&self) -> &Self::Target {
25 &self.0
26 }
27}
28
29pub struct DbHandle<C> {
30 workspace: Arc<Workspace>,
31 conn: Rc<C>,
32}
33
34impl<C> Clone for DbHandle<C> {
35 fn clone(&self) -> Self {
36 Self {
37 workspace: self.workspace.clone(),
38 conn: self.conn.clone(),
39 }
40 }
41}
42
43impl<C> DbHandle<C> {
44 pub fn new(workspace: Arc<Workspace>, conn: Rc<C>) -> Self {
45 Self { workspace, conn }
46 }
47
48 pub fn workspace(&self) -> &Workspace {
49 &self.workspace
50 }
51
52 pub fn conn(&self) -> &C {
53 self.conn.as_ref()
55 }
56}
57
58pub type GraphHandle = DbHandle<GraphConnection>;
59pub type OperationsHandle = DbHandle<OperationsConnection>;
60
61#[derive(Clone)]
62pub struct DbContext {
63 workspace: Arc<Workspace>,
64 graph: GraphHandle,
65 operations: OperationsHandle,
66}
67
68impl DbContext {
69 pub fn new(
70 workspace: Workspace,
71 graph_conn: GraphConnection,
72 operations_conn: OperationsConnection,
73 ) -> Self {
74 let workspace = Arc::new(workspace);
75 let graph = DbHandle::new(workspace.clone(), graph_conn.into());
76 let operations = DbHandle::new(workspace.clone(), operations_conn.into());
77 Self {
78 workspace,
79 graph,
80 operations,
81 }
82 }
83
84 pub fn set_graph(&mut self, graph_conn: GraphConnection) {
85 self.graph = DbHandle::new(self.workspace.clone(), graph_conn.into());
86 }
87
88 pub fn workspace(&self) -> &Workspace {
89 &self.workspace
90 }
91
92 pub fn graph(&self) -> &GraphHandle {
93 &self.graph
94 }
95
96 pub fn operations(&self) -> &OperationsHandle {
97 &self.operations
98 }
99
100 pub fn repo_root(&self) -> Result<std::path::PathBuf, ConfigError> {
101 self.workspace.repo_root()
102 }
103
104 pub fn gen_db_path(&self) -> Result<std::path::PathBuf, ConfigError> {
105 self.workspace.gen_db_path()
106 }
107}