Skip to main content

sochdb_storage/
database.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// SochDB - LLM-Optimized Embedded Database
3// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
4//
5// This program is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Affero General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU Affero General Public License for more details.
14//
15// You should have received a copy of the GNU Affero General Public License
16// along with this program. If not, see <https://www.gnu.org/licenses/>.
17
18//! SochDB Database Kernel
19//!
20//! The shared core that powers both embedded mode (`SochConnection::open`) and
21//! server mode (`sochdb-server`). This is the "SQLite engine" equivalent.
22//!
23//! ## Architecture
24//!
25//! ```text
26//! ┌──────────────────────────────────────────────────────────────────┐
27//! │                        Database Kernel                            │
28//! │  Arc<Database> - shared by all connections                       │
29//! ├──────────────────────────────────────────────────────────────────┤
30//! │                                                                   │
31//! │  ┌─────────────────┐   ┌─────────────────┐   ┌────────────────┐ │
32//! │  │  DurableStorage │   │     Catalog     │   │  Vector Index  │ │
33//! │  │  (WAL + MVCC)   │   │  (Schema Mgmt)  │   │  (HNSW/Vamana) │ │
34//! │  └────────┬────────┘   └────────┬────────┘   └───────┬────────┘ │
35//! │           │                     │                     │          │
36//! │           └─────────────────────┴─────────────────────┘          │
37//! │                                 │                                 │
38//! │  ┌─────────────────────────────────────────────────────────────┐ │
39//! │  │              Query Executor (Path-Native)                    │ │
40//! │  │  - Path resolution: O(|path|)                                │ │
41//! │  │  - Column projection: 80% I/O reduction                     │ │
42//! │  │  - Context selection: Token-aware chunking                  │ │
43//! │  └─────────────────────────────────────────────────────────────┘ │
44//! │                                                                   │
45//! └──────────────────────────────────────────────────────────────────┘
46//!
47//! Deployment Modes:
48//! ┌─────────────┐   ┌─────────────┐   ┌─────────────┐
49//! │  Embedded   │   │  IPC Server │   │  TCP Server │
50//! │  (in-proc)  │   │  (Unix sock)│   │  (remote)   │
51//! └──────┬──────┘   └──────┬──────┘   └──────┬──────┘
52//!        │                 │                 │
53//!        └─────────────────┴─────────────────┘
54//!                          │
55//!                   Arc<Database>
56//! ```
57//!
58//! ## Latency Model
59//!
60//! Let K = kernel processing cost for a query
61//!
62//! - Embedded: L_emb ≈ K (function call overhead negligible)
63//! - IPC: L_ipc ≈ K + δ_ipc (δ_ipc = ~10-50µs for Unix socket)
64//! - TCP: L_tcp ≈ K + δ_net (δ_net = 100µs-10ms depending on network)
65//!
66//! For LLM context queries where K >> δ_ipc, IPC is "nearly embedded".
67
68use std::collections::HashMap;
69use std::path::{Path, PathBuf};
70use std::sync::Arc;
71use std::sync::atomic::{AtomicU64, Ordering};
72
73use dashmap::DashMap;
74use parking_lot::RwLock;
75
76use crate::durable_storage::{DurableStorage, TransactionMode};
77use crate::index_policy::{IndexPolicy, TableIndexConfig, TableIndexRegistry};
78use crate::key_buffer::KeyBuffer;
79use crate::packed_row::{PackedColumnDef, PackedColumnType, PackedRow, PackedTableSchema};
80use sochdb_core::catalog::Catalog;
81use sochdb_core::{Result, SochDBError, SochValue};
82
83// Re-export key types
84pub use crate::durable_storage::RecoveryStats;
85
86/// Database configuration
87#[derive(Debug, Clone)]
88pub struct DatabaseConfig {
89    /// Enable group commit for better write throughput
90    pub group_commit: bool,
91    /// Maximum memory for memtables before flush (bytes)
92    pub memtable_size_limit: usize,
93    /// Enable WAL for durability
94    pub wal_enabled: bool,
95    /// Sync mode: fsync after every commit vs periodic
96    pub sync_mode: SyncMode,
97    /// Read-only mode
98    pub read_only: bool,
99    
100    /// Enable ordered index for O(log N) prefix scans
101    ///
102    /// # Deprecation Notice
103    /// 
104    /// **DEPRECATED since 0.2.0**: Use `default_index_policy` instead for per-table control.
105    /// This field will be removed in v0.3.0.
106    ///
107    /// ## Migration Guide
108    ///
109    /// Replace:
110    /// ```ignore
111    /// DatabaseConfig { enable_ordered_index: true, .. }  // Old API
112    /// DatabaseConfig { enable_ordered_index: false, .. } // Old API
113    /// ```
114    ///
115    /// With:
116    /// ```ignore
117    /// DatabaseConfig { default_index_policy: IndexPolicy::ScanOptimized, .. }  // Ordered index enabled
118    /// DatabaseConfig { default_index_policy: IndexPolicy::WriteOptimized, .. } // Ordered index disabled
119    /// ```
120    ///
121    /// ## Behavior
122    ///
123    /// When false, saves ~134 ns/op on writes (20% speedup)
124    /// but scan_prefix becomes O(N) instead of O(log N + K).
125    /// 
126    /// Set to false for write-heavy workloads without range scans.
127    #[deprecated(
128        since = "0.2.0",
129        note = "Use `default_index_policy` field instead. This field will be removed in v0.3.0. \
130                Set IndexPolicy::ScanOptimized for ordered index, WriteOptimized to disable."
131    )]
132    ///
133    /// Set to false for write-heavy workloads without range scans.
134    pub enable_ordered_index: bool,
135    /// Group commit configuration
136    pub group_commit_config: GroupCommitSettings,
137    /// Default index policy for tables not explicitly configured
138    ///
139    /// This replaces the global `enable_ordered_index` toggle with
140    /// fine-grained per-table control. Use `index_registry` to configure
141    /// individual tables.
142    ///
143    /// | Policy         | Insert Cost | Scan Cost      | Use Case              |
144    /// |----------------|-------------|----------------|------------------------|
145    /// | WriteOptimized | O(1)        | O(N)           | High-write, rare scan  |
146    /// | Balanced       | O(1) amort  | O(output+logK) | Mixed OLTP            |
147    /// | ScanOptimized  | O(log N)    | O(logN + K)    | Analytics, range query |
148    /// | AppendOnly     | O(1)        | O(N)           | Time-series logs       |
149    pub default_index_policy: IndexPolicy,
150}
151
152/// Group commit settings - mirrors SQLite's WAL mode tuning
153///
154/// ## Performance Model
155///
156/// Without group commit: Throughput = 1 / L_fsync ≈ 200 commits/sec (L=5ms)
157/// With group commit (batch size K): Throughput = K / L_fsync = K × 200 commits/sec
158///
159/// For K=100: 20,000 commits/sec (100× speedup)
160///
161/// ## SQLite Comparison
162///
163/// | Setting                    | SQLite Equivalent           |
164/// |----------------------------|-----------------------------|
165/// | batch_size = 1             | PRAGMA synchronous = FULL   |
166/// | batch_size = 100           | WAL mode with batching      |
167/// | max_wait_us = 0            | No delay, immediate flush   |
168/// | max_wait_us = 10000        | Up to 10ms delay for batch  |
169#[derive(Debug, Clone)]
170pub struct GroupCommitSettings {
171    /// Minimum batch size before flush (default: 1)
172    pub min_batch_size: usize,
173    /// Maximum batch size (default: 1000)
174    pub max_batch_size: usize,
175    /// Maximum wait time before flush in microseconds (default: 10000 = 10ms)
176    pub max_wait_us: u64,
177    /// Expected fsync latency in microseconds (for adaptive sizing)
178    pub fsync_latency_us: u64,
179}
180
181impl Default for GroupCommitSettings {
182    fn default() -> Self {
183        Self {
184            min_batch_size: 1,
185            max_batch_size: 1000,
186            max_wait_us: 10_000,     // 10ms
187            fsync_latency_us: 5_000, // 5ms
188        }
189    }
190}
191
192impl GroupCommitSettings {
193    /// High throughput preset - maximizes batching
194    pub fn high_throughput() -> Self {
195        Self {
196            min_batch_size: 50,
197            max_batch_size: 5000,
198            max_wait_us: 50_000, // 50ms
199            fsync_latency_us: 5_000,
200        }
201    }
202
203    /// Low latency preset - minimal batching
204    pub fn low_latency() -> Self {
205        Self {
206            min_batch_size: 1,
207            max_batch_size: 10,
208            max_wait_us: 1_000, // 1ms
209            fsync_latency_us: 5_000,
210        }
211    }
212
213    /// Calculate optimal batch size using Little's Law
214    ///
215    /// N* = sqrt(2 × L_fsync × λ / C_wait)
216    ///
217    /// # Arguments
218    /// * `arrival_rate` - Operations per second
219    /// * `wait_cost` - Cost coefficient for waiting (0.0-1.0)
220    pub fn optimal_batch_size(&self, arrival_rate: f64, wait_cost: f64) -> usize {
221        let l_fsync = self.fsync_latency_us as f64 / 1_000_000.0;
222        let n_star = (2.0 * l_fsync * arrival_rate / wait_cost.max(0.001)).sqrt();
223        (n_star as usize).clamp(self.min_batch_size, self.max_batch_size)
224    }
225}
226
227impl Default for DatabaseConfig {
228    #[allow(deprecated)]
229    fn default() -> Self {
230        Self {
231            group_commit: true,
232            memtable_size_limit: 64 * 1024 * 1024, // 64MB
233            wal_enabled: true,
234            sync_mode: SyncMode::Normal,
235            read_only: false,
236            enable_ordered_index: true, // Default: enabled for compatibility
237            group_commit_config: GroupCommitSettings::default(),
238            default_index_policy: IndexPolicy::Balanced, // New default: balanced OLTP policy
239        }
240    }
241}
242
243impl DatabaseConfig {
244    /// Create config optimized for throughput (Fast Mode)
245    ///
246    /// - Disables ordered index (saves ~134 ns/op)
247    /// - Uses high-throughput group commit settings
248    /// - Suitable for append-only workloads
249    #[allow(deprecated)]
250    pub fn throughput_optimized() -> Self {
251        Self {
252            group_commit: true,
253            memtable_size_limit: 128 * 1024 * 1024, // 128MB
254            wal_enabled: true,
255            sync_mode: SyncMode::Normal,
256            read_only: false,
257            enable_ordered_index: false,
258            group_commit_config: GroupCommitSettings::high_throughput(),
259            default_index_policy: IndexPolicy::WriteOptimized, // No ordered index overhead
260        }
261    }
262
263    /// Create config optimized for latency
264    ///
265    /// - Keeps ordered index for fast range scans
266    /// - Uses low-latency group commit settings
267    /// - Suitable for OLTP workloads
268    #[allow(deprecated)]
269    pub fn latency_optimized() -> Self {
270        Self {
271            group_commit: true,
272            memtable_size_limit: 32 * 1024 * 1024, // 32MB
273            wal_enabled: true,
274            sync_mode: SyncMode::Full,
275            read_only: false,
276            enable_ordered_index: true,
277            group_commit_config: GroupCommitSettings::low_latency(),
278            default_index_policy: IndexPolicy::ScanOptimized, // Fast range scans
279        }
280    }
281
282    /// Create config matching SQLite defaults
283    #[allow(deprecated)]
284    pub fn sqlite_compatible() -> Self {
285        Self {
286            group_commit: false, // SQLite default is single-commit
287            memtable_size_limit: 64 * 1024 * 1024,
288            wal_enabled: true,
289            sync_mode: SyncMode::Normal, // PRAGMA synchronous = NORMAL
290            read_only: false,
291            enable_ordered_index: true,
292            group_commit_config: GroupCommitSettings::default(),
293            default_index_policy: IndexPolicy::Balanced, // Good default for mixed workloads
294        }
295    }
296
297    /// Get effective ordered index setting, derived from `default_index_policy`.
298    /// 
299    /// This is the shim method for the deprecated `enable_ordered_index` field.
300    /// It returns `true` if the policy requires an ordered index (ScanOptimized),
301    /// and `false` otherwise (WriteOptimized, Balanced, AppendOnly).
302    ///
303    /// # Policy Mapping
304    ///
305    /// | IndexPolicy      | Returns |
306    /// |------------------|---------|
307    /// | ScanOptimized    | true    |
308    /// | Balanced         | false   |
309    /// | WriteOptimized   | false   |
310    /// | AppendOnly       | false   |
311    ///
312    /// Note: `Balanced` uses lazy compaction rather than a live ordered index,
313    /// so it returns `false` for the low-level memtable config but still supports
314    /// efficient range scans via sorted runs.
315    pub fn effective_ordered_index(&self) -> bool {
316        matches!(self.default_index_policy, IndexPolicy::ScanOptimized)
317    }
318}
319
320/// WAL sync mode - matches SQLite's PRAGMA synchronous semantics
321///
322/// | SochDB     | SQLite       | Description                                    |
323/// |------------|--------------|------------------------------------------------|
324/// | Off        | OFF (0)      | No fsync, risk of data loss on crash           |
325/// | Normal     | NORMAL (1)   | Fsync at checkpoints, not every commit         |
326/// | Full       | FULL (2)     | Fsync every commit (safest, slowest)           |
327///
328/// # Performance vs Durability Trade-offs
329///
330/// - **Off**: ~10x faster than Full, but may lose last ~100ms of data on crash
331/// - **Normal**: ~5x faster than Full, durable at checkpoint boundaries
332/// - **Full**: Every commit is fsync'd, no data loss possible
333///
334/// # SQLite Compatibility
335///
336/// ```sql
337/// -- SQLite equivalent settings
338/// PRAGMA synchronous = OFF;    -- SyncMode::Off
339/// PRAGMA synchronous = NORMAL; -- SyncMode::Normal  
340/// PRAGMA synchronous = FULL;   -- SyncMode::Full
341/// ```
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343pub enum SyncMode {
344    /// No fsync (equivalent to SQLite PRAGMA synchronous = OFF)
345    ///
346    /// Writes buffered in OS, may lose data on power failure.
347    /// Use for non-critical data or bulk loading.
348    Off = 0,
349
350    /// Fsync at checkpoints (equivalent to SQLite PRAGMA synchronous = NORMAL)
351    ///
352    /// Default mode. Syncs WAL at checkpoint boundaries.
353    /// Good balance of performance and durability.
354    Normal = 1,
355
356    /// Fsync every commit (equivalent to SQLite PRAGMA synchronous = FULL)
357    ///
358    /// Safest mode. Every commit is immediately durable.
359    /// Required for financial/critical data.
360    Full = 2,
361}
362
363impl SyncMode {
364    /// Convert from SQLite synchronous pragma value
365    pub fn from_sqlite_pragma(value: u32) -> Self {
366        match value {
367            0 => SyncMode::Off,
368            1 => SyncMode::Normal,
369            _ => SyncMode::Full, // 2+ treated as Full
370        }
371    }
372
373    /// Convert to SQLite synchronous pragma value
374    pub fn to_sqlite_pragma(self) -> u32 {
375        self as u32
376    }
377
378    /// Parse from string (case-insensitive)
379    pub fn parse(s: &str) -> Option<Self> {
380        match s.to_ascii_uppercase().as_str() {
381            "OFF" | "0" => Some(SyncMode::Off),
382            "NORMAL" | "1" => Some(SyncMode::Normal),
383            "FULL" | "2" => Some(SyncMode::Full),
384            _ => None,
385        }
386    }
387}
388
389/// Table schema for the kernel
390#[derive(Debug, Clone)]
391pub struct TableSchema {
392    pub name: String,
393    pub columns: Vec<ColumnDef>,
394}
395
396/// Column definition
397#[derive(Debug, Clone)]
398pub struct ColumnDef {
399    pub name: String,
400    pub col_type: ColumnType,
401    pub nullable: bool,
402}
403
404/// Column types
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406pub enum ColumnType {
407    Int64,
408    UInt64,
409    Float64,
410    Text,
411    Binary,
412    Bool,
413}
414
415/// Transaction handle for kernel operations
416#[derive(Debug, Clone, Copy)]
417pub struct TxnHandle {
418    pub txn_id: u64,
419    pub snapshot_ts: u64,
420}
421
422/// Query result from the kernel
423#[derive(Debug, Clone)]
424pub struct QueryResult {
425    /// Column names
426    pub columns: Vec<String>,
427    /// Row data (each row is a map of column -> value)
428    pub rows: Vec<HashMap<String, SochValue>>,
429    /// Number of rows scanned (for stats)
430    pub rows_scanned: usize,
431    /// Bytes read from storage
432    pub bytes_read: usize,
433}
434
435impl QueryResult {
436    /// Empty result
437    pub fn empty() -> Self {
438        Self {
439            columns: vec![],
440            rows: vec![],
441            rows_scanned: 0,
442            bytes_read: 0,
443        }
444    }
445
446    /// Convert to TOON format for token efficiency
447    pub fn to_toon(&self) -> String {
448        if self.rows.is_empty() {
449            return "[]".to_string();
450        }
451
452        // TOON format: table[N]{cols}: row1; row2; ...
453        let n = self.rows.len();
454        let cols = self.columns.join(",");
455
456        let rows_str: Vec<String> = self
457            .rows
458            .iter()
459            .map(|row| {
460                self.columns
461                    .iter()
462                    .map(|c| {
463                        row.get(c)
464                            .map(format_soch_value)
465                            .unwrap_or_else(|| "∅".to_string())
466                    })
467                    .collect::<Vec<_>>()
468                    .join(",")
469            })
470            .collect();
471
472        format!("result[{}]{{{}}}:{}", n, cols, rows_str.join(";"))
473    }
474}
475
476fn format_soch_value(v: &SochValue) -> String {
477    match v {
478        SochValue::Null => "∅".to_string(),
479        SochValue::Int(i) => i.to_string(),
480        SochValue::UInt(u) => u.to_string(),
481        SochValue::Float(f) => format!("{:.6}", f),
482        SochValue::Text(s) => {
483            if s.contains(',') || s.contains(';') {
484                format!("\"{}\"", s.replace('"', "\\\""))
485            } else {
486                s.clone()
487            }
488        }
489        SochValue::Bool(b) => if *b { "T" } else { "F" }.to_string(),
490        SochValue::Binary(b) => format!("b64:{}", base64_encode(b)),
491        _ => format!("{:?}", v),
492    }
493}
494
495fn base64_encode(data: &[u8]) -> String {
496    // Simple base64 encoding
497    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
498    let mut result = String::new();
499
500    for chunk in data.chunks(3) {
501        let b0 = chunk[0] as usize;
502        let b1 = chunk.get(1).copied().unwrap_or(0) as usize;
503        let b2 = chunk.get(2).copied().unwrap_or(0) as usize;
504
505        result.push(ALPHABET[b0 >> 2] as char);
506        result.push(ALPHABET[((b0 & 0x03) << 4) | (b1 >> 4)] as char);
507
508        if chunk.len() > 1 {
509            result.push(ALPHABET[((b1 & 0x0f) << 2) | (b2 >> 6)] as char);
510        } else {
511            result.push('=');
512        }
513
514        if chunk.len() > 2 {
515            result.push(ALPHABET[b2 & 0x3f] as char);
516        } else {
517            result.push('=');
518        }
519    }
520
521    result
522}
523
524// ============================================================================
525// Columnar Query Results - SIMD-friendly result format
526// ============================================================================
527
528use sochdb_core::TypedColumn as CoreTypedColumn;
529
530/// Columnar query result - SIMD-friendly format for analytics
531///
532/// Instead of row-oriented `Vec<HashMap<String, SochValue>>`, this returns
533/// column-oriented `Vec<TypedColumn>` for efficient vectorized operations.
534///
535/// ## Memory Layout
536///
537/// Row-oriented (standard):
538/// ```text
539/// Row 0: [id=1, name="Alice", score=85]
540/// Row 1: [id=2, name="Bob", score=92]
541/// Row 2: [id=3, name="Carol", score=78]
542/// ```
543///
544/// Column-oriented (this format):
545/// ```text
546/// id:    [1, 2, 3]           ← contiguous i64 array (SIMD-friendly)
547/// name:  ["Alice", "Bob", "Carol"] ← Arrow-style string encoding
548/// score: [85, 92, 78]        ← contiguous i64 array
549/// ```
550///
551/// ## Performance Benefits
552///
553/// - SIMD: Column sums use vectorized instructions (~8× faster)
554/// - Cache: Sequential access pattern maximizes L1/L2 cache hits
555/// - Compression: Same-type data compresses better (5-10× typical)
556/// - Filtering: Bitmap operations instead of row iteration
557///
558/// ## Usage
559///
560/// ```ignore
561/// let result = db.query(txn, "users")
562///     .columns(&["id", "score"])
563///     .as_columnar()?;
564///
565/// // SIMD sum
566/// let total_score = result.column("score")
567///     .map(|c| c.sum_i64())
568///     .unwrap_or(0);
569///
570/// // Stats
571/// println!("Rows: {}, Memory: {} bytes", result.row_count(), result.memory_size());
572/// ```
573#[derive(Debug, Clone)]
574pub struct ColumnarQueryResult {
575    /// Column names in order
576    pub columns: Vec<String>,
577    /// Column data - each TypedColumn contains all values for one column
578    pub data: Vec<CoreTypedColumn>,
579    /// Number of rows
580    pub row_count: usize,
581    /// Bytes read from storage
582    pub bytes_read: usize,
583}
584
585impl ColumnarQueryResult {
586    /// Create an empty result
587    pub fn empty() -> Self {
588        Self {
589            columns: vec![],
590            data: vec![],
591            row_count: 0,
592            bytes_read: 0,
593        }
594    }
595
596    /// Get column by name
597    pub fn column(&self, name: &str) -> Option<&CoreTypedColumn> {
598        self.columns
599            .iter()
600            .position(|c| c == name)
601            .and_then(|idx| self.data.get(idx))
602    }
603
604    /// Get column index by name
605    pub fn column_index(&self, name: &str) -> Option<usize> {
606        self.columns.iter().position(|c| c == name)
607    }
608
609    /// Number of rows
610    pub fn row_count(&self) -> usize {
611        self.row_count
612    }
613
614    /// Number of columns
615    pub fn column_count(&self) -> usize {
616        self.columns.len()
617    }
618
619    /// Total memory size in bytes
620    pub fn memory_size(&self) -> usize {
621        self.data.iter().map(|c| c.memory_size()).sum()
622    }
623
624    /// Sum of an i64 column (SIMD-optimized)
625    pub fn sum_i64(&self, column: &str) -> Option<i64> {
626        self.column(column).map(|c| c.sum_i64())
627    }
628
629    /// Sum of an f64 column (SIMD-optimized)
630    pub fn sum_f64(&self, column: &str) -> Option<f64> {
631        self.column(column).map(|c| c.sum_f64())
632    }
633
634    /// Zero-allocation row access by index.
635    ///
636    /// Returns a lightweight view that resolves column values on demand
637    /// from the underlying columnar arrays — no `HashMap` per row.
638    ///
639    /// ```ignore
640    /// let result = query.as_columnar()?;
641    /// for i in 0..result.row_count() {
642    ///     let row = result.row_view(i).unwrap();
643    ///     let name = row.get("name"); // SochValue::Text(...)
644    /// }
645    /// ```
646    #[inline]
647    pub fn row_view(&self, index: usize) -> Option<ColumnarRowView<'_>> {
648        if index < self.row_count {
649            Some(ColumnarRowView {
650                result: self,
651                index,
652            })
653        } else {
654            None
655        }
656    }
657
658    /// Convert to row-oriented `QueryResult` for backward compatibility.
659    ///
660    /// This materialises one `HashMap<String, SochValue>` per row, so prefer
661    /// using `row_view()` or direct columnar access when performance matters.
662    pub fn into_query_result(self) -> QueryResult {
663        let rows: Vec<HashMap<String, SochValue>> = (0..self.row_count)
664            .map(|i| {
665                self.columns
666                    .iter()
667                    .zip(self.data.iter())
668                    .map(|(name, col)| (name.clone(), col.value_at(i)))
669                    .collect()
670            })
671            .collect();
672
673        QueryResult {
674            columns: self.columns,
675            rows,
676            rows_scanned: self.row_count,
677            bytes_read: self.bytes_read,
678        }
679    }
680
681    /// Get column statistics (min, max, null count)
682    pub fn column_stats(&self, column: &str) -> Option<&sochdb_core::columnar::ColumnStats> {
683        self.column(column).map(|c| c.stats())
684    }
685
686    /// Convert to TOON format (token-efficient)
687    pub fn to_toon(&self) -> String {
688        if self.row_count == 0 {
689            return "[]".to_string();
690        }
691
692        let n = self.row_count;
693        let cols = self.columns.join(",");
694
695        // Build rows from columns
696        let mut rows_str = Vec::with_capacity(n);
697        for i in 0..n {
698            let row: Vec<String> = self
699                .data
700                .iter()
701                .map(|col| format_columnar_value(col, i))
702                .collect();
703            rows_str.push(row.join(","));
704        }
705
706        format!("result[{}]{{{}}}:{}", n, cols, rows_str.join(";"))
707    }
708}
709
710/// Format a single value from a TypedColumn at index
711fn format_columnar_value(col: &CoreTypedColumn, idx: usize) -> String {
712    match col {
713        CoreTypedColumn::Int64 {
714            values, validity, ..
715        } => {
716            if validity.is_valid(idx) && idx < values.len() {
717                values[idx].to_string()
718            } else {
719                "∅".to_string()
720            }
721        }
722        CoreTypedColumn::UInt64 {
723            values, validity, ..
724        } => {
725            if validity.is_valid(idx) && idx < values.len() {
726                values[idx].to_string()
727            } else {
728                "∅".to_string()
729            }
730        }
731        CoreTypedColumn::Float64 {
732            values, validity, ..
733        } => {
734            if validity.is_valid(idx) && idx < values.len() {
735                format!("{:.6}", values[idx])
736            } else {
737                "∅".to_string()
738            }
739        }
740        CoreTypedColumn::Text {
741            offsets,
742            data,
743            validity,
744            ..
745        } => {
746            if validity.is_valid(idx) && idx + 1 < offsets.len() {
747                let start = offsets[idx] as usize;
748                let end = offsets[idx + 1] as usize;
749                std::str::from_utf8(&data[start..end])
750                    .map(|s| {
751                        if s.contains(',') || s.contains(';') {
752                            format!("\"{}\"", s.replace('"', "\\\""))
753                        } else {
754                            s.to_string()
755                        }
756                    })
757                    .unwrap_or_else(|_| "∅".to_string())
758            } else {
759                "∅".to_string()
760            }
761        }
762        CoreTypedColumn::Binary {
763            offsets,
764            data,
765            validity,
766            ..
767        } => {
768            if validity.is_valid(idx) && idx + 1 < offsets.len() {
769                let start = offsets[idx] as usize;
770                let end = offsets[idx + 1] as usize;
771                format!("b64:{}", base64_encode(&data[start..end]))
772            } else {
773                "∅".to_string()
774            }
775        }
776        CoreTypedColumn::Bool {
777            values,
778            validity,
779            len,
780            ..
781        } => {
782            if validity.is_valid(idx) && idx < *len {
783                let word = idx / 64;
784                let bit = idx % 64;
785                if (values[word] >> bit) & 1 == 1 {
786                    "T"
787                } else {
788                    "F"
789                }
790                .to_string()
791            } else {
792                "∅".to_string()
793            }
794        }
795    }
796}
797
798/// Zero-allocation row view into a `ColumnarQueryResult`.
799///
800/// Provides named-column access (like `HashMap<String, SochValue>`)
801/// without allocating a HashMap per row. Values are read directly
802/// from the underlying typed column arrays.
803///
804/// **Cost per access:** O(1) column index lookup + O(1) array read.
805/// **Allocation:** zero (borrows from `ColumnarQueryResult`).
806#[derive(Debug)]
807pub struct ColumnarRowView<'a> {
808    result: &'a ColumnarQueryResult,
809    index: usize,
810}
811
812impl<'a> ColumnarRowView<'a> {
813    /// Get a value by column name without allocation.
814    ///
815    /// Returns `None` if the column does not exist.
816    /// Returns `Some(SochValue::Null)` if the column exists but the value is NULL.
817    #[inline]
818    pub fn get(&self, column: &str) -> Option<SochValue> {
819        self.result
820            .column_index(column)
821            .map(|ci| self.result.data[ci].value_at(self.index))
822    }
823
824    /// Get all column values as a `Vec<SochValue>` (positional, no HashMap).
825    pub fn values(&self) -> Vec<SochValue> {
826        self.result
827            .data
828            .iter()
829            .map(|col| col.value_at(self.index))
830            .collect()
831    }
832
833    /// Row index within the result set.
834    #[inline]
835    pub fn index(&self) -> usize {
836        self.index
837    }
838
839    /// Materialise this row into a `HashMap<String, SochValue>` for backward
840    /// compatibility.  Prefer `get()` for single column access.
841    pub fn to_map(&self) -> HashMap<String, SochValue> {
842        self.result
843            .columns
844            .iter()
845            .zip(self.result.data.iter())
846            .map(|(name, col)| (name.clone(), col.value_at(self.index)))
847            .collect()
848    }
849}
850
851/// Vector search result
852#[derive(Debug, Clone)]
853pub struct VectorSearchResult {
854    pub id: u64,
855    pub distance: f32,
856    pub metadata: Option<HashMap<String, SochValue>>,
857}
858
859/// The SochDB Database Kernel
860///
861/// This is the shared core used by both embedded (`SochConnection`) and
862/// server (`sochdb-server`) modes. It owns all storage, catalog, and
863/// indexing components.
864///
865/// # Thread Safety
866///
867/// The Database is fully thread-safe via internal synchronization:
868/// - Multiple readers can operate concurrently (MVCC snapshots)
869/// - Writers coordinate through WAL and group commit
870/// - All state is behind Arc/RwLock for shared access
871///
872/// # Concurrency Modes
873///
874/// ## Standard Mode (Single Process)
875/// - Uses exclusive file lock (`flock(LOCK_EX)`)
876/// - Best for: Scripts, notebooks, CLI tools
877/// - Open with: `Database::open(path)`
878///
879/// ## Concurrent Mode (Multi-Process/Web Apps)
880/// - Uses lock-free MVCC for reads, single-writer coordination for writes
881/// - Best for: Web servers, Flask/FastAPI apps, hot reloading
882/// - Open with: `Database::open_concurrent(path)`
883///
884/// # Example
885///
886/// ```ignore
887/// // Standard mode (single process)
888/// let db = Database::open("./my_data")?;
889///
890/// // Concurrent mode (multi-reader, single-writer)
891/// let db = Database::open_concurrent("./my_data")?;
892///
893/// // Begin a transaction
894/// let txn = db.begin_transaction()?;
895///
896/// // Write data
897/// db.put(txn, b"user:1:name", b"Alice")?;
898///
899/// // Commit
900/// db.commit(txn)?;
901/// ```
902#[allow(dead_code)]
903pub struct Database {
904    /// Path to database directory
905    path: PathBuf,
906    /// Durable storage layer (WAL + MVCC + memtable)
907    storage: Arc<DurableStorage>,
908    /// Concurrent MVCC manager (for concurrent mode)
909    concurrent_mvcc: Option<Arc<crate::mvcc_concurrent::ConcurrentMvcc>>,
910    /// Schema catalog
911    catalog: Arc<RwLock<Catalog>>,
912    /// Registered table schemas (name -> schema) - lock-free for reads
913    tables: DashMap<String, TableSchema>,
914    /// Cached packed schemas for fast insert (name -> packed schema)
915    packed_schemas: DashMap<String, PackedTableSchema>,
916    /// Per-table index policy registry
917    index_registry: Arc<TableIndexRegistry>,
918    /// Configuration
919    config: DatabaseConfig,
920    /// Statistics
921    stats: DatabaseStats,
922    /// Shutdown flag
923    shutdown: AtomicU64,
924    /// Whether this database is in concurrent mode
925    is_concurrent: bool,
926}
927
928/// Database statistics
929struct DatabaseStats {
930    transactions_started: AtomicU64,
931    transactions_committed: AtomicU64,
932    transactions_aborted: AtomicU64,
933    queries_executed: AtomicU64,
934    bytes_written: AtomicU64,
935    bytes_read: AtomicU64,
936}
937
938impl DatabaseStats {
939    fn new() -> Self {
940        Self {
941            transactions_started: AtomicU64::new(0),
942            transactions_committed: AtomicU64::new(0),
943            transactions_aborted: AtomicU64::new(0),
944            queries_executed: AtomicU64::new(0),
945            bytes_written: AtomicU64::new(0),
946            bytes_read: AtomicU64::new(0),
947        }
948    }
949}
950
951/// Public statistics snapshot
952#[derive(Debug, Clone)]
953pub struct Stats {
954    pub transactions_started: u64,
955    pub transactions_committed: u64,
956    pub transactions_aborted: u64,
957    pub queries_executed: u64,
958    pub bytes_written: u64,
959    pub bytes_read: u64,
960}
961
962impl Database {
963    /// Open or create a database at the given path.
964    ///
965    /// This is the primary entry point, similar to `sqlite3_open()`.
966    /// If the database exists, it will be opened and WAL recovery performed.
967    /// If it doesn't exist, a new database will be created.
968    ///
969    /// # Arguments
970    ///
971    /// * `path` - Directory path for the database files
972    ///
973    /// # Returns
974    ///
975    /// An `Arc<Database>` that can be shared across threads and connections.
976    pub fn open<P: AsRef<Path>>(path: P) -> Result<Arc<Self>> {
977        Self::open_with_config(path, DatabaseConfig::default())
978    }
979
980    /// Open without locking (for testing crash recovery scenarios)
981    ///
982    /// # Safety
983    /// This should ONLY be used in tests that simulate crashes by forgetting
984    /// the storage instance. In production, always use `open()`.
985    #[cfg(test)]
986    pub fn open_without_lock<P: AsRef<Path>>(path: P) -> Result<Arc<Self>> {
987        let path = path.as_ref().to_path_buf();
988        let config = DatabaseConfig::default();
989
990        let storage = Arc::new(DurableStorage::open_without_lock(&path)?);
991
992        let index_registry = Arc::new(TableIndexRegistry::with_default_policy(
993            config.default_index_policy,
994        ));
995
996        let db = Arc::new(Self {
997            path: path.clone(),
998            storage,
999            concurrent_mvcc: None,
1000            catalog: Arc::new(RwLock::new(Catalog::new("sochdb"))),
1001            tables: DashMap::new(),
1002            packed_schemas: DashMap::new(),
1003            index_registry,
1004            config,
1005            stats: DatabaseStats::new(),
1006            shutdown: AtomicU64::new(0),
1007            is_concurrent: false,
1008        });
1009
1010        db.recover()?;
1011        Ok(db)
1012    }
1013
1014    /// Open with custom configuration
1015    pub fn open_with_config<P: AsRef<Path>>(path: P, config: DatabaseConfig) -> Result<Arc<Self>> {
1016        let path = path.as_ref().to_path_buf();
1017
1018        // Use IndexPolicy-based storage configuration for automatic memtable selection
1019        // This derives ordered index and memtable type from the policy
1020        let storage = Arc::new(DurableStorage::open_with_policy(
1021            &path,
1022            config.default_index_policy,
1023            config.group_commit,
1024        )?);
1025
1026        // Propagate sync_mode from config to storage engine.
1027        // Without this, DurableStorage defaults to SyncMode::Normal (adaptive fsync).
1028        storage.set_sync_mode(config.sync_mode as u64);
1029
1030        // Create index registry with default policy from config
1031        let index_registry = Arc::new(TableIndexRegistry::with_default_policy(
1032            config.default_index_policy,
1033        ));
1034
1035        let db = Arc::new(Self {
1036            path: path.clone(),
1037            storage,
1038            concurrent_mvcc: None,
1039            catalog: Arc::new(RwLock::new(Catalog::new("sochdb"))),
1040            tables: DashMap::new(),
1041            packed_schemas: DashMap::new(),
1042            index_registry,
1043            config,
1044            stats: DatabaseStats::new(),
1045            shutdown: AtomicU64::new(0),
1046            is_concurrent: false,
1047        });
1048
1049        // Perform crash recovery if needed
1050        db.recover()?;
1051
1052        Ok(db)
1053    }
1054
1055    /// Open database in concurrent mode (multi-reader, single-writer)
1056    ///
1057    /// This mode allows multiple processes to access the database simultaneously:
1058    /// - **Readers**: Lock-free, concurrent access via MVCC snapshots
1059    /// - **Writers**: Single-writer coordination through atomic locks
1060    ///
1061    /// # Use Cases
1062    ///
1063    /// - Web applications (Flask, FastAPI, Django)
1064    /// - Hot reloading development servers
1065    /// - Multi-process worker pools
1066    /// - Any scenario with concurrent read access
1067    ///
1068    /// # Performance
1069    ///
1070    /// - Read latency: ~100ns (lock-free atomic operations)
1071    /// - Write latency: ~60μs amortized (with group commit)
1072    /// - Concurrent readers: Up to 1024 (configurable)
1073    ///
1074    /// # Example
1075    ///
1076    /// ```ignore
1077    /// // Multiple processes can open the same database
1078    /// let db = Database::open_concurrent("./my_data")?;
1079    ///
1080    /// // Reads are lock-free
1081    /// let value = db.get(b"key")?;
1082    ///
1083    /// // Writes coordinate automatically
1084    /// let txn = db.begin_transaction()?;
1085    /// db.put(txn, b"key", b"value")?;
1086    /// db.commit(txn)?;
1087    /// ```
1088    pub fn open_concurrent<P: AsRef<Path>>(path: P) -> Result<Arc<Self>> {
1089        Self::open_concurrent_with_config(path, DatabaseConfig::default())
1090    }
1091
1092    /// Open database in concurrent mode with custom configuration
1093    pub fn open_concurrent_with_config<P: AsRef<Path>>(
1094        path: P,
1095        config: DatabaseConfig,
1096    ) -> Result<Arc<Self>> {
1097        use crate::mvcc_concurrent::ConcurrentMvcc;
1098
1099        let path = path.as_ref().to_path_buf();
1100        std::fs::create_dir_all(&path)?;
1101
1102        // Open concurrent MVCC manager (this uses shared memory, not exclusive lock)
1103        let concurrent_mvcc = Arc::new(ConcurrentMvcc::open(&path)?);
1104
1105        // Open storage WITHOUT exclusive lock (concurrent MVCC handles coordination)
1106        // We use a special internal method that skips the file lock
1107        let storage = Arc::new(DurableStorage::open_for_concurrent(&path, config.default_index_policy)?);
1108
1109        // Propagate sync_mode from config to storage engine
1110        storage.set_sync_mode(config.sync_mode as u64);
1111
1112        // Create index registry with default policy from config
1113        let index_registry = Arc::new(TableIndexRegistry::with_default_policy(
1114            config.default_index_policy,
1115        ));
1116
1117        let db = Arc::new(Self {
1118            path: path.clone(),
1119            storage,
1120            concurrent_mvcc: Some(concurrent_mvcc),
1121            catalog: Arc::new(RwLock::new(Catalog::new("sochdb"))),
1122            tables: DashMap::new(),
1123            packed_schemas: DashMap::new(),
1124            index_registry,
1125            config,
1126            stats: DatabaseStats::new(),
1127            shutdown: AtomicU64::new(0),
1128            is_concurrent: true,
1129        });
1130
1131        // Perform crash recovery if needed
1132        db.recover()?;
1133
1134        // Clean up any stale readers from crashed processes
1135        if let Some(ref mvcc) = db.concurrent_mvcc {
1136            mvcc.cleanup_stale_readers();
1137        }
1138
1139        Ok(db)
1140    }
1141
1142    /// Check if database is in concurrent mode
1143    #[inline]
1144    pub fn is_concurrent(&self) -> bool {
1145        self.is_concurrent
1146    }
1147
1148    /// Perform crash recovery
1149    fn recover(&self) -> Result<RecoveryStats> {
1150        self.storage.recover()
1151    }
1152
1153    /// Get database path
1154    pub fn path(&self) -> &Path {
1155        &self.path
1156    }
1157
1158    // =========================================================================
1159    // Transaction API
1160    // =========================================================================
1161
1162    /// Begin a new transaction
1163    pub fn begin_transaction(&self) -> Result<TxnHandle> {
1164        self.stats
1165            .transactions_started
1166            .fetch_add(1, Ordering::Relaxed);
1167        let txn_id = self.storage.begin_transaction()?;
1168
1169        // Get snapshot timestamp from MVCC
1170        // For now, use txn_id as a proxy (the real snapshot_ts is managed internally)
1171        Ok(TxnHandle {
1172            txn_id,
1173            snapshot_ts: txn_id,
1174        })
1175    }
1176
1177    /// Begin a read-only transaction (optimized: no SSI tracking)
1178    ///
1179    /// Read-only transactions skip SSI read tracking, reducing overhead
1180    /// from ~82ns to ~32ns per read (2.6x faster).
1181    ///
1182    /// Use this for:
1183    /// - SELECT queries that don't modify data
1184    /// - Analytics and reporting queries
1185    /// - Snapshot reads for backup
1186    pub fn begin_read_only(&self) -> Result<TxnHandle> {
1187        self.stats
1188            .transactions_started
1189            .fetch_add(1, Ordering::Relaxed);
1190        let txn_id = self.storage.begin_with_mode(TransactionMode::ReadOnly)?;
1191        Ok(TxnHandle {
1192            txn_id,
1193            snapshot_ts: txn_id,
1194        })
1195    }
1196
1197    /// Begin a lightweight read-only transaction (no WAL overhead).
1198    ///
1199    /// Eliminates WAL mutex acquisitions entirely for read operations.
1200    /// The txn_id is allocated atomically and MVCC snapshot state is created,
1201    /// but NO WAL records are written (no TxnBegin, no TxnAbort).
1202    ///
1203    /// ~5-10x faster per-operation than `begin_read_only()` because it avoids:
1204    /// - 2 WAL mutex lock/unlock cycles per transaction
1205    /// - 2 WAL BufWriter serializations per transaction
1206    ///
1207    /// Callers MUST use `abort_read_only_fast()` to clean up — NOT `commit()`
1208    /// or `abort()`.
1209    #[inline]
1210    pub fn begin_read_only_fast(&self) -> TxnHandle {
1211        let txn_id = self.storage.begin_read_only_fast();
1212        TxnHandle {
1213            txn_id,
1214            snapshot_ts: txn_id,
1215        }
1216    }
1217
1218    /// Abort a fast read-only transaction — O(1), no WAL, no memtable scan.
1219    #[inline]
1220    pub fn abort_read_only_fast(&self, txn: TxnHandle) {
1221        self.storage.abort_read_only_fast(txn.txn_id);
1222    }
1223
1224    /// Read a key WITHOUT any MVCC transaction tracking.
1225    ///
1226    /// Uses the current global timestamp to see all committed writes.
1227    /// Bypasses: begin/abort, active_txns DashMap, record_read, stats.
1228    /// Only safe for single-threaded access with no concurrent writers.
1229    #[inline]
1230    pub fn get_raw_read(&self, key: &[u8]) -> Option<Vec<u8>> {
1231        self.storage.read_latest(key)
1232    }
1233
1234    /// Scan by prefix WITHOUT any MVCC transaction tracking.
1235    ///
1236    /// Uses the current global timestamp. Only safe for single-threaded access.
1237    #[inline]
1238    pub fn scan_raw(&self, prefix: &[u8]) -> Vec<(Vec<u8>, Vec<u8>)> {
1239        self.storage.scan_latest(prefix)
1240    }
1241
1242    /// Begin a write-only transaction (optimized: no read tracking)
1243    ///
1244    /// Write-only transactions skip read tracking, improving insert
1245    /// throughput for bulk loading scenarios.
1246    ///
1247    /// Use this for:
1248    /// - Bulk data imports
1249    /// - Append-only logging tables
1250    /// - ETL pipelines
1251    pub fn begin_write_only(&self) -> Result<TxnHandle> {
1252        self.stats
1253            .transactions_started
1254            .fetch_add(1, Ordering::Relaxed);
1255        let txn_id = self.storage.begin_with_mode(TransactionMode::WriteOnly)?;
1256        Ok(TxnHandle {
1257            txn_id,
1258            snapshot_ts: txn_id,
1259        })
1260    }
1261
1262    /// Commit a transaction
1263    ///
1264    /// In concurrent mode, acquires the shared writer lock to ensure
1265    /// WAL writes are serialized across processes, and forces a flush+sync
1266    /// so that subsequent processes see the committed data.
1267    pub fn commit(&self, txn: TxnHandle) -> Result<u64> {
1268        self.stats
1269            .transactions_committed
1270            .fetch_add(1, Ordering::Relaxed);
1271
1272        // In concurrent mode, acquire the cross-process writer lock
1273        // to serialize WAL commits across processes
1274        let _writer_guard = if let Some(ref mvcc) = self.concurrent_mvcc {
1275            Some(mvcc.acquire_writer(std::time::Duration::from_secs(5))?)
1276        } else {
1277            None
1278        };
1279
1280        let commit_ts = self.storage.commit(txn.txn_id)?;
1281
1282        // In concurrent mode, force flush+sync so other processes can see
1283        // the committed data when they open the DB or run recovery.
1284        // Without this, the BufWriter may hold data that isn't visible
1285        // to other processes reading the WAL file.
1286        if self.is_concurrent {
1287            self.storage.flush_wal()?;
1288            self.storage.fsync()?;
1289        }
1290
1291        // Notify concurrent MVCC of commit for GC tracking
1292        if let Some(ref mvcc) = self.concurrent_mvcc {
1293            mvcc.on_commit();
1294        }
1295
1296        Ok(commit_ts)
1297    }
1298
1299    /// Abort a transaction
1300    pub fn abort(&self, txn: TxnHandle) -> Result<()> {
1301        self.stats
1302            .transactions_aborted
1303            .fetch_add(1, Ordering::Relaxed);
1304        self.storage.abort(txn.txn_id)
1305    }
1306
1307    // =========================================================================
1308    // Per-Table Index Policy API
1309    // =========================================================================
1310
1311    /// Configure index policy for a table
1312    ///
1313    /// This allows fine-grained control over write/scan trade-offs per table:
1314    ///
1315    /// | Policy         | Insert Cost | Scan Cost      | Use Case              |
1316    /// |----------------|-------------|----------------|------------------------|
1317    /// | WriteOptimized | O(1)        | O(N)           | High-write, rare scan  |
1318    /// | Balanced       | O(1) amort  | O(output+logK) | Mixed OLTP            |
1319    /// | ScanOptimized  | O(log N)    | O(logN + K)    | Analytics, range query |
1320    /// | AppendOnly     | O(1)        | O(N)           | Time-series logs       |
1321    ///
1322    /// # Example
1323    ///
1324    /// ```ignore
1325    /// // Fast inserts for logs table (no ordered index overhead)
1326    /// db.set_table_index_policy("logs", IndexPolicy::WriteOptimized);
1327    ///
1328    /// // Efficient range scans for analytics table
1329    /// db.set_table_index_policy("analytics", IndexPolicy::ScanOptimized);
1330    ///
1331    /// // Balanced for OLTP tables
1332    /// db.set_table_index_policy("users", IndexPolicy::Balanced);
1333    /// ```
1334    pub fn set_table_index_policy(&self, table: &str, policy: IndexPolicy) {
1335        self.index_registry.configure_table(
1336            TableIndexConfig::new(table, policy)
1337        );
1338    }
1339
1340    /// Get the index policy for a table
1341    pub fn get_table_index_policy(&self, table: &str) -> IndexPolicy {
1342        self.index_registry.get_policy(table)
1343    }
1344
1345    /// Get the index registry for advanced configuration
1346    pub fn index_registry(&self) -> &Arc<TableIndexRegistry> {
1347        &self.index_registry
1348    }
1349
1350    // =========================================================================
1351    // Key-Value API (Low-level)
1352    // =========================================================================
1353
1354    /// Put a key-value pair
1355    ///
1356    /// In concurrent mode, acquires the shared writer lock to ensure
1357    /// WAL writes are serialized across processes.
1358    pub fn put(&self, txn: TxnHandle, key: &[u8], value: &[u8]) -> Result<()> {
1359        self.stats
1360            .bytes_written
1361            .fetch_add((key.len() + value.len()) as u64, Ordering::Relaxed);
1362
1363        // In concurrent mode, acquire cross-process writer lock
1364        let _writer_guard = if let Some(ref mvcc) = self.concurrent_mvcc {
1365            Some(mvcc.acquire_writer(std::time::Duration::from_secs(5))?)
1366        } else {
1367            None
1368        };
1369
1370        // Use write_refs to avoid unnecessary allocations
1371        self.storage.write_refs(txn.txn_id, key, value)
1372    }
1373
1374    /// Batch put multiple key-value pairs with reduced overhead
1375    ///
1376    /// This amortizes per-operation costs over the entire batch:
1377    /// - Single DashMap lookup
1378    /// - Batch MVCC tracking
1379    /// - Batch memtable writes
1380    ///
1381    /// For 100+ entries, this is 2-3x faster than individual puts.
1382    ///
1383    /// # Example
1384    ///
1385    /// ```ignore
1386    /// let writes: Vec<(&[u8], &[u8])> = vec![
1387    ///     (b"key1", b"value1"),
1388    ///     (b"key2", b"value2"),
1389    ///     (b"key3", b"value3"),
1390    /// ];
1391    /// db.put_batch(txn, &writes)?;
1392    /// ```
1393    pub fn put_batch(&self, txn: TxnHandle, writes: &[(&[u8], &[u8])]) -> Result<()> {
1394        let bytes: u64 = writes
1395            .iter()
1396            .map(|(k, v)| (k.len() + v.len()) as u64)
1397            .sum();
1398        self.stats.bytes_written.fetch_add(bytes, Ordering::Relaxed);
1399
1400        // In concurrent mode, acquire cross-process writer lock
1401        let _writer_guard = if let Some(ref mvcc) = self.concurrent_mvcc {
1402            Some(mvcc.acquire_writer(std::time::Duration::from_secs(5))?)
1403        } else {
1404            None
1405        };
1406
1407        self.storage.write_batch_refs(txn.txn_id, writes)
1408    }
1409
1410    /// Get a value by key
1411    pub fn get(&self, txn: TxnHandle, key: &[u8]) -> Result<Option<Vec<u8>>> {
1412        let result = self.storage.read(txn.txn_id, key)?;
1413        if let Some(ref data) = result {
1414            self.stats
1415                .bytes_read
1416                .fetch_add(data.len() as u64, Ordering::Relaxed);
1417        }
1418        Ok(result)
1419    }
1420
1421    /// Delete a key
1422    pub fn delete(&self, txn: TxnHandle, key: &[u8]) -> Result<()> {
1423        self.storage.delete(txn.txn_id, key.to_vec())
1424    }
1425
1426    /// Minimum prefix length for scan operations.
1427    /// Prevents expensive full-table scans by requiring a meaningful prefix.
1428    pub const MIN_SCAN_PREFIX_LEN: usize = 2;
1429
1430    /// Scan keys with a prefix (enforces minimum prefix length for safety).
1431    ///
1432    /// # Prefix Safety
1433    /// 
1434    /// To prevent accidental full-table scans, this method requires a minimum
1435    /// prefix length of 2 bytes. Use `scan_unchecked` for internal operations
1436    /// that need empty/short prefixes.
1437    ///
1438    /// # Errors
1439    ///
1440    /// Returns `SochDBError::InvalidInput` if prefix is too short.
1441    pub fn scan(&self, txn: TxnHandle, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1442        if prefix.len() < Self::MIN_SCAN_PREFIX_LEN {
1443            return Err(SochDBError::InvalidArgument(format!(
1444                "Prefix too short: {} bytes (minimum {} required). \
1445                 Use scan_unchecked() for unrestricted scans.",
1446                prefix.len(),
1447                Self::MIN_SCAN_PREFIX_LEN
1448            )));
1449        }
1450        self.scan_unchecked(txn, prefix)
1451    }
1452
1453    /// Scan keys with a prefix without length validation.
1454    ///
1455    /// # Warning
1456    ///
1457    /// This method allows empty/short prefixes which can cause expensive
1458    /// full-table scans. Use `scan()` unless you specifically need unrestricted
1459    /// prefix access for internal operations.
1460    pub fn scan_unchecked(&self, txn: TxnHandle, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1461        let results = self.storage.scan(txn.txn_id, prefix)?;
1462        let bytes: u64 = results
1463            .iter()
1464            .map(|(k, v)| (k.len() + v.len()) as u64)
1465            .sum();
1466        self.stats.bytes_read.fetch_add(bytes, Ordering::Relaxed);
1467        Ok(results)
1468    }
1469
1470    /// Scan keys in range
1471    pub fn scan_range(
1472        &self,
1473        txn: TxnHandle,
1474        start: &[u8],
1475        end: &[u8],
1476    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1477        let results = self.storage.scan_range(txn.txn_id, start, end)?;
1478        let bytes: u64 = results
1479            .iter()
1480            .map(|(k, v)| (k.len() + v.len()) as u64)
1481            .sum();
1482        self.stats.bytes_read.fetch_add(bytes, Ordering::Relaxed);
1483        Ok(results)
1484    }
1485
1486    /// Streaming scan for very large result sets
1487    /// 
1488    /// Returns an iterator that yields (key, value) pairs without
1489    /// materializing the entire result set. Use this for large scans
1490    /// where memory efficiency is important.
1491    /// 
1492    /// ## Performance
1493    /// 
1494    /// - Memory: O(1) per iteration vs O(N) for scan_range
1495    /// - Latency: First result available immediately vs waiting for all results
1496    /// - Throughput: Slightly lower due to per-item overhead
1497    /// 
1498    /// ## Usage
1499    /// 
1500    /// ```ignore
1501    /// for result in db.scan_range_iter(txn, b"start", b"end") {
1502    ///     let (key, value) = result?;
1503    ///     // Process immediately - no need to wait for all results
1504    /// }
1505    /// ```
1506    pub fn scan_range_iter<'a>(
1507        &'a self,
1508        txn: TxnHandle,
1509        start: &'a [u8],
1510        end: &'a [u8],
1511    ) -> impl Iterator<Item = Result<(Vec<u8>, Vec<u8>)>> + 'a {
1512        let stats = &self.stats;
1513        self.storage
1514            .scan_range_iter(txn.txn_id, start, end)
1515            .map(move |item| {
1516                stats.bytes_read.fetch_add(
1517                    (item.0.len() + item.1.len()) as u64,
1518                    Ordering::Relaxed,
1519                );
1520                Ok(item)
1521            })
1522    }
1523
1524    /// Flush memtable to WAL/Disk
1525    pub fn flush(&self) -> Result<()> {
1526        self.storage.fsync()
1527    }
1528
1529    // =========================================================================
1530    // Path-Native API (SochDB's differentiator)
1531    // =========================================================================
1532
1533    /// Get storage statistics
1534    pub fn storage_stats(&self) -> crate::durable_storage::StorageStats {
1535        self.storage.stats()
1536    }
1537
1538    /// Put a value at a path
1539    ///
1540    /// Path format: "collection/doc_id/field" or "table.row_id.column"
1541    /// Resolution is O(|path|), not O(log N) like B-tree.
1542    pub fn put_path(&self, txn: TxnHandle, path: &str, value: &[u8]) -> Result<()> {
1543        self.put(txn, path.as_bytes(), value)
1544    }
1545
1546    /// Get a value at a path
1547    pub fn get_path(&self, txn: TxnHandle, path: &str) -> Result<Option<Vec<u8>>> {
1548        self.get(txn, path.as_bytes())
1549    }
1550
1551    /// Delete at a path
1552    pub fn delete_path(&self, txn: TxnHandle, path: &str) -> Result<()> {
1553        self.delete(txn, path.as_bytes())
1554    }
1555
1556    /// Scan a path prefix
1557    ///
1558    /// Returns all key-value pairs where key starts with prefix.
1559    /// Useful for: "users/123/" -> all fields of user 123
1560    pub fn scan_path(&self, txn: TxnHandle, prefix: &str) -> Result<Vec<(String, Vec<u8>)>> {
1561        self.stats.queries_executed.fetch_add(1, Ordering::Relaxed);
1562
1563        let results = self.scan(txn, prefix.as_bytes())?;
1564
1565        Ok(results
1566            .into_iter()
1567            .filter_map(|(k, v)| String::from_utf8(k).ok().map(|path| (path, v)))
1568            .collect())
1569    }
1570
1571    // =========================================================================
1572    // Query API
1573    // =========================================================================
1574
1575    /// Execute a path query and return results
1576    ///
1577    /// This is the main query interface for LLM context retrieval.
1578    /// Supports:
1579    /// - Path prefix matching
1580    /// - Column projection (for I/O reduction)
1581    /// - Limit/offset
1582    pub fn query(&self, txn: TxnHandle, path_prefix: &str) -> QueryBuilder<'_> {
1583        QueryBuilder::new(self, txn, path_prefix.to_string())
1584    }
1585
1586    // =========================================================================
1587    // Table API (Higher-level abstraction)
1588    // =========================================================================
1589
1590    /// Register a table schema
1591    pub fn register_table(&self, schema: TableSchema) -> Result<()> {
1592        if self.tables.contains_key(&schema.name) {
1593            return Err(SochDBError::InvalidArgument(format!(
1594                "Table '{}' already exists",
1595                schema.name
1596            )));
1597        }
1598        // Cache the packed schema for fast inserts
1599        let packed_schema = Self::to_packed_schema(&schema);
1600        self.packed_schemas
1601            .insert(schema.name.clone(), packed_schema);
1602        self.tables.insert(schema.name.clone(), schema);
1603        Ok(())
1604    }
1605
1606    /// Get table schema
1607    pub fn get_table_schema(&self, name: &str) -> Option<TableSchema> {
1608        self.tables.get(name).map(|s| s.clone())
1609    }
1610
1611    /// List all tables
1612    pub fn list_tables(&self) -> Vec<String> {
1613        self.tables.iter().map(|e| e.key().clone()).collect()
1614    }
1615    /// Convert TableSchema to PackedTableSchema for efficient storage
1616    fn to_packed_schema(schema: &TableSchema) -> PackedTableSchema {
1617        let columns = schema
1618            .columns
1619            .iter()
1620            .map(|col| PackedColumnDef {
1621                name: col.name.clone(),
1622                col_type: match col.col_type {
1623                    ColumnType::Int64 => PackedColumnType::Int64,
1624                    ColumnType::UInt64 => PackedColumnType::UInt64,
1625                    ColumnType::Float64 => PackedColumnType::Float64,
1626                    ColumnType::Text => PackedColumnType::Text,
1627                    ColumnType::Binary => PackedColumnType::Binary,
1628                    ColumnType::Bool => PackedColumnType::Bool,
1629                },
1630                nullable: col.nullable,
1631            })
1632            .collect();
1633
1634        PackedTableSchema::new(&schema.name, columns)
1635    }
1636
1637    /// Insert a row into a table
1638    ///
1639    /// Uses packed row format: stores entire row as single key-value pair.
1640    /// This reduces write amplification from 4× to 1× for a 4-column table.
1641    ///
1642    /// # Performance
1643    /// - Before: 4 columns × (WAL entry + MVCC version) = 4 writes
1644    /// - After: 1 packed row = 1 write
1645    /// - Improvement: ~4× fewer WAL entries, ~48% less I/O overhead
1646    pub fn insert_row(
1647        &self,
1648        txn: TxnHandle,
1649        table: &str,
1650        row_id: u64,
1651        values: &HashMap<String, SochValue>,
1652    ) -> Result<()> {
1653        // Use cached packed schema - single DashMap lookup, no clone
1654        let packed_schema = self
1655            .packed_schemas
1656            .get(table)
1657            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1658
1659        // Pack the row using cached schema
1660        let packed_row = PackedRow::pack(&packed_schema, values);
1661
1662        // Build key using KeyBuffer - optimized stack allocation (~12-15ns vs ~30-35ns for write!())
1663        let key = KeyBuffer::format_row_key(table, row_id);
1664
1665        self.put(txn, key.as_bytes(), packed_row.as_bytes())?;
1666
1667        Ok(())
1668    }
1669
1670    /// Read a row from a table
1671    ///
1672    /// Reads packed row and extracts requested columns in O(k) time.
1673    /// Column projection happens in memory, not storage - all columns are fetched.
1674    pub fn read_row(
1675        &self,
1676        txn: TxnHandle,
1677        table: &str,
1678        row_id: u64,
1679        columns: Option<&[&str]>,
1680    ) -> Result<Option<HashMap<String, SochValue>>> {
1681        let schema = self
1682            .tables
1683            .get(table)
1684            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1685
1686        // Read the packed row with a single key lookup using KeyBuffer
1687        let key = KeyBuffer::format_row_key(table, row_id);
1688        let bytes = match self.get(txn, key.as_bytes())? {
1689            Some(b) => b,
1690            None => return Ok(None),
1691        };
1692
1693        // Use cached packed schema
1694        let packed_schema = self
1695            .packed_schemas
1696            .get(table)
1697            .ok_or_else(|| SochDBError::Internal("Packed schema not found".into()))?;
1698        let packed_row = PackedRow::from_bytes(bytes, packed_schema.num_columns())?;
1699
1700        // Determine which columns to return
1701        let cols_to_read: Vec<&str> = match columns {
1702            Some(c) => c.to_vec(),
1703            None => schema.columns.iter().map(|c| c.name.as_str()).collect(),
1704        };
1705
1706        let mut row = HashMap::new();
1707        for col_name in cols_to_read {
1708            if let Some(idx) = packed_schema.column_index(col_name)
1709                && let Some(col_def) = packed_schema.column(idx)
1710                && let Some(value) = packed_row.get_column(idx, col_def.col_type)
1711            {
1712                row.insert(col_name.to_string(), value);
1713            }
1714        }
1715
1716        Ok(Some(row))
1717    }
1718
1719    /// Insert multiple rows efficiently in a batch
1720    ///
1721    /// This method accumulates all rows and writes them with fewer WAL syncs.
1722    /// Ideal for bulk loading scenarios.
1723    ///
1724    /// # Performance
1725    /// - Uses group commit to batch fsync operations
1726    /// - Expected throughput: 500K-1M rows/sec depending on row size
1727    pub fn insert_rows_batch(
1728        &self,
1729        txn: TxnHandle,
1730        table: &str,
1731        rows: &[(u64, HashMap<String, SochValue>)],
1732    ) -> Result<usize> {
1733        // Use cached packed schema
1734        let packed_schema = self
1735            .packed_schemas
1736            .get(table)
1737            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1738
1739        let mut count = 0;
1740
1741        for (row_id, values) in rows {
1742            // Pack and write using KeyBuffer for efficient key construction
1743            let packed_row = PackedRow::pack(&packed_schema, values);
1744            let key = KeyBuffer::format_row_key(table, *row_id);
1745            self.put(txn, key.as_bytes(), packed_row.as_bytes())?;
1746            count += 1;
1747        }
1748
1749        Ok(count)
1750    }
1751
1752    /// Ultra-fast raw put - bypasses all validation
1753    ///
1754    /// Use when you've already validated the data and just need speed.
1755    /// This is ~10× faster than insert_row() for bulk inserts.
1756    #[inline]
1757    pub fn put_raw(&self, txn: TxnHandle, key: &[u8], value: &[u8]) -> Result<()> {
1758        self.storage.write_refs(txn.txn_id, key, value)
1759    }
1760
1761    /// Zero-allocation insert - fastest path for bulk inserts
1762    ///
1763    /// Takes values as a slice in schema column order, avoiding HashMap overhead.
1764    ///
1765    /// # Arguments
1766    /// * `txn` - Transaction handle
1767    /// * `table` - Table name
1768    /// * `row_id` - Row identifier
1769    /// * `values` - Values in schema column order (None = NULL)
1770    ///
1771    /// # Performance
1772    /// - Eliminates ~6 allocations per row vs insert_row()
1773    /// - Expected: 1.2M-1.5M inserts/sec
1774    ///
1775    /// # Example
1776    /// ```ignore
1777    /// let values: &[Option<&SochValue>] = &[
1778    ///     Some(&SochValue::Int(1)),
1779    ///     Some(&SochValue::Text("Alice".into())),
1780    ///     None, // NULL
1781    /// ];
1782    /// db.insert_row_slice(txn, "users", 1, values)?;
1783    /// ```
1784    #[inline]
1785    pub fn insert_row_slice(
1786        &self,
1787        txn: TxnHandle,
1788        table: &str,
1789        row_id: u64,
1790        values: &[Option<&SochValue>],
1791    ) -> Result<()> {
1792        // Use cached packed schema - single DashMap lookup
1793        let packed_schema = self
1794            .packed_schemas
1795            .get(table)
1796            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1797
1798        // Validate column count matches
1799        if values.len() != packed_schema.num_columns() {
1800            return Err(SochDBError::InvalidArgument(format!(
1801                "Expected {} columns, got {}",
1802                packed_schema.num_columns(),
1803                values.len()
1804            )));
1805        }
1806
1807        // Pack using zero-allocation path
1808        let packed_row = PackedRow::pack_slice(&packed_schema, values);
1809
1810        // Build key using KeyBuffer - optimized stack allocation (~12-15ns vs ~30-35ns for write!())
1811        let key = KeyBuffer::format_row_key(table, row_id);
1812
1813        self.put(txn, key.as_bytes(), packed_row.as_bytes())?;
1814        Ok(())
1815    }
1816
1817    // =========================================================================
1818    // Maintenance
1819    // =========================================================================
1820
1821    /// Force fsync to disk
1822    pub fn fsync(&self) -> Result<()> {
1823        self.storage.fsync()
1824    }
1825
1826    /// Create a checkpoint
1827    pub fn checkpoint(&self) -> Result<u64> {
1828        self.storage.checkpoint()
1829    }
1830
1831    /// Truncate the WAL file after a checkpoint.
1832    ///
1833    /// See [`DurableStorage::truncate_wal`] for safety notes.
1834    pub fn truncate_wal(&self) -> Result<()> {
1835        self.storage.truncate_wal()
1836    }
1837
1838    /// Run garbage collection
1839    pub fn gc(&self) -> usize {
1840        self.storage.gc()
1841    }
1842
1843    /// Get database statistics
1844    pub fn stats(&self) -> Stats {
1845        Stats {
1846            transactions_started: self.stats.transactions_started.load(Ordering::Relaxed),
1847            transactions_committed: self.stats.transactions_committed.load(Ordering::Relaxed),
1848            transactions_aborted: self.stats.transactions_aborted.load(Ordering::Relaxed),
1849            queries_executed: self.stats.queries_executed.load(Ordering::Relaxed),
1850            bytes_written: self.stats.bytes_written.load(Ordering::Relaxed),
1851            bytes_read: self.stats.bytes_read.load(Ordering::Relaxed),
1852        }
1853    }
1854
1855    /// Shutdown the database gracefully
1856    pub fn shutdown(&self) -> Result<()> {
1857        if self.shutdown.swap(1, Ordering::SeqCst) == 1 {
1858            return Ok(()); // Already shutting down
1859        }
1860
1861        // Flush any pending writes
1862        self.fsync()?;
1863
1864        // Create clean shutdown marker
1865        let marker = self.path.join(".clean_shutdown");
1866        std::fs::write(&marker, b"ok")?;
1867
1868        Ok(())
1869    }
1870}
1871
1872impl Drop for Database {
1873    fn drop(&mut self) {
1874        // Try graceful shutdown if not already done
1875        if self.shutdown.load(Ordering::SeqCst) == 0 {
1876            let _ = self.fsync();
1877            let marker = self.path.join(".clean_shutdown");
1878            let _ = std::fs::write(&marker, b"ok");
1879        }
1880    }
1881}
1882
1883/// Query builder for fluent query construction
1884pub struct QueryBuilder<'a> {
1885    db: &'a Database,
1886    txn: TxnHandle,
1887    path_prefix: String,
1888    columns: Option<Vec<String>>,
1889    limit: Option<usize>,
1890    offset: Option<usize>,
1891}
1892
1893impl<'a> QueryBuilder<'a> {
1894    fn new(db: &'a Database, txn: TxnHandle, path_prefix: String) -> Self {
1895        Self {
1896            db,
1897            txn,
1898            path_prefix,
1899            columns: None,
1900            limit: None,
1901            offset: None,
1902        }
1903    }
1904
1905    /// Select specific columns (for I/O reduction)
1906    pub fn columns(mut self, cols: &[&str]) -> Self {
1907        self.columns = Some(cols.iter().map(|s| s.to_string()).collect());
1908        self
1909    }
1910
1911    /// Limit results
1912    pub fn limit(mut self, n: usize) -> Self {
1913        self.limit = Some(n);
1914        self
1915    }
1916
1917    /// Skip results
1918    pub fn offset(mut self, n: usize) -> Self {
1919        self.offset = Some(n);
1920        self
1921    }
1922
1923    /// Execute the query
1924    ///
1925    /// Scans packed rows and unpacks them. Each key is "table/row_id" pointing to a packed row.
1926    pub fn execute(self) -> Result<QueryResult> {
1927        self.db
1928            .stats
1929            .queries_executed
1930            .fetch_add(1, Ordering::Relaxed);
1931
1932        // Get schema for the table if we're querying a table
1933        let table_name = self
1934            .path_prefix
1935            .split('/')
1936            .next()
1937            .unwrap_or(&self.path_prefix);
1938        let schema = self.db.tables.get(table_name).map(|s| s.clone());
1939
1940        // Scan the path prefix
1941        let results = self.db.scan_path(self.txn, &self.path_prefix)?;
1942
1943        let mut rows: Vec<HashMap<String, SochValue>> = Vec::new();
1944        let mut bytes_read = 0usize;
1945
1946        if let Some(ref schema) = schema {
1947            // We have a table schema - use cached packed schema
1948            let packed_schema = self
1949                .db
1950                .packed_schemas
1951                .get(table_name)
1952                .map(|ps| ps.clone())
1953                .unwrap_or_else(|| Database::to_packed_schema(schema));
1954
1955            for (path, value_bytes) in results {
1956                // Parse path: table/row_id
1957                let parts: Vec<&str> = path.split('/').collect();
1958                if parts.len() == 2 {
1959                    // This is a packed row
1960                    bytes_read += value_bytes.len();
1961
1962                    if let Ok(packed_row) =
1963                        PackedRow::from_bytes(value_bytes, packed_schema.num_columns())
1964                    {
1965                        // Unpack all columns or just requested columns
1966                        let mut row = HashMap::new();
1967
1968                        if let Some(ref cols) = self.columns {
1969                            // Only extract requested columns
1970                            for col_name in cols {
1971                                if let Some(idx) = packed_schema.column_index(col_name)
1972                                    && let Some(col_def) = packed_schema.column(idx)
1973                                    && let Some(value) =
1974                                        packed_row.get_column(idx, col_def.col_type)
1975                                {
1976                                    row.insert(col_name.clone(), value);
1977                                }
1978                            }
1979                        } else {
1980                            // Extract all columns
1981                            row = packed_row.unpack(&packed_schema);
1982                        }
1983
1984                        if !row.is_empty() {
1985                            rows.push(row);
1986                        }
1987                    }
1988                }
1989            }
1990        } else {
1991            // Fallback: no schema, try legacy column-per-key format
1992            let mut rows_map: HashMap<String, HashMap<String, SochValue>> = HashMap::new();
1993
1994            for (path, value_bytes) in results {
1995                let parts: Vec<&str> = path.split('/').collect();
1996                if parts.len() >= 3 {
1997                    let row_key = format!("{}/{}", parts[0], parts[1]);
1998                    let col_name = parts[2..].join("/");
1999
2000                    if let Some(ref cols) = self.columns
2001                        && !cols.contains(&col_name)
2002                    {
2003                        continue;
2004                    }
2005
2006                    bytes_read += value_bytes.len();
2007                    let row = rows_map.entry(row_key).or_default();
2008                    row.insert(col_name, deserialize_value(&value_bytes));
2009                }
2010            }
2011
2012            rows = rows_map.into_values().collect();
2013        }
2014
2015        // Apply offset
2016        if let Some(offset) = self.offset {
2017            rows = rows.into_iter().skip(offset).collect();
2018        }
2019
2020        // Apply limit
2021        if let Some(limit) = self.limit {
2022            rows.truncate(limit);
2023        }
2024
2025        // Collect column names
2026        let columns: Vec<String> = self.columns.unwrap_or_else(|| {
2027            rows.iter()
2028                .flat_map(|r| r.keys().cloned())
2029                .collect::<std::collections::HashSet<_>>()
2030                .into_iter()
2031                .collect()
2032        });
2033
2034        Ok(QueryResult {
2035            columns,
2036            rows_scanned: rows.len(),
2037            bytes_read,
2038            rows,
2039        })
2040    }
2041
2042    /// Execute and return TOON format (for LLM efficiency)
2043    pub fn to_toon(self) -> Result<String> {
2044        let result = self.execute()?;
2045        Ok(result.to_toon())
2046    }
2047
2048    /// Execute with lazy iteration - avoids materializing all rows
2049    ///
2050    /// Returns an iterator over rows as `Vec<SochValue>` in schema column order.
2051    /// This is more memory-efficient than `execute()` for large result sets.
2052    ///
2053    /// # Performance
2054    /// - No upfront materialization of all rows
2055    /// - ~40% less memory for large result sets
2056    /// - Ideal for streaming to network or aggregations
2057    ///
2058    /// # Example
2059    /// ```ignore
2060    /// for row_result in db.query(txn, "users").execute_iter()? {
2061    ///     let row = row_result?;
2062    ///     // row is Vec<SochValue> in column order
2063    /// }
2064    /// ```
2065    pub fn execute_iter(self) -> Result<QueryRowIterator> {
2066        self.db
2067            .stats
2068            .queries_executed
2069            .fetch_add(1, Ordering::Relaxed);
2070
2071        let table_name = self
2072            .path_prefix
2073            .split('/')
2074            .next()
2075            .unwrap_or(&self.path_prefix)
2076            .to_string();
2077
2078        // Get packed schema (clone needed for iterator ownership)
2079        let packed_schema = self.db.packed_schemas.get(&table_name).map(|ps| ps.clone());
2080
2081        // Scan the path prefix
2082        let results = self.db.scan_path(self.txn, &self.path_prefix)?;
2083
2084        Ok(QueryRowIterator {
2085            results: results.into_iter(),
2086            packed_schema,
2087            columns: self.columns,
2088            offset: self.offset.unwrap_or(0),
2089            limit: self.limit,
2090            yielded: 0,
2091            skipped: 0,
2092        })
2093    }
2094
2095    /// Execute and return columnar (SIMD-friendly) result format
2096    ///
2097    /// Instead of row-oriented `Vec<HashMap<String, SochValue>>`, returns
2098    /// column-oriented `Vec<TypedColumn>` for vectorized operations.
2099    ///
2100    /// ## Performance Benefits
2101    ///
2102    /// - SIMD: Aggregate operations (sum, avg) use vectorized instructions
2103    /// - Cache: Sequential access maximizes L1/L2 hits
2104    /// - Memory: ~30% less overhead than row-based format
2105    /// - Analytics: Ideal for ML preprocessing and statistics
2106    ///
2107    /// ## Example
2108    ///
2109    /// ```ignore
2110    /// let result = db.query(txn, "users")
2111    ///     .columns(&["id", "score"])
2112    ///     .as_columnar()?;
2113    ///
2114    /// // SIMD-optimized sum
2115    /// let total = result.sum_i64("score").unwrap_or(0);
2116    ///
2117    /// // Direct column access
2118    /// if let Some(scores) = result.column("score") {
2119    ///     for i in 0..scores.len() {
2120    ///         if let Some(v) = scores.get_i64(i) {
2121    ///             println!("Score: {}", v);
2122    ///         }
2123    ///     }
2124    /// }
2125    /// ```
2126    pub fn as_columnar(self) -> Result<ColumnarQueryResult> {
2127        self.db
2128            .stats
2129            .queries_executed
2130            .fetch_add(1, Ordering::Relaxed);
2131
2132        let table_name = self
2133            .path_prefix
2134            .split('/')
2135            .next()
2136            .unwrap_or(&self.path_prefix);
2137        let schema = self.db.tables.get(table_name).map(|s| s.clone());
2138
2139        // Get packed schema
2140        let packed_schema = match self.db.packed_schemas.get(table_name) {
2141            Some(ps) => ps.clone(),
2142            None => return Ok(ColumnarQueryResult::empty()),
2143        };
2144
2145        // Determine columns to fetch
2146        let column_names: Vec<String> = self.columns.clone().unwrap_or_else(|| {
2147            schema
2148                .as_ref()
2149                .map(|s| s.columns.iter().map(|c| c.name.clone()).collect())
2150                .unwrap_or_default()
2151        });
2152
2153        if column_names.is_empty() {
2154            return Ok(ColumnarQueryResult::empty());
2155        }
2156
2157        // Initialize TypedColumns based on schema types
2158        let mut columns: Vec<CoreTypedColumn> = column_names
2159            .iter()
2160            .map(|col_name| {
2161                packed_schema
2162                    .column_index(col_name)
2163                    .and_then(|idx| packed_schema.column(idx))
2164                    .map(|col_def| match col_def.col_type {
2165                        PackedColumnType::Int64 => CoreTypedColumn::new_int64(),
2166                        PackedColumnType::UInt64 => CoreTypedColumn::new_uint64(),
2167                        PackedColumnType::Float64 => CoreTypedColumn::new_float64(),
2168                        PackedColumnType::Text => CoreTypedColumn::new_text(),
2169                        PackedColumnType::Binary => CoreTypedColumn::new_binary(),
2170                        PackedColumnType::Bool => CoreTypedColumn::new_bool(),
2171                        PackedColumnType::Null => CoreTypedColumn::new_text(), // Null column = fallback to text
2172                    })
2173                    .unwrap_or_else(CoreTypedColumn::new_text) // fallback
2174            })
2175            .collect();
2176
2177        // Scan the path prefix
2178        let results = self.db.scan_path(self.txn, &self.path_prefix)?;
2179
2180        let mut row_count = 0;
2181        let mut bytes_read = 0;
2182        let mut skipped = 0;
2183
2184        for (path, value_bytes) in results {
2185            // Parse path: table/row_id
2186            let parts: Vec<&str> = path.split('/').collect();
2187            if parts.len() != 2 {
2188                continue;
2189            }
2190
2191            // Apply offset
2192            if let Some(offset) = self.offset
2193                && skipped < offset
2194            {
2195                skipped += 1;
2196                continue;
2197            }
2198
2199            // Apply limit
2200            if let Some(limit) = self.limit
2201                && row_count >= limit
2202            {
2203                break;
2204            }
2205
2206            bytes_read += value_bytes.len();
2207
2208            if let Ok(packed_row) = PackedRow::from_bytes(value_bytes, packed_schema.num_columns())
2209            {
2210                // Extract each column and push to corresponding TypedColumn
2211                for (col_idx, col_name) in column_names.iter().enumerate() {
2212                    if let Some(schema_idx) = packed_schema.column_index(col_name) {
2213                        if let Some(col_def) = packed_schema.column(schema_idx) {
2214                            let value = packed_row.get_column(schema_idx, col_def.col_type);
2215                            push_value_to_typed_column(&mut columns[col_idx], value);
2216                        } else {
2217                            push_null_to_typed_column(&mut columns[col_idx]);
2218                        }
2219                    } else {
2220                        push_null_to_typed_column(&mut columns[col_idx]);
2221                    }
2222                }
2223                row_count += 1;
2224            }
2225        }
2226
2227        Ok(ColumnarQueryResult {
2228            columns: column_names,
2229            data: columns,
2230            row_count,
2231            bytes_read,
2232        })
2233    }
2234}
2235
2236/// Lazy iterator over query results
2237///
2238/// Unpacks rows on-demand, avoiding upfront materialization.
2239pub struct QueryRowIterator {
2240    results: std::vec::IntoIter<(String, Vec<u8>)>,
2241    packed_schema: Option<PackedTableSchema>,
2242    columns: Option<Vec<String>>,
2243    offset: usize,
2244    limit: Option<usize>,
2245    yielded: usize,
2246    skipped: usize,
2247}
2248
2249impl Iterator for QueryRowIterator {
2250    type Item = Result<Vec<SochValue>>;
2251
2252    fn next(&mut self) -> Option<Self::Item> {
2253        // Check limit
2254        if let Some(limit) = self.limit
2255            && self.yielded >= limit
2256        {
2257            return None;
2258        }
2259
2260        loop {
2261            let (path, value_bytes) = self.results.next()?;
2262
2263            // Parse path: table/row_id
2264            let parts: Vec<&str> = path.split('/').collect();
2265            if parts.len() != 2 {
2266                continue; // Skip non-row entries
2267            }
2268
2269            // Apply offset
2270            if self.skipped < self.offset {
2271                self.skipped += 1;
2272                continue;
2273            }
2274
2275            if let Some(ref schema) = self.packed_schema {
2276                match PackedRow::from_bytes(value_bytes, schema.num_columns()) {
2277                    Ok(packed_row) => {
2278                        let row = if let Some(ref cols) = self.columns {
2279                            // Project specific columns
2280                            cols.iter()
2281                                .map(|col_name| {
2282                                    schema
2283                                        .column_index(col_name)
2284                                        .and_then(|idx| schema.column(idx))
2285                                        .and_then(|col_def| {
2286                                            packed_row.get_column(
2287                                                schema.column_index(col_name).unwrap(),
2288                                                col_def.col_type,
2289                                            )
2290                                        })
2291                                        .unwrap_or(SochValue::Null)
2292                                })
2293                                .collect()
2294                        } else {
2295                            // All columns in order
2296                            packed_row.unpack_to_vec(schema)
2297                        };
2298
2299                        self.yielded += 1;
2300                        return Some(Ok(row));
2301                    }
2302                    Err(e) => return Some(Err(e)),
2303                }
2304            } else {
2305                // No schema - return raw bytes as binary
2306                self.yielded += 1;
2307                return Some(Ok(vec![SochValue::Binary(value_bytes)]));
2308            }
2309        }
2310    }
2311}
2312
2313// Helper functions for serialization (kept for backward compatibility with legacy data)
2314
2315#[allow(dead_code)]
2316fn serialize_value(value: &SochValue) -> Vec<u8> {
2317    // Simple serialization - in production use proper format
2318    match value {
2319        SochValue::Null => vec![0],
2320        SochValue::Int(i) => {
2321            let mut buf = vec![1];
2322            buf.extend_from_slice(&i.to_le_bytes());
2323            buf
2324        }
2325        SochValue::UInt(u) => {
2326            let mut buf = vec![2];
2327            buf.extend_from_slice(&u.to_le_bytes());
2328            buf
2329        }
2330        SochValue::Float(f) => {
2331            let mut buf = vec![3];
2332            buf.extend_from_slice(&f.to_le_bytes());
2333            buf
2334        }
2335        SochValue::Text(s) => {
2336            let mut buf = vec![4];
2337            buf.extend_from_slice(s.as_bytes());
2338            buf
2339        }
2340        SochValue::Bool(b) => vec![5, if *b { 1 } else { 0 }],
2341        SochValue::Binary(b) => {
2342            let mut buf = vec![6];
2343            buf.extend_from_slice(b);
2344            buf
2345        }
2346        _ => {
2347            // Fallback: serialize as text
2348            let s = format!("{:?}", value);
2349            let mut buf = vec![4];
2350            buf.extend_from_slice(s.as_bytes());
2351            buf
2352        }
2353    }
2354}
2355
2356fn deserialize_value(bytes: &[u8]) -> SochValue {
2357    if bytes.is_empty() {
2358        return SochValue::Null;
2359    }
2360
2361    match bytes[0] {
2362        0 => SochValue::Null,
2363        1 if bytes.len() >= 9 => {
2364            let i = i64::from_le_bytes(bytes[1..9].try_into().unwrap());
2365            SochValue::Int(i)
2366        }
2367        2 if bytes.len() >= 9 => {
2368            let u = u64::from_le_bytes(bytes[1..9].try_into().unwrap());
2369            SochValue::UInt(u)
2370        }
2371        3 if bytes.len() >= 9 => {
2372            let f = f64::from_le_bytes(bytes[1..9].try_into().unwrap());
2373            SochValue::Float(f)
2374        }
2375        4 => {
2376            let s = String::from_utf8_lossy(&bytes[1..]).to_string();
2377            SochValue::Text(s)
2378        }
2379        5 if bytes.len() >= 2 => SochValue::Bool(bytes[1] != 0),
2380        6 => SochValue::Binary(bytes[1..].to_vec()),
2381        _ => {
2382            // Treat as text
2383            let s = String::from_utf8_lossy(bytes).to_string();
2384            SochValue::Text(s)
2385        }
2386    }
2387}
2388
2389// ============================================================================
2390// Helper functions for columnar query result building
2391// ============================================================================
2392
2393/// Push a SochValue into a TypedColumn
2394fn push_value_to_typed_column(col: &mut CoreTypedColumn, value: Option<SochValue>) {
2395    match value {
2396        None => push_null_to_typed_column(col),
2397        Some(v) => match (col, v) {
2398            (
2399                CoreTypedColumn::Int64 {
2400                    values,
2401                    validity,
2402                    stats,
2403                },
2404                SochValue::Int(i),
2405            ) => {
2406                values.push(i);
2407                validity.push(true);
2408                stats.update_i64(i);
2409            }
2410            (
2411                CoreTypedColumn::Int64 {
2412                    values,
2413                    validity,
2414                    stats,
2415                },
2416                SochValue::UInt(u),
2417            ) => {
2418                values.push(u as i64);
2419                validity.push(true);
2420                stats.update_i64(u as i64);
2421            }
2422            (
2423                CoreTypedColumn::UInt64 {
2424                    values,
2425                    validity,
2426                    stats,
2427                },
2428                SochValue::UInt(u),
2429            ) => {
2430                values.push(u);
2431                validity.push(true);
2432                stats.update_i64(u as i64);
2433            }
2434            (
2435                CoreTypedColumn::UInt64 {
2436                    values,
2437                    validity,
2438                    stats,
2439                },
2440                SochValue::Int(i),
2441            ) => {
2442                values.push(i as u64);
2443                validity.push(true);
2444                stats.update_i64(i);
2445            }
2446            (
2447                CoreTypedColumn::Float64 {
2448                    values,
2449                    validity,
2450                    stats,
2451                },
2452                SochValue::Float(f),
2453            ) => {
2454                values.push(f);
2455                validity.push(true);
2456                stats.update_f64(f);
2457            }
2458            (
2459                CoreTypedColumn::Float64 {
2460                    values,
2461                    validity,
2462                    stats,
2463                },
2464                SochValue::Int(i),
2465            ) => {
2466                values.push(i as f64);
2467                validity.push(true);
2468                stats.update_f64(i as f64);
2469            }
2470            (
2471                CoreTypedColumn::Text {
2472                    offsets,
2473                    data,
2474                    validity,
2475                    stats,
2476                },
2477                SochValue::Text(s),
2478            ) => {
2479                data.extend_from_slice(s.as_bytes());
2480                offsets.push(data.len() as u32);
2481                validity.push(true);
2482                stats.row_count += 1;
2483            }
2484            (
2485                CoreTypedColumn::Binary {
2486                    offsets,
2487                    data,
2488                    validity,
2489                    stats,
2490                },
2491                SochValue::Binary(b),
2492            ) => {
2493                data.extend_from_slice(&b);
2494                offsets.push(data.len() as u32);
2495                validity.push(true);
2496                stats.row_count += 1;
2497            }
2498            (
2499                CoreTypedColumn::Bool {
2500                    values,
2501                    validity,
2502                    stats,
2503                    len,
2504                },
2505                SochValue::Bool(b),
2506            ) => {
2507                let idx = *len;
2508                *len += 1;
2509                let num_words = (*len).div_ceil(64);
2510                while values.len() < num_words {
2511                    values.push(0);
2512                }
2513                if b {
2514                    let word = idx / 64;
2515                    let bit = idx % 64;
2516                    values[word] |= 1 << bit;
2517                }
2518                validity.push(true);
2519                stats.row_count += 1;
2520            }
2521            // Type mismatch - push as null
2522            (col, _) => push_null_to_typed_column(col),
2523        },
2524    }
2525}
2526
2527/// Push a null value into a TypedColumn
2528fn push_null_to_typed_column(col: &mut CoreTypedColumn) {
2529    match col {
2530        CoreTypedColumn::Int64 {
2531            values,
2532            validity,
2533            stats,
2534        } => {
2535            values.push(0);
2536            validity.push(false);
2537            stats.update_null();
2538        }
2539        CoreTypedColumn::UInt64 {
2540            values,
2541            validity,
2542            stats,
2543        } => {
2544            values.push(0);
2545            validity.push(false);
2546            stats.update_null();
2547        }
2548        CoreTypedColumn::Float64 {
2549            values,
2550            validity,
2551            stats,
2552        } => {
2553            values.push(0.0);
2554            validity.push(false);
2555            stats.update_null();
2556        }
2557        CoreTypedColumn::Text {
2558            offsets,
2559            data: _,
2560            validity,
2561            stats,
2562        } => {
2563            offsets.push(offsets.last().copied().unwrap_or(0));
2564            validity.push(false);
2565            stats.update_null();
2566        }
2567        CoreTypedColumn::Binary {
2568            offsets,
2569            data: _,
2570            validity,
2571            stats,
2572        } => {
2573            offsets.push(offsets.last().copied().unwrap_or(0));
2574            validity.push(false);
2575            stats.update_null();
2576        }
2577        CoreTypedColumn::Bool {
2578            values,
2579            validity,
2580            stats,
2581            len,
2582        } => {
2583            *len += 1;
2584            let num_words = (*len).div_ceil(64);
2585            while values.len() < num_words {
2586                values.push(0);
2587            }
2588            validity.push(false);
2589            stats.update_null();
2590        }
2591    }
2592}
2593
2594#[cfg(test)]
2595mod tests {
2596    use super::*;
2597    use tempfile::tempdir;
2598
2599    #[test]
2600    fn test_database_open_close() {
2601        let dir = tempdir().unwrap();
2602        let db = Database::open(dir.path()).unwrap();
2603
2604        // Should be able to begin a transaction
2605        let txn = db.begin_transaction().unwrap();
2606        assert!(txn.txn_id > 0);
2607
2608        db.abort(txn).unwrap();
2609        db.shutdown().unwrap();
2610    }
2611
2612    #[test]
2613    fn test_database_put_get() {
2614        let dir = tempdir().unwrap();
2615        let db = Database::open(dir.path()).unwrap();
2616
2617        let txn = db.begin_transaction().unwrap();
2618        db.put(txn, b"key1", b"value1").unwrap();
2619
2620        let val = db.get(txn, b"key1").unwrap();
2621        assert_eq!(val, Some(b"value1".to_vec()));
2622
2623        db.commit(txn).unwrap();
2624
2625        // New transaction should see committed data
2626        let txn2 = db.begin_transaction().unwrap();
2627        let val = db.get(txn2, b"key1").unwrap();
2628        assert_eq!(val, Some(b"value1".to_vec()));
2629        db.abort(txn2).unwrap();
2630    }
2631
2632    #[test]
2633    fn test_database_path_api() {
2634        let dir = tempdir().unwrap();
2635        let db = Database::open(dir.path()).unwrap();
2636
2637        let txn = db.begin_transaction().unwrap();
2638
2639        // Write using path API
2640        db.put_path(txn, "users/1/name", b"Alice").unwrap();
2641        db.put_path(txn, "users/1/email", b"alice@example.com")
2642            .unwrap();
2643        db.put_path(txn, "users/2/name", b"Bob").unwrap();
2644
2645        db.commit(txn).unwrap();
2646
2647        // Scan path prefix
2648        let txn2 = db.begin_transaction().unwrap();
2649        let results = db.scan_path(txn2, "users/1/").unwrap();
2650        assert_eq!(results.len(), 2);
2651
2652        db.abort(txn2).unwrap();
2653    }
2654
2655    #[test]
2656    fn test_database_table_api() {
2657        let dir = tempdir().unwrap();
2658        let db = Database::open(dir.path()).unwrap();
2659
2660        // Register table
2661        db.register_table(TableSchema {
2662            name: "users".to_string(),
2663            columns: vec![
2664                ColumnDef {
2665                    name: "name".to_string(),
2666                    col_type: ColumnType::Text,
2667                    nullable: false,
2668                },
2669                ColumnDef {
2670                    name: "age".to_string(),
2671                    col_type: ColumnType::Int64,
2672                    nullable: true,
2673                },
2674            ],
2675        })
2676        .unwrap();
2677
2678        // Insert row
2679        let txn = db.begin_transaction().unwrap();
2680        let mut values = HashMap::new();
2681        values.insert("name".to_string(), SochValue::Text("Alice".to_string()));
2682        values.insert("age".to_string(), SochValue::Int(30));
2683
2684        db.insert_row(txn, "users", 1, &values).unwrap();
2685        db.commit(txn).unwrap();
2686
2687        // Read row
2688        let txn2 = db.begin_transaction().unwrap();
2689        let row = db.read_row(txn2, "users", 1, None).unwrap();
2690        assert!(row.is_some());
2691
2692        let row = row.unwrap();
2693        assert_eq!(row.get("name"), Some(&SochValue::Text("Alice".to_string())));
2694
2695        db.abort(txn2).unwrap();
2696    }
2697
2698    #[test]
2699    fn test_database_query_builder() {
2700        let dir = tempdir().unwrap();
2701        let db = Database::open(dir.path()).unwrap();
2702
2703        // Insert test data
2704        let txn = db.begin_transaction().unwrap();
2705        db.put_path(txn, "docs/1/title", b"Hello").unwrap();
2706        db.put_path(txn, "docs/1/content", b"World").unwrap();
2707        db.put_path(txn, "docs/2/title", b"Foo").unwrap();
2708        db.put_path(txn, "docs/2/content", b"Bar").unwrap();
2709        db.commit(txn).unwrap();
2710
2711        // Query with limit
2712        let txn2 = db.begin_transaction().unwrap();
2713        let result = db.query(txn2, "docs/").limit(1).execute().unwrap();
2714
2715        assert_eq!(result.rows.len(), 1);
2716        db.abort(txn2).unwrap();
2717    }
2718
2719    #[test]
2720    fn test_database_crash_recovery() {
2721        let dir = tempdir().unwrap();
2722
2723        // Write and commit
2724        {
2725            // Use open_without_lock for crash simulation tests
2726            let db = Database::open_without_lock(dir.path()).unwrap();
2727            // Set sync mode to FULL to ensure data is persisted before "crash"
2728            db.storage.set_sync_mode(2);
2729            let txn = db.begin_transaction().unwrap();
2730            db.put(txn, b"persist", b"this").unwrap();
2731            db.commit(txn).unwrap();
2732            // Don't call shutdown - simulate crash
2733            std::mem::forget(db);
2734        }
2735
2736        // Reopen - should recover
2737        {
2738            let db = Database::open_without_lock(dir.path()).unwrap();
2739            let txn = db.begin_transaction().unwrap();
2740            let val = db.get(txn, b"persist").unwrap();
2741            assert_eq!(val, Some(b"this".to_vec()));
2742            db.abort(txn).unwrap();
2743        }
2744    }
2745
2746    #[test]
2747    fn test_columnar_row_view_zero_alloc() {
2748        use sochdb_core::columnar::TypedColumn;
2749
2750        // Build a small columnar result: 3 rows × 2 columns (id: i64, name: text)
2751        let mut id_col = TypedColumn::new_int64();
2752        id_col.push_i64(Some(1));
2753        id_col.push_i64(Some(2));
2754        id_col.push_i64(Some(3));
2755
2756        let mut name_col = TypedColumn::new_text();
2757        name_col.push_text(Some("Alice"));
2758        name_col.push_text(Some("Bob"));
2759        name_col.push_text(None); // NULL
2760
2761        let cr = ColumnarQueryResult {
2762            columns: vec!["id".to_string(), "name".to_string()],
2763            data: vec![id_col, name_col],
2764            row_count: 3,
2765            bytes_read: 0,
2766        };
2767
2768        // row_view access — zero HashMap allocation
2769        let row0 = cr.row_view(0).unwrap();
2770        assert_eq!(row0.get("id"), Some(SochValue::Int(1)));
2771        assert_eq!(row0.get("name"), Some(SochValue::Text("Alice".to_string())));
2772        assert_eq!(row0.get("nonexistent"), None);
2773
2774        let row2 = cr.row_view(2).unwrap();
2775        assert_eq!(row2.get("id"), Some(SochValue::Int(3)));
2776        assert_eq!(row2.get("name"), Some(SochValue::Null));
2777
2778        // Out of bounds
2779        assert!(cr.row_view(3).is_none());
2780
2781        // values() — positional
2782        let vals = row0.values();
2783        assert_eq!(vals.len(), 2);
2784        assert_eq!(vals[0], SochValue::Int(1));
2785
2786        // to_map() — backward compat
2787        let map = row0.to_map();
2788        assert_eq!(map.get("id"), Some(&SochValue::Int(1)));
2789    }
2790
2791    #[test]
2792    fn test_columnar_into_query_result() {
2793        use sochdb_core::columnar::TypedColumn;
2794
2795        let mut score_col = TypedColumn::new_float64();
2796        score_col.push_f64(Some(9.5));
2797        score_col.push_f64(Some(8.2));
2798
2799        let cr = ColumnarQueryResult {
2800            columns: vec!["score".to_string()],
2801            data: vec![score_col],
2802            row_count: 2,
2803            bytes_read: 100,
2804        };
2805
2806        let qr = cr.into_query_result();
2807        assert_eq!(qr.rows.len(), 2);
2808        assert_eq!(qr.rows[0].get("score"), Some(&SochValue::Float(9.5)));
2809        assert_eq!(qr.rows[1].get("score"), Some(&SochValue::Float(8.2)));
2810        assert_eq!(qr.bytes_read, 100);
2811    }
2812}