hyperQL 0.1.0

Query language for hyperspatial graph databases with temporal and spatial semantics
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
use crate::ast::*;
use crate::error::*;
use super::{utils, geometric, vector};

pub fn parse_simple_expression(input: &str) -> Result<Expression> {
    let input = input.trim();

    // Check for geometric expressions first (NEAR/WITHIN)
    let upper_input = input.to_uppercase();
    if upper_input.contains(" NEAR ") && upper_input.contains(" WITHIN ") {
        return geometric::parse_near_expression(input);
    }

    // Check for vector SIMILAR TO operator
    if upper_input.contains(" SIMILAR TO ") && upper_input.contains(" THRESHOLD ") {
        return vector::parse_similar_to_expression(input);
    }

    // Check for IS NULL / IS NOT NULL
    if let Some(is_null_expr) = try_parse_is_null(input)? {
        return Ok(is_null_expr);
    }

    // Check for BETWEEN
    if let Some(between_expr) = try_parse_between(input)? {
        return Ok(between_expr);
    }

    if let Some(and_pos) = utils::find_operator_position(input, " AND ") {
        let left = parse_simple_expression(&input[..and_pos])?;
        let right = parse_simple_expression(&input[and_pos + 5..])?;
        return Ok(Expression::Binary {
            left: Box::new(left),
            op: BinaryOperator::And,
            right: Box::new(right),
        });
    }

    if let Some(or_pos) = utils::find_operator_position(input, " OR ") {
        let left = parse_simple_expression(&input[..or_pos])?;
        let right = parse_simple_expression(&input[or_pos + 4..])?;
        return Ok(Expression::Binary {
            left: Box::new(left),
            op: BinaryOperator::Or,
            right: Box::new(right),
        });
    }

    // Check for LIKE / NOT LIKE
    if let Some(like_expr) = try_parse_like(input)? {
        return Ok(like_expr);
    }

    // Check for IN / NOT IN
    if let Some(in_expr) = try_parse_in(input)? {
        return Ok(in_expr);
    }

    let operators = [
        ("<=", BinaryOperator::LessThanOrEqual),
        (">=", BinaryOperator::GreaterThanOrEqual),
        ("<>", BinaryOperator::NotEqual),
        ("!=", BinaryOperator::NotEqual),
        ("=", BinaryOperator::Equal),
        ("<", BinaryOperator::LessThan),
        (">", BinaryOperator::GreaterThan),
    ];

    for (op_str, op_type) in &operators {
        if let Some(op_pos) = utils::find_operator_position(input, op_str) {
            let left_part = &input[..op_pos];
            let right_part = &input[op_pos + op_str.len()..];

            // Parse left side - handle functions, arithmetic, or simple literals
            let left = if left_part.contains('(') {
                parse_expression_or_function(left_part)?
            } else if left_part.contains('+') || left_part.contains('-') || left_part.contains('*') || left_part.contains('/') {
                parse_arithmetic_expression(left_part)?
            } else {
                parse_simple_column_or_literal(left_part)?
            };

            // Parse right side - handle functions, arithmetic, or simple literals
            let right = if right_part.contains('(') {
                parse_expression_or_function(right_part)?
            } else if right_part.contains('+') || right_part.contains('-') || right_part.contains('*') || right_part.contains('/') {
                parse_arithmetic_expression(right_part)?
            } else {
                parse_simple_column_or_literal(right_part)?
            };

            return Ok(Expression::Binary {
                left: Box::new(left),
                op: op_type.clone(),
                right: Box::new(right),
            });
        }
    }

    parse_simple_column_or_literal(input)
}

pub fn parse_simple_column_or_literal(input: &str) -> Result<Expression> {
    let input = input.trim();

    if (input.starts_with('"') && input.ends_with('"')) ||
       (input.starts_with('\'') && input.ends_with('\'')) {
        let content = &input[1..input.len()-1];
        return Ok(Expression::Literal(Literal::String(content.to_string())));
    }

    if let Ok(int_val) = input.parse::<i64>() {
        return Ok(Expression::Literal(Literal::Int(int_val)));
    }

    if let Ok(float_val) = input.parse::<f64>() {
        return Ok(Expression::Literal(Literal::Float(float_val)));
    }

    match input.to_uppercase().as_str() {
        "TRUE" => return Ok(Expression::Literal(Literal::Bool(true))),
        "FALSE" => return Ok(Expression::Literal(Literal::Bool(false))),
        "NULL" => return Ok(Expression::Literal(Literal::Null)),
        _ => {}
    }

    if let Some(dot_pos) = input.find('.') {
        Ok(Expression::Column(ColumnRef {
            table: Some(input[..dot_pos].trim().to_string()),
            name: input[dot_pos + 1..].trim().to_string(),
        }))
    } else {
        Ok(Expression::Column(ColumnRef {
            table: None,
            name: input.to_string(),
        }))
    }
}

pub fn parse_literal_expression(input: &str) -> Result<Expression> {
    let input = input.trim();

    if (input.starts_with('"') && input.ends_with('"')) ||
       (input.starts_with('\'') && input.ends_with('\'')) {
        let content = &input[1..input.len()-1];
        return Ok(Expression::Literal(Literal::String(content.to_string())));
    }

    if let Ok(int_val) = input.parse::<i64>() {
        return Ok(Expression::Literal(Literal::Int(int_val)));
    }

    if let Ok(float_val) = input.parse::<f64>() {
        return Ok(Expression::Literal(Literal::Float(float_val)));
    }

    match input.to_uppercase().as_str() {
        "TRUE" => Ok(Expression::Literal(Literal::Bool(true))),
        "FALSE" => Ok(Expression::Literal(Literal::Bool(false))),
        "NULL" => Ok(Expression::Literal(Literal::Null)),
        _ => Err(HyperQLError::simple_parse_error(
            &format!("Invalid literal value: {}", input),
            input,
            1,
            1,
        ))
    }
}

pub fn parse_expression_or_function(input: &str) -> Result<Expression> {
    let input = input.trim();

    if let Some(paren_pos) = input.find('(') {
        let func_name = input[..paren_pos].trim().to_uppercase();

        // Check for vector functions
        if func_name == "SIMILARITY" {
            return vector::parse_similarity_function(input);
        }

        if func_name == "DISTANCE" {
            return vector::parse_distance_function(input);
        }

        if utils::is_aggregate_function(&func_name) {
            return parse_function_call(input);
        }
    }

    if input.contains('+') || input.contains('-') || input.contains('*') || input.contains('/') {
        return parse_arithmetic_expression(input);
    }

    parse_simple_column_or_literal(input)
}

fn parse_function_call(input: &str) -> Result<Expression> {
    let input = input.trim();
    let paren_pos = input.find('(')
        .ok_or_else(|| HyperQLError::simple_parse_error(
            "Invalid function call syntax",
            input,
            1,
            1,
        ))?;

    let func_name = input[..paren_pos].trim().to_string();

    let end_paren = input.rfind(')')
        .ok_or_else(|| HyperQLError::simple_parse_error(
            "Missing closing parenthesis in function call",
            input,
            1,
            1,
        ))?;

    let args_str = &input[paren_pos + 1..end_paren];
    let mut args = Vec::new();

    if !args_str.trim().is_empty() {
        for arg in args_str.split(',') {
            let arg = arg.trim();
            if arg == "*" && utils::is_aggregate_function(&func_name) {
                args.push(Expression::Column(ColumnRef {
                    table: None,
                    name: "*".to_string(),
                }));
            } else {
                args.push(parse_simple_column_or_literal(arg)?);
            }
        }
    }

    Ok(Expression::Function {
        name: func_name,
        args,
    })
}

fn parse_arithmetic_expression(input: &str) -> Result<Expression> {
    parse_addition_expression(input)
}

fn parse_addition_expression(input: &str) -> Result<Expression> {
    let input = input.trim();

    let mut paren_depth = 0;
    let mut last_op_pos = None;
    let mut last_op_char = '+';

    for (i, ch) in input.char_indices().rev() {
        match ch {
            ')' => paren_depth += 1,
            '(' => paren_depth -= 1,
            '+' | '-' if paren_depth == 0 && i > 0 => {
                last_op_pos = Some(i);
                last_op_char = ch;
                break;
            },
            _ => {}
        }
    }

    if let Some(op_pos) = last_op_pos {
        let left_part = &input[..op_pos].trim();
        let right_part = &input[op_pos + 1..].trim();

        let left_expr = parse_addition_expression(left_part)?;
        let right_expr = parse_multiplication_expression(right_part)?;

        let op = match last_op_char {
            '+' => BinaryOperator::Add,
            '-' => BinaryOperator::Subtract,
            _ => unreachable!(),
        };

        return Ok(Expression::Binary {
            left: Box::new(left_expr),
            op,
            right: Box::new(right_expr),
        });
    }

    parse_multiplication_expression(input)
}

fn parse_multiplication_expression(input: &str) -> Result<Expression> {
    let input = input.trim();

    let mut paren_depth = 0;
    let mut last_op_pos = None;
    let mut last_op_char = '*';

    for (i, ch) in input.char_indices().rev() {
        match ch {
            ')' => paren_depth += 1,
            '(' => paren_depth -= 1,
            '*' | '/' if paren_depth == 0 => {
                last_op_pos = Some(i);
                last_op_char = ch;
                break;
            },
            _ => {}
        }
    }

    if let Some(op_pos) = last_op_pos {
        let left_part = &input[..op_pos].trim();
        let right_part = &input[op_pos + 1..].trim();

        let left_expr = parse_multiplication_expression(left_part)?;
        let right_expr = parse_primary_expression(right_part)?;

        let op = match last_op_char {
            '*' => BinaryOperator::Multiply,
            '/' => BinaryOperator::Divide,
            _ => unreachable!(),
        };

        return Ok(Expression::Binary {
            left: Box::new(left_expr),
            op,
            right: Box::new(right_expr),
        });
    }

    parse_primary_expression(input)
}

fn parse_primary_expression(input: &str) -> Result<Expression> {
    let input = input.trim();

    if input.starts_with('(') && input.ends_with(')') {
        let mut paren_depth = 0;
        let mut all_enclosed = true;

        for (i, ch) in input.char_indices() {
            match ch {
                '(' => paren_depth += 1,
                ')' => {
                    paren_depth -= 1;
                    if paren_depth == 0 && i < input.len() - 1 {
                        all_enclosed = false;
                        break;
                    }
                },
                _ => {}
            }
        }

        if all_enclosed && paren_depth == 0 {
            let inner = &input[1..input.len()-1];
            return parse_arithmetic_expression(inner);
        }
    }

    parse_simple_column_or_literal(input)
}

fn try_parse_is_null(input: &str) -> Result<Option<Expression>> {
    let upper = input.to_uppercase();

    if let Some(pos) = utils::find_operator_position(&upper, " IS NOT NULL") {
        let expr_part = &input[..pos].trim();
        let expr = parse_simple_column_or_literal(expr_part)?;
        return Ok(Some(Expression::Unary {
            op: UnaryOperator::IsNotNull,
            expr: Box::new(expr),
        }));
    }

    if let Some(pos) = utils::find_operator_position(&upper, " IS NULL") {
        let expr_part = &input[..pos].trim();
        let expr = parse_simple_column_or_literal(expr_part)?;
        return Ok(Some(Expression::Unary {
            op: UnaryOperator::IsNull,
            expr: Box::new(expr),
        }));
    }

    Ok(None)
}

fn try_parse_between(input: &str) -> Result<Option<Expression>> {
    let upper = input.to_uppercase();

    let (negated, between_keyword) = if let Some(pos) = upper.find(" NOT BETWEEN ") {
        (true, pos)
    } else if let Some(pos) = upper.find(" BETWEEN ") {
        (false, pos)
    } else {
        return Ok(None);
    };

    let expr_part = &input[..between_keyword].trim();
    let expr = parse_simple_column_or_literal(expr_part)?;

    let between_keyword_len = if negated { 13 } else { 9 };
    let rest = &input[between_keyword + between_keyword_len..].trim();

    if let Some(and_pos) = utils::find_operator_position(rest, " AND ") {
        let lower_part = &rest[..and_pos].trim();
        let upper_part = &rest[and_pos + 5..].trim();

        let lower = parse_simple_column_or_literal(lower_part)?;
        let upper_expr = parse_simple_column_or_literal(upper_part)?;

        return Ok(Some(Expression::Between {
            expr: Box::new(expr),
            lower: Box::new(lower),
            upper: Box::new(upper_expr),
            negated,
        }));
    }

    Err(HyperQLError::simple_parse_error(
        "BETWEEN requires AND keyword",
        input,
        1,
        1,
    ))
}

fn try_parse_like(input: &str) -> Result<Option<Expression>> {
    let upper = input.to_uppercase();

    if let Some(pos) = utils::find_operator_position(&upper, " NOT LIKE ") {
        let left_part = &input[..pos].trim();
        let right_part = &input[pos + 11..].trim();

        let left = parse_simple_column_or_literal(left_part)?;
        let right = parse_simple_column_or_literal(right_part)?;

        return Ok(Some(Expression::Binary {
            left: Box::new(left),
            op: BinaryOperator::NotLike,
            right: Box::new(right),
        }));
    }

    if let Some(pos) = utils::find_operator_position(&upper, " LIKE ") {
        let left_part = &input[..pos].trim();
        let right_part = &input[pos + 6..].trim();

        let left = parse_simple_column_or_literal(left_part)?;
        let right = parse_simple_column_or_literal(right_part)?;

        return Ok(Some(Expression::Binary {
            left: Box::new(left),
            op: BinaryOperator::Like,
            right: Box::new(right),
        }));
    }

    Ok(None)
}

fn try_parse_in(input: &str) -> Result<Option<Expression>> {
    let upper = input.to_uppercase();

    let (negated, in_keyword_pos) = if let Some(pos) = utils::find_operator_position(&upper, " NOT IN ") {
        (true, pos)
    } else if let Some(pos) = utils::find_operator_position(&upper, " IN ") {
        (false, pos)
    } else {
        return Ok(None);
    };

    let expr_part = &input[..in_keyword_pos].trim();
    let expr = parse_simple_column_or_literal(expr_part)?;

    let in_keyword_len = if negated { 8 } else { 4 };
    let list_part = &input[in_keyword_pos + in_keyword_len..].trim();

    if !list_part.starts_with('(') || !list_part.ends_with(')') {
        return Err(HyperQLError::simple_parse_error(
            "IN operator requires parenthesized list",
            input,
            1,
            1,
        ));
    }

    let inner = &list_part[1..list_part.len()-1].trim();
    let mut values = Vec::new();

    if !inner.is_empty() {
        for item in split_list_items(inner) {
            values.push(parse_simple_column_or_literal(item.trim())?);
        }
    }

    let list_expr = Expression::Function {
        name: "__IN_LIST__".to_string(),
        args: values,
    };

    let op = if negated {
        BinaryOperator::NotIn
    } else {
        BinaryOperator::In
    };

    Ok(Some(Expression::Binary {
        left: Box::new(expr),
        op,
        right: Box::new(list_expr),
    }))
}

fn split_list_items(input: &str) -> Vec<&str> {
    let mut items = Vec::new();
    let mut current_start = 0;
    let mut in_quote = false;
    let mut quote_char = '"';
    let chars: Vec<char> = input.chars().collect();

    for i in 0..chars.len() {
        let ch = chars[i];

        if (ch == '"' || ch == '\'') && (i == 0 || chars[i - 1] != '\\') {
            if !in_quote {
                in_quote = true;
                quote_char = ch;
            } else if ch == quote_char {
                in_quote = false;
            }
        }

        if ch == ',' && !in_quote {
            items.push(&input[current_start..i]);
            current_start = i + 1;
        }
    }

    if current_start < input.len() {
        items.push(&input[current_start..]);
    }

    items
}