Skip to main content

brep_plm/
sql.rs

1//! The metadata store on disk: one SQLite file, `plm.sqlite`, in WAL mode.
2//!
3//! # Shape
4//!
5//! Each kind of record has its own table. The columns the store queries or
6//! constrains on are real columns (a part's number, a revision's label, a
7//! use's child part, an MPN), and the rest of the record is a JSON `body`
8//! column. That keeps every field the model has without a column per field,
9//! and a field a later slice adds needs no schema change: it rides in `body`.
10//! A record's children live in their own tables, not in its `body`:
11//!
12//! | table | one row per | constrained / indexed on |
13//! |---|---|---|
14//! | `parts` | part | `ord` (creation order, also the FTS rowid), `id`, `number_lc` UNIQUE, `category_lc` |
15//! | `revisions` | revision | `(part_id, label_lc)` UNIQUE |
16//! | `uses` | line of a revision's uses list | `child_part`, `child_revision` |
17//! | `manufacturer_parts` | MPN on a part | `manufacturer`, `mpn_lc` |
18//! | `supplier_offers` | offer under an MPN | `supplier`, `spn_lc` |
19//! | `part_tags` | tag on a part | `tag_lc` |
20//! | `users`, `sessions`, `api_tokens`, `part_types`, `categories`, `manufacturers`, `suppliers` | record | their ids |
21//! | `change_orders` | change order | `number_lc` UNIQUE, `state` |
22//! | `workspace` | workspace folder, link or file | `(owner, parent)`, `ord` |
23//! | `changes` | document key in the change log | `seq` |
24//! | `preferences` | one reserved key of one user ([`crate::api::preferences`]), not in the in-memory state | `(user_id, key)`, `(user_id, version)` |
25//! | `audit` | audit event | `at`, the actor, `kind`, `entity_id`, `part_id`, `action` |
26//! | `meta` | the sequence, the settings, and any state field with no table | `key` |
27//! | `parts_fts` | part (FTS5, trigram, contentless) | number, name, description, category, tags, attribute values, MPNs, SPNs |
28//!
29//! Documents are NOT here: they stay one file each under `models/`, as the CAD
30//! app writes them.
31//!
32//! # Reads
33//!
34//! The server still answers reads from the whole state held in memory
35//! ([`crate::db::Db::read`]), which this file loads at start-up. What SQL
36//! adds on the read side is the search index and the audit log's indexed
37//! queries, through a second connection so a search never waits on a write.
38//!
39//! # Versions
40//!
41//! `PRAGMA user_version` is the schema version. [`MIGRATIONS`] are applied in
42//! order, each in its own transaction, from whatever version the file has.
43//! A new schema change is a new entry at the end — never an edit to an old
44//! one, which a file in the field has already run.
45
46use std::collections::{BTreeMap, BTreeSet, HashMap};
47use std::path::{Path, PathBuf};
48use std::sync::Mutex;
49
50use rusqlite::{params, params_from_iter, Connection, OptionalExtension, Transaction};
51use serde_json::{Map, Value};
52
53use crate::audit::{AuditFilter, AuditSink};
54use crate::catalog;
55use crate::db::State;
56use crate::model::{AuditEvent, Category, ManufacturerPart, Part, Revision, Session, SupplierOffer, Use, WorkspaceEntry};
57use crate::table::Parts;
58
59/// The schema, one entry per version. Index `i` takes a file from version `i`
60/// to `i + 1`.
61const MIGRATIONS: &[&str] = &[
62    // 1: the first schema.
63    r#"
64    CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
65    CREATE TABLE users (id TEXT PRIMARY KEY, username_lc TEXT NOT NULL UNIQUE, ord INTEGER NOT NULL, body TEXT NOT NULL);
66    CREATE TABLE sessions (token TEXT PRIMARY KEY, user_id TEXT NOT NULL, ord INTEGER NOT NULL, body TEXT NOT NULL);
67    CREATE INDEX sessions_user ON sessions(user_id);
68    CREATE TABLE api_tokens (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, ord INTEGER NOT NULL, body TEXT NOT NULL);
69    CREATE TABLE part_types (id TEXT PRIMARY KEY, ord INTEGER NOT NULL, body TEXT NOT NULL);
70    CREATE TABLE categories (id TEXT PRIMARY KEY, id_lc TEXT NOT NULL UNIQUE, parent TEXT NOT NULL, ord INTEGER NOT NULL, body TEXT NOT NULL);
71    CREATE TABLE manufacturers (id TEXT PRIMARY KEY, ord INTEGER NOT NULL, body TEXT NOT NULL);
72    CREATE TABLE suppliers (id TEXT PRIMARY KEY, ord INTEGER NOT NULL, body TEXT NOT NULL);
73
74    CREATE TABLE parts (
75        ord INTEGER PRIMARY KEY,
76        id TEXT NOT NULL UNIQUE,
77        number TEXT NOT NULL,
78        number_lc TEXT NOT NULL UNIQUE,
79        part_type TEXT NOT NULL,
80        category_lc TEXT NOT NULL,
81        document_class TEXT NOT NULL,
82        created_at INTEGER NOT NULL,
83        body TEXT NOT NULL
84    );
85    CREATE INDEX parts_category ON parts(category_lc);
86    CREATE TABLE revisions (
87        id TEXT PRIMARY KEY,
88        part_id TEXT NOT NULL REFERENCES parts(id) ON DELETE CASCADE,
89        ord INTEGER NOT NULL,
90        label_lc TEXT NOT NULL,
91        lifecycle TEXT NOT NULL,
92        body TEXT NOT NULL,
93        UNIQUE (part_id, label_lc)
94    );
95    CREATE TABLE uses (
96        revision_id TEXT NOT NULL REFERENCES revisions(id) ON DELETE CASCADE,
97        ord INTEGER NOT NULL,
98        child_part TEXT NOT NULL,
99        child_revision TEXT NOT NULL,
100        quantity REAL NOT NULL,
101        body TEXT NOT NULL,
102        PRIMARY KEY (revision_id, ord)
103    );
104    CREATE INDEX uses_child_part ON uses(child_part);
105    CREATE INDEX uses_child_revision ON uses(child_revision);
106    CREATE TABLE manufacturer_parts (
107        id TEXT PRIMARY KEY,
108        part_id TEXT NOT NULL REFERENCES parts(id) ON DELETE CASCADE,
109        ord INTEGER NOT NULL,
110        manufacturer TEXT NOT NULL,
111        mpn_lc TEXT NOT NULL,
112        body TEXT NOT NULL
113    );
114    CREATE INDEX mp_part ON manufacturer_parts(part_id);
115    CREATE INDEX mp_manufacturer ON manufacturer_parts(manufacturer);
116    CREATE INDEX mp_mpn ON manufacturer_parts(mpn_lc);
117    CREATE TABLE supplier_offers (
118        id TEXT PRIMARY KEY,
119        manufacturer_part_id TEXT NOT NULL REFERENCES manufacturer_parts(id) ON DELETE CASCADE,
120        ord INTEGER NOT NULL,
121        supplier TEXT NOT NULL,
122        spn_lc TEXT NOT NULL,
123        body TEXT NOT NULL
124    );
125    CREATE INDEX offer_mp ON supplier_offers(manufacturer_part_id);
126    CREATE INDEX offer_supplier ON supplier_offers(supplier);
127    CREATE INDEX offer_spn ON supplier_offers(spn_lc);
128    CREATE TABLE part_tags (
129        part_id TEXT NOT NULL REFERENCES parts(id) ON DELETE CASCADE,
130        tag_lc TEXT NOT NULL,
131        PRIMARY KEY (part_id, tag_lc)
132    );
133    CREATE INDEX tags_tag ON part_tags(tag_lc);
134
135    CREATE TABLE changes (key TEXT PRIMARY KEY, seq INTEGER NOT NULL);
136    CREATE INDEX changes_seq ON changes(seq);
137
138    CREATE TABLE audit (
139        id INTEGER PRIMARY KEY AUTOINCREMENT,
140        at INTEGER NOT NULL,
141        actor_user_id TEXT NOT NULL,
142        actor_username_lc TEXT NOT NULL,
143        action TEXT NOT NULL,
144        kind TEXT NOT NULL,
145        entity_id TEXT NOT NULL,
146        part_id TEXT NOT NULL,
147        seq INTEGER NOT NULL,
148        body TEXT NOT NULL
149    );
150    CREATE INDEX audit_at ON audit(at);
151    CREATE INDEX audit_actor ON audit(actor_user_id);
152    CREATE INDEX audit_actor_name ON audit(actor_username_lc);
153    CREATE INDEX audit_kind ON audit(kind);
154    CREATE INDEX audit_entity ON audit(entity_id);
155    CREATE INDEX audit_part ON audit(part_id);
156    CREATE INDEX audit_action ON audit(action);
157
158    CREATE VIRTUAL TABLE parts_fts USING fts5(
159        number, name, description, category_id, category_path, tags, attributes, mpn, spn,
160        tokenize = 'trigram', content = '', contentless_delete = 1
161    );
162    "#,
163    // 2: change orders.
164    r#"
165    CREATE TABLE change_orders (
166        id TEXT PRIMARY KEY,
167        ord INTEGER NOT NULL,
168        number_lc TEXT NOT NULL UNIQUE,
169        state TEXT NOT NULL,
170        body TEXT NOT NULL
171    );
172    CREATE INDEX change_orders_state ON change_orders(state);
173    "#,
174    // 3: each user's preferences (`crate::api::preferences`). Not part of the
175    // in-memory state: a value is read and written here directly. A row whose
176    // `value` is NULL is a deleted key, kept so a client polling `since` sees
177    // the deletion; `version` counts per user and never goes down.
178    r#"
179    CREATE TABLE preferences (
180        user_id TEXT NOT NULL,
181        key TEXT NOT NULL,
182        version INTEGER NOT NULL,
183        modified INTEGER NOT NULL,
184        size INTEGER NOT NULL,
185        value TEXT,
186        PRIMARY KEY (user_id, key)
187    );
188    CREATE INDEX preferences_version ON preferences(user_id, version);
189    "#,
190    // 4: workspaces (plm-cad-integration P6): one row per folder, link or file.
191    r#"
192    CREATE TABLE IF NOT EXISTS workspace (
193        id TEXT PRIMARY KEY,
194        ord INTEGER NOT NULL,
195        owner TEXT NOT NULL,
196        parent TEXT NOT NULL,
197        body TEXT NOT NULL
198    );
199    CREATE INDEX IF NOT EXISTS workspace_folder ON workspace(owner, parent);
200    CREATE INDEX IF NOT EXISTS workspace_ord ON workspace(ord);
201    "#,
202    // 5: readable part primary keys and revisions scoped to their owning part.
203    r#"
204    CREATE TABLE parts_new (
205        id TEXT PRIMARY KEY NOT NULL,
206        ord INTEGER NOT NULL UNIQUE,
207        number TEXT NOT NULL,
208        number_lc TEXT NOT NULL UNIQUE,
209        part_type TEXT NOT NULL,
210        category_lc TEXT NOT NULL,
211        document_class TEXT NOT NULL,
212        created_at INTEGER NOT NULL,
213        body TEXT NOT NULL
214    );
215    INSERT INTO parts_new SELECT id, ord, number, number_lc, part_type, category_lc, document_class, created_at, body FROM parts;
216    CREATE TABLE revisions_new (
217        id TEXT NOT NULL,
218        part_id TEXT NOT NULL REFERENCES parts(id) ON DELETE CASCADE,
219        ord INTEGER NOT NULL,
220        label_lc TEXT NOT NULL,
221        lifecycle TEXT NOT NULL,
222        body TEXT NOT NULL,
223        PRIMARY KEY(part_id, id),
224        UNIQUE(part_id, label_lc)
225    );
226    INSERT INTO revisions_new SELECT * FROM revisions;
227    CREATE TABLE uses_new (
228        part_id TEXT NOT NULL,
229        revision_id TEXT NOT NULL,
230        ord INTEGER NOT NULL,
231        child_part TEXT NOT NULL,
232        child_revision TEXT NOT NULL,
233        quantity REAL NOT NULL,
234        body TEXT NOT NULL,
235        PRIMARY KEY(part_id, revision_id, ord),
236        FOREIGN KEY(part_id, revision_id) REFERENCES revisions(part_id, id) ON DELETE CASCADE
237    );
238    INSERT INTO uses_new SELECT r.part_id, u.revision_id, u.ord, u.child_part, u.child_revision, u.quantity, u.body FROM uses u JOIN revisions r ON r.id = u.revision_id;
239    DROP TABLE uses;
240    DROP TABLE revisions;
241    DROP TABLE parts;
242    ALTER TABLE parts_new RENAME TO parts;
243    ALTER TABLE revisions_new RENAME TO revisions;
244    ALTER TABLE uses_new RENAME TO uses;
245    CREATE INDEX parts_category ON parts(category_lc);
246    CREATE INDEX uses_child_part ON uses(child_part);
247    CREATE INDEX uses_child_revision ON uses(child_part, child_revision);
248    "#,
249
250];
251
252/// The schema version this build writes. A file with a HIGHER version was
253/// written by a newer server, and this one refuses to open it rather than
254/// guess what the newer columns mean.
255pub fn schema_version() -> i32 {
256    MIGRATIONS.len() as i32
257}
258
259/// Separates the values of one multi-valued search column (tags, attribute
260/// values, MPNs), so a search cannot match across two of them. A trigram
261/// phrase never contains it: the search text is one line a person typed.
262const SEP: &str = "\u{1f}";
263
264/// The tables whose rows are one keyed record of a top-level state list, and
265/// how to fill their indexed columns from a record's JSON.
266struct Keyed {
267    /// The field of [`State`] and the table's name.
268    name: &'static str,
269    /// The record field that is the primary key.
270    key: &'static str,
271    /// Indexed columns: (column, record field, lower-cased?).
272    columns: &'static [(&'static str, &'static str, bool)],
273}
274
275const KEYED: &[Keyed] = &[
276    Keyed { name: "users", key: "id", columns: &[("username_lc", "username", true)] },
277    Keyed { name: "api_tokens", key: "id", columns: &[("user_id", "user_id", false)] },
278    Keyed { name: "part_types", key: "id", columns: &[] },
279    Keyed { name: "categories", key: "id", columns: &[("id_lc", "id", true), ("parent", "parent", false)] },
280    Keyed { name: "manufacturers", key: "id", columns: &[] },
281    Keyed { name: "suppliers", key: "id", columns: &[] },
282    Keyed {
283        name: "change_orders",
284        key: "id",
285        columns: &[("number_lc", "number", true), ("state", "state", false)],
286    },
287];
288
289/// The state fields with a home of their own; any OTHER top-level field is
290/// kept whole in `meta` under `state.<field>`, so a field a later slice adds
291/// to [`State`] is persisted before anyone gives it a table.
292const OWN_HOME: &[&str] = &["seq", "changes_from", "changes", "settings", "parts", "workspace", "sessions"];
293
294/// How long a commit waits for the disk.
295///
296/// The server always runs [`Durability::Full`]: a commit is on disk before
297/// the response that reports it. [`Durability::Normal`] exists for the test
298/// suites, which open hundreds of short-lived stores on a shared disk and
299/// spent most of their wall time in fsync. In WAL mode `NORMAL` stays
300/// consistent after a crash but may lose the last commits to a power cut, so
301/// nothing that serves users opens with it: `tests/storage.rs`
302/// (`the_server_opens_its_store_with_full_sync`) pins that.
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub enum Durability {
305    /// `PRAGMA synchronous = FULL`.
306    Full,
307    /// `PRAGMA synchronous = NORMAL`. Tests only.
308    Normal,
309}
310
311impl Durability {
312    fn pragma(self) -> &'static str {
313        match self {
314            Durability::Full => "PRAGMA synchronous = FULL;",
315            Durability::Normal => "PRAGMA synchronous = NORMAL;",
316        }
317    }
318}
319
320/// The SQLite store: a writer connection used under the store's write lock,
321/// a reader for searches and audit queries, and a checkpointer thread.
322pub struct Sql {
323    path: PathBuf,
324    writer: Mutex<Connection>,
325    reader: Mutex<Connection>,
326    checkpointer: Option<Checkpointer>,
327}
328
329/// Folds the write-ahead log back into the main file, off the request path.
330///
331/// SQLite's default is to checkpoint inside whichever commit pushes the log
332/// past 1,000 pages — so one unlucky request pays for copying and syncing
333/// everything written since the last one (half a second at small scale,
334/// seconds after a bulk import). Here the writer never checkpoints
335/// (`wal_autocheckpoint = 0`); this thread does, every second, in PASSIVE
336/// mode, which never blocks a writer or a reader.
337struct Checkpointer {
338    stop: std::sync::mpsc::Sender<()>,
339    thread: Option<std::thread::JoinHandle<()>>,
340}
341
342impl Checkpointer {
343    fn start(path: &Path, durability: Durability) -> rusqlite::Result<Checkpointer> {
344        let conn = Connection::open(path)?;
345        configure(&conn, durability)?;
346        let (stop, stopped) = std::sync::mpsc::channel::<()>();
347        let thread = std::thread::Builder::new()
348            .name("plm-checkpoint".into())
349            .spawn(move || loop {
350                let done = !matches!(
351                    stopped.recv_timeout(std::time::Duration::from_secs(1)),
352                    Err(std::sync::mpsc::RecvTimeoutError::Timeout)
353                );
354                if let Err(error) = conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE);") {
355                    eprintln!("brep-plm: checkpoint: {error}");
356                }
357                if done {
358                    break;
359                }
360            })
361            .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
362        Ok(Checkpointer { stop, thread: Some(thread) })
363    }
364}
365
366impl Drop for Sql {
367    fn drop(&mut self) {
368        if let Some(mut checkpointer) = self.checkpointer.take() {
369            let _ = checkpointer.stop.send(());
370            if let Some(thread) = checkpointer.thread.take() {
371                let _ = thread.join();
372            }
373        }
374    }
375}
376
377fn configure(conn: &Connection, durability: Durability) -> rusqlite::Result<()> {
378    // WAL: readers never block the writer or each other. synchronous=FULL,
379    // the server's only setting (see [`Durability`]): a commit is on disk
380    // before the response that reports it, so a number handed out survives a
381    // power cut, as it did with the file store.
382    conn.execute_batch(durability.pragma())?;
383    conn.execute_batch("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;")?;
384    conn.busy_timeout(std::time::Duration::from_secs(10))?;
385    Ok(())
386}
387
388/// Bring `conn`'s schema up to [`schema_version`].
389fn migrate(conn: &mut Connection) -> rusqlite::Result<()> {
390    let version: i32 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
391    if version > schema_version() {
392        return Err(rusqlite::Error::InvalidParameterName(format!(
393            "plm.sqlite is schema version {version}, and this server only knows up to {} — run a newer server",
394            schema_version()
395        )));
396    }
397    for (index, script) in MIGRATIONS.iter().enumerate().skip(version.max(0) as usize) {
398        let tx = conn.transaction()?;
399        // Development fixtures may replay earlier migrations on a database
400        // that already has scoped revision keys.
401        let scoped: bool = index == 4 && tx.query_row(
402            "SELECT EXISTS(SELECT 1 FROM pragma_table_info('uses') WHERE name = 'part_id')",
403            [], |r| r.get(0))?;
404        if !scoped { tx.execute_batch(script)?; }
405        tx.pragma_update(None, "user_version", index as i32 + 1)?;
406        tx.commit()?;
407    }
408    Ok(())
409}
410
411impl Sql {
412    /// Open (or create) the store file at `path`, migrating its schema, with
413    /// [`Durability::Full`].
414    pub fn open(path: impl Into<PathBuf>) -> rusqlite::Result<Sql> {
415        Sql::open_with(path, Durability::Full)
416    }
417
418    /// [`Sql::open`] at a chosen [`Durability`].
419    pub fn open_with(path: impl Into<PathBuf>, durability: Durability) -> rusqlite::Result<Sql> {
420        let path = path.into();
421        let mut writer = Connection::open(&path)?;
422        configure(&writer, durability)?;
423        writer.pragma_update(None, "foreign_keys", false)?;
424        migrate(&mut writer)?;
425        writer.pragma_update(None, "foreign_keys", true)?;
426        // The checkpointer thread folds the log back in; once it has, the next
427        // write restarts the log from the top, and the file is cut back to
428        // 64 MB rather than keeping the size of the largest burst ever.
429        writer.execute_batch("PRAGMA wal_autocheckpoint = 0; PRAGMA journal_size_limit = 67108864;")?;
430        let reader = Connection::open(&path)?;
431        configure(&reader, durability)?;
432        let checkpointer = Some(Checkpointer::start(&path, durability)?);
433        Ok(Sql { path, writer: Mutex::new(writer), reader: Mutex::new(reader), checkpointer })
434    }
435
436    pub fn path(&self) -> &Path {
437        &self.path
438    }
439
440    /// The writer connection's `PRAGMA synchronous`: 2 is FULL, 1 NORMAL.
441    pub fn synchronous(&self) -> rusqlite::Result<i64> {
442        self.writer().query_row("PRAGMA synchronous", [], |row| row.get(0))
443    }
444
445    fn writer(&self) -> std::sync::MutexGuard<'_, Connection> {
446        self.writer.lock().unwrap_or_else(|e| e.into_inner())
447    }
448
449    fn reader(&self) -> std::sync::MutexGuard<'_, Connection> {
450        self.reader.lock().unwrap_or_else(|e| e.into_inner())
451    }
452
453    /// A `meta` value.
454    pub fn meta(&self, key: &str) -> rusqlite::Result<Option<String>> {
455        self.writer()
456            .query_row("SELECT value FROM meta WHERE key = ?1", [key], |row| row.get(0))
457            .optional()
458    }
459
460    /// Set a `meta` value outside any change (start-up bookkeeping).
461    pub fn set_meta(&self, key: &str, value: &str) -> rusqlite::Result<()> {
462        self.writer().execute(
463            "INSERT INTO meta(key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
464            params![key, value],
465        )?;
466        Ok(())
467    }
468
469    /// The whole state, or `None` for a store nothing has been written to.
470    pub fn load(&self) -> rusqlite::Result<Option<State>> {
471        let conn = self.writer();
472        let mut object = Map::new();
473        let mut stmt = conn.prepare("SELECT key, value FROM meta")?;
474        let mut seen_seq = false;
475        for row in stmt.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))? {
476            let (key, value) = row?;
477            let parsed: Value = serde_json::from_str(&value).map_err(json_error)?;
478            match key.as_str() {
479                "seq" => {
480                    seen_seq = true;
481                    object.insert(key, parsed);
482                }
483                "changes_from" | "settings" => {
484                    object.insert(key, parsed);
485                }
486                other => {
487                    if let Some(field) = other.strip_prefix("state.") {
488                        object.insert(field.to_string(), parsed);
489                    }
490                }
491            }
492        }
493        if !seen_seq {
494            return Ok(None);
495        }
496        for keyed in KEYED {
497            let mut stmt = conn.prepare(&format!("SELECT body FROM {} ORDER BY ord", keyed.name))?;
498            let rows: Vec<Value> = stmt
499                .query_map([], |row| row.get::<_, String>(0))?
500                .map(|body| body.and_then(|b| serde_json::from_str(&b).map_err(json_error)))
501                .collect::<rusqlite::Result<_>>()?;
502            object.insert(keyed.name.to_string(), Value::Array(rows));
503        }
504        let mut stmt = conn.prepare("SELECT key, seq FROM changes ORDER BY seq, key")?;
505        let changes: Vec<Value> = stmt
506            .query_map([], |row| {
507                Ok(serde_json::json!({ "key": row.get::<_, String>(0)?, "seq": row.get::<_, i64>(1)? }))
508            })?
509            .collect::<rusqlite::Result<_>>()?;
510        object.insert("changes".into(), Value::Array(changes));
511
512        let mut state: State = serde_json::from_value(Value::Object(object)).map_err(json_error)?;
513        state.parts = load_parts(&conn)?;
514        state.workspace = load_workspace(&conn)?;
515        state.sessions = load_sessions(&conn)?;
516        Ok(Some(state))
517    }
518
519    /// Write one change in ONE transaction: the state fields that moved, the
520    /// parts that moved, the search index for them, and the change's audit
521    /// events. Either all of it is on disk when this returns `Ok`, or none of
522    /// it is. The events come back numbered.
523    pub fn write(&self, change: &Change<'_>, events: Vec<AuditEvent>) -> rusqlite::Result<Vec<AuditEvent>> {
524        let mut conn = self.writer();
525        let tx = conn.transaction()?;
526        write_small(&tx, change.before, change.after)?;
527        for (position, part) in &change.parts {
528            write_part(&tx, *position, part, change.categories)?;
529        }
530        for &position in &change.reindex {
531            index_part(&tx, position, &change.all_parts[position], change.categories)?;
532        }
533        for (id, entry) in &change.workspace {
534            write_entry(&tx, id, *entry)?;
535        }
536        for (token, session) in &change.sessions {
537            write_session(&tx, token, *session)?;
538        }
539        let events = insert_events(&tx, events)?;
540        tx.commit()?;
541        Ok(events)
542    }
543
544    /// Every part whose number, name, description, category, tags,
545    /// attribute values, MPNs or SPNs contain `needle` as a substring (at
546    /// least three characters, ignoring case) — the FTS5 trigram index —
547    /// together with the indexed narrowing in `query`. Creation order, from
548    /// after `query.after`, at most `query.limit`.
549    pub fn candidates(&self, query: &Candidates<'_>) -> rusqlite::Result<Vec<(i64, String)>> {
550        let mut sql = String::from("SELECT p.ord, p.id FROM parts p WHERE 1");
551        let mut args: Vec<rusqlite::types::Value> = Vec::new();
552        if let Some(needle) = query.needle {
553            sql.push_str(" AND p.ord IN (SELECT rowid FROM parts_fts WHERE parts_fts MATCH ?)");
554            args.push(format!("\"{}\"", needle.replace('"', "\"\"")).into());
555        }
556        if let Some(ids) = query.categories {
557            if ids.is_empty() {
558                sql.push_str(" AND 0");
559            } else {
560                sql.push_str(&format!(" AND p.category_lc IN ({})", vec!["?"; ids.len()].join(",")));
561                args.extend(ids.iter().map(|id| id.to_ascii_lowercase().into()));
562            }
563        }
564        if query.uncategorized {
565            sql.push_str(" AND p.category_lc NOT IN (SELECT id_lc FROM categories)");
566        }
567        // `IN (subquery)`, not a correlated `EXISTS`: SQLite then walks the
568        // filter's own index once instead of probing it for every part.
569        if let Some(tag) = query.tag {
570            sql.push_str(" AND p.id IN (SELECT t.part_id FROM part_tags t WHERE t.tag_lc = ?)");
571            args.push(tag.to_ascii_lowercase().into());
572        }
573        if let Some(manufacturer) = query.manufacturer {
574            sql.push_str(" AND p.id IN (SELECT m.part_id FROM manufacturer_parts m WHERE m.manufacturer = ?)");
575            args.push(manufacturer.to_string().into());
576        }
577        if let Some(supplier) = query.supplier {
578            sql.push_str(
579                " AND p.id IN (SELECT m.part_id FROM supplier_offers o JOIN manufacturer_parts m \
580                 ON m.id = o.manufacturer_part_id WHERE o.supplier = ?)",
581            );
582            args.push(supplier.to_string().into());
583        }
584        if let Some(after) = query.after {
585            sql.push_str(" AND p.ord > ?");
586            args.push(after.into());
587        }
588        sql.push_str(" ORDER BY p.ord");
589        if let Some(limit) = query.limit {
590            sql.push_str(" LIMIT ?");
591            args.push((limit as i64).into());
592        }
593        let conn = self.reader();
594        let mut stmt = conn.prepare(&sql)?;
595        let rows = stmt.query_map(params_from_iter(args), |row| Ok((row.get(0)?, row.get(1)?)))?;
596        rows.collect()
597    }
598
599    /// Replace everything in the file with `state` and `events`, in one
600    /// transaction — the import from the file store.
601    pub fn import(&self, state: &mut State, events: Vec<AuditEvent>) -> rusqlite::Result<()> {
602        let after = small_value(state);
603        let mut conn = self.writer();
604        let tx = conn.transaction()?;
605        let empty = Value::Object(Map::new());
606        write_small(&tx, &empty, &after)?;
607        for (position, part) in state.parts.iter().enumerate() {
608            write_part(&tx, position, part, &state.categories)?;
609        }
610        for entry in state.workspace.iter() {
611            write_entry(&tx, &entry.id, Some(entry))?;
612        }
613        for session in state.sessions.iter() {
614            write_session(&tx, &session.token, Some(session))?;
615        }
616        insert_events(&tx, events)?;
617        tx.commit()
618    }
619
620    /// Fold the write-ahead log into the main file, so the file alone is
621    /// the whole store (before it is renamed or copied).
622    pub fn checkpoint(&self) -> rusqlite::Result<()> {
623        self.writer().execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
624    }
625
626    /// Row counts by table, for the migration report.
627    pub fn counts(&self) -> rusqlite::Result<BTreeMap<String, i64>> {
628        let conn = self.writer();
629        let mut out = BTreeMap::new();
630        for table in [
631            "users",
632            "sessions",
633            "api_tokens",
634            "part_types",
635            "categories",
636            "manufacturers",
637            "suppliers",
638            "change_orders",
639            "workspace",
640            "parts",
641            "revisions",
642            "uses",
643            "manufacturer_parts",
644            "supplier_offers",
645            "part_tags",
646            "changes",
647            "audit",
648            "preferences",
649        ] {
650            let n: i64 = conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |row| row.get(0))?;
651            out.insert(table.to_string(), n);
652        }
653        Ok(out)
654    }
655}
656
657/// One row of a user's preferences, without its value.
658#[derive(Debug, Clone, PartialEq, serde::Serialize)]
659pub struct PreferenceRow {
660    pub key: String,
661    pub version: u64,
662    pub size: u64,
663    pub modified: u64,
664    /// A deleted key, listed only to a client asking `since` a version before
665    /// the deletion.
666    pub deleted: bool,
667}
668
669impl Sql {
670    /// A user's preferences version (0 before their first write) and their
671    /// rows: every live key by name when `since` is 0, else every row — live
672    /// or deleted — written after `since`, oldest first.
673    pub fn preferences(&self, user_id: &str, since: u64) -> rusqlite::Result<(u64, Vec<PreferenceRow>)> {
674        let conn = self.reader();
675        let version: i64 = conn.query_row(
676            "SELECT COALESCE(MAX(version), 0) FROM preferences WHERE user_id = ?1",
677            [user_id],
678            |row| row.get(0),
679        )?;
680        let sql = if since == 0 {
681            "SELECT key, version, size, modified, value IS NULL FROM preferences
682             WHERE user_id = ?1 AND value IS NOT NULL ORDER BY key"
683        } else {
684            "SELECT key, version, size, modified, value IS NULL FROM preferences
685             WHERE user_id = ?1 AND version > ?2 ORDER BY version"
686        };
687        let mut stmt = conn.prepare(sql)?;
688        let map = |row: &rusqlite::Row<'_>| {
689            Ok(PreferenceRow {
690                key: row.get(0)?,
691                version: row.get::<_, i64>(1)? as u64,
692                size: row.get::<_, i64>(2)? as u64,
693                modified: row.get::<_, i64>(3)? as u64,
694                deleted: row.get(4)?,
695            })
696        };
697        let rows = if since == 0 {
698            stmt.query_map([user_id], map)?.collect::<rusqlite::Result<_>>()?
699        } else {
700            stmt.query_map(params![user_id, since as i64], map)?.collect::<rusqlite::Result<_>>()?
701        };
702        Ok((version.max(0) as u64, rows))
703    }
704
705    /// One live preference's value and version.
706    pub fn preference(&self, user_id: &str, key: &str) -> rusqlite::Result<Option<(String, u64)>> {
707        self.reader()
708            .query_row(
709                "SELECT value, version FROM preferences WHERE user_id = ?1 AND key = ?2 AND value IS NOT NULL",
710                params![user_id, key],
711                |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as u64)),
712            )
713            .optional()
714    }
715
716    /// Write (`Some`) or delete (`None`) one preference, and its audit event
717    /// if it has one, in ONE transaction. Returns the user's version after:
718    /// bumped by a write, and by a delete of a live key; a delete of a key
719    /// that is not there changes nothing and logs nothing.
720    pub fn set_preference(
721        &self,
722        user_id: &str,
723        key: &str,
724        value: Option<&str>,
725        at: u64,
726        event: Option<AuditEvent>,
727    ) -> rusqlite::Result<u64> {
728        let mut conn = self.writer();
729        let tx = conn.transaction()?;
730        let current: i64 = tx.query_row(
731            "SELECT COALESCE(MAX(version), 0) FROM preferences WHERE user_id = ?1",
732            [user_id],
733            |row| row.get(0),
734        )?;
735        if value.is_none() {
736            let live: bool = tx.query_row(
737                "SELECT EXISTS(SELECT 1 FROM preferences WHERE user_id = ?1 AND key = ?2 AND value IS NOT NULL)",
738                params![user_id, key],
739                |row| row.get(0),
740            )?;
741            if !live {
742                return Ok(current.max(0) as u64);
743            }
744        }
745        let version = current + 1;
746        tx.execute(
747            "INSERT INTO preferences(user_id, key, version, modified, size, value) VALUES (?1, ?2, ?3, ?4, ?5, ?6)
748             ON CONFLICT(user_id, key) DO UPDATE SET
749                 version = excluded.version, modified = excluded.modified,
750                 size = excluded.size, value = excluded.value",
751            params![user_id, key, version, at as i64, value.map_or(0, |v| v.len() as i64), value],
752        )?;
753        insert_events(&tx, event.into_iter().collect())?;
754        tx.commit()?;
755        Ok(version as u64)
756    }
757}
758
759/// What one committed change moved, for [`Sql::write`].
760pub struct Change<'a> {
761    /// The state without its parts, before and after ([`small_value`]).
762    pub before: &'a Value,
763    pub after: &'a Value,
764    /// Each part that changed or was created, at its creation-order position.
765    pub parts: Vec<(usize, &'a Part)>,
766    /// The catalog after the change: a part's category path is indexed.
767    pub categories: &'a [Category],
768    /// Positions of parts whose search row must be rewritten although the
769    /// part itself did not change: its category's path moved.
770    pub reindex: Vec<usize>,
771    pub all_parts: &'a Parts,
772    /// Each workspace entry that changed: its id, and what it is now
773    /// (`None`: removed).
774    pub workspace: Vec<(String, Option<&'a WorkspaceEntry>)>,
775    /// Each session that changed: its token, and what it is now.
776    pub sessions: Vec<(String, Option<&'a Session>)>,
777}
778
779/// The indexed narrowing of a parts search ([`Sql::candidates`]).
780#[derive(Default)]
781pub struct Candidates<'a> {
782    /// Search text, at least three characters.
783    pub needle: Option<&'a str>,
784    /// Category ids the part must be in (ignoring case).
785    pub categories: Option<&'a [String]>,
786    /// Only parts whose category names no category.
787    pub uncategorized: bool,
788    pub tag: Option<&'a str>,
789    /// A manufacturer id.
790    pub manufacturer: Option<&'a str>,
791    /// A supplier id.
792    pub supplier: Option<&'a str>,
793    /// Creation-order position to continue after (a page cursor).
794    pub after: Option<i64>,
795    pub limit: Option<usize>,
796}
797
798/// The state as JSON without its parts, workspaces or sessions: every other
799/// field, whatever it is. Those lists are swapped out for the length of the
800/// serialization, so they are never serialized (they are what grows); each
801/// has its own journal and table.
802pub fn small_value(state: &mut State) -> Value {
803    let parts = std::mem::take(&mut state.parts);
804    let workspace = std::mem::take(&mut state.workspace);
805    let sessions = std::mem::take(&mut state.sessions);
806    let mut value = serde_json::to_value(&*state).unwrap_or(Value::Null);
807    state.parts = parts;
808    state.workspace = workspace;
809    state.sessions = sessions;
810    if let Some(object) = value.as_object_mut() {
811        object.remove("parts");
812        object.remove("workspace");
813        object.remove("sessions");
814    }
815    value
816}
817
818fn json_error(error: serde_json::Error) -> rusqlite::Error {
819    rusqlite::Error::ToSqlConversionFailure(Box::new(error))
820}
821
822fn text(value: &Value, field: &str) -> String {
823    match value.get(field) {
824        Some(Value::String(s)) => s.clone(),
825        Some(Value::Null) | None => String::new(),
826        Some(other) => other.to_string(),
827    }
828}
829
830/// Write the state fields that differ between `before` and `after`.
831fn write_small(tx: &Transaction<'_>, before: &Value, after: &Value) -> rusqlite::Result<()> {
832    let empty = Map::new();
833    let old = before.as_object().unwrap_or(&empty);
834    let new = after.as_object().unwrap_or(&empty);
835    let set_meta = |key: &str, value: &Value| -> rusqlite::Result<()> {
836        tx.execute(
837            "INSERT INTO meta(key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
838            params![key, value.to_string()],
839        )?;
840        Ok(())
841    };
842    let keys: BTreeSet<&String> = old.keys().chain(new.keys()).collect();
843    for key in keys {
844        let was = old.get(key).unwrap_or(&Value::Null);
845        let now = new.get(key).unwrap_or(&Value::Null);
846        if was == now {
847            continue;
848        }
849        match key.as_str() {
850            "seq" | "changes_from" | "settings" => set_meta(key, now)?,
851            "changes" => write_changes(tx, was, now)?,
852            "parts" => {}
853            name => match KEYED.iter().find(|k| k.name == name) {
854                Some(keyed) => write_keyed(tx, keyed, was, now)?,
855                None if !OWN_HOME.contains(&name) => set_meta(&format!("state.{name}"), now)?,
856                None => {}
857            },
858        }
859    }
860    Ok(())
861}
862
863/// Row-diff a keyed list: delete what went, upsert what is new, changed or moved.
864fn write_keyed(tx: &Transaction<'_>, keyed: &Keyed, before: &Value, after: &Value) -> rusqlite::Result<()> {
865    let empty = Vec::new();
866    let old: HashMap<String, (usize, &Value)> = before
867        .as_array()
868        .unwrap_or(&empty)
869        .iter()
870        .enumerate()
871        .map(|(i, v)| (text(v, keyed.key), (i, v)))
872        .collect();
873    let new_rows = after.as_array().unwrap_or(&empty);
874    let new_keys: BTreeSet<String> = new_rows.iter().map(|v| text(v, keyed.key)).collect();
875    let pk = if keyed.key == "token" { "token" } else { "id" };
876    for gone in old.keys().filter(|k| !new_keys.contains(*k)) {
877        tx.execute(&format!("DELETE FROM {} WHERE {pk} = ?1", keyed.name), [gone])?;
878    }
879    let mut columns = vec![pk, "ord", "body"];
880    columns.extend(keyed.columns.iter().map(|(c, _, _)| *c));
881    let placeholders: Vec<String> = (1..=columns.len()).map(|i| format!("?{i}")).collect();
882    let updates: Vec<String> = columns.iter().skip(1).map(|c| format!("{c} = excluded.{c}")).collect();
883    let sql = format!(
884        "INSERT INTO {}({}) VALUES ({}) ON CONFLICT({pk}) DO UPDATE SET {}",
885        keyed.name,
886        columns.join(", "),
887        placeholders.join(", "),
888        updates.join(", ")
889    );
890    let mut stmt = tx.prepare_cached(&sql)?;
891    for (ord, row) in new_rows.iter().enumerate() {
892        let key = text(row, keyed.key);
893        if old.get(&key).is_some_and(|(i, v)| *i == ord && *v == row) {
894            continue;
895        }
896        let mut values: Vec<rusqlite::types::Value> =
897            vec![key.into(), (ord as i64).into(), row.to_string().into()];
898        for (_, field, lower) in keyed.columns {
899            let value = text(row, field);
900            values.push(if *lower { value.to_ascii_lowercase() } else { value }.into());
901        }
902        stmt.execute(params_from_iter(values))?;
903    }
904    Ok(())
905}
906
907/// The change log: upsert keys that moved, delete keys that were dropped.
908fn write_changes(tx: &Transaction<'_>, before: &Value, after: &Value) -> rusqlite::Result<()> {
909    let empty = Vec::new();
910    let pairs = |v: &Value| -> HashMap<String, i64> {
911        v.as_array()
912            .unwrap_or(&empty)
913            .iter()
914            .map(|c| (text(c, "key"), c.get("seq").and_then(Value::as_i64).unwrap_or(0)))
915            .collect()
916    };
917    let old = pairs(before);
918    let new = pairs(after);
919    for key in old.keys().filter(|k| !new.contains_key(*k)) {
920        tx.execute("DELETE FROM changes WHERE key = ?1", [key])?;
921    }
922    let mut stmt =
923        tx.prepare_cached("INSERT INTO changes(key, seq) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET seq = excluded.seq")?;
924    for (key, seq) in &new {
925        if old.get(key) != Some(seq) {
926            stmt.execute(params![key, seq])?;
927        }
928    }
929    Ok(())
930}
931
932/// Write one workspace entry, or delete it (`None`). A new row goes after
933/// every other (`ord`), so entries load in creation order; an updated row
934/// keeps its place.
935fn write_entry(tx: &Transaction<'_>, id: &str, entry: Option<&WorkspaceEntry>) -> rusqlite::Result<()> {
936    match entry {
937        None => {
938            tx.execute("DELETE FROM workspace WHERE id = ?1", [id])?;
939        }
940        Some(entry) => {
941            let body = serde_json::to_string(entry).map_err(json_error)?;
942            tx.prepare_cached(
943                "INSERT INTO workspace(id, ord, owner, parent, body) \
944                 VALUES (?1, (SELECT coalesce(max(ord), 0) + 1 FROM workspace), ?2, ?3, ?4) \
945                 ON CONFLICT(id) DO UPDATE SET owner = excluded.owner, parent = excluded.parent, body = excluded.body",
946            )?
947            .execute(params![id, entry.owner, entry.parent, body])?;
948        }
949    }
950    Ok(())
951}
952
953/// Write one session, or delete it (`None`). `ord` is the sign-in time, so
954/// sessions load in the order they were made without a scan for the largest
955/// `ord` on every `last_seen` stamp.
956fn write_session(tx: &Transaction<'_>, token: &str, session: Option<&Session>) -> rusqlite::Result<()> {
957    match session {
958        None => {
959            tx.execute("DELETE FROM sessions WHERE token = ?1", [token])?;
960        }
961        Some(session) => {
962            let body = serde_json::to_string(session).map_err(json_error)?;
963            tx.prepare_cached(
964                "INSERT INTO sessions(token, user_id, ord, body) VALUES (?1, ?2, ?3, ?4) \
965                 ON CONFLICT(token) DO UPDATE SET user_id = excluded.user_id, body = excluded.body",
966            )?
967            .execute(params![token, session.user_id, session.created_at as i64, body])?;
968        }
969    }
970    Ok(())
971}
972
973fn load_sessions(conn: &Connection) -> rusqlite::Result<crate::journal::Journaled<Session>> {
974    let mut stmt = conn.prepare("SELECT body FROM sessions ORDER BY ord, rowid")?;
975    let sessions: Vec<Session> = stmt
976        .query_map([], |row| row.get::<_, String>(0))?
977        .map(|body| body.and_then(|b| serde_json::from_str(&b).map_err(json_error)))
978        .collect::<rusqlite::Result<_>>()?;
979    Ok(crate::journal::Journaled::from_vec(sessions))
980}
981
982fn load_workspace(conn: &Connection) -> rusqlite::Result<crate::workspace::Workspace> {
983    let mut stmt = conn.prepare("SELECT body FROM workspace ORDER BY ord")?;
984    let entries: Vec<WorkspaceEntry> = stmt
985        .query_map([], |row| row.get::<_, String>(0))?
986        .map(|body| body.and_then(|b| serde_json::from_str(&b).map_err(json_error)))
987        .collect::<rusqlite::Result<_>>()?;
988    Ok(crate::workspace::Workspace::from_vec(entries))
989}
990
991/// A record's JSON with its child lists taken out: they have tables.
992fn body_without(value: &impl serde::Serialize, children: &[&str]) -> rusqlite::Result<String> {
993    let mut value = serde_json::to_value(value).map_err(json_error)?;
994    if let Some(object) = value.as_object_mut() {
995        for child in children {
996            object.remove(*child);
997        }
998    }
999    Ok(value.to_string())
1000}
1001
1002/// Write one part and everything under it, and its search row.
1003fn write_part(tx: &Transaction<'_>, position: usize, part: &Part, categories: &[Category]) -> rusqlite::Result<()> {
1004    tx.prepare_cached(
1005        "INSERT INTO parts(ord, id, number, number_lc, part_type, category_lc, document_class, created_at, body)
1006         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
1007         ON CONFLICT(ord) DO UPDATE SET id = excluded.id, number = excluded.number, number_lc = excluded.number_lc,
1008           part_type = excluded.part_type, category_lc = excluded.category_lc,
1009           document_class = excluded.document_class, created_at = excluded.created_at, body = excluded.body",
1010    )?
1011    .execute(params![
1012        position as i64,
1013        part.id,
1014        part.number,
1015        part.number.to_ascii_lowercase(),
1016        part.part_type,
1017        part.category.to_ascii_lowercase(),
1018        part.document_class.as_str(),
1019        part.created_at as i64,
1020        body_without(part, &["revisions", "sourcing"])?,
1021    ])?;
1022    tx.prepare_cached("DELETE FROM revisions WHERE part_id = ?1")?.execute([&part.id])?;
1023    tx.prepare_cached("DELETE FROM manufacturer_parts WHERE part_id = ?1")?.execute([&part.id])?;
1024    tx.prepare_cached("DELETE FROM part_tags WHERE part_id = ?1")?.execute([&part.id])?;
1025    for (ord, revision) in part.revisions.iter().enumerate() {
1026        tx.prepare_cached(
1027            "INSERT INTO revisions(id, part_id, ord, label_lc, lifecycle, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1028        )?
1029        .execute(params![
1030            revision.id,
1031            part.id,
1032            ord as i64,
1033            revision.label.to_ascii_lowercase(),
1034            revision.lifecycle.as_str(),
1035            body_without(revision, &["uses"])?,
1036        ])?;
1037        for (line, use_) in revision.uses.iter().enumerate() {
1038            tx.prepare_cached(
1039                "INSERT INTO uses(revision_id, ord, child_part, child_revision, quantity, body, part_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1040            )?
1041            .execute(params![
1042                revision.id,
1043                line as i64,
1044                use_.part,
1045                use_.revision,
1046                use_.quantity,
1047                serde_json::to_string(use_).map_err(json_error)?,
1048                part.id,
1049            ])?;
1050        }
1051    }
1052    for (ord, mp) in part.sourcing.iter().enumerate() {
1053        tx.prepare_cached(
1054            "INSERT INTO manufacturer_parts(id, part_id, ord, manufacturer, mpn_lc, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1055        )?
1056        .execute(params![mp.id, part.id, ord as i64, mp.manufacturer, mp.mpn.to_ascii_lowercase(), body_without(mp, &["offers"])?])?;
1057        for (line, offer) in mp.offers.iter().enumerate() {
1058            tx.prepare_cached(
1059                "INSERT INTO supplier_offers(id, manufacturer_part_id, ord, supplier, spn_lc, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1060            )?
1061            .execute(params![
1062                offer.id,
1063                mp.id,
1064                line as i64,
1065                offer.supplier,
1066                offer.spn.to_ascii_lowercase(),
1067                serde_json::to_string(offer).map_err(json_error)?,
1068            ])?;
1069        }
1070    }
1071    let tags: BTreeSet<String> = part.tags.iter().map(|t| t.to_ascii_lowercase()).collect();
1072    for tag in tags {
1073        tx.prepare_cached("INSERT INTO part_tags(part_id, tag_lc) VALUES (?1, ?2)")?.execute(params![part.id, tag])?;
1074    }
1075    index_part(tx, position, part, categories)
1076}
1077
1078/// (Re)write a part's search row.
1079fn index_part(tx: &Transaction<'_>, position: usize, part: &Part, categories: &[Category]) -> rusqlite::Result<()> {
1080    tx.prepare_cached("DELETE FROM parts_fts WHERE rowid = ?1")?.execute([position as i64])?;
1081    let attributes: Vec<String> = part
1082        .attributes
1083        .values()
1084        .filter_map(|value| match value {
1085            Value::String(text) => Some(text.clone()),
1086            Value::Number(n) => Some(n.to_string()),
1087            _ => None,
1088        })
1089        .collect();
1090    let mpn: Vec<&str> = part.sourcing.iter().map(|mp| mp.mpn.as_str()).collect();
1091    let spn: Vec<&str> = part.sourcing.iter().flat_map(|mp| mp.offers.iter().map(|o| o.spn.as_str())).collect();
1092    tx.prepare_cached(
1093        "INSERT INTO parts_fts(rowid, number, name, description, category_id, category_path, tags, attributes, mpn, spn)
1094         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
1095    )?
1096    .execute(params![
1097        position as i64,
1098        part.number,
1099        part.name,
1100        part.description,
1101        part.category,
1102        catalog::path_name(categories, &part.category),
1103        part.tags.join(SEP),
1104        attributes.join(SEP),
1105        mpn.join(SEP),
1106        spn.join(SEP),
1107    ])?;
1108    Ok(())
1109}
1110
1111/// Every part with its revisions, uses and sourcing, in creation order.
1112fn load_parts(conn: &Connection) -> rusqlite::Result<Parts> {
1113    let rows = |sql: &str| -> rusqlite::Result<Vec<(String, String)>> {
1114        let mut stmt = conn.prepare(sql)?;
1115        let found = stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
1116        found.collect()
1117    };
1118    let parse = |body: &str| -> rusqlite::Result<Value> { serde_json::from_str(body).map_err(json_error) };
1119
1120    let mut offers: HashMap<String, Vec<SupplierOffer>> = HashMap::new();
1121    for (mp, body) in rows("SELECT manufacturer_part_id, body FROM supplier_offers ORDER BY manufacturer_part_id, ord")? {
1122        offers.entry(mp).or_default().push(serde_json::from_value(parse(&body)?).map_err(json_error)?);
1123    }
1124    let mut sourcing: HashMap<String, Vec<ManufacturerPart>> = HashMap::new();
1125    for (part, body) in rows("SELECT part_id, body FROM manufacturer_parts ORDER BY part_id, ord")? {
1126        let mut mp: ManufacturerPart = serde_json::from_value(parse(&body)?).map_err(json_error)?;
1127        mp.offers = offers.remove(&mp.id).unwrap_or_default();
1128        sourcing.entry(part).or_default().push(mp);
1129    }
1130    let mut uses: HashMap<String, Vec<Use>> = HashMap::new();
1131    for (revision, body) in rows("SELECT json_array(part_id, revision_id), body FROM uses ORDER BY part_id, revision_id, ord")? {
1132        uses.entry(revision).or_default().push(serde_json::from_value(parse(&body)?).map_err(json_error)?);
1133    }
1134    let mut revisions: HashMap<String, Vec<Revision>> = HashMap::new();
1135    for (part, body) in rows("SELECT part_id, body FROM revisions ORDER BY part_id, ord")? {
1136        let mut revision: Revision = serde_json::from_value(parse(&body)?).map_err(json_error)?;
1137        revision.uses = uses.remove(&serde_json::json!([part, revision.id]).to_string()).unwrap_or_default();
1138        revisions.entry(part).or_default().push(revision);
1139    }
1140    let mut parts = Vec::new();
1141    for (_, body) in rows("SELECT id, body FROM parts ORDER BY ord")? {
1142        let mut part: Part = serde_json::from_value(parse(&body)?).map_err(json_error)?;
1143        part.revisions = revisions.remove(&part.id).unwrap_or_default();
1144        part.sourcing = sourcing.remove(&part.id).unwrap_or_default();
1145        parts.push(part);
1146    }
1147    Ok(Parts::from_vec(parts))
1148}
1149
1150/// Append audit events inside `tx`, numbering those that carry id 0 and
1151/// keeping the ids of imported ones.
1152fn insert_events(tx: &Transaction<'_>, mut events: Vec<AuditEvent>) -> rusqlite::Result<Vec<AuditEvent>> {
1153    let mut stmt = tx.prepare_cached(
1154        "INSERT INTO audit(id, at, actor_user_id, actor_username_lc, action, kind, entity_id, part_id, seq, body)
1155         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
1156    )?;
1157    for event in &mut events {
1158        let id: Option<i64> = (event.id != 0).then_some(event.id as i64);
1159        let mut stored = event.clone();
1160        stored.id = 0;
1161        let part_id = if event.entity.kind == "part" && event.entity.part_id.is_empty() {
1162            event.entity.id.clone()
1163        } else {
1164            event.entity.part_id.clone()
1165        };
1166        stmt.execute(params![
1167            id,
1168            event.at as i64,
1169            event.actor.user_id,
1170            event.actor.username.to_ascii_lowercase(),
1171            event.action,
1172            event.entity.kind,
1173            event.entity.id,
1174            part_id,
1175            event.seq as i64,
1176            serde_json::to_string(&stored).map_err(json_error)?,
1177        ])?;
1178        event.id = tx.last_insert_rowid() as u64;
1179    }
1180    Ok(events)
1181}
1182
1183impl AuditSink for Sql {
1184    fn append(&self, events: Vec<AuditEvent>) -> std::io::Result<Vec<AuditEvent>> {
1185        if events.is_empty() {
1186            return Ok(events);
1187        }
1188        let mut conn = self.writer();
1189        let run = || -> rusqlite::Result<Vec<AuditEvent>> {
1190            let tx = conn.transaction()?;
1191            let events = insert_events(&tx, events)?;
1192            tx.commit()?;
1193            Ok(events)
1194        };
1195        run().map_err(std::io::Error::other)
1196    }
1197
1198    fn query(&self, filter: &AuditFilter) -> std::io::Result<Vec<AuditEvent>> {
1199        let mut sql = String::from("SELECT id, body FROM audit WHERE 1");
1200        let mut args: Vec<rusqlite::types::Value> = Vec::new();
1201        let mut eq = |sql: &mut String, column: &str, value: &str| {
1202            sql.push_str(&format!(" AND {column} = ?"));
1203            args.push(value.to_string().into());
1204        };
1205        if !filter.kind.is_empty() {
1206            eq(&mut sql, "kind", &filter.kind);
1207        }
1208        if !filter.entity.is_empty() {
1209            eq(&mut sql, "entity_id", &filter.entity);
1210        }
1211        if !filter.action.is_empty() {
1212            eq(&mut sql, "action", &filter.action);
1213        }
1214        if !filter.part.is_empty() {
1215            eq(&mut sql, "part_id", &filter.part);
1216        }
1217        if !filter.kinds.is_empty() {
1218            sql.push_str(&format!(" AND kind IN ({})", vec!["?"; filter.kinds.len()].join(",")));
1219            args.extend(filter.kinds.iter().map(|k| k.clone().into()));
1220        }
1221        if !filter.user.is_empty() {
1222            sql.push_str(" AND (actor_user_id = ? OR actor_username_lc = ?)");
1223            args.push(filter.user.clone().into());
1224            args.push(filter.user.to_ascii_lowercase().into());
1225        }
1226        if let Some(since) = filter.since {
1227            sql.push_str(" AND at >= ?");
1228            args.push((since as i64).into());
1229        }
1230        if let Some(until) = filter.until {
1231            sql.push_str(" AND at <= ?");
1232            args.push((until as i64).into());
1233        }
1234        if let Some(before) = filter.before {
1235            sql.push_str(" AND id < ?");
1236            args.push((before as i64).into());
1237        }
1238        sql.push_str(" ORDER BY id DESC");
1239        if let Some(limit) = filter.limit {
1240            sql.push_str(" LIMIT ?");
1241            args.push((limit as i64).into());
1242        }
1243        let run = || -> rusqlite::Result<Vec<AuditEvent>> {
1244            let conn = self.reader();
1245            let mut stmt = conn.prepare(&sql)?;
1246            let rows = stmt.query_map(params_from_iter(args), |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))?;
1247            let mut out = Vec::new();
1248            for row in rows {
1249                let (id, body) = row?;
1250                let mut event: AuditEvent = serde_json::from_str(&body).map_err(json_error)?;
1251                event.id = id as u64;
1252                out.push(event);
1253            }
1254            Ok(out)
1255        };
1256        run().map_err(std::io::Error::other)
1257    }
1258}
1259
1260/// Whether `error` is a UNIQUE (or other) constraint the schema enforces —
1261/// a rule the store's own checks should have refused first.
1262pub fn is_constraint(error: &rusqlite::Error) -> bool {
1263    matches!(
1264        error,
1265        rusqlite::Error::SqliteFailure(e, _) if e.code == rusqlite::ErrorCode::ConstraintViolation
1266    )
1267}