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
39pub fn get_connection(path: impl AsRef<Path>) -> Result<GraphConnection, rusqlite::Error> {
40 let mut conn = Connection::open(path)?;
41 rusqlite::vtab::array::load_module(&conn)?;
42 run_migrations(&mut conn);
43 Ok(GraphConnection(conn))
44}
45
46#[derive(Debug)]
47pub struct ConfigConnection(pub Connection);
48
49impl Deref for ConfigConnection {
50 type Target = Connection;
51
52 fn deref(&self) -> &Self::Target {
53 &self.0
54 }
55}
56
57pub fn get_config_connection(path: impl AsRef<Path>) -> Result<ConfigConnection, rusqlite::Error> {
58 let mut conn = Connection::open(path)?;
59 rusqlite::vtab::array::load_module(&conn)?;
60 run_config_migrations(&mut conn);
61 Ok(ConfigConnection(conn))
62}
63
64pub struct DbHandle<C> {
65 workspace: Arc<Workspace>,
66 conn: Rc<C>,
67}
68
69impl<C> Clone for DbHandle<C> {
70 fn clone(&self) -> Self {
71 Self {
72 workspace: self.workspace.clone(),
73 conn: self.conn.clone(),
74 }
75 }
76}
77
78impl<C> DbHandle<C> {
79 pub fn new(workspace: Arc<Workspace>, conn: Rc<C>) -> Self {
80 Self { workspace, conn }
81 }
82
83 pub fn workspace(&self) -> &Workspace {
84 &self.workspace
85 }
86
87 pub fn conn(&self) -> &C {
88 self.conn.as_ref()
90 }
91}
92
93pub type GraphHandle = DbHandle<GraphConnection>;
94pub type ConfigHandle = DbHandle<ConfigConnection>;
95
96#[derive(Clone)]
97pub struct DbContext {
98 workspace: Arc<Workspace>,
99 graph: GraphHandle,
100 config: ConfigHandle,
101}
102
103impl DbContext {
104 fn build(
105 workspace: Workspace,
106 graph_conn: GraphConnection,
107 config_conn: ConfigConnection,
108 ) -> Self {
109 let workspace = Arc::new(workspace);
110 let graph = DbHandle::new(workspace.clone(), graph_conn.into());
111 let config = DbHandle::new(workspace.clone(), config_conn.into());
112 Self {
113 workspace,
114 graph,
115 config,
116 }
117 }
118
119 pub fn new(
120 workspace: Workspace,
121 graph_conn: GraphConnection,
122 config_conn: ConfigConnection,
123 ) -> Result<Self, rusqlite::Error> {
124 let context = Self::build(workspace, graph_conn, config_conn);
125 if let Some(intended_branch) = Defaults::get_current_branch(context.config().conn()) {
126 let branch_name = active_branch(context.graph().conn())?;
127 if branch_name != intended_branch {
128 connect_branch(context.graph().conn(), &intended_branch)?;
129 }
130 }
131 Ok(context)
132 }
133
134 pub fn new_with_ref(
135 workspace: Workspace,
136 graph_conn: GraphConnection,
137 config_conn: ConfigConnection,
138 history_ref: &str,
139 ) -> Result<Self, rusqlite::Error> {
140 let context = Self::build(workspace, graph_conn, config_conn);
141 let branch_exists = context.graph().conn().query_row(
142 "SELECT EXISTS(SELECT 1 FROM dolt_branches WHERE name = ?1)",
143 [history_ref],
144 |row| row.get::<_, bool>(0),
145 )?;
146 if branch_exists {
147 let branch_name = active_branch(context.graph().conn())?;
148 if branch_name != history_ref {
149 connect_branch(context.graph().conn(), history_ref)?;
150 }
151 } else {
152 checkout(context.graph().conn(), history_ref)?;
153 }
154 Ok(context)
155 }
156
157 pub fn new_raw(
158 workspace: Workspace,
159 graph_conn: GraphConnection,
160 config_conn: ConfigConnection,
161 ) -> Self {
162 Self::build(workspace, graph_conn, config_conn)
163 }
164
165 pub fn set_graph(&mut self, graph_conn: GraphConnection) {
166 self.graph = DbHandle::new(self.workspace.clone(), graph_conn.into());
167 }
168
169 pub fn workspace(&self) -> &Workspace {
170 &self.workspace
171 }
172
173 pub fn graph(&self) -> &GraphHandle {
174 &self.graph
175 }
176
177 pub fn config(&self) -> &ConfigHandle {
178 &self.config
179 }
180
181 pub fn repo_root(&self) -> Result<std::path::PathBuf, ConfigError> {
182 self.workspace.repo_root()
183 }
184
185 pub fn gen_db_path(&self) -> Result<std::path::PathBuf, ConfigError> {
186 self.workspace.gen_db_path()
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use gen_core::config::Workspace;
193 use tempfile::tempdir;
194
195 use super::{DbContext, get_config_connection, get_connection};
196 use crate::{
197 collection::Collection,
198 history::dolt::{active_branch, commit_all, connect_branch, create_branch},
199 operations::Defaults,
200 sample::{NewSample, Sample},
201 };
202
203 fn branch_has_sample(context: &DbContext, sample_name: &str) -> bool {
204 context
205 .graph()
206 .conn()
207 .query_row(
208 "SELECT EXISTS(SELECT 1 FROM samples WHERE name = ?1)",
209 [sample_name],
210 |row| row.get::<_, bool>(0),
211 )
212 .expect("should query sample existence")
213 }
214
215 fn setup_branch_restore_repo() -> Workspace {
216 let temp_dir = tempdir().expect("should create temp repo");
217 let workspace = Workspace::new(temp_dir.keep());
218 workspace.ensure_gen_dir();
219 let graph_path = workspace
220 .graph_db_path()
221 .expect("should resolve graph database path");
222 let config_path = workspace
223 .gen_db_path()
224 .expect("should resolve config database path");
225
226 let graph_conn = get_connection(&graph_path).expect("should open graph connection");
227 let config_conn =
228 get_config_connection(&config_path).expect("should open config connection");
229
230 Collection::create(&graph_conn, "main-collection").expect("should create main collection");
231 commit_all(&graph_conn, "initial commit").expect("should commit initial graph state");
232 create_branch(&graph_conn, "feature").expect("should create feature branch");
233 connect_branch(&graph_conn, "feature").expect("should connect feature branch");
234 Sample::create(
235 &graph_conn,
236 NewSample {
237 name: "feature-sample",
238 is_reference: false,
239 },
240 )
241 .expect("should create feature sample");
242 commit_all(&graph_conn, "feature commit").expect("should commit feature branch change");
243 Defaults::set_current_branch(&config_conn, Some("feature"))
244 .expect("should persist current branch intent");
245
246 workspace
247 }
248
249 #[test]
250 fn test_new_restores_saved_current_branch() {
251 let workspace = setup_branch_restore_repo();
252 let graph_path = workspace
253 .graph_db_path()
254 .expect("should resolve graph database path");
255 let config_path = workspace
256 .gen_db_path()
257 .expect("should resolve config database path");
258 let graph_conn = get_connection(&graph_path).expect("should reopen graph connection");
259 let config_conn =
260 get_config_connection(&config_path).expect("should reopen config connection");
261
262 let context = DbContext::new(workspace, graph_conn, config_conn)
263 .expect("should restore current branch when opening context");
264
265 assert_eq!(
266 active_branch(context.graph().conn()).expect("should resolve active branch"),
267 "feature"
268 );
269 assert!(
270 branch_has_sample(&context, "feature-sample"),
271 "default DbContext construction should restore the saved branch contents"
272 );
273 }
274
275 #[test]
276 fn test_new_with_ref_overrides_saved_current_branch() {
277 let workspace = setup_branch_restore_repo();
278 let graph_path = workspace
279 .graph_db_path()
280 .expect("should resolve graph database path");
281 let config_path = workspace
282 .gen_db_path()
283 .expect("should resolve config database path");
284 let graph_conn = get_connection(&graph_path).expect("should reopen graph connection");
285 let config_conn =
286 get_config_connection(&config_path).expect("should reopen config connection");
287
288 let context = DbContext::new_with_ref(workspace, graph_conn, config_conn, "main")
289 .expect("should open context on explicit ref");
290
291 assert_eq!(
292 active_branch(context.graph().conn()).expect("should resolve active branch"),
293 "main"
294 );
295 assert!(
296 !branch_has_sample(&context, "feature-sample"),
297 "explicit ref checkout should override the saved branch intent"
298 );
299 }
300}