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.Ascii;
17 
18 import  hunt.sql.visitor.SQLEvalVisitor;
19 // import  hunt.sql.visitor.SQLEvalVisitor.EVAL_VALUE;
20 // import  hunt.sql.visitor.SQLEvalVisitor.EVAL_VALUE_NULL;
21 
22 import hunt.sql.ast.SQLExpr;
23 import hunt.sql.ast.expr.SQLMethodInvokeExpr;
24 import hunt.sql.visitor.SQLEvalVisitor;
25 import hunt.sql.visitor.functions.Function;
26 import hunt.String;
27 import hunt.Integer;
28 import hunt.text;
29 
30 import std.concurrency : initOnce;
31 
32 public class Ascii : Function {
33 
34     static Ascii instance() {
35         __gshared Ascii inst;
36         return initOnce!inst(new Ascii());
37     }    
38 
39     // public  static Ascii instance;
40 
41     // static this()
42     // {
43     //     instance = new Ascii();
44     // }
45 
46     public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
47         if (x.getParameters().size() == 0) {
48             return cast(Object)(SQLEvalVisitor.EVAL_ERROR);
49         }
50         SQLExpr param = x.getParameters().get(0);
51         param.accept(visitor);
52         
53         Object paramValue = param.getAttributes().get(SQLEvalVisitor.EVAL_VALUE);
54         if (paramValue is null) {
55             return cast(Object)(SQLEvalVisitor.EVAL_ERROR);
56         }
57         
58         if (paramValue == SQLEvalVisitor.EVAL_VALUE_NULL) {
59             return cast(Object)(SQLEvalVisitor.EVAL_VALUE_NULL);
60         }
61 
62         string strValue = paramValue.toString();
63         if (strValue.length == 0) {
64             return new Integer(0);
65         }
66 
67         int ascii = charAt(strValue, 0);
68         return new Integer(ascii);
69     }
70 }