acorn-lib 0.3.2

ACORN library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Database utilities for ACORN.
//!
//! This module provides database connection helpers guarded by a process-global
//! mutex so concurrent operations do not race while still respecting per-handle
//! database paths.
use crate::{
    io::{api::DatabasePersistence, ApiResult},
    util::constants::{
        app::{APPLICATION, DEFAULT_CACHE_TTL_SECONDS, ORGANIZATION, QUALIFIER},
        env::{CACHE_TTL, DATABASE_PATH},
    },
};
use acorn_core::util::to_rfc3339;
use acorn_host::terminal::Label;
use acorn_schema::validation::Validate;
use async_trait::async_trait;
use backend::{params, BackendRow, Connection, Params};
use color_eyre::eyre::eyre;
use core::marker::PhantomData;
use directories::ProjectDirs;
use jiff::{SignedDuration, Timestamp};
use std::{
    env,
    fs::create_dir_all,
    path::{Path, PathBuf},
    sync::{Mutex, OnceLock},
};
use tracing::{debug, info};

pub mod backend;
mod candidate;
mod logbook;
pub(crate) mod macros;
pub mod schema;

pub(crate) use candidate::Provenance;
pub use candidate::{CandidateAction, CandidatePersistence, ResearchActivityCandidate};
pub use logbook::LogbookGraduationPersistence;

use schema::Table;

static CONNECTION_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

/// SQL parameters produced for dynamic queries.
pub type QueryParams = backend::ParamsFromIter<Vec<Box<dyn backend::ToSql>>>;
/// SQL query string paired with its bound parameters.
pub type SelectQuery = (String, QueryParams);
/// Result of a persist operation indicating whether data was downloaded or already existed.
#[derive(Clone, Debug)]
pub enum PersistStatus {
    /// Data was downloaded and persisted (contains row count).
    Downloaded(usize),
    /// Table already contained data, no action taken.
    AlreadyExists,
}
/// Write and access data in a database
#[async_trait]
pub trait Operations {
    /// Insert a value (row) into the database
    fn insert<R>(&self, value: R) -> ApiResult<usize>
    where
        R: Row;
    /// Save data to database
    async fn persist<P>(&self, data: Option<P>) -> ApiResult<usize>
    where
        P: DatabasePersistence + Send;
    /// Download and persist data for a table if the table is empty.
    /// Returns `PersistStatus::Downloaded(n)` if data was downloaded and persisted,
    /// or `PersistStatus::AlreadyExists` if the table already contained data.
    async fn populate(&self, table: impl TableSchemaProvider + Send) -> ApiResult<PersistStatus>;
    /// Select a value from the database
    fn select<T, P>(&self, value: P) -> ApiResult<Option<T>>
    where
        T: Into<Table>,
        P: Params;
}
/// Row metadata for database table mapping
pub trait Row: RowMetadata + Validate {
    /// Returns the table associated with this row type.
    fn table(&self) -> Table;
    /// Returns row field names generated by the `DatabaseRow` derive.
    fn fields() -> &'static [&'static str]
    where
        Self: Sized,
    {
        <Self as RowMetadata>::fields()
    }
    /// Inserts this row into its corresponding table.
    fn insert(self, _conn: &Connection) -> ApiResult<usize>
    where
        Self: Sized;
    /// Selects rows from the database matching this row's field values.
    fn select_all(&self, path: Option<PathBuf>) -> ApiResult<Vec<Self>>
    where
        Self: Sized,
        for<'row> Self: From<&'row BackendRow<'row>>,
    {
        let table = self.table();
        let name = table.name();
        let fields = <Self as RowMetadata>::fields().join(", ");
        let query = format!("SELECT {fields} FROM {name}");
        let (query, params) = self.build_select_query(&query);
        table.rows(&query, params, path.as_ref())
    }
    /// Selects the first row matching this row's filter values and predicate.
    fn select<F>(&self, path: Option<PathBuf>, predicate: F) -> ApiResult<Option<Self>>
    where
        Self: Sized,
        for<'row> Self: From<&'row BackendRow<'row>>,
        F: Fn(&Self) -> bool,
    {
        self.select_all(path).map(|rows| rows.into_iter().find(predicate))
    }
    /// Builds a SQL SELECT query with optional WHERE/ORDER BY clauses.
    fn build_select_query(&self, base: &str) -> SelectQuery;
    /// Get ID for next row (used when inserting new row)
    fn next_row_id(&self, conn: &Connection) -> ApiResult<i64>
    where
        Self: Sized,
    {
        let table = self.table().name();
        conn.query_row(&format!("SELECT COALESCE(MAX(id), 0) + 1 FROM {table}"), params![], |row| row.get(0))
            .map_err(|why| eyre!("=> {} Failed to determine next id for {table} — {why}", Label::fail()))
    }
}
/// Metadata generated by `DatabaseRow` derive for row structs.
pub trait RowMetadata {
    /// Returns the list of field names for the row.
    fn fields() -> &'static [&'static str]
    where
        Self: Sized;
}
/// Table schema provider for database operations
#[async_trait]
pub trait TableSchemaProvider: Copy + Into<Table> + 'static {
    /// Returns all variants for the table type.
    fn all() -> &'static [Self];
    /// Returns the CREATE TABLE SQL statement for this table
    fn create_statement(&self) -> String;
    /// Returns the table name as a string
    fn name(&self) -> &'static str;
    /// Populate the table with data (typically downloaded use API module)
    async fn populate(&self, path: Option<PathBuf>) -> ApiResult<usize>;
    /// Print all table rows
    fn print(self, path: Option<PathBuf>);
    /// Get table rows
    fn rows<R, P>(&self, query: &str, params: P, path: Option<&PathBuf>) -> ApiResult<Vec<R>>
    where
        P: Params,
        for<'row> R: Row + From<&'row BackendRow<'row>>;
}
/// Database handle for a given table schema provider type
#[derive(Clone, Debug)]
pub struct Database<T>
where
    T: TableSchemaProvider,
{
    path: Option<PathBuf>,
    marker: PhantomData<T>,
}
impl<T> Default for Database<T>
where
    T: TableSchemaProvider,
{
    fn default() -> Self {
        Self {
            path: None,
            marker: PhantomData,
        }
    }
}
#[async_trait]
impl<S> Operations for Database<S>
where
    S: TableSchemaProvider + Sync,
{
    fn insert<R>(&self, value: R) -> ApiResult<usize>
    where
        R: Row,
    {
        let row: R = value;
        self.with_connection(|conn| row.insert(conn))
    }
    async fn persist<P>(&self, data: Option<P>) -> ApiResult<usize>
    where
        P: DatabasePersistence + Send,
    {
        let database = Database::<Table>::from_path(self.path.as_ref());
        match data {
            | Some(rows) => rows.persist(database).await,
            | None => Err(eyre!("Failed to persist data")),
        }
    }
    async fn populate(&self, table: impl TableSchemaProvider + Send) -> ApiResult<PersistStatus> {
        match self.row_count(table) {
            | Ok(count) if count > 0 => Ok(PersistStatus::AlreadyExists),
            | Ok(_) => table.into().populate(self.path.clone()).await.map(PersistStatus::Downloaded),
            | Err(why) => Err(why),
        }
    }
    fn select<T, P>(&self, _value: P) -> ApiResult<Option<T>>
    where
        T: Into<Table>,
        P: Params,
    {
        Err(eyre!("Database query is not implemented"))
    }
}
impl<T> Database<T>
where
    T: TableSchemaProvider,
{
    /// Create a new database handle from an optional database path override.
    pub fn from_path(path: Option<impl AsRef<Path>>) -> Self {
        Self {
            path: path.map(|path| path.as_ref().to_path_buf()),
            marker: PhantomData,
        }
    }
    /// Executes a callback using the database path configured on this handle.
    pub fn with_connection<U>(&self, callback: impl FnOnce(&Connection) -> ApiResult<U>) -> ApiResult<U> {
        CONNECTION_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .map_err(|why| eyre!("Failed to acquire database connection lock — {why}"))
            .and_then(|guard| {
                let result = resolve_database_path(self.path.as_ref())
                    .and_then(|db_path| Connection::open(db_path).map_err(|why| eyre!("Failed to open database connection — {why}")))
                    .and_then(|connection| callback(&connection));
                drop(guard);
                result
            })
    }
    /// Get the cache TTL value from environment or use default.
    pub fn cache_ttl(&self) -> SignedDuration {
        #[cfg(feature = "std")]
        {
            if let Ok(env_ttl) = dotenvy::var(CACHE_TTL) {
                if let Ok(seconds) = env_ttl.parse::<i64>() {
                    if seconds > 0 {
                        return SignedDuration::from_secs(seconds);
                    }
                }
            }
        }
        let default_ttl = i64::try_from(DEFAULT_CACHE_TTL_SECONDS).map_or(SignedDuration::MAX, SignedDuration::from_secs);
        if let Ok(env_ttl) = env::var(CACHE_TTL) {
            if let Ok(seconds) = env_ttl.parse::<i64>() {
                if seconds > 0 {
                    return SignedDuration::from_secs(seconds);
                }
            }
        }
        default_ttl
    }
    /// Create one table if it does not exist.
    pub fn migrate_table(&self, table: impl Into<Table>) -> ApiResult<()> {
        let table = table.into();
        self.with_connection(|conn| {
            let statement = table.create_statement();
            conn.execute(&statement, params![])
                .map_err(|why| eyre!("Failed to create table {} — {why}", table.name()))
                .map(|_| ())
        })
    }
    /// Create all tables defined by the variant provider type.
    pub fn migrate(&self) -> ApiResult<()> {
        T::all().iter().copied().try_fold((), |_, table| self.migrate_table(table)).inspect(|_| {
            debug!("{} Database migration", Label::pass());
        })
    }
    /// Delete all rows from a table.
    pub fn clear(&self, table: impl Into<Table>) -> ApiResult<usize> {
        let table = table.into();
        self.with_connection(|conn| {
            conn.execute(&format!("DELETE FROM {}", table.name()), params![]).or_else(|error| {
                if error.to_string().contains("no such table") {
                    Ok(0)
                } else {
                    Err(eyre!("Failed to clear {} — {error}", table.name()))
                }
            })
        })
    }
    /// Delete rows where a timestamp/text column is older than a cutoff value.
    pub fn delete_expired_before(&self, table: impl Into<Table>, column: &str, cutoff: &str) -> ApiResult<usize> {
        let table = table.into();
        let sql = format!("DELETE FROM {} WHERE {} < ?", table.name(), column);
        self.with_connection(|conn| {
            conn.execute(&sql, params![cutoff]).or_else(|error| {
                if error.to_string().contains("no such table") {
                    Ok(0)
                } else {
                    Err(eyre!("Failed to clean up {} — {error}", table.name()))
                }
            })
        })
    }
    /// Count rows in a table.
    pub fn row_count(&self, table: impl Into<Table>) -> ApiResult<usize> {
        let name = table.into().name();
        self.with_connection(|conn| {
            conn.query_row(&format!("SELECT COUNT(*) FROM {}", name), params![], |row| row.get::<_, i64>(0))
                .map_err(|why| eyre!("Failed to count rows in {} — {why}", name))
                .and_then(|count| usize::try_from(count).map_err(|why| eyre!("Failed to convert row count for {} — {why}", name)))
        })
    }
    /// Keep only the most recent `limit` rows using an id/order column pair.
    pub fn trim_to_recent(&self, table: impl Into<Table>, id_column: &str, order_column: &str, limit: usize) -> ApiResult<usize> {
        let table = table.into();
        let sql = format!(
            "DELETE FROM {table} WHERE {id_col} NOT IN (SELECT {id_col} FROM {table} ORDER BY {order_col} DESC LIMIT ?)",
            table = table.name(),
            id_col = id_column,
            order_col = order_column,
        );
        self.with_connection(|conn| {
            conn.execute(&sql, params![limit as i64])
                .map_err(|why| eyre!("Failed to trim {} — {why}", table.name()))
        })
    }
    /// Clean up expired link cache entries and trim validation history.
    pub fn cleanup_expired_cache(&self) -> ApiResult<usize> {
        let ttl = self.cache_ttl();
        let now = Timestamp::now();
        let cutoff = to_rfc3339(now.checked_sub(ttl).unwrap_or(now));
        self.delete_expired_before(Table::LinkCache, "expires_at", &cutoff)
            .and_then(|link_count| {
                self.trim_to_recent(Table::ValidationHistory, "id", "checked_at", 1000).map(|_| {
                    if link_count > 0 {
                        info!("=> {} Cleaned up {link_count} expired cache entries", Label::run());
                    }
                    link_count
                })
            })
    }
    /// Clear all cache-related tables.
    pub fn clear_cache(&self) -> ApiResult<usize> {
        self.clear(Table::LinkCache).and_then(|link_count| {
            self.clear(Table::ValidationHistory).map(|validation_count| {
                let total = link_count.saturating_add(validation_count);
                info!("=> {} Cleared {total} entries from cache tables", Label::pass());
                total
            })
        })
    }
    /// Clear (reset) all data from all tables.
    pub fn reset(&self) -> ApiResult<usize> {
        T::all()
            .iter()
            .copied()
            .try_fold(0usize, |total, table| self.clear(table).map(|count| total.saturating_add(count)))
            .inspect(|&total| {
                info!("=> {} Cleared {total} entries from all tables", Label::pass());
            })
    }
}
fn database_name() -> &'static str {
    #[cfg(feature = "duckdb")]
    {
        "acorn.duckdb"
    }
    #[cfg(not(feature = "duckdb"))]
    {
        "acorn.db"
    }
}
/// Resolve the effective database path from an explicit argument, environment variable, or project defaults.
pub fn resolve_database_path(path: Option<&PathBuf>) -> ApiResult<PathBuf> {
    let path = path
        .cloned()
        .or_else(|| env::var(DATABASE_PATH).ok().filter(|value| !value.trim().is_empty()).map(PathBuf::from));
    match path {
        | Some(path) => Ok(path),
        | None => ProjectDirs::from(QUALIFIER, ORGANIZATION, APPLICATION)
            .ok_or_else(|| eyre!("Failed to determine project directories"))
            .map(|directories| directories.cache_dir().join("database").join(database_name())),
    }
    .and_then(|path| {
        path.parent()
            .map(PathBuf::from)
            .ok_or_else(|| eyre!("Failed to determine database parent directory"))
            .and_then(|parent| {
                create_dir_all(&parent)
                    .map_err(|why| eyre!("Failed to create database directory: {why}"))
                    .map(|_| path)
            })
    })
}
pub(crate) fn transaction<T>(connection: &Connection, operation: impl FnOnce(&Connection) -> ApiResult<T>) -> ApiResult<T> {
    connection
        .execute_batch("BEGIN TRANSACTION")
        .map_err(|why| eyre!("Failed to begin database transaction — {why}"))
        .and_then(|()| match operation(connection) {
            | Ok(value) => connection
                .execute_batch("COMMIT")
                .map_err(|why| eyre!("Failed to commit database transaction — {why}"))
                .map(|()| value),
            | Err(why) => {
                let _rollback = connection.execute_batch("ROLLBACK");
                Err(why)
            }
        })
}

#[cfg(test)]
mod tests;