1 /*
2  * Copyright 2015-2018 HuntLabs.cn
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 module hunt.sql.visitor.functions.If;
17 
18 // import hunt.sql.visitor.SQLEvalVisitor.EVAL_ERROR;
19 // import hunt.sql.visitor.SQLEvalVisitor.SQLEvalVisitor.EVAL_VALUE;
20 
21 import hunt.Boolean;
22 import hunt.Integer;
23 import hunt.String;
24 import hunt.String;
25 import hunt.collection;
26 import std.conv;
27 import std.uni;
28 
29 import hunt.sql.ast.SQLExpr;
30 import hunt.sql.ast.expr.SQLMethodInvokeExpr;
31 import hunt.sql.visitor.SQLEvalVisitor;
32 import hunt.sql.visitor.SQLEvalVisitorUtils;
33 import hunt.sql.visitor.functions.Function;
34 
35 import std.concurrency : initOnce;
36 
37 public class If : Function {
38     
39     static If instance() {
40         __gshared If inst;
41         return initOnce!inst(new If());
42     }    
43 
44     // public  static If instance;
45 
46     // static this()
47     // {
48     //     instance = new If();
49     // }
50 
51     public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
52          List!(SQLExpr) parameters = x.getParameters();
53         if (parameters.size() == 0) {
54             return cast(Object)(SQLEvalVisitor.EVAL_ERROR);
55         }
56 
57         SQLExpr condition = parameters.get(0);
58         condition.accept(visitor);
59         Object itemValue = condition.getAttributes().get(SQLEvalVisitor.EVAL_VALUE);
60         if (itemValue is null) {
61             return null;
62         }
63         if (Boolean.TRUE == itemValue || !SQLEvalVisitorUtils.eq(itemValue, new Integer(0))) {
64             SQLExpr trueExpr = parameters.get(1);
65             trueExpr.accept(visitor);
66             return trueExpr.getAttributes().get(SQLEvalVisitor.EVAL_VALUE);
67         } else {
68             SQLExpr falseExpr = parameters.get(2);
69             falseExpr.accept(visitor);
70             return falseExpr.getAttributes().get(SQLEvalVisitor.EVAL_VALUE);
71         }
72     }
73 }