Skip to main content

mongreldb_kit/
db.rs

1//! Database handle for `mongreldb-kit`.
2
3use crate::error::{KitError, Result};
4use crate::internal::{ensure_internal_tables, internal_tables_core};
5use crate::schema::to_core_schema;
6use mongreldb_core::epoch::Snapshot;
7use mongreldb_core::memtable::Row as CoreRow;
8use mongreldb_core::memtable::Value as CoreValue;
9use mongreldb_core::schema::Schema as CoreSchema;
10use mongreldb_core::Database as CoreDatabase;
11use mongreldb_core::{AggState, ApproxAgg, NativeAgg, NativeAggResult, RowId};
12use mongreldb_kit_core::schema::IndexKind as KitIndexKind;
13use mongreldb_kit_core::schema::Schema as KitSchema;
14use mongreldb_kit_core::schema::Table as KitTable;
15use mongreldb_kit_core::{ProcedureSpec, TriggerSpec, ViewSpec};
16use serde_json::Value;
17
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21
22const SCHEMA_FILE: &str = "kit_schema.json";
23
24/// A named default-value provider registered by the application.
25pub type DefaultProvider = Box<dyn Fn() -> Value + Send + Sync>;
26
27/// The result of [`Database::explain`]: a static description of a predicate's
28/// index push-down, without running the query.
29#[derive(Debug, Clone)]
30pub struct ExplainPlan {
31    /// Whether at least one native index condition pushes down (vs. a full scan).
32    pub index_accelerated: bool,
33    /// Whether the push-down is exact — the whole predicate translated, so no
34    /// Rust-side residual re-filtering is needed.
35    pub exact: bool,
36    /// The kind of each pushed condition (e.g. `BitmapEq`, `RangeInt`, `Ann`).
37    pub pushed_conditions: Vec<String>,
38}
39
40/// A row paired with its Jaccard set-similarity to a query set (`0.0..=1.0`).
41#[derive(Debug, Clone)]
42pub struct SimilarRow {
43    pub row: crate::schema::Row,
44    pub similarity: f64,
45}
46
47/// Collect the string members of a set-valued column cell. Accepts either a
48/// JSON array value or a JSON string holding an array (how the Kit stores
49/// `json`/`text` set columns); anything else yields the empty set.
50fn parse_string_set(value: Option<&Value>) -> std::collections::HashSet<String> {
51    let arr = match value {
52        Some(Value::Array(a)) => Some(a.clone()),
53        Some(Value::String(s)) => serde_json::from_str::<Value>(s)
54            .ok()
55            .and_then(|v| v.as_array().cloned()),
56        _ => None,
57    };
58    arr.into_iter()
59        .flatten()
60        .filter_map(|v| match v {
61            Value::String(s) => Some(s),
62            Value::Number(n) => Some(n.to_string()),
63            Value::Bool(b) => Some(b.to_string()),
64            _ => None,
65        })
66        .collect()
67}
68
69/// Which aggregate to maintain incrementally.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum IncrementalAggKind {
72    Count,
73    Sum,
74    Min,
75    Max,
76    Avg,
77}
78
79/// The result of [`Database::incremental_aggregate`].
80#[derive(Debug, Clone)]
81pub struct IncrementalAggregate {
82    /// The exact aggregate value at the current epoch: a JSON number, or `null`
83    /// when no rows matched (`COUNT` returns `0`, not null).
84    pub value: Value,
85    /// `true` when produced by merging only newly-committed rows (the fast
86    /// path); `false` when a full recompute was required (cold cache, a delete,
87    /// pending writes, or the same epoch as the cached state).
88    pub incremental: bool,
89    /// Rows processed in the delta pass (`0` for a full recompute).
90    pub delta_rows: u64,
91}
92
93/// Stable per-`(table, column, agg, filter)` cache key for the engine's
94/// incremental-aggregate cache. Deterministic within a process (fixed-seed
95/// hasher); the cache itself is per-`Db`, so cross-process stability is moot.
96fn incremental_cache_key(
97    table_id: u32,
98    column: Option<u16>,
99    agg: IncrementalAggKind,
100    conditions: &[mongreldb_core::query::Condition],
101) -> u64 {
102    use std::hash::{Hash, Hasher};
103    let mut h = std::collections::hash_map::DefaultHasher::new();
104    table_id.hash(&mut h);
105    column.hash(&mut h);
106    (agg as u8).hash(&mut h);
107    // `Condition` has no `Hash`; its `Debug` form is stable and unique enough.
108    format!("{conditions:?}").hash(&mut h);
109    h.finish()
110}
111
112/// Finalize a mergeable [`AggState`] to a JSON scalar, preserving integer-ness
113/// for `COUNT`/`MIN`/`MAX`/int `SUM` and using a float for averages / float
114/// columns. `null` when there were no matching inputs.
115fn agg_state_value(s: &AggState) -> Value {
116    let num_f64 = |x: f64| {
117        serde_json::Number::from_f64(x)
118            .map(Value::Number)
119            .unwrap_or(Value::Null)
120    };
121    match s {
122        AggState::Count(n) => Value::from(*n),
123        AggState::SumI { sum, .. } => i64::try_from(*sum)
124            .map(Value::from)
125            .unwrap_or_else(|_| num_f64(*sum as f64)),
126        AggState::SumF { sum, .. } => num_f64(*sum),
127        AggState::AvgI { sum, count } if *count > 0 => num_f64(*sum as f64 / *count as f64),
128        AggState::AvgF { sum, count } if *count > 0 => num_f64(*sum / *count as f64),
129        AggState::AvgI { .. } | AggState::AvgF { .. } => Value::Null,
130        AggState::MinI(n) | AggState::MaxI(n) => Value::from(*n),
131        AggState::MinF(f) | AggState::MaxF(f) => num_f64(*f),
132        AggState::Empty => Value::Null,
133    }
134}
135
136/// Which approximate aggregate to estimate from the reservoir sample.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum ApproxAggKind {
139    Count,
140    Sum,
141    Avg,
142}
143
144/// A reservoir-sampled approximate aggregate with a normal-theory confidence
145/// interval. `ci_low`/`ci_high` bracket `point` at the requested z-score; the
146/// interval collapses to zero width when the sample covers the whole table.
147#[derive(Debug, Clone)]
148pub struct ApproxAggregate {
149    pub point: f64,
150    pub ci_low: f64,
151    pub ci_high: f64,
152    pub n_population: u64,
153    pub n_sample_live: usize,
154    pub n_passing: usize,
155}
156
157/// Short kind label for a core `Condition` (the variant name), decoupled from
158/// the enum shape via its `Debug` form.
159fn condition_label(c: &mongreldb_core::query::Condition) -> String {
160    let dbg = format!("{c:?}");
161    dbg.split(['(', '{', ' ']).next().unwrap_or("").to_string()
162}
163
164/// A kit database handle.
165///
166/// Wraps a MongrelDB core database and a kit schema, providing table metadata
167/// and transaction creation.
168pub struct Database {
169    pub(crate) inner: Arc<CoreDatabase>,
170    pub(crate) schema: KitSchema,
171    pub(crate) root: PathBuf,
172    /// Application-registered named default providers (`DefaultKind::CustomName`).
173    pub(crate) default_providers: HashMap<String, DefaultProvider>,
174    /// Lazily-initialized long-lived SQL session. Views, prepared statements,
175    /// and the result cache are session-scoped (the engine does not persist
176    /// them), so the kit holds one session for the database's lifetime rather
177    /// than opening one per `sql()` call — mirroring how the daemon and any
178    /// long-lived application use MongrelDB. Built on first use so tables
179    /// created in `Database::create` are visible to it.
180    pub(crate) session: parking_lot::Mutex<Option<mongreldb_query::MongrelSession>>,
181}
182
183impl Database {
184    /// Open an existing kit database.
185    pub fn open(path: &Path) -> Result<Self> {
186        let inner = Arc::new(CoreDatabase::open(path)?);
187        let schema = load_schema(path)?;
188        // Ensure reserved tables exist for databases created by older versions.
189        ensure_internal_tables(&inner)?;
190        reap_rotated_wal_segments(&inner);
191        Ok(Self {
192            inner,
193            schema,
194            root: path.to_path_buf(),
195            default_providers: HashMap::new(),
196            session: parking_lot::Mutex::new(None),
197        })
198    }
199
200    /// Open an existing page-encrypted kit database with its passphrase.
201    pub fn open_encrypted(path: &Path, passphrase: &str) -> Result<Self> {
202        let inner = Arc::new(CoreDatabase::open_encrypted(path, passphrase)?);
203        let schema = load_schema(path)?;
204        ensure_internal_tables(&inner)?;
205        reap_rotated_wal_segments(&inner);
206        Ok(Self {
207            inner,
208            schema,
209            root: path.to_path_buf(),
210            default_providers: HashMap::new(),
211            session: parking_lot::Mutex::new(None),
212        })
213    }
214
215    /// Create a fresh page-encrypted kit database (AES-256-GCM; the passphrase
216    /// derives the key hierarchy). Columns flagged `encrypted` /
217    /// `encrypted_indexable` are encrypted at rest.
218    pub fn create_encrypted(path: &Path, schema: KitSchema, passphrase: &str) -> Result<Self> {
219        std::fs::create_dir_all(path)?;
220        let inner = Arc::new(CoreDatabase::create_encrypted(path, passphrase)?);
221        ensure_internal_tables(&inner)?;
222        store_schema(path, &schema)?;
223        for table in &schema.tables {
224            create_core_table(&inner, &table.name, to_core_schema(table))?;
225        }
226        Ok(Self {
227            inner,
228            schema,
229            root: path.to_path_buf(),
230            default_providers: HashMap::new(),
231            session: parking_lot::Mutex::new(None),
232        })
233    }
234
235    /// Create a fresh kit database with the given schema.
236    pub fn create(path: &Path, schema: KitSchema) -> Result<Self> {
237        std::fs::create_dir_all(path)?;
238        let inner = Arc::new(CoreDatabase::create(path)?);
239
240        // Create the reserved kit tables first so we can record migrations,
241        // reserve unique keys, and touch row guards.
242        ensure_internal_tables(&inner)?;
243
244        // Persist the kit schema to a sidecar file (core tables cannot update
245        // a specific row by id, so a file is the pragmatic stable store).
246        store_schema(path, &schema)?;
247
248        // Create core tables for every user table.
249        for table in &schema.tables {
250            create_core_table(&inner, &table.name, to_core_schema(table))?;
251        }
252
253        Ok(Self {
254            inner,
255            schema,
256            root: path.to_path_buf(),
257            default_providers: HashMap::new(),
258            session: parking_lot::Mutex::new(None),
259        })
260    }
261
262    /// Open an existing kit database that has `require_auth = true`,
263    /// verifying credentials up front. Every subsequent operation is checked
264    /// against the authenticated principal's permissions.
265    ///
266    /// Returns an error if the database does not have `require_auth` enabled
267    /// (use [`open`](Self::open) for credentialless databases) or if the
268    /// credentials are invalid.
269    ///
270    /// See `docs/auth-enforcement-spec.md`.
271    pub fn open_with_credentials(path: &Path, username: &str, password: &str) -> Result<Self> {
272        let inner = Arc::new(CoreDatabase::open_with_credentials(
273            path, username, password,
274        )?);
275        let schema = load_schema(path)?;
276        ensure_internal_tables(&inner)?;
277        reap_rotated_wal_segments(&inner);
278        Ok(Self {
279            inner,
280            schema,
281            root: path.to_path_buf(),
282            default_providers: HashMap::new(),
283            session: parking_lot::Mutex::new(None),
284        })
285    }
286
287    /// Create a fresh kit database with `require_auth = true`, a single admin
288    /// user, and the given schema. The returned handle is already authenticated
289    /// as the admin.
290    ///
291    /// See `docs/auth-enforcement-spec.md`.
292    pub fn create_with_credentials(
293        path: &Path,
294        schema: KitSchema,
295        admin_username: &str,
296        admin_password: &str,
297    ) -> Result<Self> {
298        std::fs::create_dir_all(path)?;
299        let inner = Arc::new(CoreDatabase::create_with_credentials(
300            path,
301            admin_username,
302            admin_password,
303        )?);
304        ensure_internal_tables(&inner)?;
305        store_schema(path, &schema)?;
306        for table in &schema.tables {
307            create_core_table(&inner, &table.name, to_core_schema(table))?;
308        }
309        Ok(Self {
310            inner,
311            schema,
312            root: path.to_path_buf(),
313            default_providers: HashMap::new(),
314            session: parking_lot::Mutex::new(None),
315        })
316    }
317
318    /// Open an existing page-encrypted kit database that has `require_auth =
319    /// true`, combining the encryption passphrase with credential verification.
320    pub fn open_encrypted_with_credentials(
321        path: &Path,
322        passphrase: &str,
323        username: &str,
324        password: &str,
325    ) -> Result<Self> {
326        let inner = Arc::new(CoreDatabase::open_encrypted_with_credentials(
327            path, passphrase, username, password,
328        )?);
329        let schema = load_schema(path)?;
330        ensure_internal_tables(&inner)?;
331        reap_rotated_wal_segments(&inner);
332        Ok(Self {
333            inner,
334            schema,
335            root: path.to_path_buf(),
336            default_providers: HashMap::new(),
337            session: parking_lot::Mutex::new(None),
338        })
339    }
340
341    /// Create a fresh page-encrypted kit database with `require_auth = true`
342    /// and a single admin user. Composes encryption-at-rest with credential
343    /// enforcement.
344    pub fn create_encrypted_with_credentials(
345        path: &Path,
346        schema: KitSchema,
347        passphrase: &str,
348        admin_username: &str,
349        admin_password: &str,
350    ) -> Result<Self> {
351        std::fs::create_dir_all(path)?;
352        let inner = Arc::new(CoreDatabase::create_encrypted_with_credentials(
353            path,
354            passphrase,
355            admin_username,
356            admin_password,
357        )?);
358        ensure_internal_tables(&inner)?;
359        store_schema(path, &schema)?;
360        for table in &schema.tables {
361            create_core_table(&inner, &table.name, to_core_schema(table))?;
362        }
363        Ok(Self {
364            inner,
365            schema,
366            root: path.to_path_buf(),
367            default_providers: HashMap::new(),
368            session: parking_lot::Mutex::new(None),
369        })
370    }
371
372    /// Convert a credentialless kit database to a credentialed one in place.
373    /// Creates the first admin user, sets `require_auth = true`, and caches
374    /// the admin principal on this handle.
375    pub fn enable_auth(&self, admin_username: &str, admin_password: &str) -> Result<()> {
376        self.inner
377            .enable_auth(admin_username, admin_password)
378            .map_err(KitError::from)
379    }
380
381    /// Returns `true` if this database has `require_auth = true`.
382    pub fn require_auth_enabled(&self) -> bool {
383        self.inner.require_auth_enabled()
384    }
385
386    /// Re-resolve the cached principal from the on-disk catalog, picking up
387    /// role/permission changes made by other handles. No-op on credentialless
388    /// databases.
389    pub fn refresh_principal(&self) -> Result<()> {
390        self.inner.refresh_principal().map_err(KitError::from)
391    }
392
393    /// Register a named default provider used by `DefaultKind::CustomName`
394    /// columns. Returns the database for chaining.
395    pub fn register_default(
396        &mut self,
397        name: impl Into<String>,
398        provider: impl Fn() -> Value + Send + Sync + 'static,
399    ) {
400        self.default_providers
401            .insert(name.into(), Box::new(provider));
402    }
403
404    /// The raw, unguarded MongrelDB core database. This is the Rust analogue of
405    /// the TypeScript kit's `nativeDb` escape hatch: writes made directly
406    /// against it bypass all kit constraints.
407    pub fn raw(&self) -> &CoreDatabase {
408        &self.inner
409    }
410
411    /// Application table names, excluding the reserved `__kit_*` tables.
412    pub fn table_names(&self) -> Vec<String> {
413        self.schema
414            .tables
415            .iter()
416            .map(|t| t.name.clone())
417            .filter(|n| !n.starts_with("__kit_"))
418            .collect()
419    }
420
421    pub fn create_procedure(
422        &self,
423        spec: &ProcedureSpec,
424    ) -> Result<mongreldb_core::StoredProcedure> {
425        let procedure = core_procedure(spec)?;
426        self.inner
427            .create_procedure(procedure)
428            .map_err(KitError::from)
429    }
430
431    pub fn replace_procedure(
432        &self,
433        spec: &ProcedureSpec,
434    ) -> Result<mongreldb_core::StoredProcedure> {
435        let procedure = core_procedure(spec)?;
436        self.inner
437            .create_or_replace_procedure(procedure)
438            .map_err(KitError::from)
439    }
440
441    pub fn drop_procedure(&self, name: &str) -> Result<()> {
442        self.inner.drop_procedure(name).map_err(KitError::from)
443    }
444
445    pub fn call_procedure(
446        &self,
447        name: &str,
448        args: serde_json::Map<String, Value>,
449    ) -> Result<mongreldb_core::ProcedureCallResult> {
450        let args = args
451            .iter()
452            .map(|(key, value)| Ok((key.clone(), json_to_core_value(value)?)))
453            .collect::<Result<HashMap<_, _>>>()?;
454        self.inner
455            .call_procedure(name, args)
456            .map_err(KitError::from)
457    }
458
459    pub fn create_trigger(&self, spec: &TriggerSpec) -> Result<mongreldb_core::StoredTrigger> {
460        let trigger = core_trigger(spec)?;
461        self.inner.create_trigger(trigger).map_err(KitError::from)
462    }
463
464    pub fn replace_trigger(&self, spec: &TriggerSpec) -> Result<mongreldb_core::StoredTrigger> {
465        let trigger = core_trigger(spec)?;
466        self.inner
467            .create_or_replace_trigger(trigger)
468            .map_err(KitError::from)
469    }
470
471    pub fn drop_trigger(&self, name: &str) -> Result<()> {
472        self.inner.drop_trigger(name).map_err(KitError::from)
473    }
474
475    pub fn triggers(&self) -> Vec<mongreldb_core::StoredTrigger> {
476        self.inner.triggers()
477    }
478
479    pub fn trigger(&self, name: &str) -> Option<mongreldb_core::StoredTrigger> {
480        self.inner.trigger(name)
481    }
482
483    /// Allocate `count` values from the named sequence, returning the first
484    /// allocated value. A fresh sequence starts at `1` (SQL AUTO_INCREMENT
485    /// semantics). The allocation
486    /// runs in its own committed transaction and retries on write-write
487    /// conflicts.
488    pub fn allocate_sequence(&self, name: &str, count: i64) -> Result<i64> {
489        use crate::internal::cols;
490        let mut attempt = 0;
491        loop {
492            let mut txn = self.inner.begin();
493            let snapshot = txn.read_snapshot();
494            let existing = self
495                .visible_core_rows_at(crate::internal::SEQUENCES, snapshot)?
496                .into_iter()
497                .find(|r| internal_bytes(r, cols::SEQ_NAME) == Some(name.to_string()));
498
499            let now = crate::internal::iso_now();
500            // Sequences are 1-based, matching SQL AUTO_INCREMENT / SERIAL. A
501            // starting value of 0 is unsafe: applications use 0 as the "unset"
502            // sentinel for nullable foreign keys.
503            let (start, next, old_row_id) = match &existing {
504                Some(row) => {
505                    let current = match row.columns.get(&cols::SEQ_NEXT) {
506                        Some(CoreValue::Int64(i)) => *i,
507                        _ => 1,
508                    };
509                    (current, current + count, Some(row.row_id))
510                }
511                None => (1, 1 + count, None),
512            };
513
514            if let Some(rid) = old_row_id {
515                txn.delete(crate::internal::SEQUENCES, rid)
516                    .map_err(KitError::from)?;
517            }
518            txn.put(
519                crate::internal::SEQUENCES,
520                vec![
521                    (cols::SEQ_NAME, CoreValue::Bytes(name.as_bytes().to_vec())),
522                    (cols::SEQ_NEXT, CoreValue::Int64(next)),
523                    (cols::SEQ_UPDATED, CoreValue::Bytes(now.into_bytes())),
524                ],
525            )
526            .map_err(KitError::from)?;
527            match txn.commit() {
528                Ok(_) => return Ok(start),
529                Err(mongreldb_core::MongrelError::Conflict(_)) if attempt < 10_000 => {
530                    attempt += 1;
531                    std::thread::yield_now();
532                    continue;
533                }
534                Err(e) => return Err(KitError::from(e)),
535            }
536        }
537    }
538
539    /// Run `f` inside a kit transaction, committing on success and retrying on
540    /// retryable write-write conflicts up to `max_retries` times.
541    pub fn transaction<T, F>(&self, max_retries: usize, mut f: F) -> Result<T>
542    where
543        F: FnMut(&mut crate::txn::Transaction<'_>) -> Result<T>,
544    {
545        let mut attempt = 0;
546        loop {
547            let mut txn = self.begin()?;
548            match f(&mut txn) {
549                Ok(value) => match txn.commit() {
550                    Ok(()) => return Ok(value),
551                    Err(KitError::Conflict(_)) if attempt < max_retries => {
552                        attempt += 1;
553                        continue;
554                    }
555                    Err(e) => return Err(e),
556                },
557                Err(KitError::Conflict(_)) if attempt < max_retries => {
558                    txn.rollback();
559                    attempt += 1;
560                    continue;
561                }
562                Err(e) => {
563                    txn.rollback();
564                    return Err(e);
565                }
566            }
567        }
568    }
569
570    /// Look up a table definition by name.
571    pub fn table(&self, name: &str) -> Option<&KitTable> {
572        self.schema.table(name)
573    }
574
575    /// Return the currently loaded schema.
576    pub fn schema(&self) -> &KitSchema {
577        &self.schema
578    }
579
580    /// Begin a new kit transaction.
581    pub fn begin(&self) -> Result<crate::txn::Transaction<'_>> {
582        let core_txn = self.inner.begin();
583        Ok(crate::txn::Transaction::new(self, core_txn))
584    }
585
586    /// Replace the in-memory schema, usually after a migration.
587    pub fn set_schema(&mut self, schema: KitSchema) {
588        self.schema = schema;
589    }
590
591    /// Verify that the sidecar schema file and all reserved `__kit_*` tables
592    /// are present.
593    pub fn check_internal_tables(&self) -> Result<()> {
594        let schema_file = self.root.join(SCHEMA_FILE);
595        if !schema_file.exists() {
596            return Err(KitError::Integrity(format!(
597                "schema file {} is missing",
598                schema_file.display()
599            )));
600        }
601        for (name, _) in internal_tables_core() {
602            if self.inner.table_id(name).is_err() {
603                return Err(KitError::Integrity(format!(
604                    "internal table {name} is missing"
605                )));
606            }
607        }
608        Ok(())
609    }
610
611    /// Reclaim orphaned runs and stale WAL/shadow files; returns the count
612    /// removed. Safe to run on a live database.
613    pub fn gc(&self) -> Result<usize> {
614        self.inner.gc().map_err(KitError::from)
615    }
616
617    /// Verify run footer checksums; returns any integrity issues as JSON objects
618    /// (`table_id`, `table_name`, `severity`, `description`). Empty ⇒ healthy.
619    pub fn check(&self) -> Vec<serde_json::Value> {
620        self.inner
621            .check()
622            .into_iter()
623            .map(|i| {
624                serde_json::json!({
625                    "table_id": i.table_id,
626                    "table_name": i.table_name,
627                    "severity": i.severity,
628                    "description": i.description,
629                })
630            })
631            .collect()
632    }
633
634    /// Drop corrupt runs; returns the ids of the runs that were dropped.
635    pub fn doctor(&self) -> Result<Vec<u64>> {
636        self.inner.doctor().map_err(KitError::from)
637    }
638
639    /// The current visible commit epoch — a monotonically increasing version
640    /// stamp. A committed write bumps it; a snapshot at this epoch sees all
641    /// currently-committed data.
642    pub fn snapshot_epoch(&self) -> u64 {
643        self.inner.snapshot().0.epoch.0
644    }
645
646    /// Export every visible row of `table` as a TSV document (header row of
647    /// column names, tab-separated cells, `NULL` = empty field). See
648    /// [`crate::tsv`] for the escaping rules.
649    pub fn export_tsv(&self, table: &str) -> Result<String> {
650        let t = self
651            .schema
652            .tables
653            .iter()
654            .find(|t| t.name == table)
655            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?
656            .clone();
657        let tx = self.begin()?;
658        let rows = tx.all_rows(table)?;
659        Ok(crate::tsv::rows_to_tsv(&t, &rows))
660    }
661
662    /// Import a TSV document into `table` (one committed transaction). Each row
663    /// passes through defaults, validation, and constraint checks like a normal
664    /// insert. Returns the number of rows inserted.
665    pub fn import_tsv(&self, table: &str, text: &str) -> Result<usize> {
666        let t = self
667            .schema
668            .tables
669            .iter()
670            .find(|t| t.name == table)
671            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?
672            .clone();
673        let rows = crate::tsv::tsv_to_rows(&t, text)?;
674        let n = rows.len();
675        self.transaction(1, |tx| {
676            tx.insert_many(table, rows.clone())?;
677            Ok(())
678        })?;
679        Ok(n)
680    }
681
682    /// Describe how `predicate` would be executed against `table`: which native
683    /// index conditions push down, whether the push-down is exact (no residual
684    /// re-filtering), and whether any index acceleration applies at all. A pure
685    /// diagnostic — it plans but does not run the query.
686    pub fn explain(
687        &self,
688        table: &str,
689        predicate: &mongreldb_kit_core::query::Expr,
690    ) -> Result<ExplainPlan> {
691        let t = self
692            .schema
693            .tables
694            .iter()
695            .find(|t| t.name == table)
696            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?;
697        Ok(match crate::pushdown::translate_predicate(t, predicate) {
698            Some(p) => ExplainPlan {
699                index_accelerated: p.can_push(),
700                exact: p.fully_translated,
701                pushed_conditions: p.conditions.iter().map(condition_label).collect(),
702            },
703            None => ExplainPlan {
704                index_accelerated: false,
705                exact: false,
706                pushed_conditions: Vec::new(),
707            },
708        })
709    }
710
711    /// Read every row of `table` visible at commit `epoch` — a point-in-time
712    /// (MVCC time-travel) read. `epoch` must not exceed the current snapshot
713    /// epoch. Rows reclaimed by GC/compaction for retired snapshots may no
714    /// longer be reconstructable; this reads whatever the engine still retains
715    /// at that epoch.
716    pub fn rows_at_epoch(&self, table: &str, epoch: u64) -> Result<Vec<crate::schema::Row>> {
717        let t = self
718            .schema
719            .tables
720            .iter()
721            .find(|t| t.name == table)
722            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?;
723        let current = self.snapshot_epoch();
724        if epoch > current {
725            return Err(KitError::Validation(format!(
726                "epoch {epoch} is in the future (current committed epoch is {current})"
727            )));
728        }
729        let snap = Snapshot::at(mongreldb_core::epoch::Epoch(epoch));
730        let rows = self.visible_core_rows_at(table, snap)?;
731        rows.iter()
732            .map(|r| crate::schema::core_row_to_json(r, t))
733            .collect()
734    }
735
736    /// Estimate an aggregate over `table` from the engine's reservoir sample,
737    /// returning a point estimate and a `z`-score confidence interval (e.g.
738    /// `z = 1.96` for ~95%). `column` is required for `Sum`/`Avg` and ignored
739    /// for `Count`. Returns `None` when the reservoir is empty (no sampled rows
740    /// yet). Fast and O(sample) — trades exactness for speed on large tables.
741    pub fn approx_aggregate(
742        &self,
743        table: &str,
744        column: Option<&str>,
745        agg: ApproxAggKind,
746        z: f64,
747    ) -> Result<Option<ApproxAggregate>> {
748        let t = self
749            .schema
750            .tables
751            .iter()
752            .find(|t| t.name == table)
753            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?;
754        if matches!(agg, ApproxAggKind::Sum | ApproxAggKind::Avg) && column.is_none() {
755            return Err(KitError::Validation(
756                "approx sum/avg requires a column".into(),
757            ));
758        }
759        let cid = match column {
760            Some(name) => Some(
761                t.columns
762                    .iter()
763                    .find(|c| c.name == name)
764                    .ok_or_else(|| KitError::Validation(format!("unknown column '{name}'")))?
765                    .id as u16,
766            ),
767            None => None,
768        };
769        let core_agg = match agg {
770            ApproxAggKind::Count => ApproxAgg::Count,
771            ApproxAggKind::Sum => ApproxAgg::Sum,
772            ApproxAggKind::Avg => ApproxAgg::Avg,
773        };
774        let handle = self.inner.table(table).map_err(KitError::from)?;
775        let mut guard = handle.lock();
776        let res = guard
777            .approx_aggregate(&[], cid, core_agg, z)
778            .map_err(KitError::from)?;
779        Ok(res.map(|r| ApproxAggregate {
780            point: r.point,
781            ci_low: r.ci_low,
782            ci_high: r.ci_high,
783            n_population: r.n_population,
784            n_sample_live: r.n_sample_live,
785            n_passing: r.n_passing,
786        }))
787    }
788
789    /// Stream `table` in row batches without materializing the whole table at
790    /// once. `f` receives successive chunks of at most `batch_size` value-maps,
791    /// all from one snapshot. Backed by the engine's native scan cursor when the
792    /// table has a sorted run; for an overlay-only table (no run yet) it falls
793    /// back to a single in-memory pass, still chunked to `batch_size`.
794    pub fn scan_batched<F>(&self, table: &str, batch_size: usize, mut f: F) -> Result<()>
795    where
796        F: FnMut(&[serde_json::Map<String, Value>]) -> Result<()>,
797    {
798        let kit_t = self
799            .schema
800            .tables
801            .iter()
802            .find(|t| t.name == table)
803            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?;
804        let batch_size = batch_size.max(1);
805        // Keep the pin guard alive for the whole scan so GC can't reclaim the
806        // snapshot's versions mid-stream.
807        let (snapshot, _pin) = self.inner.snapshot();
808        let handle = self.inner.table(table).map_err(KitError::from)?;
809        let guard = handle.lock();
810
811        // Projection + per-column (name, kit type), index-aligned, in core order.
812        let mut projection: Vec<(u16, mongreldb_core::schema::TypeId)> = Vec::new();
813        let mut meta: Vec<(String, mongreldb_kit_core::schema::ColumnType)> = Vec::new();
814        for c in &guard.schema().columns {
815            if let Some(kc) = kit_t.columns.iter().find(|kc| kc.id as u16 == c.id) {
816                projection.push((c.id, c.ty));
817                meta.push((kc.name.clone(), kc.storage_type));
818            }
819        }
820
821        match guard
822            .scan_cursor(snapshot, projection, &[])
823            .map_err(KitError::from)?
824        {
825            Some(mut cursor) => {
826                let mut buf: Vec<serde_json::Map<String, Value>> = Vec::with_capacity(batch_size);
827                while let Some(batch) = cursor.next_batch().map_err(KitError::from)? {
828                    let nrows = batch.first().map(|c| c.len()).unwrap_or(0);
829                    for j in 0..nrows {
830                        let mut m = serde_json::Map::new();
831                        for (ci, (name, ty)) in meta.iter().enumerate() {
832                            let cv = batch
833                                .get(ci)
834                                .and_then(|col| col.value_at(j))
835                                .unwrap_or(CoreValue::Null);
836                            m.insert(name.clone(), crate::schema::core_to_json(&cv, *ty)?);
837                        }
838                        buf.push(m);
839                        if buf.len() >= batch_size {
840                            f(&buf)?;
841                            buf.clear();
842                        }
843                    }
844                }
845                if !buf.is_empty() {
846                    f(&buf)?;
847                }
848                Ok(())
849            }
850            None => {
851                drop(guard);
852                let rows = self.visible_core_rows_at(table, snapshot)?;
853                let maps: Vec<serde_json::Map<String, Value>> = rows
854                    .iter()
855                    .map(|r| crate::schema::core_row_to_json(r, kit_t).map(|row| row.values))
856                    .collect::<Result<Vec<_>>>()?;
857                for chunk in maps.chunks(batch_size) {
858                    f(chunk)?;
859                }
860                Ok(())
861            }
862        }
863    }
864
865    /// Rank rows of `table` by Jaccard set-similarity between `query` and the
866    /// string set stored (as a JSON array) in `column`, returning the top `k`
867    /// with similarity `> 0`, highest first — the dedup/join primitive.
868    ///
869    /// When `column` has a `MinHash` index, candidate rows come from the engine's
870    /// LSH index (sub-linear) and are then re-verified with exact Jaccard, so the
871    /// top-k is exact for the recalled candidates (LSH recall is high but < 100%).
872    /// Without an index it is an exact linear scan.
873    pub fn set_similarity(
874        &self,
875        table: &str,
876        column: &str,
877        query: &[String],
878        k: usize,
879    ) -> Result<Vec<SimilarRow>> {
880        let t = self
881            .schema
882            .tables
883            .iter()
884            .find(|t| t.name == table)
885            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?;
886        let col = t.columns.iter().find(|c| c.name == column).ok_or_else(|| {
887            KitError::Validation(format!("unknown column '{column}' on table '{table}'"))
888        })?;
889        let query_set: std::collections::HashSet<String> = query.iter().cloned().collect();
890
891        let has_minhash = t.indexes.iter().any(|idx| {
892            idx.kind == KitIndexKind::MinHash && idx.columns.iter().any(|c| c == column)
893        });
894        let rows = if has_minhash {
895            // Sub-linear candidate generation via the engine MinHash/LSH index.
896            let query_hashes: Vec<u64> = query
897                .iter()
898                .map(|s| mongreldb_core::index::minhash_token_hash(s))
899                .collect();
900            // Generous candidate budget so exact top-k keeps high recall.
901            let cand_k = k.saturating_mul(8).max(k + 64);
902            let cond = mongreldb_core::query::Condition::MinHashSimilar {
903                column_id: col.id as u16,
904                query: query_hashes,
905                k: cand_k,
906            };
907            let (snapshot, _pin) = self.inner.snapshot();
908            let core_rows = self.query_core_rows_at(table, &[cond], snapshot)?;
909            core_rows
910                .iter()
911                .map(|r| crate::schema::core_row_to_json(r, t))
912                .collect::<Result<Vec<_>>>()?
913        } else {
914            let tx = self.begin()?;
915            tx.all_rows(table)?
916        };
917
918        let mut scored: Vec<SimilarRow> = Vec::new();
919        for row in rows {
920            let set = parse_string_set(row.values.get(column));
921            let inter = set.iter().filter(|x| query_set.contains(*x)).count();
922            let union = set.len() + query_set.len() - inter;
923            let sim = if union == 0 {
924                0.0
925            } else {
926                inter as f64 / union as f64
927            };
928            if sim > 0.0 {
929                scored.push(SimilarRow {
930                    row,
931                    similarity: sim,
932                });
933            }
934        }
935        scored.sort_by(|a, b| {
936            b.similarity
937                .partial_cmp(&a.similarity)
938                .unwrap_or(std::cmp::Ordering::Equal)
939        });
940        scored.truncate(k);
941        Ok(scored)
942    }
943
944    /// Flush every table's in-memory writes to durable sorted runs. Besides
945    /// durability, this empties the memtable, which is what enables the engine's
946    /// incremental-aggregate fast path (see [`Self::incremental_aggregate`]).
947    pub fn flush(&self) -> Result<()> {
948        for name in self.inner.table_names() {
949            let handle = self.inner.table(&name).map_err(KitError::from)?;
950            let mut guard = handle.lock();
951            guard.flush().map_err(KitError::from)?;
952        }
953        Ok(())
954    }
955
956    /// Maintain and read an aggregate over `table` that updates by merging only
957    /// newly-committed rows instead of rescanning. `column` is required for
958    /// `Sum`/`Min`/`Max`/`Avg` and ignored for `Count`. An optional `filter`
959    /// restricts the aggregate; it must translate **exactly** to index
960    /// conditions (no residual), otherwise this errors — an inexact filter would
961    /// silently aggregate the wrong rows.
962    ///
963    /// The engine keeps a per-`(table, column, agg, filter)` cached state and,
964    /// on a warm cache with an advanced epoch and no deletes/pending writes,
965    /// folds in just the delta. The returned `value` is always exact; the
966    /// `incremental` flag reports whether the fast path was taken.
967    pub fn incremental_aggregate(
968        &self,
969        table: &str,
970        column: Option<&str>,
971        agg: IncrementalAggKind,
972        filter: Option<&mongreldb_kit_core::query::Expr>,
973    ) -> Result<IncrementalAggregate> {
974        let t = self
975            .schema
976            .tables
977            .iter()
978            .find(|t| t.name == table)
979            .ok_or_else(|| KitError::Validation(format!("unknown table '{table}'")))?;
980        if !matches!(agg, IncrementalAggKind::Count) && column.is_none() {
981            return Err(KitError::Validation(
982                "sum/min/max/avg incremental aggregate requires a column".into(),
983            ));
984        }
985        let cid = match column {
986            Some(name) => Some(
987                t.columns
988                    .iter()
989                    .find(|c| c.name == name)
990                    .ok_or_else(|| KitError::Validation(format!("unknown column '{name}'")))?
991                    .id as u16,
992            ),
993            None => None,
994        };
995        let conditions = match filter {
996            Some(expr) => {
997                let plan = crate::pushdown::translate_predicate(t, expr).ok_or_else(|| {
998                    KitError::Validation(
999                        "filter is not index-translatable for an incremental aggregate".into(),
1000                    )
1001                })?;
1002                if !plan.fully_translated {
1003                    return Err(KitError::Validation(
1004                        "filter has a residual that an incremental aggregate cannot apply exactly"
1005                            .into(),
1006                    ));
1007                }
1008                plan.conditions
1009            }
1010            None => Vec::new(),
1011        };
1012        let core_agg = match agg {
1013            IncrementalAggKind::Count => NativeAgg::Count,
1014            IncrementalAggKind::Sum => NativeAgg::Sum,
1015            IncrementalAggKind::Min => NativeAgg::Min,
1016            IncrementalAggKind::Max => NativeAgg::Max,
1017            IncrementalAggKind::Avg => NativeAgg::Avg,
1018        };
1019        let cache_key = incremental_cache_key(t.id, cid, agg, &conditions);
1020        let handle = self.inner.table(table).map_err(KitError::from)?;
1021        let mut guard = handle.lock();
1022        let res = guard
1023            .aggregate_incremental(cache_key, &conditions, cid, core_agg)
1024            .map_err(KitError::from)?;
1025        Ok(IncrementalAggregate {
1026            value: agg_state_value(&res.state),
1027            incremental: res.incremental,
1028            delta_rows: res.delta_rows,
1029        })
1030    }
1031
1032    /// Return the migrations already recorded in `__kit_schema_migrations`.
1033    pub fn applied_migrations(&self) -> Result<Vec<mongreldb_kit_core::migrations::Migration>> {
1034        crate::migrate::load_applied_migrations(&self.inner)
1035    }
1036
1037    pub(crate) fn core_db(&self) -> &CoreDatabase {
1038        &self.inner
1039    }
1040
1041    /// The underlying engine handle wrapped in an `Arc`, for callers that need
1042    /// a shared/owned reference (e.g. building a `MongrelSession`).
1043    pub(crate) fn core_arc(&self) -> Arc<CoreDatabase> {
1044        Arc::clone(&self.inner)
1045    }
1046
1047    /// Best-effort flush-on-close (§4.4): force-flush pending writes on every
1048    /// table to `.sr` sorted runs so WAL segments stay bounded across repeated
1049    /// short-lived process invocations (e.g. the CLI). Call as the last action
1050    /// before exit. The daemon does not need this (auto-compactor handles it).
1051    pub fn close(&self) -> Result<()> {
1052        self.inner.close().map_err(KitError::from)
1053    }
1054
1055    /// Compact all tables: merge sorted runs into one clean run each so query
1056    /// latency stays flat. Returns `(compacted, skipped)`. Safe to run at any
1057    /// time — honors snapshot retention. The daemon's background auto-compactor
1058    /// already does this periodically; this is for manual/cron use.
1059    pub fn compact_all(&self) -> Result<(usize, usize)> {
1060        self.inner.compact().map_err(KitError::from)
1061    }
1062
1063    /// Compact a single table by name. Returns `true` if compacted, `false` if
1064    /// skipped (< 2 runs).
1065    pub fn compact_table(&self, name: &str) -> Result<bool> {
1066        self.inner.compact_table(name).map_err(KitError::from)
1067    }
1068
1069    /// Rename a live table. Fails if `from` does not exist or `to` is already
1070    /// in use; a no-op when `from == to`. Names beginning with `__kit_` are
1071    /// reserved for internal tables and rejected here (parity with the
1072    /// TypeScript kit).
1073    ///
1074    /// Updates both the engine table and the kit schema catalog (in memory and
1075    /// persisted to `kit_schema.json`), so subsequent `table_names()`,
1076    /// `table(name)`, and transactional reads by the new name all work. Foreign
1077    /// keys in other tables that reference `from` are retargeted to `to`.
1078    pub fn rename_table(&mut self, from: &str, to: &str) -> Result<()> {
1079        if from.starts_with("__kit_") || to.starts_with("__kit_") {
1080            return Err(KitError::Validation(
1081                "rename_table: names beginning with '__kit_' are reserved for internal tables"
1082                    .into(),
1083            ));
1084        }
1085        self.inner.rename_table(from, to).map_err(KitError::from)?;
1086        // Keep the kit schema catalog in sync: rename the table (updating the
1087        // by_name index), retarget any FKs that pointed at it, then persist.
1088        if !self.schema.rename_table(from, to) {
1089            // The engine renamed it but the kit schema didn't have it / had a
1090            // clash — surface the divergence rather than silently desyncing.
1091            return Err(KitError::Integrity(format!(
1092                "rename_table: kit schema has no table '{from}' (or '{to}' already exists)"
1093            )));
1094        }
1095        for table in &mut self.schema.tables {
1096            for fk in &mut table.foreign_keys {
1097                if fk.references_table == from {
1098                    fk.references_table = to.to_string();
1099                }
1100            }
1101        }
1102        store_schema(&self.root, &self.schema)?;
1103        Ok(())
1104    }
1105
1106    /// Rebuild statistics/metadata for every table's indexes (the engine's
1107    /// `ANALYZE` equivalent: `ensure_indexes_complete` on each table). Safe to
1108    /// run at any time; useful after bulk loads so the query planner and
1109    /// learned indexes have fresh data.
1110    pub fn analyze(&self) -> Result<()> {
1111        for name in self.inner.table_names() {
1112            let handle = self.inner.table(&name).map_err(KitError::from)?;
1113            handle.lock().ensure_indexes_complete()?;
1114        }
1115        Ok(())
1116    }
1117
1118    /// Reclaim space across all tables: compacts every table's sorted runs,
1119    /// then runs `gc`. Returns the count of reclaimed orphaned runs/files.
1120    /// Equivalent to the engine's `VACUUM`. Safe to run at any time.
1121    pub fn vacuum(&self) -> Result<usize> {
1122        self.inner.compact().map_err(KitError::from)?;
1123        self.inner.gc().map_err(KitError::from)
1124    }
1125
1126    /// Create a SQL view (`CREATE VIEW <name> AS <select>`). The engine
1127    /// overwrites any existing view with the same name, so this also serves as
1128    /// replace. The view lives in the kit's long-lived SQL session — it is not
1129    /// persisted to the catalog, so reopening the database loses it (re-apply
1130    /// a `CreateView` migration to restore).
1131    pub fn create_view(&self, spec: &ViewSpec) -> Result<()> {
1132        self.sql(&spec.create_sql())?;
1133        Ok(())
1134    }
1135
1136    /// Drop a SQL view by name (idempotent — `DROP VIEW IF EXISTS`).
1137    pub fn drop_view(&self, name: &str) -> Result<()> {
1138        self.sql(&format!("DROP VIEW IF EXISTS {name}"))?;
1139        Ok(())
1140    }
1141
1142    /// Reserve (without inserting) the next engine-native `AUTO_INCREMENT` value
1143    /// for `table`, advancing the per-table counter. Returns `None` when the
1144    /// table has no auto-increment column. This is the escape hatch for callers
1145    /// that stage a row with an explicit id inside a transaction; the
1146    /// reservation becomes durable when a row carrying the id commits, and an
1147    /// unused reservation just leaves a gap. Parity with the TypeScript kit's
1148    /// `reserveAutoIncSync`.
1149    pub fn reserve_auto_inc(&self, table: &str) -> Result<Option<i64>> {
1150        let handle = self.inner.table(table).map_err(KitError::from)?;
1151        let mut guard = handle.lock();
1152        guard.reserve_auto_inc().map_err(KitError::from)
1153    }
1154
1155    // ── user/role/credentials management ─────────────────────────────────
1156
1157    /// Create a catalog user with an Argon2id-hashed password.
1158    pub fn create_user(&self, username: &str, password: &str) -> Result<()> {
1159        self.inner
1160            .create_user(username, password)
1161            .map_err(KitError::from)?;
1162        Ok(())
1163    }
1164
1165    /// Drop a user by username.
1166    pub fn drop_user(&self, username: &str) -> Result<()> {
1167        self.inner.drop_user(username).map_err(KitError::from)
1168    }
1169
1170    /// Change a user's password.
1171    pub fn alter_user_password(&self, username: &str, new_password: &str) -> Result<()> {
1172        self.inner
1173            .alter_user_password(username, new_password)
1174            .map_err(KitError::from)
1175    }
1176
1177    /// Verify credentials. Returns `Some(entry)` on success.
1178    pub fn verify_user(
1179        &self,
1180        username: &str,
1181        password: &str,
1182    ) -> Result<Option<mongreldb_core::auth::UserEntry>> {
1183        self.inner
1184            .verify_user(username, password)
1185            .map_err(KitError::from)
1186    }
1187
1188    /// Grant or revoke admin privileges on a user.
1189    pub fn set_user_admin(&self, username: &str, is_admin: bool) -> Result<()> {
1190        self.inner
1191            .set_user_admin(username, is_admin)
1192            .map_err(KitError::from)
1193    }
1194
1195    /// List all usernames.
1196    pub fn users(&self) -> Vec<String> {
1197        self.inner.users().into_iter().map(|u| u.username).collect()
1198    }
1199
1200    /// Create a role.
1201    pub fn create_role(&self, name: &str) -> Result<()> {
1202        self.inner.create_role(name).map_err(KitError::from)?;
1203        Ok(())
1204    }
1205
1206    /// Drop a role.
1207    pub fn drop_role(&self, name: &str) -> Result<()> {
1208        self.inner.drop_role(name).map_err(KitError::from)
1209    }
1210
1211    /// List all role names.
1212    pub fn roles(&self) -> Vec<String> {
1213        self.inner.roles().into_iter().map(|r| r.name).collect()
1214    }
1215
1216    /// Grant a role to a user.
1217    pub fn grant_role(&self, username: &str, role_name: &str) -> Result<()> {
1218        self.inner
1219            .grant_role(username, role_name)
1220            .map_err(KitError::from)
1221    }
1222
1223    /// Revoke a role from a user.
1224    pub fn revoke_role(&self, username: &str, role_name: &str) -> Result<()> {
1225        self.inner
1226            .revoke_role(username, role_name)
1227            .map_err(KitError::from)
1228    }
1229
1230    /// Grant a permission to a role.
1231    pub fn grant_permission(
1232        &self,
1233        role_name: &str,
1234        permission: mongreldb_core::auth::Permission,
1235    ) -> Result<()> {
1236        self.inner
1237            .grant_permission(role_name, permission)
1238            .map_err(KitError::from)
1239    }
1240
1241    /// Revoke a permission from a role.
1242    pub fn revoke_permission(
1243        &self,
1244        role_name: &str,
1245        permission: mongreldb_core::auth::Permission,
1246    ) -> Result<()> {
1247        self.inner
1248            .revoke_permission(role_name, permission)
1249            .map_err(KitError::from)
1250    }
1251
1252    // ── storage tuning & introspection (Tier 3) ─────────────────────────────
1253
1254    /// Set the per-table spill threshold (bytes). When a transaction's staged
1255    /// bytes for a single table exceed this, rows are written as a uniform-epoch
1256    /// pending run instead of streamed Put records.
1257    pub fn set_spill_threshold(&self, bytes: u64) {
1258        self.inner.set_spill_threshold(bytes);
1259    }
1260
1261    /// Enable or disable recursive trigger execution (database-wide).
1262    pub fn set_recursive_triggers(&self, enabled: bool) {
1263        self.inner.set_recursive_triggers(enabled);
1264    }
1265
1266    /// Read the current trigger execution policy.
1267    pub fn trigger_config(&self) -> mongreldb_core::TriggerConfig {
1268        self.inner.trigger_config()
1269    }
1270
1271    /// Set the trigger execution policy. `max_depth` must be > 0.
1272    pub fn set_trigger_config(&self, config: mongreldb_core::TriggerConfig) -> Result<()> {
1273        self.inner
1274            .set_trigger_config(config)
1275            .map_err(KitError::from)
1276    }
1277
1278    /// Set a table's compaction zstd level (-1 = default, 0 = none, 1..22).
1279    pub fn set_table_compaction_zstd_level(&self, table: &str, level: i32) -> Result<()> {
1280        let handle = self.inner.table(table).map_err(KitError::from)?;
1281        handle.lock().set_compaction_zstd_level(level);
1282        Ok(())
1283    }
1284
1285    /// Set a table's result-cache max bytes.
1286    pub fn set_table_result_cache_max_bytes(&self, table: &str, max_bytes: u64) -> Result<()> {
1287        let handle = self.inner.table(table).map_err(KitError::from)?;
1288        handle.lock().set_result_cache_max_bytes(max_bytes);
1289        Ok(())
1290    }
1291
1292    /// Set a table's mutable-run spill threshold (bytes).
1293    pub fn set_table_mutable_run_spill_bytes(&self, table: &str, bytes: u64) -> Result<()> {
1294        let handle = self.inner.table(table).map_err(KitError::from)?;
1295        handle.lock().set_mutable_run_spill_bytes(bytes);
1296        Ok(())
1297    }
1298
1299    /// Set a table's WAL sync byte threshold (bytes between group-syncs).
1300    pub fn set_table_sync_byte_threshold(&self, table: &str, threshold: u64) -> Result<()> {
1301        let handle = self.inner.table(table).map_err(KitError::from)?;
1302        handle.lock().set_sync_byte_threshold(threshold);
1303        Ok(())
1304    }
1305
1306    /// Set a table's index build policy (`Deferred` for fast ingest, `Eager`
1307    /// for fast first query).
1308    pub fn set_table_index_build_policy(
1309        &self,
1310        table: &str,
1311        policy: mongreldb_core::IndexBuildPolicy,
1312    ) -> Result<()> {
1313        let handle = self.inner.table(table).map_err(KitError::from)?;
1314        handle.lock().set_index_build_policy(policy);
1315        Ok(())
1316    }
1317
1318    /// Page-cache statistics for a table.
1319    pub fn table_page_cache_stats(&self, table: &str) -> Result<mongreldb_core::cache::CacheStats> {
1320        let handle = self.inner.table(table).map_err(KitError::from)?;
1321        let stats = handle.lock().page_cache_stats();
1322        Ok(stats)
1323    }
1324
1325    /// Number of sorted runs a table currently has (compaction target: 1).
1326    pub fn table_run_count(&self, table: &str) -> Result<usize> {
1327        let handle = self.inner.table(table).map_err(KitError::from)?;
1328        let n = handle.lock().run_count();
1329        Ok(n)
1330    }
1331
1332    /// Memtable length (uncommitted staged rows) for a table.
1333    pub fn table_memtable_len(&self, table: &str) -> Result<usize> {
1334        let handle = self.inner.table(table).map_err(KitError::from)?;
1335        let n = handle.lock().memtable_len();
1336        Ok(n)
1337    }
1338
1339    /// Mutable-run length for a table.
1340    pub fn table_mutable_run_len(&self, table: &str) -> Result<usize> {
1341        let handle = self.inner.table(table).map_err(KitError::from)?;
1342        let n = handle.lock().mutable_run_len();
1343        Ok(n)
1344    }
1345
1346    /// Page-cache entry count for a table.
1347    pub fn table_page_cache_len(&self, table: &str) -> Result<usize> {
1348        let handle = self.inner.table(table).map_err(KitError::from)?;
1349        let n = handle.lock().page_cache_len();
1350        Ok(n)
1351    }
1352
1353    /// Decoded-page-cache entry count for a table.
1354    pub fn table_decoded_cache_len(&self, table: &str) -> Result<usize> {
1355        let handle = self.inner.table(table).map_err(KitError::from)?;
1356        let n = handle.lock().decoded_cache_len();
1357        Ok(n)
1358    }
1359
1360    /// Run a SQL statement through the embedded `MongrelSession` (DataFusion
1361    /// frontend) and return the result as Arrow [`RecordBatch`]es. This is the
1362    /// Rust analogue of the TypeScript kit's `db.sql(sql)` (which returns Arrow
1363    /// IPC bytes) and the NAPI `Database.sql`.
1364    ///
1365    /// Read statements return their rows; DDL/DML (e.g. `CREATE VIEW`,
1366    /// `ANALYZE`, `VACUUM`, `CREATE VIRTUAL TABLE`) return an empty vec. Writes
1367    /// made directly through SQL bypass Kit-level constraints (defaults,
1368    /// enums, min/max, length, regex, triggers) — use the transactional
1369    /// [`Transaction`](crate::Transaction) API for constrained writes. The
1370    /// engine's own declarative constraints (unique, FK, check) still apply.
1371    ///
1372    /// The session is held for the database's lifetime, so session-scoped
1373    /// objects (views, prepared statements, the result cache) persist across
1374    /// calls — mirroring a long-lived database connection. After a migration
1375    /// that creates/drops tables, call [`Database::refresh_sql_session`] so the
1376    /// session sees the new table set.
1377    pub fn sql(&self, statement: &str) -> Result<Vec<arrow::record_batch::RecordBatch>> {
1378        // Take the cached session out of the mutex (or build one on first use)
1379        // so no `MutexGuard` is held across the async `run`. The kit's SQL
1380        // surface is `&self` and blocking; concurrent `sql()` calls on one
1381        // `Database` serialize here (applications needing concurrency should
1382        // use multiple handles, each with its own session).
1383        let session = match self.session.lock().take() {
1384            Some(s) => s,
1385            None => {
1386                mongreldb_query::MongrelSession::open(self.core_arc()).map_err(KitError::from)?
1387            }
1388        };
1389        let runtime = sql_runtime();
1390        let result = runtime
1391            .block_on(session.run(statement))
1392            .map_err(KitError::from);
1393        // Preserve the session (and any views/state created during the call).
1394        *self.session.lock() = Some(session);
1395        result
1396    }
1397
1398    /// (Re)build the cached SQL session so it sees the current table set. The
1399    /// engine's `MongrelSession` snapshots the table list at construction; this
1400    /// rebuilds it after a migration creates or drops tables. Views and other
1401    /// session-scoped state are reset.
1402    pub fn refresh_sql_session(&self) -> Result<()> {
1403        let session =
1404            mongreldb_query::MongrelSession::open(self.core_arc()).map_err(KitError::from)?;
1405        *self.session.lock() = Some(session);
1406        Ok(())
1407    }
1408
1409    /// Like [`Database::sql`], but returns the result serialized as Arrow IPC
1410    /// *file* bytes — the same wire format the NAPI addon and the daemon emit.
1411    /// Decode with `pyarrow.ipc.open_file`, the JS `apache-arrow`
1412    /// `tableFromIPC`, or [`crate::arrow_util::read_arrow_ipc`]. Empty for
1413    /// DDL/DML.
1414    pub fn sql_arrow(&self, statement: &str) -> Result<Vec<u8>> {
1415        let batches = self.sql(statement)?;
1416        crate::arrow_util::batches_to_ipc(&batches)
1417    }
1418
1419    /// Like [`Database::sql`], but materializes the result rows into JSON-style
1420    /// maps (column name → value) for callers that don't want to take a direct
1421    /// Arrow dependency. Empty for DDL/DML.
1422    pub fn sql_rows(&self, statement: &str) -> Result<Vec<serde_json::Map<String, Value>>> {
1423        let batches = self.sql(statement)?;
1424        crate::arrow_util::batches_to_rows(&batches)
1425    }
1426
1427    /// Direct HOT (PK → RowId) lookup via the core engine — no full-row
1428    /// materialization. Used by the §4.3 delete fast path when the table
1429    /// has no Kit-level constraints requiring guard cleanup.
1430    pub(crate) fn lookup_row_id(&self, table: &str, key: &[u8]) -> Result<Option<RowId>> {
1431        let handle = self.inner.table(table).map_err(KitError::from)?;
1432        let mut guard = handle.lock();
1433        guard.ensure_indexes_complete()?;
1434        Ok(guard.lookup_pk(key))
1435    }
1436
1437    pub(crate) fn root(&self) -> &Path {
1438        &self.root
1439    }
1440
1441    /// All visible core rows for a table at a specific read snapshot. Used so
1442    /// kit transactions read at their own snapshot (repeatable reads) rather
1443    /// than the latest committed state.
1444    pub(crate) fn visible_core_rows_at(
1445        &self,
1446        table_name: &str,
1447        snapshot: Snapshot,
1448    ) -> Result<Vec<CoreRow>> {
1449        let handle = self.inner.table(table_name).map_err(KitError::from)?;
1450        let guard = handle.lock();
1451        guard.visible_rows(snapshot).map_err(KitError::from)
1452    }
1453
1454    /// Query visible core rows with native `Condition`s at a specific read
1455    /// snapshot (Kit Priority 1 pushdown). Resolves `conditions` via core's
1456    /// indexes (HOT / bitmap / range) and returns only the matching rows —
1457    /// avoiding the full scan that `visible_core_rows_at` does. Returns the
1458    /// empty vec when no conditions match, and falls back to
1459    /// `visible_core_rows_at` when `conditions` is empty (unfiltered).
1460    pub(crate) fn query_core_rows_at(
1461        &self,
1462        table_name: &str,
1463        conditions: &[mongreldb_core::query::Condition],
1464        snapshot: Snapshot,
1465    ) -> Result<Vec<CoreRow>> {
1466        if conditions.is_empty() {
1467            return self.visible_core_rows_at(table_name, snapshot);
1468        }
1469        let handle = self.inner.table(table_name).map_err(KitError::from)?;
1470        let mut guard = handle.lock();
1471        let q = mongreldb_core::query::Query {
1472            conditions: conditions.to_vec(),
1473        };
1474        guard.query(&q).map_err(KitError::from)
1475    }
1476
1477    /// Drain `table`'s memtable into the mutable-run tier, spilling to a
1478    /// durable, checkpointed `.sr` run once the tier crosses its watermark.
1479    /// Called after a large batch commit (see `Transaction::commit`) so a
1480    /// short-lived process (the CLI, or any fresh `Database::open`) isn't
1481    /// stuck replaying the whole batch from the WAL on its next invocation —
1482    /// without a flush, committed-but-unflushed writes only exist as WAL
1483    /// records and must be fully replayed to rebuild the in-memory indexes.
1484    pub(crate) fn flush_table(&self, table_name: &str) -> Result<()> {
1485        let handle = self.inner.table(table_name).map_err(KitError::from)?;
1486        handle.lock().flush().map_err(KitError::from)?;
1487        Ok(())
1488    }
1489
1490    /// Count visible rows matching `conditions` without materializing them
1491    /// (Kit Priority 7 pushdown). Returns `None` when the conditions cannot be
1492    /// served by indexes, or when `snapshot` is not the latest committed epoch
1493    /// (caller falls back to a snapshot-correct row scan).
1494    ///
1495    /// `count_conditions` counts the engine's latest committed index state, not
1496    /// a snapshot-filtered scan, so it only matches a repeatable-read row count
1497    /// when the read snapshot IS the latest epoch. We hold the table lock while
1498    /// comparing, so no commit can interleave between the check and the count.
1499    pub(crate) fn count_core_rows_at(
1500        &self,
1501        table_name: &str,
1502        conditions: &[mongreldb_core::query::Condition],
1503        snapshot: Snapshot,
1504    ) -> Result<Option<u64>> {
1505        let handle = self.inner.table(table_name).map_err(KitError::from)?;
1506        let mut guard = handle.lock();
1507        if guard.snapshot().epoch != snapshot.epoch {
1508            return Ok(None); // stale read snapshot ⇒ caller scans
1509        }
1510        guard
1511            .count_conditions(conditions, snapshot)
1512            .map_err(KitError::from)
1513    }
1514
1515    /// Compute `SUM`/`MIN`/`MAX`/`AVG`/`COUNT(col)` over a column without
1516    /// materializing rows (Kit Priority 7), via the engine's native aggregate.
1517    /// `column` is the engine column id. Returns `None` when the engine fast
1518    /// path does not apply (multi-run / non-empty overlay / non-numeric column),
1519    /// or when `snapshot` is not the latest committed epoch — the same
1520    /// guarantee as [`count_core_rows_at`](Self::count_core_rows_at): the engine
1521    /// aggregate matches a snapshot-consistent row scan only at the latest epoch,
1522    /// and we compare under the table lock so no commit can interleave.
1523    pub(crate) fn aggregate_core_at(
1524        &self,
1525        table_name: &str,
1526        column: Option<u16>,
1527        conditions: &[mongreldb_core::query::Condition],
1528        agg: NativeAgg,
1529        snapshot: Snapshot,
1530    ) -> Result<Option<NativeAggResult>> {
1531        let handle = self.inner.table(table_name).map_err(KitError::from)?;
1532        let guard = handle.lock();
1533        if guard.snapshot().epoch != snapshot.epoch {
1534            return Ok(None); // stale read snapshot ⇒ caller scans
1535        }
1536        guard
1537            .aggregate_native(snapshot, column, conditions, agg)
1538            .map_err(KitError::from)
1539    }
1540
1541    /// `COUNT(DISTINCT col)` from the bitmap index's partition cardinality (Kit
1542    /// Priority 7) — the number of distinct indexed values, no scan. Returns
1543    /// `None` without a bitmap index on the column, when the table is not
1544    /// insert-only, or when `snapshot` is not the latest committed epoch. The
1545    /// engine method reads the latest committed index state (no snapshot
1546    /// parameter), so — as with [`count_core_rows_at`](Self::count_core_rows_at)
1547    /// — it only matches a repeatable-read scan at the latest epoch; we compare
1548    /// under the table lock so no commit can interleave.
1549    pub(crate) fn count_distinct_core_at(
1550        &self,
1551        table_name: &str,
1552        column_id: u16,
1553        snapshot: Snapshot,
1554    ) -> Result<Option<u64>> {
1555        let handle = self.inner.table(table_name).map_err(KitError::from)?;
1556        let mut guard = handle.lock();
1557        if guard.snapshot().epoch != snapshot.epoch {
1558            return Ok(None); // stale read snapshot ⇒ caller scans
1559        }
1560        guard
1561            .count_distinct_from_bitmap(column_id)
1562            .map_err(KitError::from)
1563    }
1564
1565    /// Materialize a single row by storage row id.
1566    #[allow(dead_code)]
1567    pub(crate) fn get_core_row(&self, table_name: &str, row_id: u64) -> Result<Option<CoreRow>> {
1568        let handle = self.inner.table(table_name).map_err(KitError::from)?;
1569        let guard = handle.lock();
1570        let snapshot = guard.snapshot();
1571        Ok(guard.get(mongreldb_core::RowId(row_id), snapshot))
1572    }
1573}
1574
1575pub(crate) fn create_core_table(db: &CoreDatabase, name: &str, schema: CoreSchema) -> Result<()> {
1576    if db.table_id(name).is_ok() {
1577        return Ok(());
1578    }
1579    db.create_table(name, schema).map_err(KitError::from)?;
1580    Ok(())
1581}
1582
1583/// A cached single-threaded tokio runtime for driving `MongrelSession::run`
1584/// (which is async) from the kit's otherwise-blocking SQL surface. Built once
1585/// per process and reused; `CurrentThread` is sufficient since the kit never
1586/// runs concurrent SQL statements on the same database from one thread.
1587fn sql_runtime() -> &'static tokio::runtime::Runtime {
1588    use std::sync::OnceLock;
1589    static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
1590    RT.get_or_init(|| {
1591        tokio::runtime::Builder::new_current_thread()
1592            .enable_all()
1593            .build()
1594            .expect("failed to build kit SQL tokio runtime")
1595    })
1596}
1597
1598fn core_procedure(spec: &ProcedureSpec) -> Result<mongreldb_core::StoredProcedure> {
1599    let parsed: mongreldb_core::StoredProcedure =
1600        serde_json::from_value(spec.json.clone()).map_err(KitError::from)?;
1601    mongreldb_core::StoredProcedure::new(parsed.name, parsed.mode, parsed.params, parsed.body, 0)
1602        .map_err(KitError::from)
1603}
1604
1605fn core_trigger(spec: &TriggerSpec) -> Result<mongreldb_core::StoredTrigger> {
1606    let parsed: mongreldb_core::StoredTrigger =
1607        serde_json::from_value(spec.json.clone()).map_err(KitError::from)?;
1608    mongreldb_core::StoredTrigger::new(
1609        parsed.name,
1610        mongreldb_core::TriggerDefinition {
1611            target: parsed.target,
1612            timing: parsed.timing,
1613            event: parsed.event,
1614            update_of: parsed.update_of,
1615            target_columns: parsed.target_columns,
1616            when: parsed.when,
1617            program: parsed.program,
1618        },
1619        0,
1620    )
1621    .map_err(KitError::from)
1622}
1623
1624fn json_to_core_value(value: &Value) -> Result<CoreValue> {
1625    match value {
1626        Value::Null => Ok(CoreValue::Null),
1627        Value::Bool(value) => Ok(CoreValue::Bool(*value)),
1628        Value::Number(value) => {
1629            if let Some(value) = value.as_i64() {
1630                Ok(CoreValue::Int64(value))
1631            } else if let Some(value) = value.as_f64() {
1632                Ok(CoreValue::Float64(value))
1633            } else {
1634                Err(KitError::Validation("unsupported JSON number".into()))
1635            }
1636        }
1637        Value::String(value) => Ok(CoreValue::Bytes(value.as_bytes().to_vec())),
1638        Value::Array(_) | Value::Object(_) => Err(KitError::Validation(
1639            "procedure args only support scalar JSON values".into(),
1640        )),
1641    }
1642}
1643
1644/// Read a `Bytes` column from an internal-table core row as a UTF-8 string.
1645pub(crate) fn internal_bytes(row: &CoreRow, col_id: u16) -> Option<String> {
1646    match row.columns.get(&col_id) {
1647        Some(CoreValue::Bytes(b)) => String::from_utf8(b.clone()).ok(),
1648        _ => None,
1649    }
1650}
1651
1652/// Best-effort: reap any WAL segments a previous session left rotated but
1653/// unreaped, now that this `open()` has minted a fresh active segment
1654/// (`SharedWal::open` never truncates prior segments on its own —
1655/// [`CoreDatabase::gc`] does, but only once every mounted table's data is
1656/// durable in runs). Called before any write in *this* session, so that
1657/// check reflects exactly what the previous session left behind: if that
1658/// session ended with everything flushed (e.g. a bulk `insert_many`
1659/// followed by `Transaction::commit`'s large-batch auto-flush), this is the
1660/// one moment the now-inactive segment holding that batch is actually
1661/// eligible for cleanup. Without it, a short-lived process (the CLI has no
1662/// daemon mode; every invocation opens cold) keeps paying to read and
1663/// deserialize that segment's records on every subsequent open, even though
1664/// none of them still need replaying. Errors are ignored — this is a
1665/// disk-usage/reopen-latency optimization, never a correctness requirement.
1666fn reap_rotated_wal_segments(db: &CoreDatabase) {
1667    let _ = db.gc();
1668}
1669
1670pub(crate) fn load_schema(path: &Path) -> Result<KitSchema> {
1671    let file = path.join(SCHEMA_FILE);
1672    let json = std::fs::read_to_string(&file)
1673        .map_err(|e| KitError::Migration(format!("cannot read schema file: {e}")))?;
1674    let schema: KitSchema = serde_json::from_str(&json)?;
1675    Ok(schema)
1676}
1677
1678pub(crate) fn store_schema(path: &Path, schema: &KitSchema) -> Result<()> {
1679    let file = path.join(SCHEMA_FILE);
1680    let json = serde_json::to_string_pretty(schema)?;
1681    std::fs::write(&file, json)?;
1682    Ok(())
1683}
1684
1685/// Persist a kit schema into the database. Used after migrations.
1686pub(crate) fn persist_schema(db: &Database, schema: &KitSchema) -> Result<()> {
1687    store_schema(&db.root, schema)
1688}