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