|
| 1 | +package me.zort.sqllib.mapping.builder; |
| 2 | + |
| 3 | +import me.zort.sqllib.api.SQLConnection; |
| 4 | +import me.zort.sqllib.internal.query.QueryDetails; |
| 5 | +import me.zort.sqllib.internal.query.QueryNode; |
| 6 | +import me.zort.sqllib.internal.query.QueryPriority; |
| 7 | +import me.zort.sqllib.mapping.PlaceholderMapper; |
| 8 | +import me.zort.sqllib.mapping.QueryAnnotation; |
| 9 | +import me.zort.sqllib.mapping.annotation.Exec; |
| 10 | +import me.zort.sqllib.mapping.annotation.Query; |
| 11 | +import me.zort.sqllib.util.ParameterPair; |
| 12 | + |
| 13 | +import java.lang.annotation.Annotation; |
| 14 | +import java.lang.reflect.Method; |
| 15 | +import java.util.ArrayList; |
| 16 | +import java.util.HashMap; |
| 17 | +import java.util.Map; |
| 18 | + |
| 19 | +public class NativeQueryBuilder implements QueryAnnotation.QueryBuilder<Annotation> { |
| 20 | + @Override |
| 21 | + public QueryNode<?> build(SQLConnection connection, Annotation queryAnnotation, Method method, ParameterPair[] parameters) { |
| 22 | + PlaceholderMapper mapper = new PlaceholderMapper(parameters); |
| 23 | + return new QueryNode<QueryNode<?>>(null, new ArrayList<>(), QueryPriority.GENERAL) { |
| 24 | + private int currPhIndex = 0; |
| 25 | + @Override |
| 26 | + public QueryDetails buildQueryDetails() { |
| 27 | + String annotValue; |
| 28 | + String[] annotParams; |
| 29 | + |
| 30 | + if (queryAnnotation instanceof Query) { |
| 31 | + annotValue = ((Query) queryAnnotation).value(); |
| 32 | + annotParams = ((Query) queryAnnotation).params(); |
| 33 | + } else if(queryAnnotation instanceof Exec) { |
| 34 | + annotValue = ((Exec) queryAnnotation).value(); |
| 35 | + annotParams = ((Exec) queryAnnotation).params(); |
| 36 | + } else { |
| 37 | + throw new IllegalArgumentException(String.format("NativeQueryBuilder does not support %s annotation!", queryAnnotation.getClass().getName())); |
| 38 | + } |
| 39 | + |
| 40 | + annotValue = mapper.assignValues(annotValue); |
| 41 | + |
| 42 | + Map<String, Object> params = new HashMap<>(); |
| 43 | + for (String param : annotParams) { |
| 44 | + param = mapper.assignValues(param); |
| 45 | + int index = annotValue.indexOf("?"); |
| 46 | + if (index == -1) |
| 47 | + break; |
| 48 | + |
| 49 | + String placeholder = nextPlaceholder(); |
| 50 | + annotValue = annotValue.replaceFirst("\\?", "<" + placeholder + ">"); |
| 51 | + params.put(placeholder, param); |
| 52 | + } |
| 53 | + return new QueryDetails(annotValue, params); |
| 54 | + } |
| 55 | + |
| 56 | + private String nextPlaceholder() { |
| 57 | + return "nq_" + currPhIndex++; |
| 58 | + } |
| 59 | + }; |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments