xmt-lib 0.1.1

A grounder for SMT solvers
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
// Copyright Pierre Carbonnelle, 2025.

use rusqlite::types::FromSql;
use rusqlite::{Connection, Result, Error};
use rusqlite::functions::{Context, FunctionFlags, Aggregate};

use crate::error::SolverError;

pub(crate) fn init_db(
    conn: &mut Connection
) -> Result<(), SolverError> {

    // create convenience function "apply"
    conn.create_scalar_function(
        "apply",
        -1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let (symbol, args) = get_symbol_args(ctx)?;
            Ok(format!("({} {})", symbol, args.join(" ")))
        },
    )?;

    // LINK src/doc.md#_Constructor
    // create convenience function "construct"
    // similar to "apply", but adds a space in front of the result,
    // to indicate that the result is an identifier
    conn.create_scalar_function(
        "construct",
        -1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let (symbol, args) = get_symbol_args(ctx)?;
            Ok(format!(" ({} {})", symbol, args.join(" ")))
        },
    )?;

    // LINK src/doc.md#_Constructor
    // create convenience function "construct"
    // similar to "construct", but adds a space in front of the result,
    // only when each argument is an id
    conn.create_scalar_function(
        "construct2",
        -1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let (symbol, args) = get_symbol_args(ctx)?;
            let all_ids = args.iter().all( |arg| ! arg.starts_with("(") );
            if all_ids {  // leading space
                Ok(format!(" ({} {})", symbol, args.join(" ")))
            } else {
                Ok(format!("({} {})", symbol, args.join(" ")))
            }
        },
    )?;

    // create function "not_"
    conn.create_scalar_function(
        "not_",
        1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let value = ctx.get::<String>(0)?;
            if value == "true" {
                Ok("false".to_string())
            } else if value == "false" {
                Ok("true".to_string())
            } else {
                Ok(format!("(not {})", value))
            }
        },
    )?;

    // create function "and_"
    conn.create_scalar_function(
        "and_",
        -1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let mut state = AndState(Some(vec![]));
            for i in 0..ctx.len() {
                if let AndState(Some(ref mut terms)) = state { // if not false already
                    let value = ctx.get::<String>(i)?;
                    if value == "false" {
                        state = AndState(None);
                        break
                    } else if value != "true" {
                        terms.push(value)
                    };
                }
            }
            // finalize
            if let AndState(Some(terms)) = state {  // not false
                if terms.len() == 0 {
                    Ok("true".to_string())
                } else if terms.len() == 1 {
                    Ok(terms.join(" "))  // get the first one
                } else {
                    Ok(format!("(and {})", terms.join(" ")))
                }
            } else {
                Ok("false".to_string())
            }
        },
    )?;

    // create function "or_"
    conn.create_scalar_function(
        "or_",
        -1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let mut state = OrState(Some(vec![]));
            for i in 0..ctx.len() {
                if let OrState(Some(ref mut terms)) = state { // if not true already
                    let value = ctx.get::<String>(i)?;
                    if value == "true" {
                        state = OrState(None);
                        break
                    } else if value != "false" {
                        terms.push(value)
                    };
                }
            }
            // finalize
            if let OrState(Some(terms)) = state {  // not false
                if terms.len() == 0 {
                    Ok("false".to_string())
                } else if terms.len() == 1 {
                    Ok(terms.join(" "))  // get the first one
                } else {
                    Ok(format!("(or {})", terms.join(" ")))
                }
            } else {
                Ok("true".to_string())
            }
        },
    )?;

    // create function "implies_"
    conn.create_scalar_function(
        "implies_",
        2,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let a1 = ctx.get::<String>(0)?;
            let a2 = ctx.get::<String>(1)?;

            if a1 == "true" {
                Ok(a2.to_string())
            } else if a1 == "false" {
                Ok("true".to_string())
            } else if a2 == "true" {
                Ok("true".to_string())
            } else if a2 == "false" {
                Ok(format!("(not {})", a1))
            } else {
                Ok(format!("(=> {} {})", a1, a2))
            }
        },
    )?;

    // // create function "is_id"
    conn.create_scalar_function(
        "is_id",
        1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC, // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let value = ctx.get_raw(0);
            match value {
                rusqlite::types::ValueRef::Null =>
                    Err(Error::InvalidFunctionParameterType(0, value.data_type())),
                rusqlite::types::ValueRef::Integer(_) =>{
                    Ok(true)
                },
                rusqlite::types::ValueRef::Real(_) => {
                    Ok(true)
                },
                rusqlite::types::ValueRef::Text(_) => {
                    let value = ctx.get::<String>(0)?;
                    Ok(! value.starts_with("("))
                }
                rusqlite::types::ValueRef::Blob(_) =>
                    Err(Error::InvalidFunctionParameterType(0, value.data_type())),
            }
        },
    )?;

    // create function "if_" : `is_id(a1) OR a1 == a2` in SMT-Lib
    conn.create_scalar_function(
        "if_",
        2,
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
        |ctx| {
            let value = ctx.get_raw(0);
            match value {
                rusqlite::types::ValueRef::Null =>
                    Err(Error::InvalidFunctionParameterType(0, value.data_type())),
                rusqlite::types::ValueRef::Integer(_) =>
                    bool_to_sql(true),
                rusqlite::types::ValueRef::Real(_) =>
                    bool_to_sql(true),
                rusqlite::types::ValueRef::Text(_) => {
                    let value = ctx.get::<String>(0)?;
                    if ! value.starts_with("(") {  // an id
                        bool_to_sql(true)
                    } else {
                        if let Ok(col) = ctx.get::<String>(1) {
                            Ok(format!("(= {value} {col})"))
                        } else {  // col may be null
                            bool_to_sql(false)
                        }
                    }
                },
                rusqlite::types::ValueRef::Blob(_) =>
                    Err(Error::InvalidFunctionParameterType(0, value.data_type())),
            }
        })?;

        // create function "bool_eq_".
        // The first argument is the default value for NULL arguments.
        conn.create_scalar_function(  // LINK src/doc.md#_Equality
            "bool_eq_",
            -1,                     // Number of arguments the function takes
            FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
            |ctx| {                // The function logic
                let args = get_args_default(ctx)?;
                if args.len() == 2 {  // most frequent case
                    if args[0] == args[1] {  // they might not be ids !
                        Ok("true".to_string())
                    } else if is_id(&args[0]) && is_id(&args[1]) {
                        Ok("false".to_string())
                    } else {
                        Ok(format!("(= {})", args.join(" ")))
                    }
                } else {
                    // if two ids are different, return false
                    // otherwise, if all are ids, return true
                    // else return the equality
                    let mut last_id: Option<&String> = None;
                    let mut all_ids = true;
                    for arg in &args {
                        if is_id(arg) {
                            if let Some(last_id) = last_id {
                                if *last_id != *arg {
                                    return Ok("false".to_string())
                                }
                            } else {
                                last_id = Some(arg)
                            }
                        } else {
                            all_ids = false;
                        }
                    }
                    if all_ids {
                        Ok("true".to_string())
                    } else {
                        Ok(format!("(= {})", args.join(" ")))
                    }
                }
            },
        )?;

    // create function "eq_"
    conn.create_scalar_function(  // LINK src/doc.md#_Equality
        "eq_",
        -1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let args = get_args(ctx)?;
            if args.len() == 2 {  // most frequent case
                if args[0] == args[1] {  // they might not be ids !
                    Ok("true".to_string())
                } else if is_id(&args[0]) && is_id(&args[1]) {
                    Ok("false".to_string())
                } else {
                    Ok(format!("(= {})", args.join(" ")))
                }
            } else {
                // if two ids are different, return false
                // otherwise, if all are ids, return true
                // else return the equality
                let mut last_id: Option<&String> = None;
                let mut all_ids = true;
                for arg in &args {
                    if is_id(arg) {
                        if let Some(last_id) = last_id {
                            if *last_id != *arg {
                                return Ok("false".to_string())
                            }
                        } else {
                            last_id = Some(arg)
                        }
                    } else {
                        all_ids = false;
                    }
                }
                if all_ids {
                    Ok("true".to_string())
                } else {
                    Ok(format!("(= {})", args.join(" ")))
                }
            }
        },
    )?;

    conn.create_scalar_function(
        "compare_",
        -1,
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
        |ctx| {
            // split args into strs, ints, reals values
            // raise error if both ints and reals
            // compare ints and return false if incorrect
            // compare reals and return false if incorrect
            // return true if no strs
            // return apply to all args
            let operator: String = ctx.get(0)?;

            // split args into strs, ints, reals values
            // raise error if both ints and reals
            let mut args = vec![];
            let mut strs = vec![];
            let mut ints = vec![];
            let mut reals = vec![];
            for i in 1..ctx.len() {
                let value = ctx.get_raw(i);
                match value {
                    rusqlite::types::ValueRef::Null =>
                        return Err(Error::InvalidFunctionParameterType(i, value.data_type())),
                    rusqlite::types::ValueRef::Integer(val) => {
                        if 0 < reals.len() {
                            return Err(Error::InvalidFunctionParameterType(i, value.data_type()))
                        }
                        args.push(val.to_string());
                        ints.push(val);
                    }
                    rusqlite::types::ValueRef::Real(val) => {
                        if 0 < ints.len() {
                            return Err(Error::InvalidFunctionParameterType(i, value.data_type()))
                        }
                        args.push(val.to_string());
                        reals.push(val);
                    }
                    rusqlite::types::ValueRef::Text(_) => {
                        let val = ctx.get::<String>(i)?;
                        args.push(val.clone());
                        if let Ok(val) = val.parse::<i64>() {
                            ints.push(val)
                        } else if let Ok(val) = val.parse::<f64>() {
                            reals.push(val)
                        } else {
                            strs.push(val)
                        }
                    }
                    rusqlite::types::ValueRef::Blob(_) =>
                        return Err(Error::InvalidFunctionParameterType(i, value.data_type())),
                }
            }

            // compare ints and return false if incorrect
            for (a, b) in ints.iter().zip(ints.iter().skip(1)) {
                let result = match operator.as_str() {
                    "<" => a < b,
                    "<=" => a <= b,
                    ">" => a > b,
                    ">=" => a >= b,
                    _ => return Err(Error::InvalidParameterName(operator))
                };
                if ! result {
                    return Ok("false".to_string())
                }
            }

            // compare reals and return false if incorrect
            for (a, b) in reals.iter().zip(reals.iter().skip(1)) {
                let result = match operator.as_str() {
                    "<" => a < b,
                    "<=" => a <= b,
                    ">" => a > b,
                    ">=" => a >= b,
                    _ => return Err(Error::InvalidParameterName(operator))
                };
                if ! result {
                    return Ok("false".to_string())
                }
            }

            // return true if no strs
            // else return apply to all args
            if strs.len() == 0 {
                Ok("true".to_string())
            } else {
                Ok(format!("({} {})", operator, args.join(" ")))
            }
        })?;

    // left_ associative: + - * div
    conn.create_scalar_function(
        "left_",
        -1,
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
        |ctx| {
            let operator: String = ctx.get(0)?;

            // split args into strs, ints, reals values
            // raise error if both ints and reals
            let mut args = vec![];
            let mut strs = vec![];
            let mut ints = vec![];
            let mut reals = vec![];
            for i in 1..ctx.len() {
                let value = ctx.get_raw(i);
                match value {
                    rusqlite::types::ValueRef::Null =>
                        return Err(Error::InvalidFunctionParameterType(i, value.data_type())),
                    rusqlite::types::ValueRef::Integer(val) => {
                        if 0 < reals.len() {
                            return Err(Error::InvalidFunctionParameterType(i, value.data_type()))
                        }
                        args.push(val.to_string());
                        ints.push(val);
                    }
                    rusqlite::types::ValueRef::Real(val) => {
                        if 0 < ints.len() {
                            return Err(Error::InvalidFunctionParameterType(i, value.data_type()))
                        }
                        args.push(val.to_string());
                        reals.push(val);
                    }
                    rusqlite::types::ValueRef::Text(_) => {
                        let val = ctx.get::<String>(i)?;
                        args.push(val.clone());
                        strs.push(val);
                    }
                    rusqlite::types::ValueRef::Blob(_) =>
                        return Err(Error::InvalidFunctionParameterType(i, value.data_type())),
                }
            }

            // reduce literals
            if 0 < ints.len() {
                match operator.as_str() {
                    "+" => {
                        let val = ints.into_iter().sum::<i64>();
                        if val != 0 || strs.len() == 0 {
                            strs.push(val.to_string())
                        }
                    },
                    "-" => {
                        if let rusqlite::types::ValueRef::Integer(val) = ctx.get_raw(1) {
                            if ints.len() + strs.len() == 1 {  // (- 2)
                                return Ok((-val).to_string())
                            }
                            let mut acc = val;
                            for i in ints.iter().skip(1) {
                                acc -= i;
                            };
                            if acc != 0 || strs.len() == 0 {
                                strs.insert(0, acc.to_string())
                            }
                        } else {
                            let mut acc = 0;
                            for i in ints.iter().skip(1) {
                                acc += i;
                            };
                            if acc != 0 || strs.len() == 0 {
                                strs.push(acc.to_string())
                            }
                        }
                    }
                    "*" => {
                        let val = ints.into_iter().product::<i64>();
                        if val != 1 || strs.len() == 0 {
                            strs.push(val.to_string())
                        }
                    },
                    "div" => {
                        if let rusqlite::types::ValueRef::Integer(val) = ctx.get_raw(1) {
                            let mut acc = val;
                            for i in ints.iter().skip(1) {
                                acc /= i;
                            };
                            if acc != 1 || strs.len() == 0 {
                                strs.insert(0, acc.to_string())
                            }
                        } else {
                            let mut acc = 1;
                            for i in ints.iter().skip(1) {
                                acc *= i;
                            };
                            if acc != 1 || strs.len() == 0 {
                                strs.push(acc.to_string())
                            }
                        }
                    }
                    "mod" => {
                        if let [a, b] = &ints[..] {
                            return Ok((a % b).to_string())
                        } else if let rusqlite::types::ValueRef::Integer(val) = ctx.get_raw(1) {
                            strs.insert(0, val.to_string())
                        } else if let rusqlite::types::ValueRef::Integer(val) = ctx.get_raw(2){
                            strs.push(val.to_string())
                        } else {
                            unreachable!()
                        }
                    }
                    _ => unreachable!()
                }
            }

            if 0 < reals.len() {
                match operator.as_str() {
                    "+" => {
                        let val = reals.into_iter().sum::<f64>();
                        if val != 0.0 || strs.len() == 0 {
                            strs.push(val.to_string())
                        }
                    },
                    "-" => {
                        if let rusqlite::types::ValueRef::Real(val) = ctx.get_raw(1) {
                            if reals.len() + strs.len()  == 1 {  // (- 2.0)
                                return Ok((-val).to_string())
                            }
                            let mut acc = val;
                            for i in reals.iter().skip(1) {
                                acc -= i;
                            };
                            if acc != 0.0 || strs.len() == 0 {
                                strs.insert(0, acc.to_string())
                            }
                        } else {
                            let mut acc = 0.0;
                            for i in reals.iter().skip(1) {
                                acc += i;
                            };
                            if acc != 0.0 || strs.len() == 0 {
                                strs.push(acc.to_string())
                            }
                        }
                    }
                    "*" => {
                        let val = reals.into_iter().product::<f64>();
                        if val != 1.0 || strs.len() == 0 {
                            strs.push(val.to_string())
                        }
                    },
                    "div" => {
                        if let rusqlite::types::ValueRef::Real(val) = ctx.get_raw(1) {
                            let mut acc = val;
                            for i in reals.iter().skip(1) {
                                acc /= i;
                            };
                            if acc != 1.0 || strs.len() == 0 {
                                strs.insert(0, acc.to_string())
                            }
                        } else {
                            let mut acc = 1.0;
                            for i in reals.iter().skip(1) {
                                acc *= i;
                            };
                            if acc != 1.0 || strs.len() == 0 {
                                strs.push(acc.to_string())
                            }
                        }
                    }
                    _ => unreachable!()
                }
            }

            if strs.len() == 1 {
                Ok(strs.join(" "))
            } else {
                Ok(format!("({} {})", operator, strs.join(" ")))
            }
        })?;

    // create function "abs_"
    conn.create_scalar_function(
        "abs_",
        1,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let value = ctx.get_raw(0);
            match value {
                rusqlite::types::ValueRef::Null =>
                    return Err(Error::InvalidFunctionParameterType(0, value.data_type())),
                rusqlite::types::ValueRef::Integer(val) =>
                    Ok(val.abs().to_string()),
                rusqlite::types::ValueRef::Real(val) =>
                    Ok(val.abs().to_string()),
                rusqlite::types::ValueRef::Text(_) => {
                    let value = ctx.get::<String>(0)?;
                    Ok(format!("(abs {})", value))
                }
                rusqlite::types::ValueRef::Blob(_) =>
                    return Err(Error::InvalidFunctionParameterType(0, value.data_type())),
            }
        },
    )?;

    // create function "ite_"
    conn.create_scalar_function(
        "ite_",
        3,                     // Number of arguments the function takes
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,                  // Deterministic (same input gives same output)
        |ctx| {                // The function logic
            let args = get_args(ctx)?;
            let (if_, left, right) = (&args[0], &args[1], &args[2]);
            if *if_ == "true" {
                Ok(left.to_string())
            } else if *if_ == "false" {
                Ok(right.to_string())
            } else if left == right {  // condition is irrelevant
                Ok(left.to_string())
            } else {
                Ok(format!("(ite {if_} {left} {right})"))
            }
        },
    )?;

    conn.create_aggregate_function(
        "and_aggregate",
        1,
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
        AndState(None))?;  // `init` will be called

    conn.create_aggregate_function(
        "or_aggregate",
        1,
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
        OrState(None))?;  // `init` will be called

    Ok(())
}


//////////////////////////// AND aggregate ////////////////////////////////////

#[derive(Default, Clone)]
struct AndState ( Option<Vec<String>> );

/// Implement the `Aggregate` trait for `SumSquares`
impl Aggregate<AndState, String> for AndState {

    fn init(&self, _ctx: &mut Context<'_>)  -> Result<AndState> {
        Ok(AndState(Some(vec![])))
    }
    /// Called for each row in the query
    fn step(&self, ctx: &mut Context<'_>, acc: &mut AndState) -> rusqlite::Result<()> {
        let value: String = ctx.get(0)?;
        if let AndState(Some(terms)) = acc { // if not false already
            if value == "false" {
                *acc = AndState(None)
            } else if value != "true" {
                terms.push(value)
            };
        }
        Ok(())
    }

    /// Called at the end to return the final result
    fn finalize(&self, _ctx: &mut Context<'_>, acc: Option<AndState>) -> rusqlite::Result<String> {
        if let Some(AndState(Some(terms))) = acc {  // not false
            if terms.len() == 0 {
                Ok("true".to_string())
            } else if terms.len() == 1 {
                Ok(terms.join(" "))  // get the first one
            } else {
                Ok(format!("(and {})", terms.join(" ")))
            }
        } else {
            Ok("false".to_string())
        }
    }
}


//////////////////////////// OR aggregate ////////////////////////////////////

#[derive(Default, Clone)]
struct OrState ( Option<Vec<String>> );

/// Implement the `Aggregate` trait for `SumSquares`
impl Aggregate<OrState, String> for OrState {

    fn init(&self, _ctx: &mut Context<'_>)  -> Result<OrState> {
        Ok(OrState(Some(vec![])))
    }
    /// Called for each row in the query
    fn step(&self, ctx: &mut Context<'_>, acc: &mut OrState) -> rusqlite::Result<()> {
        let value: String = ctx.get(0)?;
        if let OrState(Some(terms)) = acc { // if not true already
            if value == "true" {
                *acc = OrState(None)
            } else if value != "false" {
                terms.push(value)
            };
        }
        Ok(())
    }

    /// Called at the end to return the final result
    fn finalize(&self, _ctx: &mut Context<'_>, acc: Option<OrState>) -> rusqlite::Result<String> {
        if let Some(OrState(Some(terms))) = acc {  // not true
            if terms.len() == 0 {
                Ok("false".to_string())
            } else if terms.len() == 1 {
                Ok(terms.join(" "))
            } else {
                Ok(format!("(or {})", terms.join(" ")))
            }
        } else {
            Ok("true".to_string())
        }
    }
}


/// get the symbol and args from the context
fn get_symbol_args (ctx: &Context) -> Result<(String, Vec<String>), Error> {
    let symbol: String = ctx.get(0)?; // Get the string
    let args: Vec<String> = (1..ctx.len())
        .map(|i| {
            let value = ctx.get_raw(i);
            match value {
                rusqlite::types::ValueRef::Null =>
                    Err(Error::InvalidFunctionParameterType(i, value.data_type())),
                rusqlite::types::ValueRef::Integer(i) =>
                    Ok(i.to_string()),
                rusqlite::types::ValueRef::Real(r) =>
                    Ok(r.to_string()),
                rusqlite::types::ValueRef::Text(_) =>
                    FromSql::column_result(value)
                        .map_err(|_| Error::InvalidFunctionParameterType(i, value.data_type())),
                rusqlite::types::ValueRef::Blob(_) =>
                    Err(Error::InvalidFunctionParameterType(i, value.data_type())),
            }
        }).collect::<Result<_, Error>>()?;     // Collect results or propagate errors
    Ok((symbol, args))
}

/// get the args from the context
fn get_args (ctx: &Context) -> Result<Vec<String>, Error> {
    let args: Vec<String> = (0..ctx.len())
        .map(|i| {
            let value = ctx.get_raw(i);
            match value {
                rusqlite::types::ValueRef::Null =>
                    Err(Error::InvalidFunctionParameterType(i, value.data_type())),
                rusqlite::types::ValueRef::Integer(i) =>
                    Ok(i.to_string()),
                rusqlite::types::ValueRef::Real(r) =>
                    Ok(r.to_string()),
                rusqlite::types::ValueRef::Text(_) =>
                    FromSql::column_result(value)
                        .map_err(|_| Error::InvalidFunctionParameterType(i, value.data_type())),
                rusqlite::types::ValueRef::Blob(_) =>
                    Err(Error::InvalidFunctionParameterType(i, value.data_type())),
            }
        }).collect::<Result<_, Error>>()?;     // Collect results or propagate errors
    Ok(args)
}

/// get the args from the context.  The first argument is the default value for NULL arguments.
fn get_args_default (ctx: &Context) -> Result<Vec<String>, Error> {
    let mut default = "".to_string();
    let args: Vec<String> = (0..ctx.len())
        .filter_map(|i| {
            let value = ctx.get_raw(i);
            let value = match value {
                rusqlite::types::ValueRef::Null =>
                    Ok(default.clone()),
                rusqlite::types::ValueRef::Integer(i) =>
                    Ok(i.to_string()),
                rusqlite::types::ValueRef::Real(r) =>
                    Ok(r.to_string()),
                rusqlite::types::ValueRef::Text(_) =>
                    ctx.get::<String>(i),
                rusqlite::types::ValueRef::Blob(_) =>
                    Err(Error::InvalidFunctionParameterType(i, value.data_type())),
            };
            if i == 0 {
                default = value.unwrap_or_else(|_| "".to_string());
                None
            } else {
                Some(value)
            }
        }).collect::<Result<_, Error>>()?;     // Collect results or propagate errors
    Ok(args)
}

#[inline]
fn is_id(value: &str) -> bool {
    ! value.starts_with("(")
}
#[inline]
fn bool_to_sql(b: bool) -> Result<String, Error> {
    if b { Ok("true".to_string()) }
    else { Ok("false".to_string()) }
}