af_path 0.2.3

path查询语言库
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
extern crate serde_json;

use std::rc::Rc;
use crate::json::{Table, Field};
use std::collections::HashMap;

use syn::__private::TokenStream2;
use iso8601;

// path语法解析出来的语法节点
#[derive(Debug)]
pub enum Expression {
    // 查询(查询类型,表名,过滤条件,选择内容)
    // 查询类型有:数据库,变量,子查询
    // 表名可以为空,以便支持对表本身做聚集处理
    // 选择内容比较复杂,单独表示了
    // 过滤条件支持多次过滤,所以是数组
    Query(QueryType, Option<syn::Ident>, Vec<Expression>, Box<Select>),
    // 二元操作符(操作符,左操作数,右操作数)
    Binary(String, Box<Expression>, Box<Expression>),
    // if条件表达式(if条件,if内容,else内容)
    Cond(Box<Expression>, Box<Expression>, Box<Expression>),
    // 常数
    Lit(syn::Lit),
    // 变量
    Ident(syn::Ident),
    // 变量定义(变量名,变量类型)
    Var(String, String),
    // 范围,用rust的范围表示
    Range(syn::ExprRange),
    // ()包围的表达式,转换时,要再次加上(),保证优先级
    Expr(Box<Expression>),
    // 函数调用(函数名,参数表达式)
    Call(syn::Ident, Vec<Expression>),
    // 函数声明(函数名,表达式)
    Func(syn::Ident, Box<Expression>),
    // 取参数值(参数名)
    ParamValue(String),
    // 程序,一批语句
    Program(Vec<Expression>),
    // 参数声明,包含一批变量
    Params(Vec<Expression>),

    // 以下语法单元用于中间解析过程,最终语法树不会出现。
    // 带操作数的操作符,用于解析过程。中间过程。
    OperOne(String, Box<Expression>),
    // 名称及表达式
    Attr(syn::Ident, Box<Expression>),
}

impl Expression {
    // 获取临时操作的操作符及表达式
    pub fn to_oper_one(self) -> (String, Expression) {
        match self {
            Expression::OperOne(oper, exp) => (oper, *exp),
            _ => panic!("只有临时操作才能转")
        }
    }

    // 获取临时操作的属性表示
    pub fn to_attr(self) -> (syn::Ident, Box<Expression>) {
        match self {
            Expression::Attr(ident, exp) => (ident, exp),
            _ => panic!("只有属性才能转")
        }
    }
}

// query类型
#[derive(Debug, Clone)]
pub enum QueryType {
    // query是全局数据库类型
    Database,
    // query是当前的某个迭代变量
    Var,
    // query是子查询
    Sub,
}

// select的选择内容
#[derive(Debug)]
pub enum Select {
    // 最终要显示的内容,每个包括别名
    // (是否迭代本身聚集,Vec<别名,表达式>)
    Selects(bool, Vec<(syn::Ident, Expression)>),
    // 聚集函数,包括聚集函数名,及对应表达式,只能是一个
    Agg(syn::Ident, Option<Expression>),
    // 一对多关系的属性,不需要别名,只包括属性名
    Field(syn::Ident)
}

impl Select {
    // 看是否聚集查询过程
    fn is_total(&self) -> bool {
        match &self {
            Select::Selects(is_total, _exps) => *is_total,
            _ => false
        }
    }

    // 看是否有一批选择内容
    fn is_selects(&self) -> bool {
        match &self {
            Select::Selects(_, exps) => !exps.is_empty(),
            _ => false
        }
    }

    // 取一般选择内容,如果不是一般选择,返回错误
    fn selects(&self) -> Result<&Vec<(syn::Ident, Expression)>, String> {
        match &self {
            Select::Selects(_, exps) => Ok(&exps),
            _ => Err(format!("必须是一般选择内容, {:?}", &self))
        }
    }
}

/// 表达式的数据类型, 用于进行类型推断
#[derive(Debug)]
pub enum Type<'a> {
    // 浮点数
    Double,
    // 整形数
    Int,
    // bool值
    Bool,
    // 字符串
    String,
    // 日期
    Datetime,
    // 无法推断
    Unknown,
    // 另外一个表,具体内容用json对象表示
    Json(&'a Table),
    // 无值
    None,
}

impl<'a> Type<'a> {
    // 一对多关系,进行空值判断时,字符串要加‘&’,数字型不加
    fn has_borrow(&self) -> TokenStream2 {
        if let Type::String = self {
            quote! {&}
        } else {
            quote! {}
        }
    }

    // 获取对应类型的默认值代码,用于一对多关系时,有空值的情况
    fn default(&self) -> TokenStream2 {
        match self {
            Type::Double => quote! {0.0},
            Type::Int => quote! {0},
            Type::Bool => quote! {false},
            Type::String => quote! {""},
            Type::Datetime => quote! {0},
            _ => panic!("无法得到默认值:{:?}", self),
        }
    }
}

// 把程序转换成代码片段
// exp: ast语法树
// del: 系统定义的函数表,是系统定义的函数,标识符前不加x
// json: json格式定义的属性,根据属性定义的类型在查询路径上确定表达式类型
// config: 全局的数据库表定义,在语法树遍历过程中不动,用于从全局配置获取从表的字段定义
// 返回:(
//      rust代码
//      类型推断:推断出来的类型要在求和等聚集函数中使用
//      可为空的字段名:一对一关系有可能为空,为空时,选择内容变为空值
//pub fn to_exp<'a>(exp: &Expression, 
    del: &mut HashMap<String, Rc<Type<'a>>>,
    json: Option<&Table>, config: &'a HashMap<String, Table>
) -> (TokenStream2, Rc<Type<'a>>, Vec<TokenStream2>) {
    match exp {
        // 如果是程序,调用程序中的每一个语句处理过程
        Expression::Program(exps) => {
            // 保存可以为空的字段内容
            let mut nulls = Vec::new();
            let gen: TokenStream2 = exps.iter().map(|v| {
                let (one_exp, _, mut null) = to_exp(v, del, json, config);
                nulls.append(&mut null);
                one_exp
            }).collect();
            (gen, Rc::new(Type::Unknown), nulls)
        },        
        // 如果是函数声明,产生函数声明过程
        Expression::Func(name, exp) => {
            let (one_exp, ty, nulls) = to_exp(exp, del, json, config);
            let gen = quote! {
                let #name = #one_exp;
            };
            // 把变量定义的类型添加到变量表中,以便使用变量时知道类型
            del.insert(name.to_string(), Rc::clone(&ty));
            (gen, Rc::new(Type::None), nulls)
        },
        Expression::Query(q_type, name, cond, selects) => {
            to_query(q_type, name, cond, selects.as_ref(), del, json, config)
        },
        // 常数,直接转换
        Expression::Lit(lit) => {
            let gen = match lit {
                // 字符串,日期格式,转换成日期
                syn::Lit::Str(lit_str) => {
                    let str = lit_str.value();
                    // 满足日期格式,转换成日期,否则,原样输出
                    if is_datetime(&str) {
                        quote! { LocalDateTime::from_str(#str).expect("日志格式错误") }
                    } else {
                        quote! { #lit }
                    }
                },
                // 非字符串,直接输出
                _ => quote! { #lit }
            };

            // 根据常数类型进行类型推断
            let ty = match lit {
                syn::Lit::Str(_) => Type::String,
                syn::Lit::Int(_) => Type::Int,
                syn::Lit::Float(_) => Type::Double,
                syn::Lit::Bool(_) => Type::Bool,
                _ => panic!("不识别的常量, {:?}", lit)
            };

            (gen, Rc::new(ty), Vec::new())
        },
        // 变量,直接转换
        Expression::Ident(ident) => {
            // 变量值不好推导,按未知处理
            (quote! { #ident }, Rc::new(Type::Unknown), Vec::new())
        },
        // 二元操作符,递归转换
        Expression::Binary(op, left, right) => {
            let (left, ty, mut l_nulls) = to_exp(&left, del, json, config);
            let (right, _, mut r_nulls) = to_exp(&right, del, json, config);
            let op = to_oper(&op);
            // 类型推断,暂时按左边的算
            // 可以为空的字段为左右之和
            let mut nulls = Vec::new();
            nulls.append(&mut l_nulls);
            nulls.append(&mut r_nulls);
            (quote! { #left #op #right }, ty, nulls)
        },
        // if条件表达式,直接产生if的结果
        Expression::Cond(if_cond, if_exp, else_exp) => {
            // 把if条件,if内容,else内容全部转换成rust代码
            let (if_cond, ty, mut cond_null) = to_exp(&if_cond, del, json, config);
            let (if_exp, _, mut if_null) = to_exp(&if_exp, del, json, config);
            let (else_exp, _, mut else_null) = to_exp(&else_exp, del, json, config);
            // 返回完整条件表达式代码
            let gen = quote! { 
                if #if_cond { #if_exp } else { #else_exp }
            };
            // 条件表达式的类型,按if部分内容定
            // 可以为空字段,为各部分之和
            let mut nulls = Vec::new();
            nulls.append(&mut cond_null);
            nulls.append(&mut if_null);
            nulls.append(&mut else_null);
            (gen, ty, nulls)
        },
        // ()里内容,要输出(),保证优先级
        Expression::Expr(exp) => {
            let (result, ty, nulls) = to_exp(&exp, del, json, config);
            (quote! { (#result) }, ty, nulls)
        },
        // 函数调用
        Expression::Call(ident, params) => {
            // 可为空的内容,为各表达式之和
            let mut nulls = Vec::new();
            // 对参数进行转换
            let (rel_params, _) = params.iter().fold( (quote!{}, 0), |(acc, i), v| {
                let (value, _, mut null) = to_exp(&v, del, json, config);
                nulls.append(&mut null);
                if i == 0 {
                    (quote! { #value }, i + 1)
                } else {
                    (quote! { #acc, #value }, i + 1)
                }
            });
            (quote! { #ident(#rel_params) }, Rc::new(Type::Unknown), nulls)
        },
        // 取参数值,转换成参数取值过程
        Expression::ParamValue(name_str) => {
            let name: syn::Ident = syn::parse_str(name_str).expect("变量名不合法");
            let p_name: syn::Ident = syn::parse_str(&format!("p_{}", name_str)).expect("变量名不合法");
            // 如果是取参数的原值,按名字获取,否则,添加上p_前缀
            if name_str.starts_with("s_") {
                (quote! { #name }, Rc::new(Type::Unknown), Vec::new())
            } else {
                (quote! { #p_name }, Rc::new(Type::Unknown), Vec::new())
            }
        },
        // 参数变量定义
        Expression::Var(name_str, ty) => {
            let s_name: syn::Ident = syn::parse_str(&format!("s_{}", name_str)).expect("变量名不合法");
            let p_name: syn::Ident = syn::parse_str(&format!("p_{}", name_str)).expect("变量名不合法");
            // 取原始内容,原始内容必须是字符串
            let s_value = quote! {
                params[#name_str].as_str().expect(&format!("参数不存在, {}, {:?}", #name_str, params))
            };
            // 根据字段类型,产生从参数中取值的代码
            let value = get_value(&s_name, ty);
            // 变量名前面加p_,原始的字符串内容,变量名前加s_
            let gen = quote! {
                // 原始值
                let #s_name = #s_value;
                // 转换后的值
                let #p_name = #value;
            };
            (gen, Rc::new(Type::None), Vec::new())
        },
        // 参数定义表的处理
        Expression::Params(exps) => {
            // 可以为空的内容,为各表达式之和
            let mut nulls = Vec::new();
            let gen = exps.iter().fold(quote!{}, |acc, x| {
                let (one_gen, _, mut null) = to_exp(x, del, json, config);
                nulls.append(&mut null);
                quote! { #acc #one_gen }
            });
            (gen, Rc::new(Type::None), nulls)
        },
        Expression::Range(_) => {
            let err = format!("quey查询中的表达式不可能出现这个语法结构, {:?}", exp);
            panic!("{}", err)
        },
        // 临时节点不能出现
        Expression::OperOne(_, _) | Expression::Attr(_, _) => panic!("None不能在表达式中出现"),
    }
}
    
// 把表达式转换成query代码片段
// q_type: 查询类型,数据库类型,从全局数据库中取,变量类型,取变量名字,子类型,取名字
// name: 查询的名字,如果是取迭代的聚集内容,会没有
// cond: 查询条件部分
// selects: 查询的选择部分
// table_op: 上层数据库表,如果是最上层的全局数据库,这个值为空
fn to_query<'a>(q_type: &QueryType, name: &Option<syn::Ident>, cond: &Vec<Expression>, selects: &Select, 
    del: &mut HashMap<String, Rc<Type<'a>>>, 
    table_op: Option<&Table>, config: &'a HashMap<String, Table>
) -> (TokenStream2, Rc<Type<'a>>, Vec<TokenStream2>) {
    // 取得名称部分代码
    let (name_gen, name_iter) = to_name(q_type, name);

    // 如果select是聚集查询,得按迭代自身处理方式,进行处理
    if selects.is_total() {
        let ty = get_type(table_op, &name.as_ref().expect("聚集查询有空值").to_string(), config, del, q_type);

        // 取过滤条件
        // 如果类型是另一个表,做过滤过程,否则,不做
        let filter_exp = if let Type::Json(ref json) = *ty {
            to_conds(&cond, del, json, config)
        } else {
            quote!{}
        };
        
        // 获得select部分的函数集
        let select_exp = if let Type::Json(ref json) = *ty {
            to_agg_selects(&selects.selects().expect("必须是一般选择内容"), del, json, config)
        } else {
            panic!("取聚集值必须有表")
        };

        // 变量形式的query,不会有迭代
        let has_iter = if let QueryType::Var = q_type {
            quote! {}
        } else if name_iter {
            quote! {.iter()}            
        } else {
            quote! {}
        };

        let gen = quote! {
            let x = #name_gen#has_iter#filter_exp;
            #select_exp
            select(vec![result])
        };
        (gen, Rc::new(Type::Unknown), Vec::new())
    }
    // 有名字,按正常query处理
    else if let Some(name) = name {    
        let ty = get_type(table_op, &name.to_string(), config, del, q_type);

        // 取过滤条件
        // 如果类型是另一个表,做过滤过程,否则,不做
        let filter_exp = if let Type::Json(ref json) = *ty {
            to_conds(&cond, del, json, config)
        } else {
            quote!{}
        };
        
        // 取选择内容
        // 如果类型是另一个表,做表的选择过程,否则,不做
        let (select_exp, has_agg, proc_null, select_type) = if let Type::Json(ref json) = *ty {
            to_select(q_type, &selects, del, json, config)
        } else {
            (quote!{}, false, false, Rc::new(Type::Unknown))
        };
        
        // 变量形式的query,不会有迭代
        let has_iter = if let QueryType::Var = q_type {
            quote! {}
        }
        // 如果有过滤,或者选择,或者聚集函数,均需要加上迭代调用
        else if (!cond.is_empty() || has_agg) && name_iter {
            quote! { .iter() }
        } else {
            quote! {}
        };

        // 是否要处理空值,该内容会返回
        let mut nulls = Vec::new();

        // 如果要处理空值,把要处理的空值传出去,以便最上层进行空值处理
        let mut gen = if proc_null {
            nulls.push(quote! { x.#name });
            // 获取空值时的默认值
            let default_gen = select_type.default();
            // 字符串需要加&符号
            let has_borrow = select_type.has_borrow();

            quote! {
                (match &#name_gen {
                    Some(x) => #has_borrow x#has_iter#filter_exp#select_exp,
                    // 空值,根据字段类型返回默认值
                    None => #default_gen,
                })
            }
        } else {
            quote! { #name_gen#has_iter#filter_exp#select_exp }
        };

        // 如果有一批select,添加上select部分
        if selects.is_selects() {
            gen = quote! { select(#gen.collect()) };
        }

        (gen, ty, nulls)
    }
    // 如果没有名字,按聚集函数的选择处理
    else {
        let table = table_op.expect("聚集函数必须有上层table");
        let (select_exp, _has_agg, _proc_null, _) = to_select(q_type, &selects, del, &table, config);
        (quote! { x#select_exp }, Rc::new(Type::Unknown), Vec::new())
    }
}

// 根据query类型,取得名字部分的代码内容
fn to_name(q_type: &QueryType, name: &Option<syn::Ident>) -> (TokenStream2, bool) {
    match q_type {
        // 数据库,取全局数据库的表
        QueryType::Database => (quote! {DATABASE.#name.data.values()}, false),
        // 本地变量名,按原名输出
        QueryType::Var => (quote! {#name}, true),
        // 子查询,名字加'x.'
        QueryType::Sub => (quote! {x.#name}, true),
    }
}

// 把一批条件表达式转换成query的过滤过程
fn to_conds<'a>(exps: &Vec<Expression>, 
    del: &mut HashMap<String, Rc<Type<'a>>>,
    json: &Table, config: &'a HashMap<String, Table>
) -> TokenStream2 {
    // 对每一个表达式
    exps.iter().map(|exp| {
        match exp {
            // 如果是取范围,转换成取范围处理
            Expression::Range(range) => {
                // (起始语句, 起始数字) 起始数字用于计算获取个数
                let (start_gen, start_num) = match &range.from {
                    // 有开始,添加开始内容
                    Some(start) => (quote! { .skip(#start) }, quote! { #start }),
                    None => (quote! {}, quote! { 0 })
                };
                // 结束
                let end_gen = match &range.to {
                    // 有结束,添加结束内容,要把范围转换成获取的多少
                    Some(end) => quote! { .take(#end - #start_num) },
                    None => quote! {}
                };
                quote! { #start_gen#end_gen }
            },
            // 其它情况,调用表达式处理过程
            _ => {
                let (exp_gen, _, _nulls) = to_exp(&exp, del, Some(json), config);
                quote! { .filter(|x| {#exp_gen}) }
            }
        }
    }).collect::<TokenStream2>()
}

// 把选择内容转换成rust语句
// 返回:(rust语句, 是否需要加迭代, 是否需要处理空值,取属性时的类型)
fn to_select<'a>(q_type: &QueryType, select: &Select, 
    del: &mut HashMap<String, Rc<Type<'a>>>,
    json: &Table, config: &'a HashMap<String, Table>
) -> (TokenStream2, bool, bool, Rc<Type<'a>>) {
    match select {
        // 是聚集函数
        Select::Agg(agg, exp) => {
            (to_agg_select(&exp, &agg, del, json, config), true, false, Rc::new(Type::None))
        },
        // 是普通选择,按普通选择处理
        Select::Selects(_is_total, exps) => {
            if exps.is_empty() {
                (quote! {}, false, false, Rc::new(Type::None))
            } else {
                let select = to_selects(&exps, del, json, config);
                (quote! { .map(|x| {#select}) }, true, false, Rc::new(Type::None))
            }
        },
        // 是取属性,返回取属性过程
        Select::Field(field_name) => {
            // 返回属性类型
            let ty = get_type(Some(json), &field_name.to_string(), config, del, q_type);
            (quote! { .#field_name }, false, true, ty)
        }
    }
}

// 转换多个聚集的选择内容
fn to_agg_selects<'a>(exps: &Vec<(syn::Ident, Expression)>, 
    del: &mut HashMap<String, Rc::<Type<'a>>>,
    json: &Table, config: &'a HashMap<String, Table>
) -> TokenStream2 {
    // 调用每一个表达式处理过程,放到结果集中
    let gen: TokenStream2 = exps.iter().map(|(name, exp)| {
        let name_str = format!("\"{}\"", name.to_string());
        let (one_exp, _, _nulls) = to_exp(&exp, del, Some(json), config);
        // 没有为空情况下的rust代码
        let init = quote! { 
            format!("{:?}", #one_exp) 
        };
        quote! {
            result.push((#name_str, #init));
        }
    }).collect();

    quote! {
        let mut result: Vec<(&str, String)> = Vec::new();
        #gen
    }
}

// 把选择部分转换成query的转换函数,用于一般内容选择
// 选择部分包含别名及表达式两个部分
// @param nulls: 所有可能为空的表达式,有空值,选择内容插入null
fn to_selects<'a>(exps: &Vec<(syn::Ident, Expression)>, 
    del: &mut HashMap<String, Rc::<Type<'a>>>,
    json: &Table, config: &'a HashMap<String, Table>
) -> TokenStream2 {
    // 调用每一个表达式处理过程,放到结果集中
    let gen = exps.iter().map(|(name, exp)| {
        let name_str = format!("\"{}\"", name.to_string());
        let (one_exp, _, nulls) = to_exp(&exp, del, Some(json), config);
        // 没有为空情况下的rust代码
        let init = quote! { format!("{:?}", #one_exp) };
        // 添加上为空判断后的rust代码
        let one_exp = to_nulls(&nulls, init);
        quote! {
            result.push((#name_str, #one_exp));
        }
    }).collect::<TokenStream2>();

    quote! {
        let mut result: Vec<(&str, String)> = Vec::new();
        #gen
        result
    }
}

// 把一批可能为空的值转换成match嵌套形式
// @params nulls: 一批可能为空的值的rust代码
fn to_nulls(nulls: &Vec<TokenStream2>, init: TokenStream2) -> TokenStream2 {
    nulls.iter().fold(init, |acc, x| {
        quote! {
            match #x {
                None => "null".to_string(),
                Some(_) => #acc
            }
        }
    })
}

// 有聚集函数的情况下,把选择部分转换成选择内容,这时,选择部分只能有一个表达式,或没有表达式
// @param agg: 聚集函数
fn to_agg_select<'a>(exp: &Option<Expression>, agg: &syn::Ident, 
    del: &mut HashMap<String, Rc<Type<'a>>>,
    json: &Table, config: &'a HashMap<String, Table>
) -> TokenStream2 {
    // 如果有表达式,产生映射过程
    let (select, ty) = match exp {
        Some(e) => {
            let (first, ty, _nulls) = to_exp(&e, del, Some(json), config);
            (quote! { .map(|x| #first) }, ty)
        },
        None => (quote! {}, Rc::new(Type::None))
    };

    // 根据表达式类型确定聚集后的类型
    let type_gen = match *ty {
        Type::Double => {
            match agg{
                _ if agg.to_string() == "max" => quote! {max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default },
                _ if agg.to_string() == "min" => quote! {min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or_default },
                _ => quote! { #agg::<f64> },
            }
        }
        Type::Int => {
            match agg {
                _ if agg.to_string() == "max" => quote! { #agg().unwrap_or_default },
                _ if agg.to_string() == "min" => quote! { #agg().unwrap_or_default },
                _ => quote! { #agg::<i32> },
            }
         },
        // 无类型,目前只有count,不加类型
        Type::None => quote! {#agg},
        _ => panic!("表达式类型错误:{:?}", ty),
    };

    // 返回映射后的函数调用
    let result = quote! { #select.#type_gen() };
    result
}

// 把操作符转rust代码
fn to_oper(str: &str) -> TokenStream2 {
    match str {
        "+" => quote!{ + },
        "-" => quote!{ - },
        "*" => quote!{ * },
        "/" => quote!{ / },
        "%" => quote!{ % },
        ">" => quote!{ > },
        ">=" => quote!{ >= },
        "<" => quote!{ < },
        "<=" => quote!{ <= },
        "==" => quote!{ == },
        "!=" => quote!{ != },
        "&&" => quote!{ && },
        "||" => quote!{ || },
        "!" => quote!{ ! },
        _ => panic!("暂时不能转, {}", str)
    }
}

// 根据参数类型,从json参数中获取值的rust代码
// s_name: 原始参数的名
// ty: 参数类型
fn get_value(s_name: &syn::Ident, ty: &str) -> TokenStream2 {
    if ty == "string" {
        quote! { #s_name.to_string() }
    } else if ty == "int" {
        // 字符串转整数
        quote! { i32::from_str_radix(&#s_name, 10).expect("必须是整数") }
    } else if ty == "datetime" {
        // 字符串转日期,必须满足日期格式
        quote! { datetime(&#s_name) }
    } else if ty == "double" {
        // 字符串转浮点数
        quote! { f64::from_str(&#s_name) }
    } else {
        panic!("类型不正确,{}", ty)
    }
}

// 获得表的字段的数据类型,如果是一对多或者一对一类型,找到对应表的描述
// table_op: 表的定义,如果是全局数据库,为空
// name: 要取的字段名,如果是全局数据库,名字为表名
// config: 全局的表配置,一对多关系要根据全局表配置获取描述
// del: 定义的变量的及其类型表
// q_type: 查询类型,根据查询类型,取得不同类型
// return: 字段类型
fn get_type<'a>(table_op: Option<&Table>, name: &str, config: &'a HashMap<String, Table>, 
    del: &HashMap<String, Rc<Type<'a>>>, q_type: &QueryType
) -> Rc<Type<'a>> {
    // 根据查询类型,确定数据类型的获取办法
    match q_type {
        // 全局数据库,从全局数据库中按表名取
        QueryType::Database => Rc::new(Type::Json(&config.get(name).expect(&format!("没有找到全局表的定义, {}", name)))),
        // 子查询处理过程
        QueryType::Sub => {
            let ty = &table_op.expect("找不到表").fields.get(name).expect(&format!("没有找到字段, {}", name));
            match ty {
                Field::Int => Rc::new(Type::Int),
                Field::String => Rc::new(Type::String),
                Field::Double => Rc::new(Type::Double),
                Field::Datetime => Rc::new(Type::Datetime),
                // 一对多及一对一关系,要从全局表定义获取内容
                Field::OneToOne(entity, _) | Field::OneToMany(entity, _) | Field::ManyToOne(entity, _) => {
                    let table_str = entity.to_string();
                    Rc::new(Type::Json(&config.get(&table_str).expect(&format!("没有找到表的定义, {}", table_str))))
                }
            }
        },
        // 定义的变量,取变量登记的类型
        QueryType::Var => Rc::clone(del.get(name).expect(&format!("为定义的变量, {}", name))),
    }
}

// 检查字符串是否日期格式
fn is_datetime(str: &str) -> bool {
    match iso8601::datetime(str) {
        Ok(_) => true,
        Err(_) => false,
    }
}