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
// 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.

//! Result trait for query results
//!

use rustc_hash::FxHashMap;

use crate::common::CompactArc;
use crate::core::{Result, Row, Value};

/// QueryResult represents the result of a SQL query
///
/// This trait provides iteration over result rows with both cursor-style
/// and direct row access patterns. It handles column metadata and aliasing.
///
/// # Example
///
/// ```ignore
/// let result = transaction.select("users", &["id", "name"], None)?;
/// println!("Columns: {:?}", result.columns());
/// while result.next() {
///     let row = result.row();
///     // Process row...
/// }
/// result.close()?;
/// ```
pub trait QueryResult: Send {
    /// Returns the column names in the result
    ///
    /// If aliases are set, this returns the aliased column names.
    fn columns(&self) -> &[String];

    /// Returns column names as Arc for zero-copy sharing
    ///
    /// This is an optimization for the API layer to avoid cloning column names.
    /// Default implementation returns None, meaning caller should fall back to
    /// cloning from columns().
    fn columns_arc(&self) -> Option<CompactArc<Vec<String>>> {
        None
    }

    /// Moves the cursor to the next row
    ///
    /// Returns `true` if there is another row available, `false` otherwise.
    fn next(&mut self) -> bool;

    /// Scans the current row into the provided values
    ///
    /// The number of destination values must match the number of columns.
    /// Values are converted to the destination types where possible.
    fn scan(&self, dest: &mut [Value]) -> Result<()>;

    /// Returns the current row directly without copying
    ///
    /// This is a high-performance method to access raw column values.
    /// The returned row is valid until the next call to `next()` or `close()`.
    fn row(&self) -> &Row;

    /// Takes ownership of the current row (avoids clone)
    ///
    /// This is a high-performance method that moves the row data out of the result.
    /// After calling this, `row()` will return an empty row until `next()` is called.
    /// The default implementation clones the row for backward compatibility.
    fn take_row(&mut self) -> Row {
        self.row().clone()
    }

    /// Closes the result set and releases resources
    ///
    /// Default implementation does nothing. Override if cleanup is needed.
    fn close(&mut self) -> Result<()> {
        Ok(())
    }

    /// Returns the number of rows affected by an INSERT, UPDATE, or DELETE
    ///
    /// Default implementation returns 0. Override for DML results.
    fn rows_affected(&self) -> i64 {
        0
    }

    /// Returns the last inserted ID for an INSERT operation
    ///
    /// Default implementation returns 0. Override for INSERT results.
    fn last_insert_id(&self) -> i64 {
        0
    }

    /// Try to extract all rows as CompactArc<Vec<Row>> for zero-copy joins
    ///
    /// Returns None if the result cannot provide Arc-wrapped rows.
    /// This consumes the result - after calling, iteration will yield no more rows.
    /// Default implementation returns None.
    fn try_into_arc_rows(&mut self) -> Option<CompactArc<Vec<Row>>> {
        None
    }

    /// Returns an estimate of the total number of rows in the result.
    ///
    /// This is used for pre-allocating vectors to avoid reallocations.
    /// Returns None if the count is unknown. Default implementation returns None.
    fn estimated_count(&self) -> Option<usize> {
        None
    }

    /// Returns a pending error from the last `next()` call, if any.
    ///
    /// When `next()` returns false due to a runtime error (e.g. invalid REGEXP
    /// pattern), this method returns the error so callers can surface it.
    /// Default returns None (no error).
    fn last_error(&mut self) -> Option<crate::core::Error> {
        None
    }

    /// Sets column aliases for this result
    ///
    /// The map keys are alias names, values are original column names.
    /// Returns a new result with the aliases applied.
    fn with_aliases(self: Box<Self>, aliases: FxHashMap<String, String>) -> Box<dyn QueryResult>;
}

/// A simple in-memory query result (useful for testing and simple results)
pub struct MemoryResult {
    columns: Vec<String>,
    rows: Vec<Row>,
    current_index: Option<usize>,
    rows_affected: i64,
    last_insert_id: i64,
    closed: bool,
}

impl MemoryResult {
    /// Creates a new empty result with the given columns
    pub fn new(columns: Vec<String>) -> Self {
        Self {
            columns,
            rows: Vec::new(),
            current_index: None,
            rows_affected: 0,
            last_insert_id: 0,
            closed: false,
        }
    }

    /// Creates a result with columns and rows
    pub fn with_rows(columns: Vec<String>, rows: Vec<Row>) -> Self {
        Self {
            columns,
            rows,
            current_index: None,
            rows_affected: 0,
            last_insert_id: 0,
            closed: false,
        }
    }

    /// Creates a result for a modification operation (INSERT/UPDATE/DELETE)
    pub fn for_modification(rows_affected: i64, last_insert_id: i64) -> Self {
        Self {
            columns: Vec::new(),
            rows: Vec::new(),
            current_index: None,
            rows_affected,
            last_insert_id,
            closed: false,
        }
    }

    /// Adds a row to the result
    pub fn add_row(&mut self, row: Row) {
        self.rows.push(row);
    }

    /// Sets the rows affected count
    pub fn set_rows_affected(&mut self, count: i64) {
        self.rows_affected = count;
    }

    /// Sets the last insert ID
    pub fn set_last_insert_id(&mut self, id: i64) {
        self.last_insert_id = id;
    }
}

impl QueryResult for MemoryResult {
    fn columns(&self) -> &[String] {
        &self.columns
    }

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

    fn next(&mut self) -> bool {
        if self.closed {
            return false;
        }

        let next_index = match self.current_index {
            None => 0,
            Some(i) => i + 1,
        };

        if next_index < self.rows.len() {
            self.current_index = Some(next_index);
            true
        } else {
            false
        }
    }

    fn scan(&self, dest: &mut [Value]) -> Result<()> {
        let row = self.row();

        if dest.len() != row.len() {
            return Err(crate::core::Error::internal(format!(
                "scan destination has {} values but row has {} columns",
                dest.len(),
                row.len()
            )));
        }

        for (i, value) in row.iter().enumerate() {
            dest[i] = value.clone();
        }

        Ok(())
    }

    fn row(&self) -> &Row {
        match self.current_index {
            Some(i) if i < self.rows.len() => &self.rows[i],
            _ => panic!("row() called without successful next()"),
        }
    }

    /// Optimized take_row that swaps out the row instead of cloning
    fn take_row(&mut self) -> Row {
        match self.current_index {
            Some(i) if i < self.rows.len() => std::mem::take(&mut self.rows[i]),
            _ => panic!("take_row() called without successful next()"),
        }
    }

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

    fn rows_affected(&self) -> i64 {
        self.rows_affected
    }

    fn last_insert_id(&self) -> i64 {
        self.last_insert_id
    }

    fn with_aliases(
        mut self: Box<Self>,
        aliases: FxHashMap<String, String>,
    ) -> Box<dyn QueryResult> {
        // Apply aliases to column names
        for col in &mut self.columns {
            // Find if this column has an alias (reverse lookup)
            for (alias, original) in &aliases {
                if col == original {
                    *col = alias.clone();
                    break;
                }
            }
        }
        self
    }
}

/// An empty result that returns no rows
pub struct EmptyResult {
    columns: Vec<String>,
    rows_affected: i64,
    last_insert_id: i64,
}

impl EmptyResult {
    /// Creates a new empty result
    pub fn new() -> Self {
        Self {
            columns: Vec::new(),
            rows_affected: 0,
            last_insert_id: 0,
        }
    }

    /// Creates an empty result for a modification operation
    pub fn for_modification(rows_affected: i64, last_insert_id: i64) -> Self {
        Self {
            columns: Vec::new(),
            rows_affected,
            last_insert_id,
        }
    }
}

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

impl QueryResult for EmptyResult {
    fn columns(&self) -> &[String] {
        &self.columns
    }

    fn next(&mut self) -> bool {
        false
    }

    fn scan(&self, _dest: &mut [Value]) -> Result<()> {
        Err(crate::core::Error::internal(
            "scan() called on empty result",
        ))
    }

    fn row(&self) -> &Row {
        panic!("row() called on empty result")
    }

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

    fn rows_affected(&self) -> i64 {
        self.rows_affected
    }

    fn last_insert_id(&self) -> i64 {
        self.last_insert_id
    }

    fn with_aliases(self: Box<Self>, _aliases: FxHashMap<String, String>) -> Box<dyn QueryResult> {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_memory_result_empty() {
        let mut result = MemoryResult::new(vec!["id".to_string(), "name".to_string()]);

        assert_eq!(result.columns(), &["id", "name"]);
        assert!(!result.next());
        assert_eq!(result.rows_affected(), 0);
        assert_eq!(result.last_insert_id(), 0);
    }

    #[test]
    fn test_memory_result_with_rows() {
        let rows = vec![
            Row::from_values(vec![Value::Integer(1), Value::text("Alice")]),
            Row::from_values(vec![Value::Integer(2), Value::text("Bob")]),
        ];

        let mut result = MemoryResult::with_rows(vec!["id".to_string(), "name".to_string()], rows);

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

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

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

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

        let mut result = MemoryResult::with_rows(vec!["id".to_string(), "name".to_string()], rows);

        assert!(result.next());

        let mut dest = vec![Value::null_unknown(), Value::null_unknown()];
        result.scan(&mut dest).unwrap();

        assert_eq!(dest[0], Value::Integer(42));
        assert_eq!(dest[1], Value::text("test"));
    }

    #[test]
    fn test_memory_result_for_modification() {
        let result = MemoryResult::for_modification(5, 100);

        assert_eq!(result.rows_affected(), 5);
        assert_eq!(result.last_insert_id(), 100);
    }

    #[test]
    fn test_memory_result_close() {
        let rows = vec![Row::from_values(vec![Value::Integer(1)])];
        let mut result = MemoryResult::with_rows(vec!["id".to_string()], rows);

        assert!(result.next());
        assert!(result.close().is_ok());
        assert!(!result.next()); // After close, next returns false
    }

    #[test]
    fn test_memory_result_with_aliases() {
        let rows = vec![Row::from_values(vec![Value::Integer(1)])];
        let result = Box::new(MemoryResult::with_rows(vec!["user_id".to_string()], rows));

        let mut aliases = FxHashMap::default();
        aliases.insert("id".to_string(), "user_id".to_string());

        let aliased = result.with_aliases(aliases);
        assert_eq!(aliased.columns(), &["id"]);
    }

    #[test]
    fn test_empty_result() {
        let mut result = EmptyResult::new();

        assert!(result.columns().is_empty());
        assert!(!result.next());
        assert_eq!(result.rows_affected(), 0);
        assert!(result.close().is_ok());
    }

    #[test]
    fn test_empty_result_for_modification() {
        let result = EmptyResult::for_modification(10, 0);

        assert_eq!(result.rows_affected(), 10);
        assert_eq!(result.last_insert_id(), 0);
    }
}