1
//! POD types for the SQL database surface (SUPER_PLAN_2 §4 P4.3).
2
//!
3
//! Engine-agnostic: the public API is SQL strings plus typed value arrays,
4
//! so the engine (bundled SQLite via `rusqlite`) stays fully hidden behind
5
//! the `db-sqlite` feature in `azul-dll`. The handle type (`Db`, wrapping a
6
//! `rusqlite::Connection`) lives in the dll — like `App` — because it
7
//! carries an engine resource; these param/result *data* types live here in
8
//! `azul-core` (no engine dep) so they're always present and codegen-able.
9
//!
10
//! Shape: `db.execute(sql, params: DbValueVec) -> rows_affected` and
11
//! `db.query(sql, params) -> DbRows`. `DbValue` maps onto SQLite's five
12
//! storage classes.
13

            
14
use alloc::vec::Vec;
15

            
16
use azul_css::{corety::OptionString, AzString, StringVec, U8Vec};
17

            
18
use crate::refany::{OptionRefAny, RefAny};
19

            
20
/// A single SQL value — a bound statement parameter or a result cell.
21
/// Mirrors `SQLite`'s storage classes (Null / Integer / Real / Text / Blob)
22
/// but names nothing engine-specific.
23
#[repr(C, u8)]
24
#[derive(Debug, Clone, PartialEq, Default)]
25
pub enum DbValue {
26
    /// SQL `NULL`. Also the `Default`: the Python binding's callback
27
    /// trampolines return `<ReturnType>::default()` when the Python side
28
    /// cannot be reached, and a callback that yields a `DbValue` has to have
29
    /// one — without it `python_api.rs` failed to compile on all three OSes.
30
    #[default]
31
    Null,
32
    /// 64-bit signed integer.
33
    Integer(i64),
34
    /// 64-bit IEEE float.
35
    Real(f64),
36
    /// UTF-8 text.
37
    Text(AzString),
38
    /// Raw bytes.
39
    Blob(U8Vec),
40
}
41

            
42
impl DbValue {
43
    #[must_use]
44
14
    pub const fn is_null(&self) -> bool {
45
14
        matches!(self, Self::Null)
46
14
    }
47
    #[must_use]
48
22
    pub const fn as_integer(&self) -> Option<i64> {
49
22
        if let Self::Integer(i) = self {
50
15
            Some(*i)
51
        } else {
52
7
            None
53
        }
54
22
    }
55
    #[must_use]
56
21
    pub const fn as_real(&self) -> Option<f64> {
57
21
        if let Self::Real(r) = self {
58
16
            Some(*r)
59
        } else {
60
5
            None
61
        }
62
21
    }
63
    #[must_use]
64
12
    pub const fn as_text(&self) -> Option<&AzString> {
65
12
        if let Self::Text(t) = self {
66
7
            Some(t)
67
        } else {
68
5
            None
69
        }
70
12
    }
71
}
72

            
73
impl_vec!(
74
    DbValue,
75
    DbValueVec,
76
    DbValueVecDestructor,
77
    DbValueVecDestructorType,
78
    DbValueVecSlice,
79
    OptionDbValue
80
);
81
impl_vec_debug!(DbValue, DbValueVec);
82
impl_vec_clone!(DbValue, DbValueVec, DbValueVecDestructor);
83
impl_vec_partialeq!(DbValue, DbValueVec);
84
impl_option!(
85
    DbValue,
86
    OptionDbValue,
87
    copy = false,
88
    [Debug, Clone, PartialEq]
89
);
90

            
91
/// The result of `db.query(...)` — a column-named, row-major value grid.
92
/// Flat (not nested vectors) for a simple FFI shape: cell `(row, col)` is
93
/// `values[row * num_columns + col]`.
94
#[repr(C)]
95
#[derive(Debug, Clone, PartialEq)]
96
pub struct DbRows {
97
    /// Column names; `len()` is the number of columns.
98
    pub columns: StringVec,
99
    /// All cells, row-major. `len()` is `num_rows * num_columns`.
100
    pub values: DbValueVec,
101
}
102

            
103
impl DbRows {
104
    /// Number of result columns.
105
    #[must_use]
106
1925
    pub fn num_columns(&self) -> usize {
107
1925
        self.columns.as_ref().len()
108
1925
    }
109
    /// Number of result rows (`0` when there are no columns).
110
    #[must_use]
111
518
    pub fn num_rows(&self) -> usize {
112
518
        let cols = self.num_columns();
113
518
        if cols == 0 {
114
24
            0
115
        } else {
116
494
            self.values.as_ref().len() / cols
117
        }
118
518
    }
119
    /// The cell at `(row, col)`, or `None` if out of range.
120
    #[must_use]
121
1162
    pub fn get(&self, row: usize, col: usize) -> Option<&DbValue> {
122
1162
        let cols = self.num_columns();
123
1162
        if col >= cols {
124
190
            return None;
125
972
        }
126
        // Checked so an out-of-range `row` (whose `row * cols + col` overflows
127
        // usize) resolves to None instead of panicking (debug) / wrapping to a
128
        // real cell (release).
129
972
        let idx = row.checked_mul(cols)?.checked_add(col)?;
130
971
        self.values.as_ref().get(idx)
131
1162
    }
132
}
133

            
134
// ============================================================================
135
// Local-first key/value store: configuration, schema, scope, sync, results
136
// ============================================================================
137
//
138
// The portable `Db` surface is a key/value + index store with working-set
139
// replication: the local store (turso-backed SQLite on desktop, IndexedDB on
140
// web) holds a scoped working set, writes are queued in a row-level oplog,
141
// and `sync_now` pushes dirty rows to an optional backup endpoint and pulls
142
// the remote changes back. Raw SQL is not part of the API on any target.
143
// These are the POD halves; the handle (`Db`) lives in the dll with the
144
// engine.
145

            
146
/// How a sync conflict (the same key changed locally and remotely since the
147
/// last sync) is resolved for a store.
148
#[repr(C)]
149
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150
pub enum DbConflictPolicy {
151
    /// The newer modification wins (the default).
152
    LastWriteWins,
153
    /// The remote value always wins.
154
    ServerWins,
155
    /// The local value always wins.
156
    ClientWins,
157
    /// The store's `DbMergeCallback` (see `Db::set_on_conflict`) computes the
158
    /// merged value; falls back to `LastWriteWins` when none is registered.
159
    Merge,
160
}
161

            
162
/// A secondary index over a store.
163
///
164
/// Values are indexed when they are JSON
165
/// objects: `key_path` names the top-level field whose value becomes the
166
/// index key; values that are not JSON objects, or lack the field, are
167
/// simply not indexed.
168
#[repr(C)]
169
#[derive(Debug, Clone, PartialEq, Eq)]
170
pub struct DbIndexSchema {
171
    pub name: AzString,
172
    pub key_path: AzString,
173
    pub unique: bool,
174
}
175

            
176
impl_vec!(
177
    DbIndexSchema,
178
    DbIndexSchemaVec,
179
    DbIndexSchemaVecDestructor,
180
    DbIndexSchemaVecDestructorType,
181
    DbIndexSchemaVecSlice,
182
    OptionDbIndexSchema
183
);
184
impl_vec_debug!(DbIndexSchema, DbIndexSchemaVec);
185
impl_vec_clone!(DbIndexSchema, DbIndexSchemaVec, DbIndexSchemaVecDestructor);
186
impl_vec_partialeq!(DbIndexSchema, DbIndexSchemaVec);
187
impl_option!(
188
    DbIndexSchema,
189
    OptionDbIndexSchema,
190
    copy = false,
191
    [Debug, Clone, PartialEq, Eq]
192
);
193

            
194
/// One store (collection) of a `DbSchema`: its name, indexes and the
195
/// conflict policy applied when syncing it.
196
#[repr(C)]
197
#[derive(Debug, Clone, PartialEq)]
198
pub struct DbStoreSchema {
199
    pub name: AzString,
200
    pub indexes: DbIndexSchemaVec,
201
    pub conflict_policy: DbConflictPolicy,
202
}
203

            
204
impl_vec!(
205
    DbStoreSchema,
206
    DbStoreSchemaVec,
207
    DbStoreSchemaVecDestructor,
208
    DbStoreSchemaVecDestructorType,
209
    DbStoreSchemaVecSlice,
210
    OptionDbStoreSchema
211
);
212
impl_vec_debug!(DbStoreSchema, DbStoreSchemaVec);
213
impl_vec_clone!(DbStoreSchema, DbStoreSchemaVec, DbStoreSchemaVecDestructor);
214
impl_vec_partialeq!(DbStoreSchema, DbStoreSchemaVec);
215
impl_option!(
216
    DbStoreSchema,
217
    OptionDbStoreSchema,
218
    copy = false,
219
    [Debug, Clone, PartialEq]
220
);
221

            
222
/// The declarative schema of a database: its stores with their indexes and
223
/// conflict policies.
224
///
225
/// No DDL strings - the engine derives its tables from
226
/// this on every target. Stores not declared here are created on first
227
/// write, without indexes and with `LastWriteWins`.
228
#[repr(C)]
229
#[derive(Debug, Clone, PartialEq)]
230
pub struct DbSchema {
231
    pub stores: DbStoreSchemaVec,
232
}
233

            
234
impl DbSchema {
235
    /// A schema with no declared stores.
236
    #[must_use]
237
    pub const fn empty() -> Self {
238
        Self {
239
            stores: DbStoreSchemaVec::from_vec(Vec::new()),
240
        }
241
    }
242

            
243
    /// The declared schema of `store`, if any.
244
    #[must_use]
245
    pub fn store(&self, store: &str) -> Option<&DbStoreSchema> {
246
        self.stores
247
            .as_ref()
248
            .iter()
249
            .find(|s| s.name.as_str() == store)
250
    }
251
}
252

            
253
impl Default for DbSchema {
254
    fn default() -> Self {
255
        Self::empty()
256
    }
257
}
258

            
259
/// A key range: `None` bounds are unbounded, `*_open` excludes the bound
260
/// itself. Keys order the way `SQLite` orders values (Null < numbers < text <
261
/// blobs).
262
#[repr(C)]
263
#[derive(Debug, Clone, PartialEq)]
264
pub struct DbKeyRange {
265
    pub lower: OptionDbValue,
266
    pub upper: OptionDbValue,
267
    pub lower_open: bool,
268
    pub upper_open: bool,
269
}
270

            
271
impl DbKeyRange {
272
    /// Every key.
273
    #[must_use]
274
    pub const fn all() -> Self {
275
        Self {
276
            lower: OptionDbValue::None,
277
            upper: OptionDbValue::None,
278
            lower_open: false,
279
            upper_open: false,
280
        }
281
    }
282

            
283
    /// `lower <= key <= upper`.
284
    #[must_use]
285
    pub const fn between(lower: DbValue, upper: DbValue) -> Self {
286
        Self {
287
            lower: OptionDbValue::Some(lower),
288
            upper: OptionDbValue::Some(upper),
289
            lower_open: false,
290
            upper_open: false,
291
        }
292
    }
293

            
294
    /// Exactly `key`.
295
    #[must_use]
296
    pub fn only(key: DbValue) -> Self {
297
        Self::between(key.clone(), key)
298
    }
299
}
300

            
301
impl Default for DbKeyRange {
302
    fn default() -> Self {
303
        Self::all()
304
    }
305
}
306

            
307
impl_option!(
308
    DbKeyRange,
309
    OptionDbKeyRange,
310
    copy = false,
311
    [Debug, Clone, PartialEq]
312
);
313

            
314
/// A predicate over a store's secondary index: the rows whose index key
315
/// falls in `range`.
316
#[repr(C)]
317
#[derive(Debug, Clone, PartialEq)]
318
pub struct DbIndexPredicate {
319
    pub index: AzString,
320
    pub range: DbKeyRange,
321
}
322

            
323
impl_option!(
324
    DbIndexPredicate,
325
    OptionDbIndexPredicate,
326
    copy = false,
327
    [Debug, Clone, PartialEq]
328
);
329

            
330
/// The part of one store a scope covers: a key range and / or an index
331
/// predicate; both `None` means the whole store.
332
#[repr(C)]
333
#[derive(Debug, Clone, PartialEq)]
334
pub struct DbCollectionScope {
335
    pub store: AzString,
336
    pub range: OptionDbKeyRange,
337
    pub index_predicate: OptionDbIndexPredicate,
338
}
339

            
340
impl DbCollectionScope {
341
    /// The whole `store`.
342
    #[must_use]
343
    pub const fn whole_store(store: AzString) -> Self {
344
        Self {
345
            store,
346
            range: OptionDbKeyRange::None,
347
            index_predicate: OptionDbIndexPredicate::None,
348
        }
349
    }
350

            
351
    /// Whether `key` in `store` falls inside this collection scope. Index
352
    /// predicates cannot be evaluated from the key alone and count as a
353
    /// match; the engine narrows them where it has the index.
354
    #[must_use]
355
    pub fn covers(&self, store: &str, key: &DbValue) -> bool {
356
        if self.store.as_str() != store {
357
            return false;
358
        }
359
        self.range
360
            .as_ref()
361
            .is_none_or(|range| range_contains(range, key))
362
    }
363
}
364

            
365
impl_vec!(
366
    DbCollectionScope,
367
    DbCollectionScopeVec,
368
    DbCollectionScopeVecDestructor,
369
    DbCollectionScopeVecDestructorType,
370
    DbCollectionScopeVecSlice,
371
    OptionDbCollectionScope
372
);
373
impl_vec_debug!(DbCollectionScope, DbCollectionScopeVec);
374
impl_vec_clone!(
375
    DbCollectionScope,
376
    DbCollectionScopeVec,
377
    DbCollectionScopeVecDestructor
378
);
379
impl_vec_partialeq!(DbCollectionScope, DbCollectionScopeVec);
380
impl_option!(
381
    DbCollectionScope,
382
    OptionDbCollectionScope,
383
    copy = false,
384
    [Debug, Clone, PartialEq]
385
);
386

            
387
/// The working set a database replicates locally: a set of collection
388
/// scopes. An empty scope means "everything the remote has".
389
#[repr(C)]
390
#[derive(Debug, Clone, PartialEq)]
391
pub struct DbScope {
392
    pub collections: DbCollectionScopeVec,
393
}
394

            
395
impl DbScope {
396
    /// Everything.
397
    #[must_use]
398
    pub const fn everything() -> Self {
399
        Self {
400
            collections: DbCollectionScopeVec::from_vec(Vec::new()),
401
        }
402
    }
403

            
404
    /// Whether `key` in `store` falls inside this scope.
405
    #[must_use]
406
    pub fn covers(&self, store: &str, key: &DbValue) -> bool {
407
        let collections = self.collections.as_ref();
408
        collections.is_empty() || collections.iter().any(|c| c.covers(store, key))
409
    }
410
}
411

            
412
impl Default for DbScope {
413
    fn default() -> Self {
414
        Self::everything()
415
    }
416
}
417

            
418
impl_option!(
419
    DbScope,
420
    OptionDbScope,
421
    copy = false,
422
    [Debug, Clone, PartialEq]
423
);
424

            
425
/// Compares two values the way the store orders keys: Null < numbers < text
426
/// < blobs, numbers by value, text and blobs bytewise.
427
#[must_use]
428
/// Order an integer against a real the way `SQLite` does
429
/// (`sqlite3IntFloatCompare`), without first rounding the integer to `f64`.
430
///
431
/// `i64 as f64` is exact only up to 2^53; above that, integers that differ
432
/// round to the same double and would compare `Equal` — 9007199254740993 vs
433
/// 9007199254740992.0, say — and the DB would treat two distinct keys as one.
434
/// So: decide by the real's magnitude first (outside i64's range the answer
435
/// needs no conversion), then compare the integer against the real's
436
/// truncation, and only if THOSE are equal look at the real's fraction.
437
fn compare_int_real(i: i64, r: f64) -> core::cmp::Ordering {
438
    use core::cmp::Ordering;
439
    // `total_cmp` semantics for NaN, matching the Real/Real arm: NaN sorts
440
    // after every finite value.
441
    if r.is_nan() {
442
        return Ordering::Less;
443
    }
444
    // 2^63 is exactly representable; everything at or beyond it is above
445
    // any i64, everything below -2^63 is below any i64.
446
    if r >= 9_223_372_036_854_775_808.0 {
447
        return Ordering::Less;
448
    }
449
    if r < -9_223_372_036_854_775_808.0 {
450
        return Ordering::Greater;
451
    }
452
    // In range: truncation toward zero is exact for a double this size.
453
    #[allow(clippy::cast_possible_truncation)] // bounds checked just above
454
    let r_trunc = r as i64;
455
    match i.cmp(&r_trunc) {
456
        Ordering::Equal => {
457
            // Same integer part. The real is bigger iff it has a positive
458
            // fraction, smaller iff negative; `r - trunc` is exact here
459
            // because both share an exponent.
460
            #[allow(clippy::cast_precision_loss)]
461
            // |r_trunc| == |trunc(r)| <= 2^63, and r_trunc == trunc(r) exactly, so this cast reproduces r's own integer part
462
            let frac = r - (r_trunc as f64);
463
            if frac > 0.0 {
464
                Ordering::Less
465
            } else if frac < 0.0 {
466
                Ordering::Greater
467
            } else {
468
                Ordering::Equal
469
            }
470
        }
471
        other => other,
472
    }
473
}
474

            
475
#[must_use]
476
pub fn compare_db_values(a: &DbValue, b: &DbValue) -> core::cmp::Ordering {
477
    use core::cmp::Ordering;
478
    const fn class(v: &DbValue) -> u8 {
479
        match v {
480
            DbValue::Null => 0,
481
            DbValue::Integer(_) | DbValue::Real(_) => 1,
482
            DbValue::Text(_) => 2,
483
            DbValue::Blob(_) => 3,
484
        }
485
    }
486
    match class(a).cmp(&class(b)) {
487
        Ordering::Equal => {}
488
        other => return other,
489
    }
490
    match (a, b) {
491
        (DbValue::Integer(x), DbValue::Integer(y)) => x.cmp(y),
492
        (DbValue::Integer(x), DbValue::Real(y)) => compare_int_real(*x, *y),
493
        (DbValue::Real(x), DbValue::Integer(y)) => compare_int_real(*y, *x).reverse(),
494
        (DbValue::Real(x), DbValue::Real(y)) => x.total_cmp(y),
495
        (DbValue::Text(x), DbValue::Text(y)) => x.as_str().as_bytes().cmp(y.as_str().as_bytes()),
496
        (DbValue::Blob(x), DbValue::Blob(y)) => x.as_ref().cmp(y.as_ref()),
497
        _ => Ordering::Equal,
498
    }
499
}
500

            
501
/// Whether `key` falls inside `range` under [`compare_db_values`].
502
#[must_use]
503
pub fn range_contains(range: &DbKeyRange, key: &DbValue) -> bool {
504
    use core::cmp::Ordering;
505
    if let Some(lower) = range.lower.as_ref() {
506
        match compare_db_values(key, lower) {
507
            Ordering::Less => return false,
508
            Ordering::Equal if range.lower_open => return false,
509
            _ => {}
510
        }
511
    }
512
    if let Some(upper) = range.upper.as_ref() {
513
        match compare_db_values(key, upper) {
514
            Ordering::Greater => return false,
515
            Ordering::Equal if range.upper_open => return false,
516
            _ => {}
517
        }
518
    }
519
    true
520
}
521

            
522
/// When the runtime syncs on its own: every `interval`, and / or when the
523
/// app has not written to the store for a moment (`on_idle`, about 1.5 s
524
/// after the last write, when unpushed writes exist).
525
///
526
/// Both are driven by the runtime's per-frame pump on desktop and by the
527
/// host on web; every automatic sync reports through
528
/// `Db::set_on_sync_status` like an explicit `sync_now`.
529
#[repr(C)]
530
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
531
pub struct DbAutoSync {
532
    pub interval: crate::task::OptionDuration,
533
    pub on_idle: bool,
534
}
535

            
536
impl DbAutoSync {
537
    /// No automatic sync: only explicit `sync_now` calls.
538
    #[must_use]
539
    pub const fn manual() -> Self {
540
        Self {
541
            interval: crate::task::OptionDuration::None,
542
            on_idle: false,
543
        }
544
    }
545
}
546

            
547
impl Default for DbAutoSync {
548
    fn default() -> Self {
549
        Self::manual()
550
    }
551
}
552

            
553
/// How to open a database.
554
///
555
/// Builder-style: `DbConfig::new(local_name)` plus
556
/// the `with_*` setters. Identical on every target; the local store is a
557
/// file under the app's data directory on desktop and `IndexedDB` on web.
558
#[repr(C)]
559
#[derive(Debug, Clone, PartialEq)]
560
pub struct DbConfig {
561
    /// Name of the local store (a file name stem on desktop, the `IndexedDB`
562
    /// database name on web). `":memory:"` opens a throwaway in-memory store.
563
    pub local_name: AzString,
564
    /// Remote backup / sync endpoint (HTTPS). `None` = local only.
565
    pub backup_sync_url: OptionString,
566
    /// Bearer token sent with every sync request.
567
    pub auth_token: OptionString,
568
    pub schema: DbSchema,
569
    /// The working set replicated locally; `None` = everything.
570
    pub scope: OptionDbScope,
571
    /// Local size budget in bytes; `0` = unlimited. Clean rows are evicted
572
    /// under pressure, dirty (unpushed) rows never.
573
    pub local_budget_bytes: u64,
574
    pub auto_sync: DbAutoSync,
575
}
576

            
577
impl DbConfig {
578
    /// A local-only database called `local_name` with no schema, no scope,
579
    /// no budget and manual sync.
580
    #[must_use]
581
    pub const fn new(local_name: AzString) -> Self {
582
        Self {
583
            local_name,
584
            backup_sync_url: OptionString::None,
585
            auth_token: OptionString::None,
586
            schema: DbSchema::empty(),
587
            scope: OptionDbScope::None,
588
            local_budget_bytes: 0,
589
            auto_sync: DbAutoSync::manual(),
590
        }
591
    }
592

            
593
    #[must_use]
594
    pub fn with_backup_sync_url(mut self, url: AzString) -> Self {
595
        self.backup_sync_url = OptionString::Some(url);
596
        self
597
    }
598

            
599
    #[must_use]
600
    pub fn with_auth_token(mut self, token: AzString) -> Self {
601
        self.auth_token = OptionString::Some(token);
602
        self
603
    }
604

            
605
    #[must_use]
606
    pub fn with_schema(mut self, schema: DbSchema) -> Self {
607
        self.schema = schema;
608
        self
609
    }
610

            
611
    #[must_use]
612
    pub fn with_scope(mut self, scope: DbScope) -> Self {
613
        self.scope = OptionDbScope::Some(scope);
614
        self
615
    }
616

            
617
    #[must_use]
618
    pub const fn with_local_budget_bytes(mut self, bytes: u64) -> Self {
619
        self.local_budget_bytes = bytes;
620
        self
621
    }
622

            
623
    #[must_use]
624
    pub const fn with_auto_sync(mut self, auto: DbAutoSync) -> Self {
625
        self.auto_sync = auto;
626
        self
627
    }
628
}
629

            
630
/// Where a database stands with its backup endpoint.
631
#[repr(C)]
632
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633
pub enum DbSyncState {
634
    /// No `backup_sync_url` configured, or the handle is closed.
635
    Disconnected,
636
    /// Everything pushed and pulled.
637
    Idle,
638
    Pushing,
639
    Pulling,
640
    /// Offline: local writes are queued in the oplog and pushed on the next
641
    /// successful sync. Never an error.
642
    Queued,
643
    /// The last sync failed for a reason other than being offline (`error`
644
    /// says why).
645
    Error,
646
}
647

            
648
/// A snapshot of a database's sync state, delivered by `Db::sync_status`,
649
/// `Db::sync_now` and `Db::set_on_sync_status`. Timestamps are milliseconds
650
/// since the Unix epoch (`0` = never).
651
#[repr(C)]
652
#[derive(Debug, Clone, PartialEq, Eq)]
653
pub struct DbSyncStatus {
654
    pub state: DbSyncState,
655
    /// How much of the configured scope the local working set holds, in
656
    /// thousandths (`1000` = complete).
657
    pub working_set_coverage_x1000: u32,
658
    /// Local operations not yet acknowledged by the backup endpoint.
659
    pub pending_push_ops: u64,
660
    pub last_synced_ms: u64,
661
    pub local_bytes_used: u64,
662
    pub local_bytes_budget: u64,
663
    /// Storage the platform reports as available for the local store
664
    /// (`navigator.storage.estimate()` on web; the data volume on desktop;
665
    /// `0` = unknown).
666
    pub quota_bytes_available: u64,
667
    pub error: OptionString,
668
}
669

            
670
impl DbSyncStatus {
671
    /// The status of a closed or engine-less handle.
672
    #[must_use]
673
    pub const fn disconnected() -> Self {
674
        Self {
675
            state: DbSyncState::Disconnected,
676
            working_set_coverage_x1000: 0,
677
            pending_push_ops: 0,
678
            last_synced_ms: 0,
679
            local_bytes_used: 0,
680
            local_bytes_budget: 0,
681
            quota_bytes_available: 0,
682
            error: OptionString::None,
683
        }
684
    }
685
}
686

            
687
impl_option!(
688
    DbSyncStatus,
689
    OptionDbSyncStatus,
690
    copy = false,
691
    [Debug, Clone, PartialEq, Eq]
692
);
693

            
694
/// A sync conflict handed to a store's `DbMergeCallback`: the same key was
695
/// modified locally and remotely since the last sync. Timestamps are
696
/// milliseconds since the Unix epoch.
697
#[repr(C)]
698
#[derive(Debug, Clone, PartialEq)]
699
pub struct DbConflict {
700
    pub store: AzString,
701
    pub key: DbValue,
702
    pub local: DbValue,
703
    pub remote: DbValue,
704
    pub local_modified_ms: u64,
705
    pub remote_modified_ms: u64,
706
}
707

            
708
/// Computes the merged value for a `DbConflict`. A pure function over the
709
/// two versions, invoked synchronously while a sync is applied - it must not
710
/// touch the UI, which is why it takes no `CallbackInfo`.
711
pub type DbMergeCallbackType = extern "C" fn(RefAny, DbConflict) -> DbValue;
712

            
713
/// Function pointer + host context for a store's merge policy
714
/// (`Db::set_on_conflict`).
715
#[repr(C)]
716
pub struct DbMergeCallback {
717
    pub cb: DbMergeCallbackType,
718
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
719
    /// Native Rust code sets this to None
720
    pub ctx: OptionRefAny,
721
}
722

            
723
crate::impl_callback!(DbMergeCallback, DbMergeCallbackType);
724

            
725
impl DbMergeCallback {
726
    /// Create a merge callback from a raw function pointer (ctx = None).
727
    #[must_use]
728
    pub const fn create(cb: DbMergeCallbackType) -> Self {
729
        Self {
730
            cb,
731
            ctx: OptionRefAny::None,
732
        }
733
    }
734
}
735

            
736
/// Why a database operation failed.
737
#[repr(C)]
738
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
739
pub enum DbErrorKind {
740
    /// The handle is closed (or `open` never succeeded).
741
    NotOpen,
742
    /// The store name is empty or not usable as a store.
743
    InvalidStore,
744
    /// The key is not usable as a key (`Null` keys are rejected).
745
    InvalidKey,
746
    /// The local store could not be read or written.
747
    Io,
748
    /// The local engine reported an error.
749
    Engine,
750
    /// This build has no local engine (`db-sqlite` feature off).
751
    NoEngine,
752
    /// The backup endpoint answered with an error.
753
    Sync,
754
    Other,
755
}
756

            
757
/// A database error: a kind plus a message.
758
#[repr(C)]
759
#[derive(Debug, Clone, PartialEq, Eq)]
760
pub struct DbError {
761
    pub kind: DbErrorKind,
762
    pub message: AzString,
763
}
764

            
765
impl DbError {
766
    #[must_use]
767
    pub fn new(kind: DbErrorKind, message: impl Into<AzString>) -> Self {
768
        Self {
769
            kind,
770
            message: message.into(),
771
        }
772
    }
773
}
774

            
775
impl core::fmt::Display for DbError {
776
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
777
        write!(f, "{:?}: {}", self.kind, self.message.as_str())
778
    }
779
}
780

            
781
// ---- result structs delivered to `ResumeCallback`s ----------------------
782

            
783
/// Result of `Db::get`: the value (`None` when absent) or an error message.
784
#[repr(C)]
785
#[derive(Debug, Clone, PartialEq)]
786
pub struct DbValueResult {
787
    pub value: OptionDbValue,
788
    pub error: OptionString,
789
}
790

            
791
impl_option!(
792
    DbValueResult,
793
    OptionDbValueResult,
794
    copy = false,
795
    [Debug, Clone, PartialEq]
796
);
797

            
798
impl DbValueResult {
799
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
800
    #[must_use]
801
    pub fn downcast(mut result: RefAny) -> OptionDbValueResult {
802
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
803
    }
804
}
805

            
806
/// Result of `Db::iterate` / `Db::query_index`: the matching rows as a
807
/// two-column grid (`key`, `value`) or an error message.
808
#[repr(C)]
809
#[derive(Debug, Clone, PartialEq)]
810
pub struct DbRowsResult {
811
    pub rows: DbRows,
812
    pub error: OptionString,
813
}
814

            
815
impl_option!(
816
    DbRowsResult,
817
    OptionDbRowsResult,
818
    copy = false,
819
    [Debug, Clone, PartialEq]
820
);
821

            
822
impl DbRowsResult {
823
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
824
    #[must_use]
825
    pub fn downcast(mut result: RefAny) -> OptionDbRowsResult {
826
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
827
    }
828
}
829

            
830
/// One change delivered to a `Db::subscribe` callback: `value` is `None`
831
/// when the key was deleted.
832
#[repr(C)]
833
#[derive(Debug, Clone, PartialEq)]
834
pub struct DbChangeResult {
835
    pub store: AzString,
836
    pub key: DbValue,
837
    pub value: OptionDbValue,
838
}
839

            
840
impl_option!(
841
    DbChangeResult,
842
    OptionDbChangeResult,
843
    copy = false,
844
    [Debug, Clone, PartialEq]
845
);
846

            
847
impl DbChangeResult {
848
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
849
    #[must_use]
850
    pub fn downcast(mut result: RefAny) -> OptionDbChangeResult {
851
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
852
    }
853
}
854

            
855
/// Result of `Db::sync_now` and every `Db::set_on_sync_status` delivery.
856
#[repr(C)]
857
#[derive(Debug, Clone, PartialEq, Eq)]
858
pub struct DbSyncStatusResult {
859
    pub status: DbSyncStatus,
860
}
861

            
862
impl_option!(
863
    DbSyncStatusResult,
864
    OptionDbSyncStatusResult,
865
    copy = false,
866
    [Debug, Clone, PartialEq, Eq]
867
);
868

            
869
impl DbSyncStatusResult {
870
    /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
871
    #[must_use]
872
    pub fn downcast(mut result: RefAny) -> OptionDbSyncStatusResult {
873
        result.downcast_ref::<Self>().map(|r| r.clone()).into()
874
    }
875
}
876

            
877
#[cfg(test)]
878
#[path = "db_test.rs"]
879
mod db_test;