sqjson 0.1.10

A simple JSON-based embedded database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// src/your_db.rs
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::fs;
// no external cache; rely on pager directly
use serde_json::Value;

use crate::{error::DbError, pager::Pager};

/// State captured when a transaction begins, plus the writes it has staged so far.
///
/// Transactions are implemented with *staged writes* + *copy-on-write pages*:
///
/// * Record pages produced inside a transaction are buffered in `staged_pages` and are
///   **not** handed to the pager until `commit()`. Nothing an uncommitted transaction
///   does can reach the file.
/// * Every record written inside a transaction gets a **fresh** page id, so pages that
///   the pre-transaction index points at are never overwritten in place. Rollback
///   therefore has no page repair work to do at all, and commit can switch the whole
///   database over with the single page-0 (index) write.
/// * The in-memory indexes *are* mutated as the transaction runs, which is what makes
///   reads inside the transaction observe its own uncommitted changes. The originals are
///   snapshotted here so `rollback()` can put them back verbatim.
pub struct Transaction {
    /// Primary index (key -> page_id) as it was when `begin_transaction()` was called.
    original_index: HashMap<String, u32>,
    /// Secondary indexes as they were when `begin_transaction()` was called.
    original_secondary_indexes: HashMap<String, HashMap<Value, HashSet<String>>>,
    /// Page allocation watermark as it was when `begin_transaction()` was called.
    original_next_page_id: u32,

    /// Record pages written by this transaction, keyed by page id. Written to the pager
    /// only on commit, dropped on rollback.
    staged_pages: HashMap<u32, Vec<u8>>,

    /// Keys touched by this transaction (put / update_field / delete). Informational:
    /// rollback restores from the snapshots above rather than replaying these.
    modified_keys: HashSet<String>,
}

/// Small file-backed key/value JSON DB with optional secondary indexes.
/// - Page 0 is reserved for the index (key -> page_id) serialized as JSON.
/// - Pages start at 1 for records.
/// - Each record page layout: [u32 little-endian length][json bytes][padding...]
///
/// Improvements vs original:
/// - safer page length checks (no panics),
/// - selective secondary indexing (only index fields present in `indexed_fields` set; empty set = index all),
/// - helper methods: list_keys, count, compact, etc.
/// - optional atomic transactions: `begin_transaction` / `commit` / `rollback`.
pub struct YourDb {
    pager: Pager,
    index: HashMap<String, u32>, // maps key -> page_id
    /// secondary_indexes: field -> (value -> set of keys)
    secondary_indexes: HashMap<String, HashMap<Value, HashSet<String>>>,
    next_page_id: u32, // next free page id
    /// If non-empty, only fields present here will be indexed. If empty, index all fields.
    indexed_fields: HashSet<String>,
    /// `Some` while a transaction is active. All write paths consult this.
    transaction: Option<Transaction>,
}

impl YourDb {
    /// Open existing DB or create a new one if path missing.
    pub fn open(path: &str) -> Result<Self, DbError> {
        let pager = Pager::new(path)?;

        // Read index from page 0 (length-prefixed JSON). Empty or invalid = new DB.
        let index: HashMap<String, u32> = match pager.get_page(0) {
            Ok(page0) => match Self::read_json_from_page(page0) {
                Ok(val) => serde_json::from_value(val).unwrap_or_default(),
                Err(_) => HashMap::new(),
            },
            Err(_) => HashMap::new(),
        };

        // compute next_page_id safely
        let next_page_id = index.values().copied().max().unwrap_or(0).saturating_add(1);

        // create empty secondary index map
        let mut secondary_indexes: HashMap<String, HashMap<Value, HashSet<String>>> =
            HashMap::new();

        // build secondary indexes by scanning existing records (index all fields by default)
        for (key, &page_id) in &index {
            if let Ok(data) = pager.get_page(page_id) {
                match Self::read_json_from_page(data) {
                    Ok(val) => {
                        if let Some(obj) = val.as_object() {
                            for (field, field_value) in obj {
                                let entry = secondary_indexes
                                    .entry(field.clone())
                                    .or_default()
                                    .entry(field_value.clone())
                                    .or_default();
                                entry.insert(key.clone());
                            }
                        }
                    }
                    Err(_) => {
                        // skip corrupted record page
                        continue;
                    }
                }
            }
        }

        Ok(Self {
            pager,
            index,
            secondary_indexes,
            next_page_id,
            indexed_fields: HashSet::new(),
            transaction: None,
        })
    }

    /// Helper: read JSON Value from a page byte slice with safety checks.
    fn read_json_from_page(page: &[u8]) -> Result<Value, DbError> {
        if page.len() < 4 {
            return Err(DbError::Other("Corrupted page: too short".into()));
        }
        let len_bytes: [u8; 4] = page[..4]
            .try_into()
            .map_err(|_| DbError::Other("Failed to read length".into()))?;
        let len = u32::from_le_bytes(len_bytes) as usize;
        if page.len() < 4 + len {
            return Err(DbError::Other(
                "Corrupted page: length out of bounds".into(),
            ));
        }
        let json = serde_json::from_slice(&page[4..4 + len])
            .map_err(|e| DbError::Other(format!("Invalid JSON on page: {}", e)))?;
        Ok(json)
    }

    // cache removed — use pager directly

    /// Serialize a JSON value into a full, zero-padded record page.
    fn build_record_page(value: &Value) -> Result<Vec<u8>, DbError> {
        let json_bytes = serde_json::to_vec(value)
            .map_err(|e| DbError::Other(format!("Serialize error: {}", e)))?;
        if (json_bytes.len() + 4) > crate::util::PAGE_SIZE {
            return Err(DbError::Other("JSON too large for page".into()));
        }
        let mut page_data = vec![0u8; crate::util::PAGE_SIZE];
        page_data[..4].copy_from_slice(&(json_bytes.len() as u32).to_le_bytes());
        page_data[4..4 + json_bytes.len()].copy_from_slice(&json_bytes);
        Ok(page_data)
    }

    /// Page bytes staged by the active transaction for `page_id`, if any.
    /// Reads go through here first so a transaction sees its own uncommitted writes.
    fn staged_page(&self, page_id: u32) -> Option<&[u8]> {
        self.transaction
            .as_ref()
            .and_then(|tx| tx.staged_pages.get(&page_id))
            .map(|p| p.as_slice())
    }

    /// Put key -> JSON value (replaces existing if present).
    ///
    /// Inside a transaction the page is staged in memory instead of being written to the
    /// pager; the change is visible to subsequent reads but hits the file only on commit.
    pub fn put(&mut self, key: &str, value: &Value) -> Result<(), DbError> {
        if key.is_empty() {
            return Err(DbError::Other("Key must not be empty".into()));
        }

        // Build (and size-check) the page before touching any index state.
        let page_data = Self::build_record_page(value)?;

        // Remove old secondary index entries if present
        if let Some(existing_val) = self.get(key)? {
            if let Some(obj) = existing_val.as_object() {
                for (field, field_value) in obj {
                    if !self.indexed_fields.is_empty() && !self.indexed_fields.contains(field) {
                        continue;
                    }
                    if let Some(val_map) = self.secondary_indexes.get_mut(field) {
                        if let Some(keys) = val_map.get_mut(field_value) {
                            keys.remove(key);
                            if keys.is_empty() {
                                val_map.remove(field_value);
                            }
                        }
                        if val_map.is_empty() {
                            self.secondary_indexes.remove(field);
                        }
                    }
                }
            }
        }

        // Choose the page id.
        // * Outside a transaction: reuse the record's existing page (unchanged behaviour).
        // * Inside a transaction: never overwrite a page the committed index points at.
        //   Allocate a fresh page id instead (copy-on-write) so rollback has nothing to
        //   repair on disk. A page this same transaction already staged is reused, since
        //   nothing on disk refers to it yet.
        let existing_page_id = self.index.get(key).copied();
        let is_own_staged_page = match (&self.transaction, existing_page_id) {
            (Some(tx), Some(pid)) => tx.staged_pages.contains_key(&pid),
            _ => false,
        };
        let page_id = match existing_page_id {
            Some(pid) if self.transaction.is_none() || is_own_staged_page => pid,
            _ => {
                let pid = self.next_page_id;
                self.next_page_id = self.next_page_id.saturating_add(1);
                pid
            }
        };

        // Stage the page inside a transaction, otherwise write straight through.
        match self.transaction.as_mut() {
            Some(tx) => {
                tx.staged_pages.insert(page_id, page_data);
                tx.modified_keys.insert(key.to_string());
            }
            None => {
                self.pager.write_page(page_id, &page_data)?;
                // no cache layer; pager writes directly
            }
        }

        self.index.insert(key.to_string(), page_id);

        // Update secondary indexes for the new value
        if let Some(obj) = value.as_object() {
            for (field, field_value) in obj {
                if !self.indexed_fields.is_empty() && !self.indexed_fields.contains(field) {
                    continue;
                }
                let entry = self
                    .secondary_indexes
                    .entry(field.clone())
                    .or_default()
                    .entry(field_value.clone())
                    .or_default();
                entry.insert(key.to_string());
            }
        }

        Ok(())
    }

    /// Get full JSON value for a key.
    ///
    /// Inside a transaction this sees the transaction's own uncommitted writes.
    pub fn get(&self, key: &str) -> Result<Option<Value>, DbError> {
        if let Some(&page_id) = self.index.get(key) {
            // Prefer a page staged by the active transaction over the on-disk page.
            if let Some(staged) = self.staged_page(page_id) {
                return match Self::read_json_from_page(staged) {
                    Ok(json) => Ok(Some(json)),
                    Err(_) => Ok(None),
                };
            }
            let data = self.pager.get_page(page_id)?;
            match Self::read_json_from_page(data) {
                Ok(json) => Ok(Some(json)),
                Err(_) => Ok(None), // treat corrupted page as missing
            }
        } else {
            Ok(None)
        }
    }

    /// Write the primary index to page 0 as length-prefixed JSON (no pager flush).
    fn write_index_page(&mut self) -> Result<(), DbError> {
        let index_bytes = serde_json::to_vec(&self.index)
            .map_err(|e| DbError::Other(format!("Index serialize error: {}", e)))?;
        let mut page = vec![0u8; crate::util::PAGE_SIZE];
        if index_bytes.len() + 4 > page.len() {
            return Err(DbError::Other("Index too large for a single page".into()));
        }
        page[..4].copy_from_slice(&(index_bytes.len() as u32).to_le_bytes());
        page[4..4 + index_bytes.len()].copy_from_slice(&index_bytes);
        self.pager.write_page(0, &page)
    }

    /// Flush: write index to page 0 as length-prefixed JSON.
    ///
    /// Refused while a transaction is active: persisting the index mid-transaction would
    /// make uncommitted changes durable. Use `commit()` or `rollback()` first.
    pub fn flush(&mut self) -> Result<(), DbError> {
        if self.in_transaction() {
            return Err(DbError::Other(
                "flush() is not allowed inside a transaction; use commit() or rollback()".into(),
            ));
        }
        self.write_index_page()?;
        self.pager.flush()
    }

    /// Delete a key and remove from secondary indexes.
    pub fn delete(&mut self, key: &str) -> Result<(), DbError> {
        // remove from secondary indexes
        if let Some(existing_val) = self.get(key)? {
            if let Some(obj) = existing_val.as_object() {
                for (field, field_value) in obj {
                    if !self.indexed_fields.is_empty() && !self.indexed_fields.contains(field) {
                        continue;
                    }
                    if let Some(val_map) = self.secondary_indexes.get_mut(field) {
                        if let Some(keys) = val_map.get_mut(field_value) {
                            keys.remove(key);
                            if keys.is_empty() {
                                val_map.remove(field_value);
                            }
                        }
                        if val_map.is_empty() {
                            self.secondary_indexes.remove(field);
                        }
                    }
                }
            }
        }

        match self.index.remove(key) {
            Some(page_id) => {
                if let Some(tx) = self.transaction.as_mut() {
                    tx.modified_keys.insert(key.to_string());
                    // A page staged earlier in this same transaction is now unreachable,
                    // so drop it rather than writing it at commit time.
                    tx.staged_pages.remove(&page_id);
                }
                Ok(())
            }
            None => Err(DbError::Other("Key not found".into())),
        }
    }

    // ----------------------------------------------------------------------------
    // Transactions
    // ----------------------------------------------------------------------------

    /// Whether a transaction is currently active.
    pub fn in_transaction(&self) -> bool {
        self.transaction.is_some()
    }

    /// Keys touched by the active transaction (empty when no transaction is active).
    pub fn transaction_modified_keys(&self) -> Vec<String> {
        self.transaction
            .as_ref()
            .map(|tx| tx.modified_keys.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Begin a transaction.
    ///
    /// Snapshots the in-memory index state so `rollback()` can restore it exactly.
    /// Nested transactions are not supported and are rejected with an error.
    pub fn begin_transaction(&mut self) -> Result<(), DbError> {
        if self.in_transaction() {
            return Err(DbError::Other(
                "A transaction is already active; nested transactions are not supported".into(),
            ));
        }

        self.transaction = Some(Transaction {
            original_index: self.index.clone(),
            original_secondary_indexes: self.secondary_indexes.clone(),
            original_next_page_id: self.next_page_id,
            staged_pages: HashMap::new(),
            modified_keys: HashSet::new(),
        });

        Ok(())
    }

    /// Commit the active transaction, persisting all of its changes.
    ///
    /// Order matters: staged record pages are written and flushed *first*, and only then
    /// is the index written to page 0 and flushed. Page 0 is the commit point — because
    /// transactional writes go to fresh pages, an interruption before the page-0 write
    /// leaves the previous index (and the previous records it points at) fully intact.
    ///
    /// The transaction is only cleared once persistence has succeeded; if it fails the
    /// transaction stays active so the caller can still `rollback()`.
    pub fn commit(&mut self) -> Result<(), DbError> {
        if !self.in_transaction() {
            return Err(DbError::Other(
                "commit() called with no active transaction".into(),
            ));
        }

        // Move the staged pages out so the write loop does not borrow `self.transaction`.
        let staged = match self.transaction.as_mut() {
            Some(tx) => std::mem::take(&mut tx.staged_pages),
            None => HashMap::new(),
        };

        match self.persist_staged_pages(&staged) {
            Ok(()) => {
                // Persistence succeeded: the transaction is now committed data.
                self.transaction = None;
                Ok(())
            }
            Err(e) => {
                // Put the staged pages back so the transaction stays intact and the
                // caller can roll back (or retry) without losing state.
                if let Some(tx) = self.transaction.as_mut() {
                    tx.staged_pages = staged;
                }
                Err(e)
            }
        }
    }

    /// Write staged record pages, then the index page, flushing at both steps.
    fn persist_staged_pages(&mut self, staged: &HashMap<u32, Vec<u8>>) -> Result<(), DbError> {
        for (page_id, page_data) in staged {
            self.pager.write_page(*page_id, page_data)?;
        }
        // Record pages must be durable before the index that points at them.
        self.pager.flush()?;
        self.write_index_page()?;
        self.pager.flush()
    }

    /// Roll back the active transaction, discarding all of its changes.
    ///
    /// Staged pages were never handed to the pager and transactional writes always went
    /// to freshly allocated page ids, so no on-disk page needs repairing: restoring the
    /// snapshotted in-memory state is enough to make the transaction invisible.
    pub fn rollback(&mut self) -> Result<(), DbError> {
        let tx = self
            .transaction
            .take()
            .ok_or_else(|| DbError::Other("rollback() called with no active transaction".into()))?;

        self.index = tx.original_index;
        self.secondary_indexes = tx.original_secondary_indexes;
        self.next_page_id = tx.original_next_page_id;
        // tx.staged_pages is dropped here — those pages never reached the file.

        Ok(())
    }

    /// Return a specific field from the JSON stored at `key`.
    pub fn get_field(&self, key: &str, field: &str) -> Result<Option<Value>, DbError> {
        if let Some(val) = self.get(key)? {
            Ok(val.get(field).cloned())
        } else {
            Ok(None)
        }
    }

    /// Filter all records with a predicate function. Be careful: this iterates records.
    pub fn filter<F>(&self, predicate: F) -> Result<Vec<(String, Value)>, DbError>
    where
        F: Fn(&Value) -> bool,
    {
        let mut results = Vec::new();
        for key in self.index.keys() {
            if let Some(val) = self.get(key)? {
                if predicate(&val) {
                    results.push((key.clone(), val));
                }
            }
        }
        Ok(results)
    }

    /// Query by field = value (via secondary index)
    pub fn query(&self, field: &str, value: impl Into<Value>) -> Result<Vec<String>, DbError> {
        let val = value.into();
        if let Some(val_map) = self.secondary_indexes.get(field) {
            if let Some(keys) = val_map.get(&val) {
                return Ok(keys.iter().cloned().collect());
            }
        }
        Ok(vec![])
    }

    /// Query page (limit/offset applied)
    pub fn query_page(
        &self,
        field: &str,
        value: impl Into<Value>,
        limit: usize,
        offset: usize,
    ) -> Result<Vec<String>, DbError> {
        let keys = self.query(field, value)?;
        Ok(keys.into_iter().skip(offset).take(limit).collect())
    }

    /// Export query results (key -> value) to a JSON file
    pub fn export_query(
        &self,
        field: &str,
        value: impl Into<Value>,
        path: &str,
    ) -> Result<(), DbError> {
        let keys = self.query(field, value)?;
        let mut map = HashMap::new();
        for k in keys {
            if let Some(v) = self.get(&k)? {
                map.insert(k, v);
            }
        }
        fs::write(
            path,
            serde_json::to_string_pretty(&map).map_err(|e| DbError::Other(format!("{}", e)))?,
        )?;
        Ok(())
    }

    /// Export entire DB to a JSON file.
    pub fn export_to_file(&self, path: &str) -> Result<(), DbError> {
        let mut map = HashMap::new();
        for (k, _) in &self.index {
            if let Some(v) = self.get(k)? {
                map.insert(k.clone(), v);
            }
        }
        let json =
            serde_json::to_string_pretty(&map).map_err(|e| DbError::Other(format!("{}", e)))?;
        fs::write(path, json)?;
        Ok(())
    }

    /// Print all keys->json to stdout (for debugging)
    pub fn show_all(&self) -> Result<(), DbError> {
        for key in self.index.keys() {
            let json = match self.get(key)? {
                Some(v) => v,
                None => serde_json::json!(null),
            };
            println!("{} => {}", key, json);
        }
        Ok(())
    }

    /// Range query (numeric) for a field between min..=max
    pub fn range_query(&self, field: &str, min: Value, max: Value) -> Result<Vec<String>, DbError> {
        if let Some(val_map) = self.secondary_indexes.get(field) {
            let mut results = Vec::new();
            let min_n = min.as_f64();
            let max_n = max.as_f64();
            if min_n.is_none() || max_n.is_none() {
                return Ok(vec![]);
            }
            let min_n = min_n.unwrap();
            let max_n = max_n.unwrap();
            for (val, keys) in val_map {
                if let Some(n) = val.as_f64() {
                    if n >= min_n && n <= max_n {
                        results.extend(keys.iter().cloned());
                    }
                }
            }
            return Ok(results);
        }
        Ok(vec![])
    }

    /// Update a single field on a record (updates secondary indexes accordingly).
    pub fn update_field(
        &mut self,
        key: &str,
        field: &str,
        new_value: Value,
    ) -> Result<(), DbError> {
        if let Some(mut val) = self.get(key)? {
            if let Some(obj) = val.as_object_mut() {
                // remove old secondary index reference
                if let Some(old_val) = obj.get(field) {
                    if !self.indexed_fields.is_empty() && !self.indexed_fields.contains(field) {
                        // not indexed -> just update JSON
                    } else if let Some(val_map) = self.secondary_indexes.get_mut(field) {
                        if let Some(keys) = val_map.get_mut(old_val) {
                            keys.remove(key);
                            if keys.is_empty() {
                                val_map.remove(old_val);
                            }
                        }
                        if val_map.is_empty() {
                            self.secondary_indexes.remove(field);
                        }
                    }
                }
                // insert new value
                obj.insert(field.to_string(), new_value.clone());
            }
            // call put to write page and update indexes (put will re-add secondary index entries)
            self.put(key, &val)?;
        } else {
            return Err(DbError::Other("Key not found".into()));
        }
        Ok(())
    }

    /// Search text fields for substring (only works for string-valued indexed fields).
    pub fn search_contains(&self, field: &str, substring: &str) -> Result<Vec<String>, DbError> {
        let mut results = Vec::new();
        if let Some(val_map) = self.secondary_indexes.get(field) {
            for (val, keys) in val_map {
                if let Some(s) = val.as_str() {
                    if s.contains(substring) {
                        results.extend(keys.iter().cloned());
                    }
                }
            }
        }
        Ok(results)
    }

    /// Return all keys (lightweight)
    pub fn list_keys(&self) -> Vec<String> {
        self.index.keys().cloned().collect()
    }

    /// Count records
    pub fn count(&self) -> usize {
        self.index.len()
    }

    /// Compact DB: rewrite record pages sequentially, rebuild index and secondary indexes.
    /// Note: this rewrites pages starting at 1 and will update page ids accordingly.
    ///
    /// Refused while a transaction is active: compaction rewrites pages in place and
    /// flushes, which would make uncommitted changes durable and unrecoverable.
    pub fn compact(&mut self) -> Result<(), DbError> {
        if self.in_transaction() {
            return Err(DbError::Other(
                "compact() is not allowed inside a transaction; use commit() or rollback() first"
                    .into(),
            ));
        }

        // Read every live record *before* writing anything. Compaction renumbers pages
        // from 1 upwards, so a freshly assigned page id can alias the page a not-yet-read
        // record still lives on; reading first keeps that record from being clobbered.
        let mut records: Vec<(String, Value)> = Vec::with_capacity(self.index.len());
        for key in self.index.keys().cloned().collect::<Vec<_>>() {
            if let Some(val) = self.get(&key)? {
                records.push((key, val));
            }
        }

        let mut new_index = HashMap::new();
        let mut new_secondary: HashMap<String, HashMap<Value, HashSet<String>>> = HashMap::new();
        let mut new_page_id: u32 = 1;

        for (key, val) in records {
            let page_data = Self::build_record_page(&val).map_err(|_| {
                DbError::Other(format!("Record too large during compact: key={}", key))
            })?;

            self.pager.write_page(new_page_id, &page_data)?;

            new_index.insert(key.clone(), new_page_id);

            if let Some(obj) = val.as_object() {
                for (field, field_value) in obj {
                    if !self.indexed_fields.is_empty() && !self.indexed_fields.contains(field) {
                        continue;
                    }
                    new_secondary
                        .entry(field.clone())
                        .or_default()
                        .entry(field_value.clone())
                        .or_default()
                        .insert(key.clone());
                }
            }

            new_page_id = new_page_id.saturating_add(1);
        }

        self.index = new_index;
        self.secondary_indexes = new_secondary;
        self.next_page_id = new_page_id;
        self.flush()
    }
}