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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// 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.

//! LIKE expression for SQL pattern matching
//!
//! Supports SQL LIKE and ILIKE (case-insensitive) pattern matching.
//! - `%` matches any sequence of characters (including empty)
//! - `_` matches any single character

use std::any::Any;
use std::cell::RefCell;
use std::fmt;
use std::num::NonZeroUsize;

use lru::LruCache;
use regex::Regex;
use rustc_hash::FxHashMap;

use super::{find_column_index, resolve_alias, Expression};
use crate::core::{Result, Row, Schema};

/// Maximum number of cached LIKE regex patterns per thread
const LIKE_REGEX_CACHE_SIZE: usize = 128;

// Thread-local LRU cache for compiled regex patterns
thread_local! {
    static LIKE_REGEX_CACHE: RefCell<LruCache<String, Regex>> =
        RefCell::new(LruCache::new(NonZeroUsize::new(LIKE_REGEX_CACHE_SIZE).unwrap()));
}

/// Clear the thread-local LIKE regex cache to release memory
pub fn clear_like_regex_cache() {
    LIKE_REGEX_CACHE.with(|cache| {
        cache.borrow_mut().clear();
    });
}

/// Get or compile a regex pattern, using thread-local LRU cache
fn get_or_compile_like_regex(pattern: &str) -> Option<Regex> {
    LIKE_REGEX_CACHE.with(|cache| {
        let mut cache = cache.borrow_mut();
        if let Some(regex) = cache.get(pattern) {
            return Some(regex.clone());
        }
        match Regex::new(pattern) {
            Ok(regex) => {
                cache.put(pattern.to_string(), regex.clone());
                Some(regex)
            }
            Err(_) => None,
        }
    })
}

/// LIKE expression for SQL pattern matching
///
/// Matches a column value against a SQL LIKE pattern.
/// - `%` matches any sequence of characters (including empty)
/// - `_` matches any single character
///
/// # Examples
///
/// ```text
/// name LIKE 'John%'     -- starts with "John"
/// name LIKE '%son'      -- ends with "son"
/// name LIKE '%oh%'      -- contains "oh"
/// name LIKE 'J_n'       -- matches "Jon", "Jan", etc.
/// name ILIKE 'JOHN%'    -- case-insensitive match
/// ```
pub struct LikeExpr {
    /// Column name to match
    column: String,
    /// SQL LIKE pattern
    pattern: String,
    /// Whether the match is case-insensitive (ILIKE)
    case_insensitive: bool,
    /// Negated (NOT LIKE)
    negated: bool,
    /// Pre-computed column index for fast evaluation
    col_index: Option<usize>,
    /// Compiled regex pattern
    regex: Option<Regex>,
    /// Whether preparation has been attempted
    prepared: bool,
}

impl LikeExpr {
    /// Create a new LIKE expression
    pub fn new(column: impl Into<String>, pattern: impl Into<String>) -> Self {
        let pattern_str = pattern.into();
        let regex = Self::compile_pattern(&pattern_str, false);
        Self {
            column: column.into(),
            pattern: pattern_str,
            case_insensitive: false,
            negated: false,
            col_index: None,
            regex,
            prepared: false,
        }
    }

    /// Create a new ILIKE expression (case-insensitive)
    pub fn new_ilike(column: impl Into<String>, pattern: impl Into<String>) -> Self {
        let pattern_str = pattern.into();
        let regex = Self::compile_pattern(&pattern_str, true);
        Self {
            column: column.into(),
            pattern: pattern_str,
            case_insensitive: true,
            negated: false,
            col_index: None,
            regex,
            prepared: false,
        }
    }

    /// Create a NOT LIKE expression
    pub fn not_like(column: impl Into<String>, pattern: impl Into<String>) -> Self {
        let mut expr = Self::new(column, pattern);
        expr.negated = true;
        expr
    }

    /// Create a NOT ILIKE expression
    pub fn not_ilike(column: impl Into<String>, pattern: impl Into<String>) -> Self {
        let mut expr = Self::new_ilike(column, pattern);
        expr.negated = true;
        expr
    }

    /// Compile SQL LIKE pattern to regex (with caching)
    ///
    /// Handles `\` as the SQL LIKE escape character:
    /// - `\%` matches a literal `%`
    /// - `\_` matches a literal `_`
    /// - `\\` matches a literal `\`
    pub fn compile_pattern(pattern: &str, case_insensitive: bool) -> Option<Regex> {
        // Build regex pattern character by character
        // We need to handle % and _ specially while escaping everything else
        let mut regex_pattern = String::with_capacity(pattern.len() * 2);
        regex_pattern.push('^'); // Anchor start

        let mut chars = pattern.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '%' => regex_pattern.push_str(".*"),
                '_' => regex_pattern.push('.'),
                '\\' => {
                    // Backslash escapes the next character in LIKE
                    if let Some(&next) = chars.peek() {
                        if next == '%' || next == '_' || next == '\\' {
                            // Escaped LIKE special char or literal backslash
                            regex_pattern.push_str(&regex::escape(&next.to_string()));
                            chars.next();
                        } else {
                            // Backslash followed by non-special char: literal backslash
                            regex_pattern.push_str("\\\\");
                        }
                    } else {
                        // Trailing backslash: literal
                        regex_pattern.push_str("\\\\");
                    }
                }
                // Escape regex special characters
                '.' | '+' | '*' | '?' | '^' | '$' | '(' | ')' | '[' | ']' | '{' | '}' | '|' => {
                    regex_pattern.push('\\');
                    regex_pattern.push(c);
                }
                _ => regex_pattern.push(c),
            }
        }

        regex_pattern.push('$'); // Anchor end

        // Build regex with case insensitivity if needed
        let regex_str = if case_insensitive {
            format!("(?i){}", regex_pattern)
        } else {
            regex_pattern
        };

        // Use cached compilation to avoid recompiling same patterns
        get_or_compile_like_regex(&regex_str)
    }

    /// Check if a string matches the pattern
    fn matches(&self, value: &str) -> bool {
        if let Some(ref regex) = self.regex {
            regex.is_match(value)
        } else {
            false
        }
    }

    /// Get the pattern (for expression compilation)
    pub fn get_pattern(&self) -> &str {
        &self.pattern
    }

    /// Check if case insensitive (for expression compilation)
    pub fn is_case_insensitive(&self) -> bool {
        self.case_insensitive
    }

    /// Check if negated (for expression compilation)
    pub fn is_negated(&self) -> bool {
        self.negated
    }
}

impl fmt::Debug for LikeExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.negated {
            if self.case_insensitive {
                write!(f, "{} NOT ILIKE '{}'", self.column, self.pattern)
            } else {
                write!(f, "{} NOT LIKE '{}'", self.column, self.pattern)
            }
        } else if self.case_insensitive {
            write!(f, "{} ILIKE '{}'", self.column, self.pattern)
        } else {
            write!(f, "{} LIKE '{}'", self.column, self.pattern)
        }
    }
}

impl Expression for LikeExpr {
    fn evaluate(&self, row: &Row) -> Result<bool> {
        // Get column value
        let value = if let Some(idx) = self.col_index {
            row.get(idx)
        } else {
            None
        };

        let value = match value {
            Some(v) => v,
            None => return Ok(false),
        };

        // NULL handling: LIKE with NULL returns false
        if value.is_null() {
            return Ok(false);
        }

        // OPTIMIZATION: Use Cow to avoid allocation for Text values
        let str_value: std::borrow::Cow<'_, str> = match value.as_str() {
            Some(s) => std::borrow::Cow::Borrowed(s),
            None => std::borrow::Cow::Owned(value.to_string()),
        };

        let matched = self.matches(&str_value);
        Ok(if self.negated { !matched } else { matched })
    }

    fn evaluate_fast(&self, row: &Row) -> bool {
        let idx = match self.col_index {
            Some(i) => i,
            None => return false,
        };

        let value = match row.get(idx) {
            Some(v) => v,
            None => return false,
        };

        if value.is_null() {
            return false;
        }

        // OPTIMIZATION: Use Cow to avoid allocation for Text values
        let str_value: std::borrow::Cow<'_, str> = match value.as_str() {
            Some(s) => std::borrow::Cow::Borrowed(s),
            None => std::borrow::Cow::Owned(value.to_string()),
        };

        let matched = self.matches(&str_value);
        if self.negated {
            !matched
        } else {
            matched
        }
    }

    fn with_aliases(&self, aliases: &FxHashMap<String, String>) -> Box<dyn Expression> {
        let resolved = resolve_alias(&self.column, aliases);
        let mut expr = LikeExpr {
            column: resolved.to_string(),
            pattern: self.pattern.clone(),
            case_insensitive: self.case_insensitive,
            negated: self.negated,
            col_index: None,
            regex: self.regex.clone(),
            prepared: false,
        };
        expr.regex = Self::compile_pattern(&self.pattern, self.case_insensitive);
        Box::new(expr)
    }

    fn prepare_for_schema(&mut self, schema: &Schema) {
        self.col_index = find_column_index(schema, &self.column);
        self.prepared = true;
    }

    fn collect_column_indices(&self, out: &mut Vec<usize>) -> bool {
        if let Some(idx) = self.col_index {
            out.push(idx);
            true
        } else {
            false
        }
    }

    fn is_prepared(&self) -> bool {
        self.prepared
    }

    fn get_column_name(&self) -> Option<&str> {
        Some(&self.column)
    }

    fn can_use_index(&self) -> bool {
        // LIKE can use index for prefix patterns (no leading %)
        !self.pattern.starts_with('%')
    }

    fn get_like_prefix_info(&self) -> Option<(&str, String, bool)> {
        // Only optimize non-negated, case-sensitive LIKE with prefix pattern
        if self.case_insensitive || self.pattern.starts_with('%') {
            return None;
        }

        // Extract prefix before first wildcard (% or _)
        let prefix: String = self
            .pattern
            .chars()
            .take_while(|&c| c != '%' && c != '_')
            .collect();

        // Need at least one character of prefix to be useful
        if prefix.is_empty() {
            return None;
        }

        Some((&self.column, prefix, self.negated))
    }

    fn clone_box(&self) -> Box<dyn Expression> {
        Box::new(LikeExpr {
            column: self.column.clone(),
            pattern: self.pattern.clone(),
            case_insensitive: self.case_insensitive,
            negated: self.negated,
            col_index: self.col_index,
            regex: self.regex.clone(),
            prepared: self.prepared,
        })
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

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

    fn test_schema() -> Schema {
        SchemaBuilder::new("test")
            .add_primary_key("id", DataType::Integer)
            .add("name", DataType::Text)
            .add_nullable("email", DataType::Text)
            .build()
    }

    #[test]
    fn test_like_starts_with() {
        let schema = test_schema();
        let mut expr = LikeExpr::new("name", "John%");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("John"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("Johnny"),
            Value::null_unknown(),
        ]);
        let row3 = Row::from(vec![
            Value::Integer(3),
            Value::text("Jane"),
            Value::null_unknown(),
        ]);

        assert!(expr.evaluate(&row1).unwrap());
        assert!(expr.evaluate(&row2).unwrap());
        assert!(!expr.evaluate(&row3).unwrap());
    }

    #[test]
    fn test_like_ends_with() {
        let schema = test_schema();
        let mut expr = LikeExpr::new("name", "%son");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("Johnson"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("Jason"),
            Value::null_unknown(),
        ]);
        let row3 = Row::from(vec![
            Value::Integer(3),
            Value::text("John"),
            Value::null_unknown(),
        ]);

        assert!(expr.evaluate(&row1).unwrap());
        assert!(expr.evaluate(&row2).unwrap());
        assert!(!expr.evaluate(&row3).unwrap());
    }

    #[test]
    fn test_like_contains() {
        let schema = test_schema();
        let mut expr = LikeExpr::new("name", "%oh%");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("John"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("Mohawk"),
            Value::null_unknown(),
        ]);
        let row3 = Row::from(vec![
            Value::Integer(3),
            Value::text("Jane"),
            Value::null_unknown(),
        ]);

        assert!(expr.evaluate(&row1).unwrap());
        assert!(expr.evaluate(&row2).unwrap());
        assert!(!expr.evaluate(&row3).unwrap());
    }

    #[test]
    fn test_like_single_char() {
        let schema = test_schema();
        let mut expr = LikeExpr::new("name", "J_n");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("Jon"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("Jan"),
            Value::null_unknown(),
        ]);
        let row3 = Row::from(vec![
            Value::Integer(3),
            Value::text("John"),
            Value::null_unknown(),
        ]);

        assert!(expr.evaluate(&row1).unwrap());
        assert!(expr.evaluate(&row2).unwrap());
        assert!(!expr.evaluate(&row3).unwrap()); // 4 chars, not 3
    }

    #[test]
    fn test_ilike_case_insensitive() {
        let schema = test_schema();
        let mut expr = LikeExpr::new_ilike("name", "JOHN%");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("john"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("JOHN"),
            Value::null_unknown(),
        ]);
        let row3 = Row::from(vec![
            Value::Integer(3),
            Value::text("JoHn"),
            Value::null_unknown(),
        ]);

        assert!(expr.evaluate(&row1).unwrap());
        assert!(expr.evaluate(&row2).unwrap());
        assert!(expr.evaluate(&row3).unwrap());
    }

    #[test]
    fn test_not_like() {
        let schema = test_schema();
        let mut expr = LikeExpr::not_like("name", "John%");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("John"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("Jane"),
            Value::null_unknown(),
        ]);

        assert!(!expr.evaluate(&row1).unwrap());
        assert!(expr.evaluate(&row2).unwrap());
    }

    #[test]
    fn test_like_null() {
        let schema = test_schema();
        let mut expr = LikeExpr::new("name", "John%");
        expr.prepare_for_schema(&schema);

        let row = Row::from(vec![
            Value::Integer(1),
            Value::null_unknown(),
            Value::null_unknown(),
        ]);
        assert!(!expr.evaluate(&row).unwrap());
    }

    #[test]
    fn test_like_exact_match() {
        let schema = test_schema();
        let mut expr = LikeExpr::new("name", "John");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("John"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("Johnny"),
            Value::null_unknown(),
        ]);

        assert!(expr.evaluate(&row1).unwrap());
        assert!(!expr.evaluate(&row2).unwrap());
    }

    #[test]
    fn test_like_special_chars() {
        let schema = test_schema();
        // Pattern with regex special characters that should be escaped
        let mut expr = LikeExpr::new("name", "test.name%");
        expr.prepare_for_schema(&schema);

        let row1 = Row::from(vec![
            Value::Integer(1),
            Value::text("test.name123"),
            Value::null_unknown(),
        ]);
        let row2 = Row::from(vec![
            Value::Integer(2),
            Value::text("testXname123"),
            Value::null_unknown(),
        ]);

        assert!(expr.evaluate(&row1).unwrap());
        assert!(!expr.evaluate(&row2).unwrap()); // . should be literal, not regex wildcard
    }

    #[test]
    fn test_can_use_index() {
        // Prefix pattern can use index
        let expr1 = LikeExpr::new("name", "John%");
        assert!(expr1.can_use_index());

        // Leading wildcard cannot use index
        let expr2 = LikeExpr::new("name", "%John");
        assert!(!expr2.can_use_index());

        let expr3 = LikeExpr::new("name", "%John%");
        assert!(!expr3.can_use_index());
    }
}