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