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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
|
/*
* Copyright 2004-2011 H2 Group.
* Copyright 2011 James Moger.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iciql;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import com.iciql.Iciql.EnumId;
import com.iciql.Iciql.EnumType;
import com.iciql.Iciql.IQColumn;
import com.iciql.Iciql.IQEnum;
import com.iciql.Iciql.IQIndex;
import com.iciql.Iciql.IQIndexes;
import com.iciql.Iciql.IQSchema;
import com.iciql.Iciql.IQTable;
import com.iciql.Iciql.IQVersion;
import com.iciql.Iciql.IndexType;
import com.iciql.util.StatementBuilder;
import com.iciql.util.IciqlLogger;
import com.iciql.util.StringUtils;
import com.iciql.util.Utils;
/**
* A table definition contains the index definitions of a table, the field
* definitions, the table name, and other meta data.
*
* @param <T>
* the table type
*/
public class TableDefinition<T> {
/**
* The meta data of an index.
*/
public static class IndexDefinition {
public IndexType type;
public String indexName;
public List<String> columnNames;
}
/**
* The meta data of a field.
*/
static class FieldDefinition {
String columnName;
Field field;
String dataType;
int length;
int scale;
boolean isPrimaryKey;
boolean isAutoIncrement;
boolean trim;
boolean nullable;
String defaultValue;
EnumType enumType;
boolean isPrimitive;
Object getValue(Object obj) {
try {
return field.get(obj);
} catch (Exception e) {
throw new IciqlException(e);
}
}
private Object initWithNewObject(Object obj) {
Object o = Utils.newObject(field.getType());
setValue(obj, o);
return o;
}
private void setValue(Object obj, Object o) {
try {
if (!field.isAccessible()) {
field.setAccessible(true);
}
Class<?> targetType = field.getType();
if (targetType.isEnum()) {
o = Utils.convertEnum(o, targetType, enumType);
} else {
o = Utils.convert(o, targetType);
}
field.set(obj, o);
} catch (IciqlException e) {
throw e;
} catch (Exception e) {
throw new IciqlException(e);
}
}
private Object read(ResultSet rs, int columnIndex) {
try {
return rs.getObject(columnIndex);
} catch (SQLException e) {
throw new IciqlException(e);
}
}
}
public ArrayList<FieldDefinition> fields = Utils.newArrayList();
String schemaName;
String tableName;
int tableVersion;
List<String> primaryKeyColumnNames;
boolean memoryTable;
private boolean createIfRequired = true;
private Class<T> clazz;
private IdentityHashMap<Object, FieldDefinition> fieldMap = Utils.newIdentityHashMap();
private ArrayList<IndexDefinition> indexes = Utils.newArrayList();
TableDefinition(Class<T> clazz) {
this.clazz = clazz;
schemaName = null;
tableName = clazz.getSimpleName();
}
Class<T> getModelClass() {
return clazz;
}
List<FieldDefinition> getFields() {
return fields;
}
void defineSchemaName(String schemaName) {
this.schemaName = schemaName;
}
void defineTableName(String tableName) {
this.tableName = tableName;
}
/**
* Define a primary key by the specified model fields.
*
* @param modelFields
* the ordered list of model fields
*/
void definePrimaryKey(Object[] modelFields) {
List<String> columnNames = mapColumnNames(modelFields);
setPrimaryKey(columnNames);
}
/**
* Define a primary key by the specified column names.
*
* @param columnNames
* the ordered list of column names
*/
private void setPrimaryKey(List<String> columnNames) {
primaryKeyColumnNames = Utils.newArrayList(columnNames);
// set isPrimaryKey flag for all field definitions
for (FieldDefinition fieldDefinition : fieldMap.values()) {
fieldDefinition.isPrimaryKey = this.primaryKeyColumnNames.contains(fieldDefinition.columnName);
}
}
private <A> String getColumnName(A fieldObject) {
FieldDefinition def = fieldMap.get(fieldObject);
return def == null ? null : def.columnName;
}
private ArrayList<String> mapColumnNames(Object[] columns) {
ArrayList<String> columnNames = Utils.newArrayList();
for (Object column : columns) {
columnNames.add(getColumnName(column));
}
return columnNames;
}
/**
* Defines an index with the specified model fields.
*
* @param type
* the index type (STANDARD, HASH, UNIQUE, UNIQUE_HASH)
* @param modelFields
* the ordered list of model fields
*/
void defineIndex(IndexType type, Object[] modelFields) {
List<String> columnNames = mapColumnNames(modelFields);
addIndex(null, type, columnNames);
}
/**
* Defines an index with the specified column names.
*
* @param type
* the index type (STANDARD, HASH, UNIQUE, UNIQUE_HASH)
* @param columnNames
* the ordered list of column names
*/
private void addIndex(String name, IndexType type, List<String> columnNames) {
IndexDefinition index = new IndexDefinition();
if (StringUtils.isNullOrEmpty(name)) {
index.indexName = tableName + "_" + indexes.size();
} else {
index.indexName = name;
}
index.columnNames = Utils.newArrayList(columnNames);
index.type = type;
indexes.add(index);
}
void defineColumnName(Object column, String columnName) {
FieldDefinition def = fieldMap.get(column);
if (def != null) {
def.columnName = columnName;
}
}
void defineLength(Object column, int length) {
FieldDefinition def = fieldMap.get(column);
if (def != null) {
def.length = length;
}
}
void defineScale(Object column, int scale) {
FieldDefinition def = fieldMap.get(column);
if (def != null) {
def.scale = scale;
}
}
void mapFields() {
boolean byAnnotationsOnly = false;
boolean inheritColumns = false;
if (clazz.isAnnotationPresent(IQTable.class)) {
IQTable tableAnnotation = clazz.getAnnotation(IQTable.class);
byAnnotationsOnly = tableAnnotation.annotationsOnly();
inheritColumns = tableAnnotation.inheritColumns();
}
List<Field> classFields = Utils.newArrayList();
classFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
if (inheritColumns) {
Class<?> superClass = clazz.getSuperclass();
classFields.addAll(Arrays.asList(superClass.getDeclaredFields()));
}
T defaultObject = Db.instance(clazz);
for (Field f : classFields) {
// default to field name
String columnName = f.getName();
boolean isAutoIncrement = false;
boolean isPrimaryKey = false;
int length = 0;
int scale = 0;
boolean trim = false;
boolean nullable = !f.getType().isPrimitive();
EnumType enumType = null;
String defaultValue = "";
// configure Java -> SQL enum mapping
if (f.getType().isEnum()) {
enumType = EnumType.DEFAULT_TYPE;
if (f.getType().isAnnotationPresent(IQEnum.class)) {
// enum definition is annotated for all instances
IQEnum iqenum = f.getType().getAnnotation(IQEnum.class);
enumType = iqenum.value();
}
if (f.isAnnotationPresent(IQEnum.class)) {
// this instance of the enum is annotated
IQEnum iqenum = f.getAnnotation(IQEnum.class);
enumType = iqenum.value();
}
}
boolean hasAnnotation = f.isAnnotationPresent(IQColumn.class);
if (hasAnnotation) {
IQColumn col = f.getAnnotation(IQColumn.class);
if (!StringUtils.isNullOrEmpty(col.name())) {
columnName = col.name();
}
isAutoIncrement = col.autoIncrement();
isPrimaryKey = col.primaryKey();
length = col.length();
scale = col.scale();
trim = col.trim();
nullable = col.nullable();
// try using default object
try {
f.setAccessible(true);
Object value = f.get(defaultObject);
if (value != null) {
if (value.getClass().isEnum()) {
// enum default, convert to target type
Enum<?> anEnum = (Enum<?>) value;
Object o = Utils.convertEnum(anEnum, enumType);
defaultValue = ModelUtils.formatDefaultValue(o);
} else {
// object default
defaultValue = ModelUtils.formatDefaultValue(value);
}
}
} catch (IllegalAccessException e) {
throw new IciqlException(e, "failed to get default object for {0}", columnName);
}
// annotation overrides
if (!StringUtils.isNullOrEmpty(col.defaultValue())) {
defaultValue = col.defaultValue();
}
}
boolean isPublic = Modifier.isPublic(f.getModifiers());
boolean reflectiveMatch = isPublic && !byAnnotationsOnly;
if (reflectiveMatch || hasAnnotation) {
FieldDefinition fieldDef = new FieldDefinition();
fieldDef.isPrimitive = f.getType().isPrimitive();
fieldDef.field = f;
fieldDef.columnName = columnName;
fieldDef.isAutoIncrement = isAutoIncrement;
fieldDef.isPrimaryKey = isPrimaryKey;
fieldDef.length = length;
fieldDef.scale = scale;
fieldDef.trim = trim;
fieldDef.nullable = nullable;
fieldDef.defaultValue = defaultValue;
fieldDef.enumType = enumType;
fieldDef.dataType = ModelUtils.getDataType(fieldDef);
fields.add(fieldDef);
}
}
List<String> primaryKey = Utils.newArrayList();
for (FieldDefinition fieldDef : fields) {
if (fieldDef.isPrimaryKey) {
primaryKey.add(fieldDef.columnName);
}
}
if (primaryKey.size() > 0) {
setPrimaryKey(primaryKey);
}
}
/**
* Optionally truncates strings to the maximum length and converts
* java.lang.Enum types to Strings or Integers.
*/
Object getValue(Object obj, FieldDefinition field) {
Object value = field.getValue(obj);
if (value == null) {
return value;
}
if (field.enumType != null) {
// convert enumeration to INT or STRING
Enum<?> iqenum = (Enum<?>) value;
switch (field.enumType) {
case NAME:
if (field.trim && field.length > 0) {
if (iqenum.name().length() > field.length) {
return iqenum.name().substring(0, field.length);
}
}
return iqenum.name();
case ORDINAL:
return iqenum.ordinal();
case ENUMID:
if (!EnumId.class.isAssignableFrom(value.getClass())) {
throw new IciqlException(field.field.getName() + " does not implement EnumId!");
}
EnumId enumid = (EnumId) value;
return enumid.enumId();
}
}
if (field.trim && field.length > 0) {
if (value instanceof String) {
// clip strings
String s = (String) value;
if (s.length() > field.length) {
return s.substring(0, field.length);
}
return s;
}
return value;
}
// return the value unchanged
return value;
}
long insert(Db db, Object obj, boolean returnKey) {
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("INSERT INTO ");
buff.append(db.getDialect().prepareTableName(schemaName, tableName)).append('(');
for (FieldDefinition field : fields) {
if (skipInsertField(field, obj)) {
continue;
}
buff.appendExceptFirst(", ");
buff.append(db.getDialect().prepareColumnName(field.columnName));
}
buff.append(") VALUES(");
buff.resetCount();
for (FieldDefinition field : fields) {
if (skipInsertField(field, obj)) {
continue;
}
buff.appendExceptFirst(", ");
buff.append('?');
Object value = getValue(obj, field);
stat.addParameter(value);
}
buff.append(')');
stat.setSQL(buff.toString());
IciqlLogger.insert(stat.getSQL());
if (returnKey) {
return stat.executeInsert();
}
return stat.executeUpdate();
}
private boolean skipInsertField(FieldDefinition field, Object obj) {
if (field.isAutoIncrement) {
Object value = getValue(obj, field);
if (field.isPrimitive) {
// skip uninitialized primitive autoincrement values
if (value.toString().equals("0")) {
return true;
}
} else if (value == null) {
// skip null object autoincrement values
return true;
}
}
return false;
}
int merge(Db db, Object obj) {
if (primaryKeyColumnNames == null || primaryKeyColumnNames.size() == 0) {
throw new IllegalStateException("No primary key columns defined for table " + obj.getClass()
+ " - no update possible");
}
SQLStatement stat = new SQLStatement(db);
db.getDialect().prepareMerge(stat, schemaName, tableName, this, obj);
IciqlLogger.merge(stat.getSQL());
return stat.executeUpdate();
}
int update(Db db, Object obj) {
if (primaryKeyColumnNames == null || primaryKeyColumnNames.size() == 0) {
throw new IllegalStateException("No primary key columns defined for table " + obj.getClass()
+ " - no update possible");
}
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(db.getDialect().prepareTableName(schemaName, tableName)).append(" SET ");
buff.resetCount();
for (FieldDefinition field : fields) {
if (!field.isPrimaryKey) {
buff.appendExceptFirst(", ");
buff.append(db.getDialect().prepareColumnName(field.columnName));
buff.append(" = ?");
Object value = getValue(obj, field);
stat.addParameter(value);
}
}
Object alias = Utils.newObject(obj.getClass());
Query<Object> query = Query.from(db, alias);
boolean firstCondition = true;
for (FieldDefinition field : fields) {
if (field.isPrimaryKey) {
Object fieldAlias = field.getValue(alias);
Object value = field.getValue(obj);
if (field.isPrimitive) {
fieldAlias = query.getPrimitiveAliasByValue(fieldAlias);
}
if (!firstCondition) {
query.addConditionToken(ConditionAndOr.AND);
}
firstCondition = false;
query.addConditionToken(new Condition<Object>(fieldAlias, value, CompareType.EQUAL));
}
}
stat.setSQL(buff.toString());
query.appendWhere(stat);
IciqlLogger.update(stat.getSQL());
return stat.executeUpdate();
}
int delete(Db db, Object obj) {
if (primaryKeyColumnNames == null || primaryKeyColumnNames.size() == 0) {
throw new IllegalStateException("No primary key columns defined for table " + obj.getClass()
+ " - no update possible");
}
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("DELETE FROM ");
buff.append(db.getDialect().prepareTableName(schemaName, tableName));
buff.resetCount();
Object alias = Utils.newObject(obj.getClass());
Query<Object> query = Query.from(db, alias);
boolean firstCondition = true;
for (FieldDefinition field : fields) {
if (field.isPrimaryKey) {
Object fieldAlias = field.getValue(alias);
Object value = field.getValue(obj);
if (field.isPrimitive) {
fieldAlias = query.getPrimitiveAliasByValue(fieldAlias);
}
if (!firstCondition) {
query.addConditionToken(ConditionAndOr.AND);
}
firstCondition = false;
query.addConditionToken(new Condition<Object>(fieldAlias, value, CompareType.EQUAL));
}
}
stat.setSQL(buff.toString());
query.appendWhere(stat);
IciqlLogger.delete(stat.getSQL());
return stat.executeUpdate();
}
TableDefinition<T> createIfRequired(Db db) {
if (!createIfRequired) {
// skip table and index creation
// but still check for upgrades
db.upgradeTable(this);
return this;
}
SQLStatement stat = new SQLStatement(db);
db.getDialect().prepareCreateTable(stat, this);
IciqlLogger.create(stat.getSQL());
try {
stat.executeUpdate();
} catch (IciqlException e) {
if (e.getIciqlCode() != IciqlException.CODE_OBJECT_ALREADY_EXISTS) {
throw e;
}
}
// create indexes
for (IndexDefinition index : indexes) {
stat = new SQLStatement(db);
db.getDialect().prepareCreateIndex(stat, schemaName, tableName, index);
IciqlLogger.create(stat.getSQL());
try {
stat.executeUpdate();
} catch (IciqlException e) {
if (e.getIciqlCode() != IciqlException.CODE_OBJECT_ALREADY_EXISTS
&& e.getIciqlCode() != IciqlException.CODE_DUPLICATE_KEY) {
throw e;
}
}
}
// tables are created using IF NOT EXISTS
// but we may still need to upgrade
db.upgradeTable(this);
return this;
}
void mapObject(Object obj) {
fieldMap.clear();
initObject(obj, fieldMap);
if (clazz.isAnnotationPresent(IQSchema.class)) {
IQSchema schemaAnnotation = clazz.getAnnotation(IQSchema.class);
// setup schema name mapping, if properly annotated
if (!StringUtils.isNullOrEmpty(schemaAnnotation.value())) {
schemaName = schemaAnnotation.value();
}
}
if (clazz.isAnnotationPresent(IQTable.class)) {
IQTable tableAnnotation = clazz.getAnnotation(IQTable.class);
// setup table name mapping, if properly annotated
if (!StringUtils.isNullOrEmpty(tableAnnotation.name())) {
tableName = tableAnnotation.name();
}
// allow control over createTableIfRequired()
createIfRequired = tableAnnotation.create();
// model version
if (clazz.isAnnotationPresent(IQVersion.class)) {
IQVersion versionAnnotation = clazz.getAnnotation(IQVersion.class);
if (versionAnnotation.value() > 0) {
tableVersion = versionAnnotation.value();
}
}
// setup the primary index, if properly annotated
if (tableAnnotation.primaryKey().length > 0) {
List<String> primaryKey = Utils.newArrayList();
primaryKey.addAll(Arrays.asList(tableAnnotation.primaryKey()));
setPrimaryKey(primaryKey);
}
}
if (clazz.isAnnotationPresent(IQIndex.class)) {
// single table index
IQIndex index = clazz.getAnnotation(IQIndex.class);
addIndex(index);
}
if (clazz.isAnnotationPresent(IQIndexes.class)) {
// multiple table indexes
IQIndexes indexes = clazz.getAnnotation(IQIndexes.class);
for (IQIndex index : indexes.value()) {
addIndex(index);
}
}
}
private void addIndex(IQIndex index) {
List<String> columns = Arrays.asList(index.value());
addIndex(index.name(), index.type(), columns);
}
List<IndexDefinition> getIndexes() {
return indexes;
}
private void initObject(Object obj, Map<Object, FieldDefinition> map) {
for (FieldDefinition def : fields) {
Object newValue = def.initWithNewObject(obj);
map.put(newValue, def);
}
}
void initSelectObject(SelectTable<T> table, Object obj, Map<Object, SelectColumn<T>> map) {
for (FieldDefinition def : fields) {
Object newValue = def.initWithNewObject(obj);
SelectColumn<T> column = new SelectColumn<T>(table, def);
map.put(newValue, column);
}
}
void readRow(Object item, ResultSet rs) {
for (int i = 0; i < fields.size(); i++) {
FieldDefinition def = fields.get(i);
Object o = def.read(rs, i + 1);
def.setValue(item, o);
}
}
void appendSelectList(SQLStatement stat) {
for (int i = 0; i < fields.size(); i++) {
if (i > 0) {
stat.appendSQL(", ");
}
FieldDefinition def = fields.get(i);
stat.appendColumn(def.columnName);
}
}
<Y, X> void appendSelectList(SQLStatement stat, Query<Y> query, X x) {
for (int i = 0; i < fields.size(); i++) {
if (i > 0) {
stat.appendSQL(", ");
}
FieldDefinition def = fields.get(i);
Object obj = def.getValue(x);
query.appendSQL(stat, x, obj);
}
}
}
|