IT-KIMI_SHI\SINOIT.KIMI
2018-06-04 b12dfac6e495d6cf38df6b7e5222191f59762900
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package foundation.persist.sql;
 
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
 
import com.vaadin.data.util.sqlcontainer.query.OrderBy;
 
import foundation.data.Entity;
import foundation.persist.Field;
import foundation.persist.SystemCondition;
import foundation.persist.TableMeta;
import foundation.util.ContentBuilder;
import foundation.util.Util;
import foundation.variant.Expression;
import foundation.variant.IExpression;
import foundation.variant.VariantList;
import foundation.variant.VariantSegment;
 
 
public class NamedSQL implements Iterable<VariantSegment>, IExpression {
 
    public static final String Param_Schema = "schema";
    public static final String Param_TableName = "tablename";
    public static final String Param_FieldNames = "fieldNames";
    public static final String Param_FieldNameValues = "fieldNameValues";
    public static final String Param_Values = "fieldValues";    
    public static final String Param_PlaceHolders = "placeHolders";
    public static final String Param_Filter = "filter";
    public static final String Param_FieldNamePlaceHolders = "fieldNamePlaceHolders";
    public static final String Param_KeyFieldName = "keyFieldName";
    public static final String Param_OrderBy = "orderby";
    
    private static NamedSQLContainer namedSQLContainer;
    
    protected String name;
    protected String sql;
    protected ReturnType returnType;
    protected Expression expression;
    protected String countSQL;
    
    static {
        namedSQLContainer = NamedSQLContainer.getInstance();
    }
 
    private NamedSQL(String name) {
        this.name = name;
        returnType = ReturnType.None;
    }
    
    public NamedSQL(String name, String sql) throws Exception {
        this.name = name;
        this.sql = sql;
        
        parseSQL(sql, true);
    }
    
    public NamedSQL(String name, String sql, boolean parseRowNum) throws Exception {
        this.name = name;
        this.sql = sql;
        
        parseSQL(sql, parseRowNum);
    }
    
    protected void parseSQL(String sql, boolean parseRowNum) throws Exception {
        String lower = sql.toLowerCase();
        
        if (parseRowNum) {
            if (lower.indexOf("row_number()") > 0) {
                int pos_order = lower.lastIndexOf("order by");
                
                String temp = null;
                
                String prior = lower.substring(pos_order - 5, pos_order);
                
                if (!"over(".equals(prior)) {
                    int pos_desc = lower.indexOf(" desc", pos_order);
                    temp = sql.substring(0, pos_order);
                    String orderBy = sql.substring(pos_order);
                    if (pos_desc != -1) {
                        temp +=  sql.substring(pos_desc + " desc".length());
                        orderBy = sql.substring(pos_order, pos_desc + " desc".length());
                    }
                        
                    countSQL = "select count(1) from (" + temp + ") tempTbl";
                    sql = "select * from (" + temp + ")table_t where rownum > @{beginNo} and rownum <= @{endNo}"
                        + " " + orderBy;
 
                }
                else {
                    countSQL = "select count(1) from (" + sql + ") tempTbl";
                    sql = "select * from (" + sql + ")table_t where rownum > @{beginNo} and rownum <= @{endNo}";
                }
            }
        }
        
        expression = new SQLCreator(sql);
    }
 
    public String getSQL() throws Exception {
        String result = expression.getString();
        return result;
    }
    
    public void setSql(String sqlString){
        this.sql = sqlString;
    }
    
    public String getCountSQL() throws Exception {
        if (countSQL != null) {
            return countSQL;
        }
        
        return "select count(1) from (" + getSQL() + ") tempTbl";
    }
    
    public static NamedSQL[] getInstance(String[] names) throws Exception {
        if (names == null) { return new NamedSQL[0]; };
        
        NamedSQL[] result = new NamedSQL[names.length];
        
        for (int i = 0; i < names.length; i++) {
            result[i] = getInstance(names[i]);
        }
        
        return result;
    }
    
    public static NamedSQL getInstance(String name) throws Exception {
        String condtion = SystemCondition.getValue();
        
        NamedSQL result = namedSQLContainer.get(name, condtion);
        
        if (result == null) {
            result = namedSQLContainer.get(name, null);
        }
        
        if (result == null) {
            throw new Exception("can not find named sql: " + name);
        }
        
        result = result.newInstance();
        return result;
    }
    
    public NamedSQL newInstance() throws Exception {
        NamedSQL instance = new NamedSQL(this.name);
        instance.sql = this.sql;
        instance.countSQL = this.countSQL;
        instance.expression = this.expression.newInstance();
        
        return instance;
    }
 
    public String getOriginalSql(){
        return sql;
    }
 
    public Result exec() throws Exception {
        Result result = SQLRunner.getResult(this);
        return result;
    }
    
    public void setSchema(String schema) {
        setParam(Param_Schema, schema);
    }
 
    public void setTableName(String tableName) {
        setParam(Param_TableName, tableName);
    }
 
    public void setFieldNames(String names) {
        setParam(Param_FieldNames, names);
    }
    
    public void setFieldNames(TableMeta tableMeta) {
        StringBuilder result = new StringBuilder();
        boolean empty = true;
        
        for (Field field: tableMeta) {
            if (!empty) {
                result.append(", ");
            }
            
            result.append(field.getName());
            
            empty = false;
        }
        
        setParam(Param_FieldNames, result.toString());
    }
    
    public void setFieldNames(TableMeta tableMeta, Entity entity) {
        StringBuilder result = new StringBuilder();
        boolean empty = true;
        Field field;
        
        for (int i = 0; i < tableMeta.getFieldCount(); i++) {
            if (entity.isEmptyField(i)) {
                continue;
            }
                
            field = tableMeta.get(i);
            
            if (!empty) {
                result.append(", ");
            }
 
            result.append(field.getName());
            empty = false;
        }
        
        setParam(Param_FieldNames, result.toString());
    }
    
    public void setFieldNames(Collection<Field> fields) {
        ContentBuilder result = new ContentBuilder();
        
        for (Field field: fields) {
            result.append(field.getName(), ", ");
        }
        
        setParam(Param_FieldNames, result.toString());
    }
    
    public void setValues(Entity entity) throws Exception {
        ContentBuilder result = new ContentBuilder();
        int cnt = entity.getFieldCount();
        
        for (int i = 0; i < cnt; i++) {
            if (entity.isEmptyField(i)) {
                continue;
            }
            
            result.append(entity.getSQLString(i), ", ");
        }
        
        setParam(Param_Values, result.toString());
    }
    
    public void setQuotedFieldNames(TableMeta tableMeta) {
        ContentBuilder result = new ContentBuilder();
        
        for (Field field: tableMeta) {
            result.append(Util.doubleQuotedStr(field.getName()), ", ");
        }
        
        setParam(Param_FieldNames, result.toString());
    }
 
    public void setPlaceHolders(Collection<Field> fields) {
        ContentBuilder result = new ContentBuilder();
        int cnt = fields.size();
        
        for (int i = 0; i < cnt; i++) {
            result.append("?", ", ");
        }
        
        setParam(Param_PlaceHolders, result.toString());
    }
    
    public void setPlaceHolders(String placeHolders) {
        setParam(Param_PlaceHolders, placeHolders);
    }
 
    public void setFieldNamePlaceHolders(TableMeta tableMeta) {
        ContentBuilder result = new ContentBuilder();
        
        for (Field field: tableMeta) {
            result.append(field.getName() + " = ? ", ", ");
        }
        
        setParam(Param_FieldNamePlaceHolders, result.toString());
    }
 
    public void setKeyFieldName(TableMeta tableMeta) throws Exception {
        String keyName = tableMeta.getFiledName_Key();
        setParam(Param_KeyFieldName, keyName);        
    }
 
    public void setKeyFieldName(String fieldName) throws Exception {
        setParam(Param_KeyFieldName, fieldName);            
    }
    
    public void setFilter(String filter) {
        if (Util.isEmptyStr(filter)) {
            filter = "1=1";
        }
        
        setParam(Param_Filter, filter);    
    }
 
    public void setOrderBy(String orderby) {
        setParam(Param_OrderBy, orderby);    
    }
 
    public void setFieldNameValues(Entity entity) throws Exception {
        ContentBuilder result = new ContentBuilder();
        
        TableMeta tableMeta = entity.getTableMeta();
        int cnt = tableMeta.getFieldCount();
        
        for (int i = 0; i < cnt; i++) {
            if (entity.isEmptyField(i)) {
                continue;
            }
            
            Field field = tableMeta.get(i);
            result.append(field.getName() + "=" + entity.getSQLString(i), ", ");
        }
        
        setParam(Param_FieldNameValues, result.toString());
    }
 
    public void setParam(String name, String value) {
        if (value == null) {
            return;
        }
        
        VariantSegment variant = expression.getVariant(name);
        
        if (variant != null) {
            variant.setValue(value);
        }
    }
    
    public void setParam(String name, String value, String defaultValue) {
        if (value == null) {
            value = defaultValue;
        }
        
        VariantSegment sqllVariant = expression.getVariant(name);
        
        if (sqllVariant != null) {
            sqllVariant.setValue(value);
        }
    }
    
    public void setParam(String name, int value) {
        String stringValue = String.valueOf(value);
        setParam(name, stringValue);
    }
    
    public void setParam(String name, BigDecimal value) {
        String stringValue = value.toString();
        setParam(name, stringValue);        
    }
    
    public void setParam(String name, Date date) {
        String stringValue = Util.toMySQLDateStr(date);
        setParam(name, stringValue);
    }
    
    public void setParam(String name, boolean value) {
        String stringValue = Util.booleanToStr(value);
        setParam(name, stringValue);
    }
 
    public String getName() {
        return name;
    }
 
    public ReturnType getReturnType() {
        return returnType;
    }
    
 
    public void setReturnType(ReturnType returnType) {
        this.returnType = returnType;
    }
    
    public String getSQLString() throws Exception {
        return expression.tryGetString(); 
    }
    
    @Override
    public String toString() {
        return expression.getString();
    }
 
    @Override
    public Iterator<VariantSegment> iterator() {
        return expression.iterator();
    }
 
    public void clearVariantValues() {
        expression.clearVariantValues();
    }
 
    public VariantList getVariantList() {
        return expression.getVariantList();
    }
 
    public Expression getExpression() {
        return expression;
    }
    
    public static void main(String[] args) {
        String sql = "where 1 =1   AND DistributorLevel ='一级商' order by [BizDate] desc";
        sql = sql.toLowerCase();
        int pos_order = sql.indexOf("order by");
        int pos_desc = sql.indexOf(" desc", pos_order);
        String temp = sql.substring(0, pos_order) + sql.substring(pos_desc + " desc".length());
        System.out.println(temp);
    }
}