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