rustledger-query 0.10.0

Beancount query engine (BQL) with SQL-like syntax for ledger queries
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
//! BQL query completion engine.
//!
//! Provides context-aware completions for the BQL query language,
//! suitable for IDE integration, CLI autocomplete, or WASM playgrounds.
//!
//! # Example
//!
//! ```
//! use rustledger_query::completions::{complete, Completion};
//!
//! let completions = complete("SELECT ", 7);
//! assert!(completions.completions.iter().any(|c| c.text == "account"));
//! ```

/// A completion suggestion.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Completion {
    /// The completion text to insert.
    pub text: String,
    /// Category: keyword, function, column, operator, literal.
    pub category: CompletionCategory,
    /// Optional description/documentation.
    pub description: Option<String>,
}

/// Category of completion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionCategory {
    /// SQL keyword (SELECT, WHERE, etc.).
    Keyword,
    /// Aggregate or scalar function.
    Function,
    /// Column name.
    Column,
    /// Operator (+, -, =, etc.).
    Operator,
    /// Literal value.
    Literal,
}

impl CompletionCategory {
    /// Returns the category as a string for serialization.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Keyword => "keyword",
            Self::Function => "function",
            Self::Column => "column",
            Self::Operator => "operator",
            Self::Literal => "literal",
        }
    }
}

/// Result of a completion request.
#[derive(Debug, Clone)]
pub struct CompletionResult {
    /// List of completions.
    pub completions: Vec<Completion>,
    /// Current parsing context (for debugging).
    pub context: BqlContext,
}

/// BQL parsing context state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BqlContext {
    /// At the start, expecting a statement keyword.
    Start,
    /// After SELECT, expecting columns/expressions.
    AfterSelect,
    /// After SELECT columns, could have FROM, WHERE, GROUP BY, etc.
    AfterSelectTargets,
    /// After FROM keyword.
    AfterFrom,
    /// After FROM clause modifiers (OPEN ON, CLOSE ON, CLEAR).
    AfterFromModifiers,
    /// After WHERE keyword, expecting expression.
    AfterWhere,
    /// Inside WHERE expression.
    InWhereExpr,
    /// After GROUP keyword, expecting BY.
    AfterGroup,
    /// After GROUP BY, expecting columns.
    AfterGroupBy,
    /// After ORDER keyword, expecting BY.
    AfterOrder,
    /// After ORDER BY, expecting columns.
    AfterOrderBy,
    /// After LIMIT keyword, expecting number.
    AfterLimit,
    /// After JOURNAL keyword.
    AfterJournal,
    /// After BALANCES keyword.
    AfterBalances,
    /// After PRINT keyword.
    AfterPrint,
    /// Inside a function call, after opening paren.
    InFunction(String),
    /// After a comparison operator, expecting value.
    AfterOperator,
    /// After AS keyword, expecting alias.
    AfterAs,
    /// Inside a string literal.
    InString,
}

/// Get BQL query completions at cursor position.
///
/// Returns context-aware completions for the BQL query language.
///
/// # Arguments
///
/// * `partial_query` - The query text so far
/// * `cursor_pos` - Byte offset of cursor position
///
/// # Example
///
/// ```
/// use rustledger_query::completions::complete;
///
/// let result = complete("SELECT ", 7);
/// assert!(!result.completions.is_empty());
/// ```
#[must_use]
pub fn complete(partial_query: &str, cursor_pos: usize) -> CompletionResult {
    // Get the text up to cursor
    let text = if cursor_pos <= partial_query.len() {
        &partial_query[..cursor_pos]
    } else {
        partial_query
    };

    // Tokenize (simple whitespace/punctuation split)
    let tokens = tokenize_bql(text);
    let context = determine_context(&tokens);
    let completions = get_completions_for_context(&context);

    CompletionResult {
        completions,
        context,
    }
}

/// Simple tokenizer for BQL.
fn tokenize_bql(text: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut in_string = false;
    let mut chars = text.chars().peekable();

    while let Some(c) = chars.next() {
        if in_string {
            current.push(c);
            if c == '"' {
                tokens.push(current.clone());
                current.clear();
                in_string = false;
            }
        } else if c == '"' {
            if !current.is_empty() {
                tokens.push(current.clone());
                current.clear();
            }
            current.push(c);
            in_string = true;
        } else if c.is_whitespace() {
            if !current.is_empty() {
                tokens.push(current.clone());
                current.clear();
            }
        } else if "(),*+-/=<>!~".contains(c) {
            if !current.is_empty() {
                tokens.push(current.clone());
                current.clear();
            }
            // Handle multi-char operators (!=, <=, >=)
            if (c == '!' || c == '<' || c == '>') && chars.peek() == Some(&'=') {
                // Safety: we just checked peek() == Some(&'='), so next() is guaranteed
                if let Some(next_char) = chars.next() {
                    tokens.push(format!("{c}{next_char}"));
                }
            } else {
                tokens.push(c.to_string());
            }
        } else {
            current.push(c);
        }
    }

    if !current.is_empty() {
        tokens.push(current);
    }

    tokens
}

/// Determine the current context from tokens.
fn determine_context(tokens: &[String]) -> BqlContext {
    if tokens.is_empty() {
        return BqlContext::Start;
    }

    let upper_tokens: Vec<String> = tokens.iter().map(|t| t.to_uppercase()).collect();

    // Check for incomplete string
    if let Some(last) = tokens.last()
        && last.starts_with('"')
        && !last.ends_with('"')
    {
        return BqlContext::InString;
    }

    // Find the main statement type
    let first = upper_tokens.first().map_or("", String::as_str);

    match first {
        "SELECT" => determine_select_context(&upper_tokens),
        "JOURNAL" => BqlContext::AfterJournal,
        "BALANCES" => BqlContext::AfterBalances,
        "PRINT" => BqlContext::AfterPrint,
        _ => BqlContext::Start,
    }
}

/// Determine context within a SELECT statement.
fn determine_select_context(tokens: &[String]) -> BqlContext {
    // Find positions of key clauses
    let mut from_pos = None;
    let mut where_pos = None;
    let mut group_pos = None;
    let mut order_pos = None;
    let mut limit_pos = None;
    let mut last_as_pos = None;

    for (i, token) in tokens.iter().enumerate() {
        match token.as_str() {
            "FROM" => from_pos = Some(i),
            "WHERE" => where_pos = Some(i),
            "GROUP" => group_pos = Some(i),
            "ORDER" => order_pos = Some(i),
            "LIMIT" => limit_pos = Some(i),
            "AS" => last_as_pos = Some(i),
            _ => {}
        }
    }

    let last_idx = tokens.len() - 1;
    let last = tokens.last().map_or("", String::as_str);

    // Check for AS context
    if last == "AS" || last_as_pos == Some(last_idx) {
        return BqlContext::AfterAs;
    }

    // Determine context based on last keyword position
    if let Some(pos) = limit_pos
        && last_idx == pos
    {
        return BqlContext::AfterLimit;
    }

    if let Some(pos) = order_pos {
        if last_idx == pos {
            return BqlContext::AfterOrder;
        }
        if last_idx > pos {
            if tokens.get(pos + 1).map(String::as_str) == Some("BY") {
                return BqlContext::AfterOrderBy;
            }
            return BqlContext::AfterOrder;
        }
    }

    if let Some(pos) = group_pos {
        if last_idx == pos {
            return BqlContext::AfterGroup;
        }
        if last_idx > pos {
            if tokens.get(pos + 1).map(String::as_str) == Some("BY") {
                return BqlContext::AfterGroupBy;
            }
            return BqlContext::AfterGroup;
        }
    }

    if let Some(pos) = where_pos {
        if last_idx == pos {
            return BqlContext::AfterWhere;
        }
        // Check if last token is an operator
        if [
            "=", "!=", "<", "<=", ">", ">=", "~", "AND", "OR", "NOT", "IN",
        ]
        .contains(&last)
        {
            return BqlContext::AfterOperator;
        }
        return BqlContext::InWhereExpr;
    }

    if let Some(pos) = from_pos {
        if last_idx == pos {
            return BqlContext::AfterFrom;
        }
        // Check for FROM modifiers
        if ["OPEN", "CLOSE", "CLEAR", "ON"].contains(&last) {
            return BqlContext::AfterFromModifiers;
        }
        return BqlContext::AfterFromModifiers;
    }

    // We're still in SELECT targets
    if last_idx == 0 {
        return BqlContext::AfterSelect;
    }

    // Check if we just finished a function call or have comma
    if last == "," || last == "(" {
        return BqlContext::AfterSelect;
    }

    BqlContext::AfterSelectTargets
}

/// Get completions for the given context.
fn get_completions_for_context(context: &BqlContext) -> Vec<Completion> {
    match context {
        BqlContext::Start => vec![
            keyword("SELECT", Some("Query with filtering and aggregation")),
            keyword("BALANCES", Some("Show account balances")),
            keyword("JOURNAL", Some("Show account journal")),
            keyword("PRINT", Some("Print transactions")),
        ],

        BqlContext::AfterSelect => {
            let mut completions = vec![
                keyword("DISTINCT", Some("Remove duplicate rows")),
                keyword("*", Some("Select all columns")),
            ];
            completions.extend(column_completions());
            completions.extend(function_completions());
            completions
        }

        BqlContext::AfterSelectTargets => vec![
            keyword("FROM", Some("Specify data source")),
            keyword("WHERE", Some("Filter results")),
            keyword("GROUP BY", Some("Group results")),
            keyword("ORDER BY", Some("Sort results")),
            keyword("LIMIT", Some("Limit result count")),
            keyword("AS", Some("Alias column")),
            operator(",", Some("Add another column")),
        ],

        BqlContext::AfterFrom => vec![
            keyword("OPEN ON", Some("Summarize entries before date")),
            keyword("CLOSE ON", Some("Truncate entries after date")),
            keyword("CLEAR", Some("Transfer income/expense to equity")),
            keyword("WHERE", Some("Filter results")),
            keyword("GROUP BY", Some("Group results")),
            keyword("ORDER BY", Some("Sort results")),
        ],

        BqlContext::AfterFromModifiers => vec![
            keyword("WHERE", Some("Filter results")),
            keyword("GROUP BY", Some("Group results")),
            keyword("ORDER BY", Some("Sort results")),
            keyword("LIMIT", Some("Limit result count")),
        ],

        BqlContext::AfterWhere | BqlContext::AfterOperator => {
            let mut completions = column_completions();
            completions.extend(function_completions());
            completions.extend(vec![
                literal("TRUE"),
                literal("FALSE"),
                literal("NULL"),
                keyword("NOT", Some("Negate condition")),
            ]);
            completions
        }

        BqlContext::InWhereExpr => {
            vec![
                keyword("AND", Some("Logical AND")),
                keyword("OR", Some("Logical OR")),
                operator("=", Some("Equals")),
                operator("!=", Some("Not equals")),
                operator("~", Some("Regex match")),
                operator("<", Some("Less than")),
                operator(">", Some("Greater than")),
                operator("<=", Some("Less or equal")),
                operator(">=", Some("Greater or equal")),
                keyword("IN", Some("Set membership")),
                keyword("GROUP BY", Some("Group results")),
                keyword("ORDER BY", Some("Sort results")),
                keyword("LIMIT", Some("Limit result count")),
            ]
        }

        BqlContext::AfterGroup => vec![keyword("BY", None)],

        BqlContext::AfterGroupBy => {
            let mut completions = column_completions();
            completions.extend(vec![
                keyword("ORDER BY", Some("Sort results")),
                keyword("LIMIT", Some("Limit result count")),
                operator(",", Some("Add another group column")),
            ]);
            completions
        }

        BqlContext::AfterOrder => vec![keyword("BY", None)],

        BqlContext::AfterOrderBy => {
            let mut completions = column_completions();
            completions.extend(vec![
                keyword("ASC", Some("Ascending order")),
                keyword("DESC", Some("Descending order")),
                keyword("LIMIT", Some("Limit result count")),
                operator(",", Some("Add another sort column")),
            ]);
            completions
        }

        BqlContext::AfterLimit => vec![literal("10"), literal("100"), literal("1000")],

        BqlContext::AfterJournal | BqlContext::AfterBalances | BqlContext::AfterPrint => vec![
            keyword("AT", Some("Apply function to results")),
            keyword("FROM", Some("Specify data source")),
        ],

        BqlContext::AfterAs | BqlContext::InString | BqlContext::InFunction(_) => vec![],
    }
}

// Helper constructors

fn keyword(text: &str, description: Option<&str>) -> Completion {
    Completion {
        text: text.to_string(),
        category: CompletionCategory::Keyword,
        description: description.map(String::from),
    }
}

fn operator(text: &str, description: Option<&str>) -> Completion {
    Completion {
        text: text.to_string(),
        category: CompletionCategory::Operator,
        description: description.map(String::from),
    }
}

fn literal(text: &str) -> Completion {
    Completion {
        text: text.to_string(),
        category: CompletionCategory::Literal,
        description: None,
    }
}

fn column(text: &str, description: &str) -> Completion {
    Completion {
        text: text.to_string(),
        category: CompletionCategory::Column,
        description: Some(description.to_string()),
    }
}

fn function(text: &str, description: &str) -> Completion {
    Completion {
        text: text.to_string(),
        category: CompletionCategory::Function,
        description: Some(description.to_string()),
    }
}

/// Get column completions.
fn column_completions() -> Vec<Completion> {
    vec![
        column("account", "Account name"),
        column("date", "Transaction date"),
        column("narration", "Transaction description"),
        column("payee", "Transaction payee"),
        column("flag", "Transaction flag"),
        column("tags", "Transaction tags"),
        column("links", "Document links"),
        column("position", "Posting amount"),
        column("units", "Posting units"),
        column("cost", "Cost basis"),
        column("weight", "Balancing weight"),
        column("balance", "Running balance"),
        column("year", "Transaction year"),
        column("month", "Transaction month"),
        column("day", "Transaction day"),
        column("currency", "Posting currency"),
        column("number", "Posting amount number"),
        column("cost_number", "Per-unit cost number"),
        column("cost_currency", "Cost currency"),
        column("cost_date", "Cost lot date"),
        column("cost_label", "Cost lot label"),
        column("has_cost", "Whether posting has cost"),
        column("entry", "Parent transaction object"),
        column("meta", "All metadata as object"),
    ]
}

/// Get function completions.
fn function_completions() -> Vec<Completion> {
    vec![
        // Aggregates
        function("SUM(", "Sum of values"),
        function("COUNT(", "Count of rows"),
        function("MIN(", "Minimum value"),
        function("MAX(", "Maximum value"),
        function("AVG(", "Average value"),
        function("FIRST(", "First value"),
        function("LAST(", "Last value"),
        // Date functions
        function("YEAR(", "Extract year"),
        function("MONTH(", "Extract month"),
        function("DAY(", "Extract day"),
        function("QUARTER(", "Extract quarter"),
        function("WEEKDAY(", "Day of week (0=Mon)"),
        function("YMONTH(", "Year-month format"),
        function("TODAY()", "Current date"),
        // String functions
        function("LENGTH(", "String length"),
        function("UPPER(", "Uppercase"),
        function("LOWER(", "Lowercase"),
        function("TRIM(", "Trim whitespace"),
        function("SUBSTR(", "Substring"),
        function("COALESCE(", "First non-null"),
        // Account functions
        function("PARENT(", "Parent account"),
        function("LEAF(", "Leaf component"),
        function("ROOT(", "Root components"),
        // Amount functions
        function("NUMBER(", "Extract number"),
        function("CURRENCY(", "Extract currency"),
        function("ABS(", "Absolute value"),
        function("ROUND(", "Round number"),
        // Metadata functions
        function("META(", "Get metadata value (posting or entry)"),
        function("ENTRY_META(", "Get entry metadata value"),
        function("POSTING_META(", "Get posting metadata value"),
    ]
}

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

    #[test]
    fn test_complete_start() {
        let result = complete("", 0);
        assert_eq!(result.context, BqlContext::Start);
        assert!(result.completions.iter().any(|c| c.text == "SELECT"));
    }

    #[test]
    fn test_complete_after_select() {
        let result = complete("SELECT ", 7);
        assert_eq!(result.context, BqlContext::AfterSelect);
        assert!(result.completions.iter().any(|c| c.text == "account"));
        assert!(result.completions.iter().any(|c| c.text == "SUM("));
    }

    #[test]
    fn test_complete_after_where() {
        let result = complete("SELECT * WHERE ", 15);
        assert_eq!(result.context, BqlContext::AfterWhere);
        assert!(result.completions.iter().any(|c| c.text == "account"));
    }

    #[test]
    fn test_complete_in_where_expr() {
        let result = complete("SELECT * WHERE account ", 23);
        assert_eq!(result.context, BqlContext::InWhereExpr);
        assert!(result.completions.iter().any(|c| c.text == "="));
        assert!(result.completions.iter().any(|c| c.text == "~"));
    }

    #[test]
    fn test_complete_group_by() {
        let result = complete("SELECT * GROUP ", 15);
        assert_eq!(result.context, BqlContext::AfterGroup);
        assert!(result.completions.iter().any(|c| c.text == "BY"));
    }

    #[test]
    fn test_tokenize_bql() {
        let tokens = tokenize_bql("SELECT account, SUM(position)");
        assert_eq!(
            tokens,
            vec!["SELECT", "account", ",", "SUM", "(", "position", ")"]
        );
    }

    #[test]
    fn test_tokenize_bql_with_string() {
        let tokens = tokenize_bql("WHERE account ~ \"Expenses\"");
        assert_eq!(tokens, vec!["WHERE", "account", "~", "\"Expenses\""]);
    }

    #[test]
    fn test_tokenize_multi_char_operators() {
        let tokens = tokenize_bql("WHERE x >= 10 AND y != 5");
        assert!(tokens.contains(&">=".to_string()));
        assert!(tokens.contains(&"!=".to_string()));
    }
}