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