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    /// Get column statistics (min, max, null count)
635    pub fn column_stats(&self, column: &str) -> Option<&sochdb_core::columnar::ColumnStats> {
636        self.column(column).map(|c| c.stats())
637    }
638
639    /// Convert to TOON format (token-efficient)
640    pub fn to_toon(&self) -> String {
641        if self.row_count == 0 {
642            return "[]".to_string();
643        }
644
645        let n = self.row_count;
646        let cols = self.columns.join(",");
647
648        // Build rows from columns
649        let mut rows_str = Vec::with_capacity(n);
650        for i in 0..n {
651            let row: Vec<String> = self
652                .data
653                .iter()
654                .map(|col| format_columnar_value(col, i))
655                .collect();
656            rows_str.push(row.join(","));
657        }
658
659        format!("result[{}]{{{}}}:{}", n, cols, rows_str.join(";"))
660    }
661}
662
663/// Format a single value from a TypedColumn at index
664fn format_columnar_value(col: &CoreTypedColumn, idx: usize) -> String {
665    match col {
666        CoreTypedColumn::Int64 {
667            values, validity, ..
668        } => {
669            if validity.is_valid(idx) && idx < values.len() {
670                values[idx].to_string()
671            } else {
672                "∅".to_string()
673            }
674        }
675        CoreTypedColumn::UInt64 {
676            values, validity, ..
677        } => {
678            if validity.is_valid(idx) && idx < values.len() {
679                values[idx].to_string()
680            } else {
681                "∅".to_string()
682            }
683        }
684        CoreTypedColumn::Float64 {
685            values, validity, ..
686        } => {
687            if validity.is_valid(idx) && idx < values.len() {
688                format!("{:.6}", values[idx])
689            } else {
690                "∅".to_string()
691            }
692        }
693        CoreTypedColumn::Text {
694            offsets,
695            data,
696            validity,
697            ..
698        } => {
699            if validity.is_valid(idx) && idx + 1 < offsets.len() {
700                let start = offsets[idx] as usize;
701                let end = offsets[idx + 1] as usize;
702                std::str::from_utf8(&data[start..end])
703                    .map(|s| {
704                        if s.contains(',') || s.contains(';') {
705                            format!("\"{}\"", s.replace('"', "\\\""))
706                        } else {
707                            s.to_string()
708                        }
709                    })
710                    .unwrap_or_else(|_| "∅".to_string())
711            } else {
712                "∅".to_string()
713            }
714        }
715        CoreTypedColumn::Binary {
716            offsets,
717            data,
718            validity,
719            ..
720        } => {
721            if validity.is_valid(idx) && idx + 1 < offsets.len() {
722                let start = offsets[idx] as usize;
723                let end = offsets[idx + 1] as usize;
724                format!("b64:{}", base64_encode(&data[start..end]))
725            } else {
726                "∅".to_string()
727            }
728        }
729        CoreTypedColumn::Bool {
730            values,
731            validity,
732            len,
733            ..
734        } => {
735            if validity.is_valid(idx) && idx < *len {
736                let word = idx / 64;
737                let bit = idx % 64;
738                if (values[word] >> bit) & 1 == 1 {
739                    "T"
740                } else {
741                    "F"
742                }
743                .to_string()
744            } else {
745                "∅".to_string()
746            }
747        }
748    }
749}
750
751/// Vector search result
752#[derive(Debug, Clone)]
753pub struct VectorSearchResult {
754    pub id: u64,
755    pub distance: f32,
756    pub metadata: Option<HashMap<String, SochValue>>,
757}
758
759/// The SochDB Database Kernel
760///
761/// This is the shared core used by both embedded (`SochConnection`) and
762/// server (`sochdb-server`) modes. It owns all storage, catalog, and
763/// indexing components.
764///
765/// # Thread Safety
766///
767/// The Database is fully thread-safe via internal synchronization:
768/// - Multiple readers can operate concurrently (MVCC snapshots)
769/// - Writers coordinate through WAL and group commit
770/// - All state is behind Arc/RwLock for shared access
771///
772/// # Concurrency Modes
773///
774/// ## Standard Mode (Single Process)
775/// - Uses exclusive file lock (`flock(LOCK_EX)`)
776/// - Best for: Scripts, notebooks, CLI tools
777/// - Open with: `Database::open(path)`
778///
779/// ## Concurrent Mode (Multi-Process/Web Apps)
780/// - Uses lock-free MVCC for reads, single-writer coordination for writes
781/// - Best for: Web servers, Flask/FastAPI apps, hot reloading
782/// - Open with: `Database::open_concurrent(path)`
783///
784/// # Example
785///
786/// ```ignore
787/// // Standard mode (single process)
788/// let db = Database::open("./my_data")?;
789///
790/// // Concurrent mode (multi-reader, single-writer)
791/// let db = Database::open_concurrent("./my_data")?;
792///
793/// // Begin a transaction
794/// let txn = db.begin_transaction()?;
795///
796/// // Write data
797/// db.put(txn, b"user:1:name", b"Alice")?;
798///
799/// // Commit
800/// db.commit(txn)?;
801/// ```
802#[allow(dead_code)]
803pub struct Database {
804    /// Path to database directory
805    path: PathBuf,
806    /// Durable storage layer (WAL + MVCC + memtable)
807    storage: Arc<DurableStorage>,
808    /// Concurrent MVCC manager (for concurrent mode)
809    concurrent_mvcc: Option<Arc<crate::mvcc_concurrent::ConcurrentMvcc>>,
810    /// Schema catalog
811    catalog: Arc<RwLock<Catalog>>,
812    /// Registered table schemas (name -> schema) - lock-free for reads
813    tables: DashMap<String, TableSchema>,
814    /// Cached packed schemas for fast insert (name -> packed schema)
815    packed_schemas: DashMap<String, PackedTableSchema>,
816    /// Per-table index policy registry
817    index_registry: Arc<TableIndexRegistry>,
818    /// Configuration
819    config: DatabaseConfig,
820    /// Statistics
821    stats: DatabaseStats,
822    /// Shutdown flag
823    shutdown: AtomicU64,
824    /// Whether this database is in concurrent mode
825    is_concurrent: bool,
826}
827
828/// Database statistics
829struct DatabaseStats {
830    transactions_started: AtomicU64,
831    transactions_committed: AtomicU64,
832    transactions_aborted: AtomicU64,
833    queries_executed: AtomicU64,
834    bytes_written: AtomicU64,
835    bytes_read: AtomicU64,
836}
837
838impl DatabaseStats {
839    fn new() -> Self {
840        Self {
841            transactions_started: AtomicU64::new(0),
842            transactions_committed: AtomicU64::new(0),
843            transactions_aborted: AtomicU64::new(0),
844            queries_executed: AtomicU64::new(0),
845            bytes_written: AtomicU64::new(0),
846            bytes_read: AtomicU64::new(0),
847        }
848    }
849}
850
851/// Public statistics snapshot
852#[derive(Debug, Clone)]
853pub struct Stats {
854    pub transactions_started: u64,
855    pub transactions_committed: u64,
856    pub transactions_aborted: u64,
857    pub queries_executed: u64,
858    pub bytes_written: u64,
859    pub bytes_read: u64,
860}
861
862impl Database {
863    /// Open or create a database at the given path.
864    ///
865    /// This is the primary entry point, similar to `sqlite3_open()`.
866    /// If the database exists, it will be opened and WAL recovery performed.
867    /// If it doesn't exist, a new database will be created.
868    ///
869    /// # Arguments
870    ///
871    /// * `path` - Directory path for the database files
872    ///
873    /// # Returns
874    ///
875    /// An `Arc<Database>` that can be shared across threads and connections.
876    pub fn open<P: AsRef<Path>>(path: P) -> Result<Arc<Self>> {
877        Self::open_with_config(path, DatabaseConfig::default())
878    }
879
880    /// Open without locking (for testing crash recovery scenarios)
881    ///
882    /// # Safety
883    /// This should ONLY be used in tests that simulate crashes by forgetting
884    /// the storage instance. In production, always use `open()`.
885    #[cfg(test)]
886    pub fn open_without_lock<P: AsRef<Path>>(path: P) -> Result<Arc<Self>> {
887        let path = path.as_ref().to_path_buf();
888        let config = DatabaseConfig::default();
889
890        let storage = Arc::new(DurableStorage::open_without_lock(&path)?);
891
892        let index_registry = Arc::new(TableIndexRegistry::with_default_policy(
893            config.default_index_policy,
894        ));
895
896        let db = Arc::new(Self {
897            path: path.clone(),
898            storage,
899            concurrent_mvcc: None,
900            catalog: Arc::new(RwLock::new(Catalog::new("sochdb"))),
901            tables: DashMap::new(),
902            packed_schemas: DashMap::new(),
903            index_registry,
904            config,
905            stats: DatabaseStats::new(),
906            shutdown: AtomicU64::new(0),
907            is_concurrent: false,
908        });
909
910        db.recover()?;
911        Ok(db)
912    }
913
914    /// Open with custom configuration
915    pub fn open_with_config<P: AsRef<Path>>(path: P, config: DatabaseConfig) -> Result<Arc<Self>> {
916        let path = path.as_ref().to_path_buf();
917
918        // Use IndexPolicy-based storage configuration for automatic memtable selection
919        // This derives ordered index and memtable type from the policy
920        let storage = Arc::new(DurableStorage::open_with_policy(
921            &path,
922            config.default_index_policy,
923            config.group_commit,
924        )?);
925
926        // Create index registry with default policy from config
927        let index_registry = Arc::new(TableIndexRegistry::with_default_policy(
928            config.default_index_policy,
929        ));
930
931        let db = Arc::new(Self {
932            path: path.clone(),
933            storage,
934            concurrent_mvcc: None,
935            catalog: Arc::new(RwLock::new(Catalog::new("sochdb"))),
936            tables: DashMap::new(),
937            packed_schemas: DashMap::new(),
938            index_registry,
939            config,
940            stats: DatabaseStats::new(),
941            shutdown: AtomicU64::new(0),
942            is_concurrent: false,
943        });
944
945        // Perform crash recovery if needed
946        db.recover()?;
947
948        Ok(db)
949    }
950
951    /// Open database in concurrent mode (multi-reader, single-writer)
952    ///
953    /// This mode allows multiple processes to access the database simultaneously:
954    /// - **Readers**: Lock-free, concurrent access via MVCC snapshots
955    /// - **Writers**: Single-writer coordination through atomic locks
956    ///
957    /// # Use Cases
958    ///
959    /// - Web applications (Flask, FastAPI, Django)
960    /// - Hot reloading development servers
961    /// - Multi-process worker pools
962    /// - Any scenario with concurrent read access
963    ///
964    /// # Performance
965    ///
966    /// - Read latency: ~100ns (lock-free atomic operations)
967    /// - Write latency: ~60μs amortized (with group commit)
968    /// - Concurrent readers: Up to 1024 (configurable)
969    ///
970    /// # Example
971    ///
972    /// ```ignore
973    /// // Multiple processes can open the same database
974    /// let db = Database::open_concurrent("./my_data")?;
975    ///
976    /// // Reads are lock-free
977    /// let value = db.get(b"key")?;
978    ///
979    /// // Writes coordinate automatically
980    /// let txn = db.begin_transaction()?;
981    /// db.put(txn, b"key", b"value")?;
982    /// db.commit(txn)?;
983    /// ```
984    pub fn open_concurrent<P: AsRef<Path>>(path: P) -> Result<Arc<Self>> {
985        Self::open_concurrent_with_config(path, DatabaseConfig::default())
986    }
987
988    /// Open database in concurrent mode with custom configuration
989    pub fn open_concurrent_with_config<P: AsRef<Path>>(
990        path: P,
991        config: DatabaseConfig,
992    ) -> Result<Arc<Self>> {
993        use crate::mvcc_concurrent::ConcurrentMvcc;
994
995        let path = path.as_ref().to_path_buf();
996        std::fs::create_dir_all(&path)?;
997
998        // Open concurrent MVCC manager (this uses shared memory, not exclusive lock)
999        let concurrent_mvcc = Arc::new(ConcurrentMvcc::open(&path)?);
1000
1001        // Open storage WITHOUT exclusive lock (concurrent MVCC handles coordination)
1002        // We use a special internal method that skips the file lock
1003        let storage = Arc::new(DurableStorage::open_for_concurrent(&path, config.default_index_policy)?);
1004
1005        // Create index registry with default policy from config
1006        let index_registry = Arc::new(TableIndexRegistry::with_default_policy(
1007            config.default_index_policy,
1008        ));
1009
1010        let db = Arc::new(Self {
1011            path: path.clone(),
1012            storage,
1013            concurrent_mvcc: Some(concurrent_mvcc),
1014            catalog: Arc::new(RwLock::new(Catalog::new("sochdb"))),
1015            tables: DashMap::new(),
1016            packed_schemas: DashMap::new(),
1017            index_registry,
1018            config,
1019            stats: DatabaseStats::new(),
1020            shutdown: AtomicU64::new(0),
1021            is_concurrent: true,
1022        });
1023
1024        // Perform crash recovery if needed
1025        db.recover()?;
1026
1027        // Clean up any stale readers from crashed processes
1028        if let Some(ref mvcc) = db.concurrent_mvcc {
1029            mvcc.cleanup_stale_readers();
1030        }
1031
1032        Ok(db)
1033    }
1034
1035    /// Check if database is in concurrent mode
1036    #[inline]
1037    pub fn is_concurrent(&self) -> bool {
1038        self.is_concurrent
1039    }
1040
1041    /// Perform crash recovery
1042    fn recover(&self) -> Result<RecoveryStats> {
1043        self.storage.recover()
1044    }
1045
1046    /// Get database path
1047    pub fn path(&self) -> &Path {
1048        &self.path
1049    }
1050
1051    // =========================================================================
1052    // Transaction API
1053    // =========================================================================
1054
1055    /// Begin a new transaction
1056    pub fn begin_transaction(&self) -> Result<TxnHandle> {
1057        self.stats
1058            .transactions_started
1059            .fetch_add(1, Ordering::Relaxed);
1060        let txn_id = self.storage.begin_transaction()?;
1061
1062        // Get snapshot timestamp from MVCC
1063        // For now, use txn_id as a proxy (the real snapshot_ts is managed internally)
1064        Ok(TxnHandle {
1065            txn_id,
1066            snapshot_ts: txn_id,
1067        })
1068    }
1069
1070    /// Begin a read-only transaction (optimized: no SSI tracking)
1071    ///
1072    /// Read-only transactions skip SSI read tracking, reducing overhead
1073    /// from ~82ns to ~32ns per read (2.6x faster).
1074    ///
1075    /// Use this for:
1076    /// - SELECT queries that don't modify data
1077    /// - Analytics and reporting queries
1078    /// - Snapshot reads for backup
1079    pub fn begin_read_only(&self) -> Result<TxnHandle> {
1080        self.stats
1081            .transactions_started
1082            .fetch_add(1, Ordering::Relaxed);
1083        let txn_id = self.storage.begin_with_mode(TransactionMode::ReadOnly)?;
1084        Ok(TxnHandle {
1085            txn_id,
1086            snapshot_ts: txn_id,
1087        })
1088    }
1089
1090    /// Begin a write-only transaction (optimized: no read tracking)
1091    ///
1092    /// Write-only transactions skip read tracking, improving insert
1093    /// throughput for bulk loading scenarios.
1094    ///
1095    /// Use this for:
1096    /// - Bulk data imports
1097    /// - Append-only logging tables
1098    /// - ETL pipelines
1099    pub fn begin_write_only(&self) -> Result<TxnHandle> {
1100        self.stats
1101            .transactions_started
1102            .fetch_add(1, Ordering::Relaxed);
1103        let txn_id = self.storage.begin_with_mode(TransactionMode::WriteOnly)?;
1104        Ok(TxnHandle {
1105            txn_id,
1106            snapshot_ts: txn_id,
1107        })
1108    }
1109
1110    /// Commit a transaction
1111    pub fn commit(&self, txn: TxnHandle) -> Result<u64> {
1112        self.stats
1113            .transactions_committed
1114            .fetch_add(1, Ordering::Relaxed);
1115        self.storage.commit(txn.txn_id)
1116    }
1117
1118    /// Abort a transaction
1119    pub fn abort(&self, txn: TxnHandle) -> Result<()> {
1120        self.stats
1121            .transactions_aborted
1122            .fetch_add(1, Ordering::Relaxed);
1123        self.storage.abort(txn.txn_id)
1124    }
1125
1126    // =========================================================================
1127    // Per-Table Index Policy API
1128    // =========================================================================
1129
1130    /// Configure index policy for a table
1131    ///
1132    /// This allows fine-grained control over write/scan trade-offs per table:
1133    ///
1134    /// | Policy         | Insert Cost | Scan Cost      | Use Case              |
1135    /// |----------------|-------------|----------------|------------------------|
1136    /// | WriteOptimized | O(1)        | O(N)           | High-write, rare scan  |
1137    /// | Balanced       | O(1) amort  | O(output+logK) | Mixed OLTP            |
1138    /// | ScanOptimized  | O(log N)    | O(logN + K)    | Analytics, range query |
1139    /// | AppendOnly     | O(1)        | O(N)           | Time-series logs       |
1140    ///
1141    /// # Example
1142    ///
1143    /// ```ignore
1144    /// // Fast inserts for logs table (no ordered index overhead)
1145    /// db.set_table_index_policy("logs", IndexPolicy::WriteOptimized);
1146    ///
1147    /// // Efficient range scans for analytics table
1148    /// db.set_table_index_policy("analytics", IndexPolicy::ScanOptimized);
1149    ///
1150    /// // Balanced for OLTP tables
1151    /// db.set_table_index_policy("users", IndexPolicy::Balanced);
1152    /// ```
1153    pub fn set_table_index_policy(&self, table: &str, policy: IndexPolicy) {
1154        self.index_registry.configure_table(
1155            TableIndexConfig::new(table, policy)
1156        );
1157    }
1158
1159    /// Get the index policy for a table
1160    pub fn get_table_index_policy(&self, table: &str) -> IndexPolicy {
1161        self.index_registry.get_policy(table)
1162    }
1163
1164    /// Get the index registry for advanced configuration
1165    pub fn index_registry(&self) -> &Arc<TableIndexRegistry> {
1166        &self.index_registry
1167    }
1168
1169    // =========================================================================
1170    // Key-Value API (Low-level)
1171    // =========================================================================
1172
1173    /// Put a key-value pair
1174    pub fn put(&self, txn: TxnHandle, key: &[u8], value: &[u8]) -> Result<()> {
1175        self.stats
1176            .bytes_written
1177            .fetch_add((key.len() + value.len()) as u64, Ordering::Relaxed);
1178        // Use write_refs to avoid unnecessary allocations
1179        self.storage.write_refs(txn.txn_id, key, value)
1180    }
1181
1182    /// Batch put multiple key-value pairs with reduced overhead
1183    ///
1184    /// This amortizes per-operation costs over the entire batch:
1185    /// - Single DashMap lookup
1186    /// - Batch MVCC tracking
1187    /// - Batch memtable writes
1188    ///
1189    /// For 100+ entries, this is 2-3x faster than individual puts.
1190    ///
1191    /// # Example
1192    ///
1193    /// ```ignore
1194    /// let writes: Vec<(&[u8], &[u8])> = vec![
1195    ///     (b"key1", b"value1"),
1196    ///     (b"key2", b"value2"),
1197    ///     (b"key3", b"value3"),
1198    /// ];
1199    /// db.put_batch(txn, &writes)?;
1200    /// ```
1201    pub fn put_batch(&self, txn: TxnHandle, writes: &[(&[u8], &[u8])]) -> Result<()> {
1202        let bytes: u64 = writes
1203            .iter()
1204            .map(|(k, v)| (k.len() + v.len()) as u64)
1205            .sum();
1206        self.stats.bytes_written.fetch_add(bytes, Ordering::Relaxed);
1207        self.storage.write_batch_refs(txn.txn_id, writes)
1208    }
1209
1210    /// Get a value by key
1211    pub fn get(&self, txn: TxnHandle, key: &[u8]) -> Result<Option<Vec<u8>>> {
1212        let result = self.storage.read(txn.txn_id, key)?;
1213        if let Some(ref data) = result {
1214            self.stats
1215                .bytes_read
1216                .fetch_add(data.len() as u64, Ordering::Relaxed);
1217        }
1218        Ok(result)
1219    }
1220
1221    /// Delete a key
1222    pub fn delete(&self, txn: TxnHandle, key: &[u8]) -> Result<()> {
1223        self.storage.delete(txn.txn_id, key.to_vec())
1224    }
1225
1226    /// Minimum prefix length for scan operations.
1227    /// Prevents expensive full-table scans by requiring a meaningful prefix.
1228    pub const MIN_SCAN_PREFIX_LEN: usize = 2;
1229
1230    /// Scan keys with a prefix (enforces minimum prefix length for safety).
1231    ///
1232    /// # Prefix Safety
1233    /// 
1234    /// To prevent accidental full-table scans, this method requires a minimum
1235    /// prefix length of 2 bytes. Use `scan_unchecked` for internal operations
1236    /// that need empty/short prefixes.
1237    ///
1238    /// # Errors
1239    ///
1240    /// Returns `SochDBError::InvalidInput` if prefix is too short.
1241    pub fn scan(&self, txn: TxnHandle, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1242        if prefix.len() < Self::MIN_SCAN_PREFIX_LEN {
1243            return Err(SochDBError::InvalidArgument(format!(
1244                "Prefix too short: {} bytes (minimum {} required). \
1245                 Use scan_unchecked() for unrestricted scans.",
1246                prefix.len(),
1247                Self::MIN_SCAN_PREFIX_LEN
1248            )));
1249        }
1250        self.scan_unchecked(txn, prefix)
1251    }
1252
1253    /// Scan keys with a prefix without length validation.
1254    ///
1255    /// # Warning
1256    ///
1257    /// This method allows empty/short prefixes which can cause expensive
1258    /// full-table scans. Use `scan()` unless you specifically need unrestricted
1259    /// prefix access for internal operations.
1260    pub fn scan_unchecked(&self, txn: TxnHandle, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1261        let results = self.storage.scan(txn.txn_id, prefix)?;
1262        let bytes: u64 = results
1263            .iter()
1264            .map(|(k, v)| (k.len() + v.len()) as u64)
1265            .sum();
1266        self.stats.bytes_read.fetch_add(bytes, Ordering::Relaxed);
1267        Ok(results)
1268    }
1269
1270    /// Scan keys in range
1271    pub fn scan_range(
1272        &self,
1273        txn: TxnHandle,
1274        start: &[u8],
1275        end: &[u8],
1276    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1277        let results = self.storage.scan_range(txn.txn_id, start, end)?;
1278        let bytes: u64 = results
1279            .iter()
1280            .map(|(k, v)| (k.len() + v.len()) as u64)
1281            .sum();
1282        self.stats.bytes_read.fetch_add(bytes, Ordering::Relaxed);
1283        Ok(results)
1284    }
1285
1286    /// Streaming scan for very large result sets
1287    /// 
1288    /// Returns an iterator that yields (key, value) pairs without
1289    /// materializing the entire result set. Use this for large scans
1290    /// where memory efficiency is important.
1291    /// 
1292    /// ## Performance
1293    /// 
1294    /// - Memory: O(1) per iteration vs O(N) for scan_range
1295    /// - Latency: First result available immediately vs waiting for all results
1296    /// - Throughput: Slightly lower due to per-item overhead
1297    /// 
1298    /// ## Usage
1299    /// 
1300    /// ```ignore
1301    /// for result in db.scan_range_iter(txn, b"start", b"end") {
1302    ///     let (key, value) = result?;
1303    ///     // Process immediately - no need to wait for all results
1304    /// }
1305    /// ```
1306    pub fn scan_range_iter<'a>(
1307        &'a self,
1308        txn: TxnHandle,
1309        start: &'a [u8],
1310        end: &'a [u8],
1311    ) -> impl Iterator<Item = Result<(Vec<u8>, Vec<u8>)>> + 'a {
1312        let stats = &self.stats;
1313        self.storage
1314            .scan_range_iter(txn.txn_id, start, end)
1315            .map(move |item| {
1316                stats.bytes_read.fetch_add(
1317                    (item.0.len() + item.1.len()) as u64,
1318                    Ordering::Relaxed,
1319                );
1320                Ok(item)
1321            })
1322    }
1323
1324    /// Flush memtable to WAL/Disk
1325    pub fn flush(&self) -> Result<()> {
1326        self.storage.fsync()
1327    }
1328
1329    // =========================================================================
1330    // Path-Native API (SochDB's differentiator)
1331    // =========================================================================
1332
1333    /// Get storage statistics
1334    pub fn storage_stats(&self) -> crate::durable_storage::StorageStats {
1335        self.storage.stats()
1336    }
1337
1338    /// Put a value at a path
1339    ///
1340    /// Path format: "collection/doc_id/field" or "table.row_id.column"
1341    /// Resolution is O(|path|), not O(log N) like B-tree.
1342    pub fn put_path(&self, txn: TxnHandle, path: &str, value: &[u8]) -> Result<()> {
1343        self.put(txn, path.as_bytes(), value)
1344    }
1345
1346    /// Get a value at a path
1347    pub fn get_path(&self, txn: TxnHandle, path: &str) -> Result<Option<Vec<u8>>> {
1348        self.get(txn, path.as_bytes())
1349    }
1350
1351    /// Delete at a path
1352    pub fn delete_path(&self, txn: TxnHandle, path: &str) -> Result<()> {
1353        self.delete(txn, path.as_bytes())
1354    }
1355
1356    /// Scan a path prefix
1357    ///
1358    /// Returns all key-value pairs where key starts with prefix.
1359    /// Useful for: "users/123/" -> all fields of user 123
1360    pub fn scan_path(&self, txn: TxnHandle, prefix: &str) -> Result<Vec<(String, Vec<u8>)>> {
1361        self.stats.queries_executed.fetch_add(1, Ordering::Relaxed);
1362
1363        let results = self.scan(txn, prefix.as_bytes())?;
1364
1365        Ok(results
1366            .into_iter()
1367            .filter_map(|(k, v)| String::from_utf8(k).ok().map(|path| (path, v)))
1368            .collect())
1369    }
1370
1371    // =========================================================================
1372    // Query API
1373    // =========================================================================
1374
1375    /// Execute a path query and return results
1376    ///
1377    /// This is the main query interface for LLM context retrieval.
1378    /// Supports:
1379    /// - Path prefix matching
1380    /// - Column projection (for I/O reduction)
1381    /// - Limit/offset
1382    pub fn query(&self, txn: TxnHandle, path_prefix: &str) -> QueryBuilder<'_> {
1383        QueryBuilder::new(self, txn, path_prefix.to_string())
1384    }
1385
1386    // =========================================================================
1387    // Table API (Higher-level abstraction)
1388    // =========================================================================
1389
1390    /// Register a table schema
1391    pub fn register_table(&self, schema: TableSchema) -> Result<()> {
1392        if self.tables.contains_key(&schema.name) {
1393            return Err(SochDBError::InvalidArgument(format!(
1394                "Table '{}' already exists",
1395                schema.name
1396            )));
1397        }
1398        // Cache the packed schema for fast inserts
1399        let packed_schema = Self::to_packed_schema(&schema);
1400        self.packed_schemas
1401            .insert(schema.name.clone(), packed_schema);
1402        self.tables.insert(schema.name.clone(), schema);
1403        Ok(())
1404    }
1405
1406    /// Get table schema
1407    pub fn get_table_schema(&self, name: &str) -> Option<TableSchema> {
1408        self.tables.get(name).map(|s| s.clone())
1409    }
1410
1411    /// List all tables
1412    pub fn list_tables(&self) -> Vec<String> {
1413        self.tables.iter().map(|e| e.key().clone()).collect()
1414    }
1415    /// Convert TableSchema to PackedTableSchema for efficient storage
1416    fn to_packed_schema(schema: &TableSchema) -> PackedTableSchema {
1417        let columns = schema
1418            .columns
1419            .iter()
1420            .map(|col| PackedColumnDef {
1421                name: col.name.clone(),
1422                col_type: match col.col_type {
1423                    ColumnType::Int64 => PackedColumnType::Int64,
1424                    ColumnType::UInt64 => PackedColumnType::UInt64,
1425                    ColumnType::Float64 => PackedColumnType::Float64,
1426                    ColumnType::Text => PackedColumnType::Text,
1427                    ColumnType::Binary => PackedColumnType::Binary,
1428                    ColumnType::Bool => PackedColumnType::Bool,
1429                },
1430                nullable: col.nullable,
1431            })
1432            .collect();
1433
1434        PackedTableSchema::new(&schema.name, columns)
1435    }
1436
1437    /// Insert a row into a table
1438    ///
1439    /// Uses packed row format: stores entire row as single key-value pair.
1440    /// This reduces write amplification from 4× to 1× for a 4-column table.
1441    ///
1442    /// # Performance
1443    /// - Before: 4 columns × (WAL entry + MVCC version) = 4 writes
1444    /// - After: 1 packed row = 1 write
1445    /// - Improvement: ~4× fewer WAL entries, ~48% less I/O overhead
1446    pub fn insert_row(
1447        &self,
1448        txn: TxnHandle,
1449        table: &str,
1450        row_id: u64,
1451        values: &HashMap<String, SochValue>,
1452    ) -> Result<()> {
1453        // Use cached packed schema - single DashMap lookup, no clone
1454        let packed_schema = self
1455            .packed_schemas
1456            .get(table)
1457            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1458
1459        // Pack the row using cached schema
1460        let packed_row = PackedRow::pack(&packed_schema, values);
1461
1462        // Build key using KeyBuffer - optimized stack allocation (~12-15ns vs ~30-35ns for write!())
1463        let key = KeyBuffer::format_row_key(table, row_id);
1464
1465        self.put(txn, key.as_bytes(), packed_row.as_bytes())?;
1466
1467        Ok(())
1468    }
1469
1470    /// Read a row from a table
1471    ///
1472    /// Reads packed row and extracts requested columns in O(k) time.
1473    /// Column projection happens in memory, not storage - all columns are fetched.
1474    pub fn read_row(
1475        &self,
1476        txn: TxnHandle,
1477        table: &str,
1478        row_id: u64,
1479        columns: Option<&[&str]>,
1480    ) -> Result<Option<HashMap<String, SochValue>>> {
1481        let schema = self
1482            .tables
1483            .get(table)
1484            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1485
1486        // Read the packed row with a single key lookup using KeyBuffer
1487        let key = KeyBuffer::format_row_key(table, row_id);
1488        let bytes = match self.get(txn, key.as_bytes())? {
1489            Some(b) => b,
1490            None => return Ok(None),
1491        };
1492
1493        // Use cached packed schema
1494        let packed_schema = self
1495            .packed_schemas
1496            .get(table)
1497            .ok_or_else(|| SochDBError::Internal("Packed schema not found".into()))?;
1498        let packed_row = PackedRow::from_bytes(bytes, packed_schema.num_columns())?;
1499
1500        // Determine which columns to return
1501        let cols_to_read: Vec<&str> = match columns {
1502            Some(c) => c.to_vec(),
1503            None => schema.columns.iter().map(|c| c.name.as_str()).collect(),
1504        };
1505
1506        let mut row = HashMap::new();
1507        for col_name in cols_to_read {
1508            if let Some(idx) = packed_schema.column_index(col_name)
1509                && let Some(col_def) = packed_schema.column(idx)
1510                && let Some(value) = packed_row.get_column(idx, col_def.col_type)
1511            {
1512                row.insert(col_name.to_string(), value);
1513            }
1514        }
1515
1516        Ok(Some(row))
1517    }
1518
1519    /// Insert multiple rows efficiently in a batch
1520    ///
1521    /// This method accumulates all rows and writes them with fewer WAL syncs.
1522    /// Ideal for bulk loading scenarios.
1523    ///
1524    /// # Performance
1525    /// - Uses group commit to batch fsync operations
1526    /// - Expected throughput: 500K-1M rows/sec depending on row size
1527    pub fn insert_rows_batch(
1528        &self,
1529        txn: TxnHandle,
1530        table: &str,
1531        rows: &[(u64, HashMap<String, SochValue>)],
1532    ) -> Result<usize> {
1533        // Use cached packed schema
1534        let packed_schema = self
1535            .packed_schemas
1536            .get(table)
1537            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1538
1539        let mut count = 0;
1540
1541        for (row_id, values) in rows {
1542            // Pack and write using KeyBuffer for efficient key construction
1543            let packed_row = PackedRow::pack(&packed_schema, values);
1544            let key = KeyBuffer::format_row_key(table, *row_id);
1545            self.put(txn, key.as_bytes(), packed_row.as_bytes())?;
1546            count += 1;
1547        }
1548
1549        Ok(count)
1550    }
1551
1552    /// Ultra-fast raw put - bypasses all validation
1553    ///
1554    /// Use when you've already validated the data and just need speed.
1555    /// This is ~10× faster than insert_row() for bulk inserts.
1556    #[inline]
1557    pub fn put_raw(&self, txn: TxnHandle, key: &[u8], value: &[u8]) -> Result<()> {
1558        self.storage.write_refs(txn.txn_id, key, value)
1559    }
1560
1561    /// Zero-allocation insert - fastest path for bulk inserts
1562    ///
1563    /// Takes values as a slice in schema column order, avoiding HashMap overhead.
1564    ///
1565    /// # Arguments
1566    /// * `txn` - Transaction handle
1567    /// * `table` - Table name
1568    /// * `row_id` - Row identifier
1569    /// * `values` - Values in schema column order (None = NULL)
1570    ///
1571    /// # Performance
1572    /// - Eliminates ~6 allocations per row vs insert_row()
1573    /// - Expected: 1.2M-1.5M inserts/sec
1574    ///
1575    /// # Example
1576    /// ```ignore
1577    /// let values: &[Option<&SochValue>] = &[
1578    ///     Some(&SochValue::Int(1)),
1579    ///     Some(&SochValue::Text("Alice".into())),
1580    ///     None, // NULL
1581    /// ];
1582    /// db.insert_row_slice(txn, "users", 1, values)?;
1583    /// ```
1584    #[inline]
1585    pub fn insert_row_slice(
1586        &self,
1587        txn: TxnHandle,
1588        table: &str,
1589        row_id: u64,
1590        values: &[Option<&SochValue>],
1591    ) -> Result<()> {
1592        // Use cached packed schema - single DashMap lookup
1593        let packed_schema = self
1594            .packed_schemas
1595            .get(table)
1596            .ok_or_else(|| SochDBError::InvalidArgument(format!("Table '{}' not found", table)))?;
1597
1598        // Validate column count matches
1599        if values.len() != packed_schema.num_columns() {
1600            return Err(SochDBError::InvalidArgument(format!(
1601                "Expected {} columns, got {}",
1602                packed_schema.num_columns(),
1603                values.len()
1604            )));
1605        }
1606
1607        // Pack using zero-allocation path
1608        let packed_row = PackedRow::pack_slice(&packed_schema, values);
1609
1610        // Build key using KeyBuffer - optimized stack allocation (~12-15ns vs ~30-35ns for write!())
1611        let key = KeyBuffer::format_row_key(table, row_id);
1612
1613        self.put(txn, key.as_bytes(), packed_row.as_bytes())?;
1614        Ok(())
1615    }
1616
1617    // =========================================================================
1618    // Maintenance
1619    // =========================================================================
1620
1621    /// Force fsync to disk
1622    pub fn fsync(&self) -> Result<()> {
1623        self.storage.fsync()
1624    }
1625
1626    /// Create a checkpoint
1627    pub fn checkpoint(&self) -> Result<u64> {
1628        self.storage.checkpoint()
1629    }
1630
1631    /// Run garbage collection
1632    pub fn gc(&self) -> usize {
1633        self.storage.gc()
1634    }
1635
1636    /// Get database statistics
1637    pub fn stats(&self) -> Stats {
1638        Stats {
1639            transactions_started: self.stats.transactions_started.load(Ordering::Relaxed),
1640            transactions_committed: self.stats.transactions_committed.load(Ordering::Relaxed),
1641            transactions_aborted: self.stats.transactions_aborted.load(Ordering::Relaxed),
1642            queries_executed: self.stats.queries_executed.load(Ordering::Relaxed),
1643            bytes_written: self.stats.bytes_written.load(Ordering::Relaxed),
1644            bytes_read: self.stats.bytes_read.load(Ordering::Relaxed),
1645        }
1646    }
1647
1648    /// Shutdown the database gracefully
1649    pub fn shutdown(&self) -> Result<()> {
1650        if self.shutdown.swap(1, Ordering::SeqCst) == 1 {
1651            return Ok(()); // Already shutting down
1652        }
1653
1654        // Flush any pending writes
1655        self.fsync()?;
1656
1657        // Create clean shutdown marker
1658        let marker = self.path.join(".clean_shutdown");
1659        std::fs::write(&marker, b"ok")?;
1660
1661        Ok(())
1662    }
1663}
1664
1665impl Drop for Database {
1666    fn drop(&mut self) {
1667        // Try graceful shutdown if not already done
1668        if self.shutdown.load(Ordering::SeqCst) == 0 {
1669            let _ = self.fsync();
1670            let marker = self.path.join(".clean_shutdown");
1671            let _ = std::fs::write(&marker, b"ok");
1672        }
1673    }
1674}
1675
1676/// Query builder for fluent query construction
1677pub struct QueryBuilder<'a> {
1678    db: &'a Database,
1679    txn: TxnHandle,
1680    path_prefix: String,
1681    columns: Option<Vec<String>>,
1682    limit: Option<usize>,
1683    offset: Option<usize>,
1684}
1685
1686impl<'a> QueryBuilder<'a> {
1687    fn new(db: &'a Database, txn: TxnHandle, path_prefix: String) -> Self {
1688        Self {
1689            db,
1690            txn,
1691            path_prefix,
1692            columns: None,
1693            limit: None,
1694            offset: None,
1695        }
1696    }
1697
1698    /// Select specific columns (for I/O reduction)
1699    pub fn columns(mut self, cols: &[&str]) -> Self {
1700        self.columns = Some(cols.iter().map(|s| s.to_string()).collect());
1701        self
1702    }
1703
1704    /// Limit results
1705    pub fn limit(mut self, n: usize) -> Self {
1706        self.limit = Some(n);
1707        self
1708    }
1709
1710    /// Skip results
1711    pub fn offset(mut self, n: usize) -> Self {
1712        self.offset = Some(n);
1713        self
1714    }
1715
1716    /// Execute the query
1717    ///
1718    /// Scans packed rows and unpacks them. Each key is "table/row_id" pointing to a packed row.
1719    pub fn execute(self) -> Result<QueryResult> {
1720        self.db
1721            .stats
1722            .queries_executed
1723            .fetch_add(1, Ordering::Relaxed);
1724
1725        // Get schema for the table if we're querying a table
1726        let table_name = self
1727            .path_prefix
1728            .split('/')
1729            .next()
1730            .unwrap_or(&self.path_prefix);
1731        let schema = self.db.tables.get(table_name).map(|s| s.clone());
1732
1733        // Scan the path prefix
1734        let results = self.db.scan_path(self.txn, &self.path_prefix)?;
1735
1736        let mut rows: Vec<HashMap<String, SochValue>> = Vec::new();
1737        let mut bytes_read = 0usize;
1738
1739        if let Some(ref schema) = schema {
1740            // We have a table schema - use cached packed schema
1741            let packed_schema = self
1742                .db
1743                .packed_schemas
1744                .get(table_name)
1745                .map(|ps| ps.clone())
1746                .unwrap_or_else(|| Database::to_packed_schema(schema));
1747
1748            for (path, value_bytes) in results {
1749                // Parse path: table/row_id
1750                let parts: Vec<&str> = path.split('/').collect();
1751                if parts.len() == 2 {
1752                    // This is a packed row
1753                    bytes_read += value_bytes.len();
1754
1755                    if let Ok(packed_row) =
1756                        PackedRow::from_bytes(value_bytes, packed_schema.num_columns())
1757                    {
1758                        // Unpack all columns or just requested columns
1759                        let mut row = HashMap::new();
1760
1761                        if let Some(ref cols) = self.columns {
1762                            // Only extract requested columns
1763                            for col_name in cols {
1764                                if let Some(idx) = packed_schema.column_index(col_name)
1765                                    && let Some(col_def) = packed_schema.column(idx)
1766                                    && let Some(value) =
1767                                        packed_row.get_column(idx, col_def.col_type)
1768                                {
1769                                    row.insert(col_name.clone(), value);
1770                                }
1771                            }
1772                        } else {
1773                            // Extract all columns
1774                            row = packed_row.unpack(&packed_schema);
1775                        }
1776
1777                        if !row.is_empty() {
1778                            rows.push(row);
1779                        }
1780                    }
1781                }
1782            }
1783        } else {
1784            // Fallback: no schema, try legacy column-per-key format
1785            let mut rows_map: HashMap<String, HashMap<String, SochValue>> = HashMap::new();
1786
1787            for (path, value_bytes) in results {
1788                let parts: Vec<&str> = path.split('/').collect();
1789                if parts.len() >= 3 {
1790                    let row_key = format!("{}/{}", parts[0], parts[1]);
1791                    let col_name = parts[2..].join("/");
1792
1793                    if let Some(ref cols) = self.columns
1794                        && !cols.contains(&col_name)
1795                    {
1796                        continue;
1797                    }
1798
1799                    bytes_read += value_bytes.len();
1800                    let row = rows_map.entry(row_key).or_default();
1801                    row.insert(col_name, deserialize_value(&value_bytes));
1802                }
1803            }
1804
1805            rows = rows_map.into_values().collect();
1806        }
1807
1808        // Apply offset
1809        if let Some(offset) = self.offset {
1810            rows = rows.into_iter().skip(offset).collect();
1811        }
1812
1813        // Apply limit
1814        if let Some(limit) = self.limit {
1815            rows.truncate(limit);
1816        }
1817
1818        // Collect column names
1819        let columns: Vec<String> = self.columns.unwrap_or_else(|| {
1820            rows.iter()
1821                .flat_map(|r| r.keys().cloned())
1822                .collect::<std::collections::HashSet<_>>()
1823                .into_iter()
1824                .collect()
1825        });
1826
1827        Ok(QueryResult {
1828            columns,
1829            rows_scanned: rows.len(),
1830            bytes_read,
1831            rows,
1832        })
1833    }
1834
1835    /// Execute and return TOON format (for LLM efficiency)
1836    pub fn to_toon(self) -> Result<String> {
1837        let result = self.execute()?;
1838        Ok(result.to_toon())
1839    }
1840
1841    /// Execute with lazy iteration - avoids materializing all rows
1842    ///
1843    /// Returns an iterator over rows as `Vec<SochValue>` in schema column order.
1844    /// This is more memory-efficient than `execute()` for large result sets.
1845    ///
1846    /// # Performance
1847    /// - No upfront materialization of all rows
1848    /// - ~40% less memory for large result sets
1849    /// - Ideal for streaming to network or aggregations
1850    ///
1851    /// # Example
1852    /// ```ignore
1853    /// for row_result in db.query(txn, "users").execute_iter()? {
1854    ///     let row = row_result?;
1855    ///     // row is Vec<SochValue> in column order
1856    /// }
1857    /// ```
1858    pub fn execute_iter(self) -> Result<QueryRowIterator> {
1859        self.db
1860            .stats
1861            .queries_executed
1862            .fetch_add(1, Ordering::Relaxed);
1863
1864        let table_name = self
1865            .path_prefix
1866            .split('/')
1867            .next()
1868            .unwrap_or(&self.path_prefix)
1869            .to_string();
1870
1871        // Get packed schema (clone needed for iterator ownership)
1872        let packed_schema = self.db.packed_schemas.get(&table_name).map(|ps| ps.clone());
1873
1874        // Scan the path prefix
1875        let results = self.db.scan_path(self.txn, &self.path_prefix)?;
1876
1877        Ok(QueryRowIterator {
1878            results: results.into_iter(),
1879            packed_schema,
1880            columns: self.columns,
1881            offset: self.offset.unwrap_or(0),
1882            limit: self.limit,
1883            yielded: 0,
1884            skipped: 0,
1885        })
1886    }
1887
1888    /// Execute and return columnar (SIMD-friendly) result format
1889    ///
1890    /// Instead of row-oriented `Vec<HashMap<String, SochValue>>`, returns
1891    /// column-oriented `Vec<TypedColumn>` for vectorized operations.
1892    ///
1893    /// ## Performance Benefits
1894    ///
1895    /// - SIMD: Aggregate operations (sum, avg) use vectorized instructions
1896    /// - Cache: Sequential access maximizes L1/L2 hits
1897    /// - Memory: ~30% less overhead than row-based format
1898    /// - Analytics: Ideal for ML preprocessing and statistics
1899    ///
1900    /// ## Example
1901    ///
1902    /// ```ignore
1903    /// let result = db.query(txn, "users")
1904    ///     .columns(&["id", "score"])
1905    ///     .as_columnar()?;
1906    ///
1907    /// // SIMD-optimized sum
1908    /// let total = result.sum_i64("score").unwrap_or(0);
1909    ///
1910    /// // Direct column access
1911    /// if let Some(scores) = result.column("score") {
1912    ///     for i in 0..scores.len() {
1913    ///         if let Some(v) = scores.get_i64(i) {
1914    ///             println!("Score: {}", v);
1915    ///         }
1916    ///     }
1917    /// }
1918    /// ```
1919    pub fn as_columnar(self) -> Result<ColumnarQueryResult> {
1920        self.db
1921            .stats
1922            .queries_executed
1923            .fetch_add(1, Ordering::Relaxed);
1924
1925        let table_name = self
1926            .path_prefix
1927            .split('/')
1928            .next()
1929            .unwrap_or(&self.path_prefix);
1930        let schema = self.db.tables.get(table_name).map(|s| s.clone());
1931
1932        // Get packed schema
1933        let packed_schema = match self.db.packed_schemas.get(table_name) {
1934            Some(ps) => ps.clone(),
1935            None => return Ok(ColumnarQueryResult::empty()),
1936        };
1937
1938        // Determine columns to fetch
1939        let column_names: Vec<String> = self.columns.clone().unwrap_or_else(|| {
1940            schema
1941                .as_ref()
1942                .map(|s| s.columns.iter().map(|c| c.name.clone()).collect())
1943                .unwrap_or_default()
1944        });
1945
1946        if column_names.is_empty() {
1947            return Ok(ColumnarQueryResult::empty());
1948        }
1949
1950        // Initialize TypedColumns based on schema types
1951        let mut columns: Vec<CoreTypedColumn> = column_names
1952            .iter()
1953            .map(|col_name| {
1954                packed_schema
1955                    .column_index(col_name)
1956                    .and_then(|idx| packed_schema.column(idx))
1957                    .map(|col_def| match col_def.col_type {
1958                        PackedColumnType::Int64 => CoreTypedColumn::new_int64(),
1959                        PackedColumnType::UInt64 => CoreTypedColumn::new_uint64(),
1960                        PackedColumnType::Float64 => CoreTypedColumn::new_float64(),
1961                        PackedColumnType::Text => CoreTypedColumn::new_text(),
1962                        PackedColumnType::Binary => CoreTypedColumn::new_binary(),
1963                        PackedColumnType::Bool => CoreTypedColumn::new_bool(),
1964                        PackedColumnType::Null => CoreTypedColumn::new_text(), // Null column = fallback to text
1965                    })
1966                    .unwrap_or_else(CoreTypedColumn::new_text) // fallback
1967            })
1968            .collect();
1969
1970        // Scan the path prefix
1971        let results = self.db.scan_path(self.txn, &self.path_prefix)?;
1972
1973        let mut row_count = 0;
1974        let mut bytes_read = 0;
1975        let mut skipped = 0;
1976
1977        for (path, value_bytes) in results {
1978            // Parse path: table/row_id
1979            let parts: Vec<&str> = path.split('/').collect();
1980            if parts.len() != 2 {
1981                continue;
1982            }
1983
1984            // Apply offset
1985            if let Some(offset) = self.offset
1986                && skipped < offset
1987            {
1988                skipped += 1;
1989                continue;
1990            }
1991
1992            // Apply limit
1993            if let Some(limit) = self.limit
1994                && row_count >= limit
1995            {
1996                break;
1997            }
1998
1999            bytes_read += value_bytes.len();
2000
2001            if let Ok(packed_row) = PackedRow::from_bytes(value_bytes, packed_schema.num_columns())
2002            {
2003                // Extract each column and push to corresponding TypedColumn
2004                for (col_idx, col_name) in column_names.iter().enumerate() {
2005                    if let Some(schema_idx) = packed_schema.column_index(col_name) {
2006                        if let Some(col_def) = packed_schema.column(schema_idx) {
2007                            let value = packed_row.get_column(schema_idx, col_def.col_type);
2008                            push_value_to_typed_column(&mut columns[col_idx], value);
2009                        } else {
2010                            push_null_to_typed_column(&mut columns[col_idx]);
2011                        }
2012                    } else {
2013                        push_null_to_typed_column(&mut columns[col_idx]);
2014                    }
2015                }
2016                row_count += 1;
2017            }
2018        }
2019
2020        Ok(ColumnarQueryResult {
2021            columns: column_names,
2022            data: columns,
2023            row_count,
2024            bytes_read,
2025        })
2026    }
2027}
2028
2029/// Lazy iterator over query results
2030///
2031/// Unpacks rows on-demand, avoiding upfront materialization.
2032pub struct QueryRowIterator {
2033    results: std::vec::IntoIter<(String, Vec<u8>)>,
2034    packed_schema: Option<PackedTableSchema>,
2035    columns: Option<Vec<String>>,
2036    offset: usize,
2037    limit: Option<usize>,
2038    yielded: usize,
2039    skipped: usize,
2040}
2041
2042impl Iterator for QueryRowIterator {
2043    type Item = Result<Vec<SochValue>>;
2044
2045    fn next(&mut self) -> Option<Self::Item> {
2046        // Check limit
2047        if let Some(limit) = self.limit
2048            && self.yielded >= limit
2049        {
2050            return None;
2051        }
2052
2053        loop {
2054            let (path, value_bytes) = self.results.next()?;
2055
2056            // Parse path: table/row_id
2057            let parts: Vec<&str> = path.split('/').collect();
2058            if parts.len() != 2 {
2059                continue; // Skip non-row entries
2060            }
2061
2062            // Apply offset
2063            if self.skipped < self.offset {
2064                self.skipped += 1;
2065                continue;
2066            }
2067
2068            if let Some(ref schema) = self.packed_schema {
2069                match PackedRow::from_bytes(value_bytes, schema.num_columns()) {
2070                    Ok(packed_row) => {
2071                        let row = if let Some(ref cols) = self.columns {
2072                            // Project specific columns
2073                            cols.iter()
2074                                .map(|col_name| {
2075                                    schema
2076                                        .column_index(col_name)
2077                                        .and_then(|idx| schema.column(idx))
2078                                        .and_then(|col_def| {
2079                                            packed_row.get_column(
2080                                                schema.column_index(col_name).unwrap(),
2081                                                col_def.col_type,
2082                                            )
2083                                        })
2084                                        .unwrap_or(SochValue::Null)
2085                                })
2086                                .collect()
2087                        } else {
2088                            // All columns in order
2089                            packed_row.unpack_to_vec(schema)
2090                        };
2091
2092                        self.yielded += 1;
2093                        return Some(Ok(row));
2094                    }
2095                    Err(e) => return Some(Err(e)),
2096                }
2097            } else {
2098                // No schema - return raw bytes as binary
2099                self.yielded += 1;
2100                return Some(Ok(vec![SochValue::Binary(value_bytes)]));
2101            }
2102        }
2103    }
2104}
2105
2106// Helper functions for serialization (kept for backward compatibility with legacy data)
2107
2108#[allow(dead_code)]
2109fn serialize_value(value: &SochValue) -> Vec<u8> {
2110    // Simple serialization - in production use proper format
2111    match value {
2112        SochValue::Null => vec![0],
2113        SochValue::Int(i) => {
2114            let mut buf = vec![1];
2115            buf.extend_from_slice(&i.to_le_bytes());
2116            buf
2117        }
2118        SochValue::UInt(u) => {
2119            let mut buf = vec![2];
2120            buf.extend_from_slice(&u.to_le_bytes());
2121            buf
2122        }
2123        SochValue::Float(f) => {
2124            let mut buf = vec![3];
2125            buf.extend_from_slice(&f.to_le_bytes());
2126            buf
2127        }
2128        SochValue::Text(s) => {
2129            let mut buf = vec![4];
2130            buf.extend_from_slice(s.as_bytes());
2131            buf
2132        }
2133        SochValue::Bool(b) => vec![5, if *b { 1 } else { 0 }],
2134        SochValue::Binary(b) => {
2135            let mut buf = vec![6];
2136            buf.extend_from_slice(b);
2137            buf
2138        }
2139        _ => {
2140            // Fallback: serialize as text
2141            let s = format!("{:?}", value);
2142            let mut buf = vec![4];
2143            buf.extend_from_slice(s.as_bytes());
2144            buf
2145        }
2146    }
2147}
2148
2149fn deserialize_value(bytes: &[u8]) -> SochValue {
2150    if bytes.is_empty() {
2151        return SochValue::Null;
2152    }
2153
2154    match bytes[0] {
2155        0 => SochValue::Null,
2156        1 if bytes.len() >= 9 => {
2157            let i = i64::from_le_bytes(bytes[1..9].try_into().unwrap());
2158            SochValue::Int(i)
2159        }
2160        2 if bytes.len() >= 9 => {
2161            let u = u64::from_le_bytes(bytes[1..9].try_into().unwrap());
2162            SochValue::UInt(u)
2163        }
2164        3 if bytes.len() >= 9 => {
2165            let f = f64::from_le_bytes(bytes[1..9].try_into().unwrap());
2166            SochValue::Float(f)
2167        }
2168        4 => {
2169            let s = String::from_utf8_lossy(&bytes[1..]).to_string();
2170            SochValue::Text(s)
2171        }
2172        5 if bytes.len() >= 2 => SochValue::Bool(bytes[1] != 0),
2173        6 => SochValue::Binary(bytes[1..].to_vec()),
2174        _ => {
2175            // Treat as text
2176            let s = String::from_utf8_lossy(bytes).to_string();
2177            SochValue::Text(s)
2178        }
2179    }
2180}
2181
2182// ============================================================================
2183// Helper functions for columnar query result building
2184// ============================================================================
2185
2186/// Push a SochValue into a TypedColumn
2187fn push_value_to_typed_column(col: &mut CoreTypedColumn, value: Option<SochValue>) {
2188    match value {
2189        None => push_null_to_typed_column(col),
2190        Some(v) => match (col, v) {
2191            (
2192                CoreTypedColumn::Int64 {
2193                    values,
2194                    validity,
2195                    stats,
2196                },
2197                SochValue::Int(i),
2198            ) => {
2199                values.push(i);
2200                validity.push(true);
2201                stats.update_i64(i);
2202            }
2203            (
2204                CoreTypedColumn::Int64 {
2205                    values,
2206                    validity,
2207                    stats,
2208                },
2209                SochValue::UInt(u),
2210            ) => {
2211                values.push(u as i64);
2212                validity.push(true);
2213                stats.update_i64(u as i64);
2214            }
2215            (
2216                CoreTypedColumn::UInt64 {
2217                    values,
2218                    validity,
2219                    stats,
2220                },
2221                SochValue::UInt(u),
2222            ) => {
2223                values.push(u);
2224                validity.push(true);
2225                stats.update_i64(u as i64);
2226            }
2227            (
2228                CoreTypedColumn::UInt64 {
2229                    values,
2230                    validity,
2231                    stats,
2232                },
2233                SochValue::Int(i),
2234            ) => {
2235                values.push(i as u64);
2236                validity.push(true);
2237                stats.update_i64(i);
2238            }
2239            (
2240                CoreTypedColumn::Float64 {
2241                    values,
2242                    validity,
2243                    stats,
2244                },
2245                SochValue::Float(f),
2246            ) => {
2247                values.push(f);
2248                validity.push(true);
2249                stats.update_f64(f);
2250            }
2251            (
2252                CoreTypedColumn::Float64 {
2253                    values,
2254                    validity,
2255                    stats,
2256                },
2257                SochValue::Int(i),
2258            ) => {
2259                values.push(i as f64);
2260                validity.push(true);
2261                stats.update_f64(i as f64);
2262            }
2263            (
2264                CoreTypedColumn::Text {
2265                    offsets,
2266                    data,
2267                    validity,
2268                    stats,
2269                },
2270                SochValue::Text(s),
2271            ) => {
2272                data.extend_from_slice(s.as_bytes());
2273                offsets.push(data.len() as u32);
2274                validity.push(true);
2275                stats.row_count += 1;
2276            }
2277            (
2278                CoreTypedColumn::Binary {
2279                    offsets,
2280                    data,
2281                    validity,
2282                    stats,
2283                },
2284                SochValue::Binary(b),
2285            ) => {
2286                data.extend_from_slice(&b);
2287                offsets.push(data.len() as u32);
2288                validity.push(true);
2289                stats.row_count += 1;
2290            }
2291            (
2292                CoreTypedColumn::Bool {
2293                    values,
2294                    validity,
2295                    stats,
2296                    len,
2297                },
2298                SochValue::Bool(b),
2299            ) => {
2300                let idx = *len;
2301                *len += 1;
2302                let num_words = (*len).div_ceil(64);
2303                while values.len() < num_words {
2304                    values.push(0);
2305                }
2306                if b {
2307                    let word = idx / 64;
2308                    let bit = idx % 64;
2309                    values[word] |= 1 << bit;
2310                }
2311                validity.push(true);
2312                stats.row_count += 1;
2313            }
2314            // Type mismatch - push as null
2315            (col, _) => push_null_to_typed_column(col),
2316        },
2317    }
2318}
2319
2320/// Push a null value into a TypedColumn
2321fn push_null_to_typed_column(col: &mut CoreTypedColumn) {
2322    match col {
2323        CoreTypedColumn::Int64 {
2324            values,
2325            validity,
2326            stats,
2327        } => {
2328            values.push(0);
2329            validity.push(false);
2330            stats.update_null();
2331        }
2332        CoreTypedColumn::UInt64 {
2333            values,
2334            validity,
2335            stats,
2336        } => {
2337            values.push(0);
2338            validity.push(false);
2339            stats.update_null();
2340        }
2341        CoreTypedColumn::Float64 {
2342            values,
2343            validity,
2344            stats,
2345        } => {
2346            values.push(0.0);
2347            validity.push(false);
2348            stats.update_null();
2349        }
2350        CoreTypedColumn::Text {
2351            offsets,
2352            data: _,
2353            validity,
2354            stats,
2355        } => {
2356            offsets.push(offsets.last().copied().unwrap_or(0));
2357            validity.push(false);
2358            stats.update_null();
2359        }
2360        CoreTypedColumn::Binary {
2361            offsets,
2362            data: _,
2363            validity,
2364            stats,
2365        } => {
2366            offsets.push(offsets.last().copied().unwrap_or(0));
2367            validity.push(false);
2368            stats.update_null();
2369        }
2370        CoreTypedColumn::Bool {
2371            values,
2372            validity,
2373            stats,
2374            len,
2375        } => {
2376            *len += 1;
2377            let num_words = (*len).div_ceil(64);
2378            while values.len() < num_words {
2379                values.push(0);
2380            }
2381            validity.push(false);
2382            stats.update_null();
2383        }
2384    }
2385}
2386
2387#[cfg(test)]
2388mod tests {
2389    use super::*;
2390    use tempfile::tempdir;
2391
2392    #[test]
2393    fn test_database_open_close() {
2394        let dir = tempdir().unwrap();
2395        let db = Database::open(dir.path()).unwrap();
2396
2397        // Should be able to begin a transaction
2398        let txn = db.begin_transaction().unwrap();
2399        assert!(txn.txn_id > 0);
2400
2401        db.abort(txn).unwrap();
2402        db.shutdown().unwrap();
2403    }
2404
2405    #[test]
2406    fn test_database_put_get() {
2407        let dir = tempdir().unwrap();
2408        let db = Database::open(dir.path()).unwrap();
2409
2410        let txn = db.begin_transaction().unwrap();
2411        db.put(txn, b"key1", b"value1").unwrap();
2412
2413        let val = db.get(txn, b"key1").unwrap();
2414        assert_eq!(val, Some(b"value1".to_vec()));
2415
2416        db.commit(txn).unwrap();
2417
2418        // New transaction should see committed data
2419        let txn2 = db.begin_transaction().unwrap();
2420        let val = db.get(txn2, b"key1").unwrap();
2421        assert_eq!(val, Some(b"value1".to_vec()));
2422        db.abort(txn2).unwrap();
2423    }
2424
2425    #[test]
2426    fn test_database_path_api() {
2427        let dir = tempdir().unwrap();
2428        let db = Database::open(dir.path()).unwrap();
2429
2430        let txn = db.begin_transaction().unwrap();
2431
2432        // Write using path API
2433        db.put_path(txn, "users/1/name", b"Alice").unwrap();
2434        db.put_path(txn, "users/1/email", b"alice@example.com")
2435            .unwrap();
2436        db.put_path(txn, "users/2/name", b"Bob").unwrap();
2437
2438        db.commit(txn).unwrap();
2439
2440        // Scan path prefix
2441        let txn2 = db.begin_transaction().unwrap();
2442        let results = db.scan_path(txn2, "users/1/").unwrap();
2443        assert_eq!(results.len(), 2);
2444
2445        db.abort(txn2).unwrap();
2446    }
2447
2448    #[test]
2449    fn test_database_table_api() {
2450        let dir = tempdir().unwrap();
2451        let db = Database::open(dir.path()).unwrap();
2452
2453        // Register table
2454        db.register_table(TableSchema {
2455            name: "users".to_string(),
2456            columns: vec![
2457                ColumnDef {
2458                    name: "name".to_string(),
2459                    col_type: ColumnType::Text,
2460                    nullable: false,
2461                },
2462                ColumnDef {
2463                    name: "age".to_string(),
2464                    col_type: ColumnType::Int64,
2465                    nullable: true,
2466                },
2467            ],
2468        })
2469        .unwrap();
2470
2471        // Insert row
2472        let txn = db.begin_transaction().unwrap();
2473        let mut values = HashMap::new();
2474        values.insert("name".to_string(), SochValue::Text("Alice".to_string()));
2475        values.insert("age".to_string(), SochValue::Int(30));
2476
2477        db.insert_row(txn, "users", 1, &values).unwrap();
2478        db.commit(txn).unwrap();
2479
2480        // Read row
2481        let txn2 = db.begin_transaction().unwrap();
2482        let row = db.read_row(txn2, "users", 1, None).unwrap();
2483        assert!(row.is_some());
2484
2485        let row = row.unwrap();
2486        assert_eq!(row.get("name"), Some(&SochValue::Text("Alice".to_string())));
2487
2488        db.abort(txn2).unwrap();
2489    }
2490
2491    #[test]
2492    fn test_database_query_builder() {
2493        let dir = tempdir().unwrap();
2494        let db = Database::open(dir.path()).unwrap();
2495
2496        // Insert test data
2497        let txn = db.begin_transaction().unwrap();
2498        db.put_path(txn, "docs/1/title", b"Hello").unwrap();
2499        db.put_path(txn, "docs/1/content", b"World").unwrap();
2500        db.put_path(txn, "docs/2/title", b"Foo").unwrap();
2501        db.put_path(txn, "docs/2/content", b"Bar").unwrap();
2502        db.commit(txn).unwrap();
2503
2504        // Query with limit
2505        let txn2 = db.begin_transaction().unwrap();
2506        let result = db.query(txn2, "docs/").limit(1).execute().unwrap();
2507
2508        assert_eq!(result.rows.len(), 1);
2509        db.abort(txn2).unwrap();
2510    }
2511
2512    #[test]
2513    fn test_database_crash_recovery() {
2514        let dir = tempdir().unwrap();
2515
2516        // Write and commit
2517        {
2518            // Use open_without_lock for crash simulation tests
2519            let db = Database::open_without_lock(dir.path()).unwrap();
2520            // Set sync mode to FULL to ensure data is persisted before "crash"
2521            db.storage.set_sync_mode(2);
2522            let txn = db.begin_transaction().unwrap();
2523            db.put(txn, b"persist", b"this").unwrap();
2524            db.commit(txn).unwrap();
2525            // Don't call shutdown - simulate crash
2526            std::mem::forget(db);
2527        }
2528
2529        // Reopen - should recover
2530        {
2531            let db = Database::open_without_lock(dir.path()).unwrap();
2532            let txn = db.begin_transaction().unwrap();
2533            let val = db.get(txn, b"persist").unwrap();
2534            assert_eq!(val, Some(b"this".to_vec()));
2535            db.abort(txn).unwrap();
2536        }
2537    }
2538}