stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! MVCC Scanner implementations
//!
//! Provides scanner implementations for MVCC query results.
//!

use crate::common::CompactArc;
use crate::core::{Result, Row, RowVec, Schema};
use crate::storage::expression::Expression;
use crate::storage::traits::Scanner;

/// MVCC Scanner for iterating over versioned rows
pub struct MVCCScanner {
    /// Source rows with their IDs (cached - returns to pool on drop)
    rows: RowVec,
    /// Current index in the rows vector
    current_index: isize,
    /// Column indices to include in projection
    column_indices: Vec<usize>,
    /// Table schema (kept for future projection improvements)
    #[allow(dead_code)]
    schema: CompactArc<Schema>,
    /// Filter expression (optional, kept for streaming filter support)
    #[allow(dead_code)]
    filter: Option<Box<dyn Expression>>,
    /// Any error that occurred
    error: Option<crate::core::Error>,
    /// Pre-allocated buffer for projected row (kept for future optimization)
    #[allow(dead_code)]
    projected_row: Row,
    /// Whether the scanner has been closed
    closed: bool,
}

impl MVCCScanner {
    /// Creates a new MVCC scanner with filtering (legacy method)
    pub fn new(
        rows: RowVec,
        schema: CompactArc<Schema>,
        column_indices: Vec<usize>,
        filter: Option<Box<dyn Expression>>,
    ) -> Self {
        // Filter rows if needed
        let filtered_rows: RowVec = if let Some(ref expr) = filter {
            rows.into_iter()
                .filter(|(_, row)| expr.evaluate(row).unwrap_or_default())
                .collect()
        } else {
            rows
        };

        Self::from_rows(filtered_rows, schema, column_indices)
    }

    /// Creates scanner from RowVec
    #[inline]
    pub fn from_rows(rows: RowVec, schema: CompactArc<Schema>, column_indices: Vec<usize>) -> Self {
        let num_schema_cols = schema.columns.len();

        // Check if we need projection (column_indices is a proper subset)
        let needs_projection = !column_indices.is_empty()
            && column_indices.len() < num_schema_cols
            && !column_indices.iter().enumerate().all(|(i, &idx)| i == idx);

        // Project rows upfront if needed
        let projected_rows: RowVec = if needs_projection {
            rows.into_iter()
                .map(|(id, row)| {
                    let projected_values: Vec<crate::core::Value> = column_indices
                        .iter()
                        .map(|&idx| {
                            row.get(idx)
                                .cloned()
                                .unwrap_or_else(crate::core::Value::null_unknown)
                        })
                        .collect();
                    (id, Row::from_values(projected_values))
                })
                .collect()
        } else {
            rows
        };

        Self {
            rows: projected_rows,
            current_index: -1,
            column_indices: if needs_projection {
                vec![]
            } else {
                column_indices
            }, // Clear if already projected
            schema,
            filter: None,
            error: None,
            projected_row: Row::default(),
            closed: false,
        }
    }

    /// Creates an empty scanner
    #[inline]
    pub fn empty(schema: CompactArc<Schema>, column_indices: Vec<usize>) -> Self {
        Self {
            rows: RowVec::new(),
            current_index: -1,
            column_indices,
            schema,
            filter: None,
            error: None,
            projected_row: Row::default(),
            closed: false,
        }
    }

    /// Creates a scanner with a single row
    pub fn single(row: Row, schema: CompactArc<Schema>, column_indices: Vec<usize>) -> Self {
        let mut rows = RowVec::new();
        rows.push((0, row));
        Self {
            rows,
            current_index: -1,
            column_indices: column_indices.clone(),
            schema,
            filter: None,
            error: None,
            projected_row: Row::from_values(vec![
                crate::core::Value::null_unknown();
                column_indices.len()
            ]),
            closed: false,
        }
    }

    /// Returns the number of rows in the scanner
    pub fn len(&self) -> usize {
        self.rows.len()
    }

    /// Returns true if the scanner has no rows
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }
}

impl Scanner for MVCCScanner {
    fn next(&mut self) -> bool {
        if self.closed || self.error.is_some() {
            return false;
        }

        self.current_index += 1;

        (self.current_index as usize) < self.rows.len()
    }

    fn row(&self) -> &Row {
        if self.current_index < 0 || (self.current_index as usize) >= self.rows.len() {
            // Return a static empty row for safety
            static EMPTY_ROW: std::sync::OnceLock<Row> = std::sync::OnceLock::new();
            return EMPTY_ROW.get_or_init(|| Row::from_values(vec![]));
        }

        let (_, ref source_row) = self.rows[self.current_index as usize];

        // If no column projection, return the row directly
        if self.column_indices.is_empty() {
            return source_row;
        }

        // We need to return a reference to a projected row
        // This is tricky because we need to modify projected_row
        // For now, return the source row if indices match all columns
        if self.column_indices.len() == source_row.len() {
            let all_match = self
                .column_indices
                .iter()
                .enumerate()
                .all(|(i, &idx)| i == idx);
            if all_match {
                return source_row;
            }
        }

        // Otherwise return source row - projection handled in caller
        source_row
    }

    fn err(&self) -> Option<&crate::core::Error> {
        self.error.as_ref()
    }

    fn close(&mut self) -> Result<()> {
        self.closed = true;
        self.rows.clear();
        Ok(())
    }

    fn take_row(&mut self) -> Row {
        if self.current_index < 0 || (self.current_index as usize) >= self.rows.len() {
            return Row::new();
        }

        // Swap out the row with an empty one to avoid cloning
        let idx = self.current_index as usize;
        std::mem::take(&mut self.rows[idx].1)
    }

    fn estimated_count(&self) -> Option<usize> {
        Some(self.rows.len())
    }
}

/// Range scanner optimized for consecutive ID range queries
pub struct RangeScanner {
    /// Transaction ID for visibility checks
    txn_id: i64,
    /// Current ID in range (kept for range iteration improvements)
    #[allow(dead_code)]
    current_id: i64,
    /// End ID in range (kept for range iteration improvements)
    #[allow(dead_code)]
    end_id: i64,
    /// Whether end_id is inclusive (kept for range iteration improvements)
    #[allow(dead_code)]
    inclusive: bool,
    /// Column indices to include (kept for future projection improvements)
    #[allow(dead_code)]
    column_indices: Vec<usize>,
    /// Table schema (kept for future projection improvements)
    #[allow(dead_code)]
    schema: CompactArc<Schema>,
    /// Any scanning error
    error: Option<crate::core::Error>,
    /// Pre-allocated projected row buffer (kept for future optimization)
    #[allow(dead_code)]
    projected_row: Row,
    /// Row iterator (stores pre-fetched rows)
    rows: RowVec,
    /// Current position in rows
    row_index: isize,
}

impl RangeScanner {
    /// Creates a new range scanner
    pub fn new(
        start_id: i64,
        end_id: i64,
        inclusive: bool,
        txn_id: i64,
        schema: CompactArc<Schema>,
        column_indices: Vec<usize>,
        rows: RowVec,
    ) -> Self {
        // Filter rows to only include those in range
        let actual_end = if inclusive { end_id } else { end_id - 1 };
        let filtered_rows: RowVec = rows
            .into_iter()
            .filter(|(id, _)| *id >= start_id && *id <= actual_end)
            .collect();

        Self {
            txn_id,
            current_id: start_id,
            end_id,
            inclusive,
            column_indices: column_indices.clone(),
            schema,
            error: None,
            projected_row: Row::from_values(vec![
                crate::core::Value::null_unknown();
                column_indices.len()
            ]),
            rows: filtered_rows,
            row_index: -1,
        }
    }

    /// Returns the transaction ID
    pub fn txn_id(&self) -> i64 {
        self.txn_id
    }
}

impl Scanner for RangeScanner {
    fn next(&mut self) -> bool {
        if self.error.is_some() {
            return false;
        }

        self.row_index += 1;

        // OPTIMIZATION: Don't clone the row here - just track the index
        // We can return a reference directly in row() since rows are stored in self.rows
        (self.row_index as usize) < self.rows.len()
    }

    fn row(&self) -> &Row {
        static EMPTY_ROW: std::sync::OnceLock<Row> = std::sync::OnceLock::new();

        // OPTIMIZATION: Return reference directly from self.rows instead of cloning
        if self.row_index >= 0 && (self.row_index as usize) < self.rows.len() {
            let (_, ref row) = self.rows[self.row_index as usize];
            row
        } else {
            EMPTY_ROW.get_or_init(|| Row::from_values(vec![]))
        }
    }

    fn err(&self) -> Option<&crate::core::Error> {
        self.error.as_ref()
    }

    fn close(&mut self) -> Result<()> {
        self.rows.clear();
        Ok(())
    }

    fn take_row(&mut self) -> Row {
        if self.row_index >= 0 && (self.row_index as usize) < self.rows.len() {
            let idx = self.row_index as usize;
            std::mem::take(&mut self.rows[idx].1)
        } else {
            Row::new()
        }
    }
}

/// Empty scanner that returns no rows
pub struct EmptyScanner;

impl EmptyScanner {
    /// Creates a new empty scanner
    pub fn new() -> Self {
        Self
    }
}

impl Default for EmptyScanner {
    fn default() -> Self {
        Self::new()
    }
}

impl Scanner for EmptyScanner {
    fn next(&mut self) -> bool {
        false
    }

    fn row(&self) -> &Row {
        static EMPTY_ROW: std::sync::OnceLock<Row> = std::sync::OnceLock::new();
        EMPTY_ROW.get_or_init(|| Row::from_values(vec![]))
    }

    fn err(&self) -> Option<&crate::core::Error> {
        None
    }

    fn close(&mut self) -> Result<()> {
        Ok(())
    }
}

/// Single row scanner that returns exactly one row
pub struct SingleRowScanner {
    /// The single row to return
    row: Row,
    /// Column indices for projection (kept for future projection support)
    #[allow(dead_code)]
    column_indices: Vec<usize>,
    /// Whether next() has been called
    done: bool,
}

impl SingleRowScanner {
    /// Creates a new single row scanner
    pub fn new(row: Row, column_indices: Vec<usize>) -> Self {
        Self {
            row,
            column_indices,
            done: false,
        }
    }
}

impl Scanner for SingleRowScanner {
    fn next(&mut self) -> bool {
        if self.done {
            false
        } else {
            self.done = true;
            true
        }
    }

    fn row(&self) -> &Row {
        if self.done {
            &self.row
        } else {
            static EMPTY_ROW: std::sync::OnceLock<Row> = std::sync::OnceLock::new();
            EMPTY_ROW.get_or_init(|| Row::from_values(vec![]))
        }
    }

    fn err(&self) -> Option<&crate::core::Error> {
        None
    }

    fn close(&mut self) -> Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{DataType, SchemaBuilder, Value};

    fn test_schema() -> CompactArc<Schema> {
        CompactArc::new(
            SchemaBuilder::new("test")
                .column("id", DataType::Integer, false, false)
                .build(),
        )
    }

    #[test]
    fn test_mvcc_scanner_empty() {
        let schema = test_schema();

        let mut scanner = MVCCScanner::empty(schema, vec![0]);

        assert!(!scanner.next());
        assert!(scanner.is_empty());
    }

    #[test]
    fn test_mvcc_scanner_single() {
        let schema = test_schema();

        let row = Row::from_values(vec![Value::Integer(42)]);
        let mut scanner = MVCCScanner::single(row, schema, vec![0]);

        assert_eq!(scanner.len(), 1);
        assert!(!scanner.is_empty());

        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(42)));

        assert!(!scanner.next());
    }

    #[test]
    fn test_mvcc_scanner_multiple_rows() {
        let schema = test_schema();

        let mut rows = RowVec::new();
        rows.push((1, Row::from_values(vec![Value::Integer(1)])));
        rows.push((2, Row::from_values(vec![Value::Integer(2)])));
        rows.push((3, Row::from_values(vec![Value::Integer(3)])));

        let mut scanner = MVCCScanner::from_rows(rows, schema, vec![0]);

        assert_eq!(scanner.len(), 3);

        // Check all rows
        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(1)));

        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(2)));

        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(3)));

        assert!(!scanner.next());
    }

    #[test]
    fn test_mvcc_scanner_close() {
        let schema = test_schema();

        let mut rows = RowVec::new();
        rows.push((1, Row::from_values(vec![Value::Integer(1)])));

        let mut scanner = MVCCScanner::from_rows(rows, schema, vec![0]);

        assert!(scanner.next());
        assert!(scanner.close().is_ok());

        // After close, next should return false
        assert!(!scanner.next());
    }

    #[test]
    fn test_empty_scanner() {
        let mut scanner = EmptyScanner::new();

        assert!(!scanner.next());
        assert!(scanner.err().is_none());
        assert!(scanner.close().is_ok());
    }

    #[test]
    fn test_single_row_scanner() {
        let row = Row::from_values(vec![Value::Integer(42), Value::text("test")]);

        let mut scanner = SingleRowScanner::new(row, vec![0, 1]);

        // First call to next should succeed
        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(42)));
        assert_eq!(scanner.row().get(1), Some(&Value::text("test")));

        // Second call should fail
        assert!(!scanner.next());
    }

    #[test]
    fn test_range_scanner() {
        let schema = test_schema();

        let mut rows = RowVec::new();
        rows.push((1, Row::from_values(vec![Value::Integer(1)])));
        rows.push((2, Row::from_values(vec![Value::Integer(2)])));
        rows.push((3, Row::from_values(vec![Value::Integer(3)])));
        rows.push((5, Row::from_values(vec![Value::Integer(5)])));

        // Inclusive range 1-3
        let mut scanner = RangeScanner::new(1, 3, true, 1, schema, vec![0], rows);

        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(1)));

        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(2)));

        assert!(scanner.next());
        assert_eq!(scanner.row().get(0), Some(&Value::Integer(3)));

        assert!(!scanner.next()); // Row 5 is outside range
    }
}