You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TableInspector.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /*
  2. * Copyright 2004-2011 H2 Group.
  3. * Copyright 2011 James Moger.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package com.iciql;
  18. import static com.iciql.ValidationRemark.consider;
  19. import static com.iciql.ValidationRemark.error;
  20. import static com.iciql.ValidationRemark.warn;
  21. import static com.iciql.util.JdbcUtils.closeSilently;
  22. import static com.iciql.util.StringUtils.isNullOrEmpty;
  23. import static java.text.MessageFormat.format;
  24. import java.lang.reflect.Modifier;
  25. import java.sql.DatabaseMetaData;
  26. import java.sql.ResultSet;
  27. import java.sql.SQLException;
  28. import java.util.ArrayList;
  29. import java.util.Collections;
  30. import java.util.Date;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Set;
  34. import com.iciql.Iciql.IndexType;
  35. import com.iciql.Iciql.IQColumn;
  36. import com.iciql.Iciql.IQIndex;
  37. import com.iciql.Iciql.IQSchema;
  38. import com.iciql.Iciql.IQTable;
  39. import com.iciql.TableDefinition.FieldDefinition;
  40. import com.iciql.TableDefinition.IndexDefinition;
  41. import com.iciql.util.StatementBuilder;
  42. import com.iciql.util.Utils;
  43. /**
  44. * Class to inspect the contents of a particular table including its indexes.
  45. * This class does the bulk of the work in terms of model generation and model
  46. * validation.
  47. */
  48. public class TableInspector {
  49. private String schema;
  50. private String table;
  51. private boolean forceUpperCase;
  52. private Class<? extends java.util.Date> dateTimeClass;
  53. private List<String> primaryKeys = Utils.newArrayList();
  54. private Map<String, IndexInspector> indexes;
  55. private Map<String, ColumnInspector> columns;
  56. private final String eol = "\n";
  57. TableInspector(String schema, String table, boolean forceUpperCase,
  58. Class<? extends java.util.Date> dateTimeClass) {
  59. this.schema = schema;
  60. this.table = table;
  61. this.forceUpperCase = forceUpperCase;
  62. this.dateTimeClass = dateTimeClass;
  63. }
  64. /**
  65. * Tests to see if this TableInspector represents schema.table.
  66. * <p>
  67. *
  68. * @param schema
  69. * the schema name
  70. * @param table
  71. * the table name
  72. * @return true if the table matches
  73. */
  74. boolean matches(String schema, String table) {
  75. if (isNullOrEmpty(schema)) {
  76. // table name matching
  77. return this.table.equalsIgnoreCase(table);
  78. } else if (isNullOrEmpty(table)) {
  79. // schema name matching
  80. return this.schema.equalsIgnoreCase(schema);
  81. } else {
  82. // exact table matching
  83. return this.schema.equalsIgnoreCase(schema) && this.table.equalsIgnoreCase(table);
  84. }
  85. }
  86. /**
  87. * Reads the DatabaseMetaData for the details of this table including
  88. * primary keys and indexes.
  89. *
  90. * @param metaData
  91. * the database meta data
  92. */
  93. void read(DatabaseMetaData metaData) throws SQLException {
  94. ResultSet rs = null;
  95. // primary keys
  96. try {
  97. rs = metaData.getPrimaryKeys(null, schema, table);
  98. while (rs.next()) {
  99. String c = rs.getString("COLUMN_NAME");
  100. primaryKeys.add(c);
  101. }
  102. closeSilently(rs);
  103. // indexes
  104. rs = metaData.getIndexInfo(null, schema, table, false, true);
  105. indexes = Utils.newHashMap();
  106. while (rs.next()) {
  107. IndexInspector info = new IndexInspector(rs);
  108. if (info.type.equals(IndexType.UNIQUE) && info.name.toLowerCase().startsWith("primary")) {
  109. // skip primary key indexes
  110. continue;
  111. }
  112. if (indexes.containsKey(info.name)) {
  113. indexes.get(info.name).addColumn(rs);
  114. } else {
  115. indexes.put(info.name, info);
  116. }
  117. }
  118. closeSilently(rs);
  119. // columns
  120. rs = metaData.getColumns(null, schema, table, null);
  121. columns = Utils.newHashMap();
  122. while (rs.next()) {
  123. ColumnInspector col = new ColumnInspector();
  124. col.name = rs.getString("COLUMN_NAME");
  125. col.type = rs.getString("TYPE_NAME");
  126. col.clazz = ModelUtils.getClassForSqlType(col.type, dateTimeClass);
  127. col.size = rs.getInt("COLUMN_SIZE");
  128. col.allowNull = rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable;
  129. col.isAutoIncrement = rs.getBoolean("IS_AUTOINCREMENT");
  130. if (primaryKeys.size() == 1) {
  131. if (col.name.equalsIgnoreCase(primaryKeys.get(0))) {
  132. col.isPrimaryKey = true;
  133. }
  134. }
  135. if (!col.isAutoIncrement) {
  136. col.defaultValue = rs.getString("COLUMN_DEF");
  137. }
  138. columns.put(col.name, col);
  139. }
  140. } finally {
  141. closeSilently(rs);
  142. }
  143. }
  144. /**
  145. * Generates a model (class definition) from this table. The model includes
  146. * indexes, primary keys, default values, maxLengths, and allowNull
  147. * information.
  148. * <p>
  149. * The caller may optionally set a destination package name, whether or not
  150. * to include the schema name (setting schema can be a problem when using
  151. * the model between databases), and if to automatically trim strings for
  152. * those that have a maximum length.
  153. * <p>
  154. *
  155. * @param packageName
  156. * @param annotateSchema
  157. * @param trimStrings
  158. * @return a complete model (class definition) for this table as a string
  159. */
  160. String generateModel(String packageName, boolean annotateSchema, boolean trimStrings) {
  161. // import statements
  162. Set<String> imports = Utils.newHashSet();
  163. imports.add(IQSchema.class.getCanonicalName());
  164. imports.add(IQTable.class.getCanonicalName());
  165. imports.add(IQIndex.class.getCanonicalName());
  166. imports.add(IQColumn.class.getCanonicalName());
  167. // fields
  168. StringBuilder fields = new StringBuilder();
  169. List<ColumnInspector> sortedColumns = Utils.newArrayList(columns.values());
  170. Collections.sort(sortedColumns);
  171. for (ColumnInspector col : sortedColumns) {
  172. fields.append(generateColumn(imports, col, trimStrings));
  173. }
  174. // build complete class definition
  175. StringBuilder model = new StringBuilder();
  176. if (!isNullOrEmpty(packageName)) {
  177. // package
  178. model.append("package " + packageName + ";");
  179. model.append(eol).append(eol);
  180. }
  181. // imports
  182. List<String> sortedImports = new ArrayList<String>(imports);
  183. Collections.sort(sortedImports);
  184. for (String imp : sortedImports) {
  185. model.append("import ").append(imp).append(';').append(eol);
  186. }
  187. model.append(eol);
  188. // @IQSchema
  189. if (annotateSchema && !isNullOrEmpty(schema)) {
  190. model.append('@').append(IQSchema.class.getSimpleName());
  191. model.append('(');
  192. AnnotationBuilder ap = new AnnotationBuilder();
  193. ap.addParameter("name", schema);
  194. model.append(ap);
  195. model.append(')').append(eol);
  196. }
  197. // @IQTable
  198. model.append('@').append(IQTable.class.getSimpleName());
  199. model.append('(');
  200. // IQTable annotation parameters
  201. AnnotationBuilder ap = new AnnotationBuilder();
  202. ap.addParameter("name", table);
  203. if (primaryKeys.size() > 1) {
  204. StringBuilder pk = new StringBuilder();
  205. for (String key : primaryKeys) {
  206. pk.append(key).append(' ');
  207. }
  208. pk.trimToSize();
  209. ap.addParameter("primaryKey", pk.toString());
  210. }
  211. // finish @IQTable annotation
  212. model.append(ap);
  213. model.append(')').append(eol);
  214. // @IQIndex
  215. ap = new AnnotationBuilder();
  216. generateIndexAnnotations(ap, "standard", IndexType.STANDARD);
  217. generateIndexAnnotations(ap, "unique", IndexType.UNIQUE);
  218. generateIndexAnnotations(ap, "hash", IndexType.HASH);
  219. generateIndexAnnotations(ap, "uniqueHash", IndexType.UNIQUE_HASH);
  220. if (ap.length() > 0) {
  221. model.append('@').append(IQIndex.class.getSimpleName());
  222. model.append('(');
  223. model.append(ap);
  224. model.append(')').append(eol);
  225. }
  226. // class declaration
  227. String clazzName = ModelUtils.convertTableToClassName(table);
  228. model.append(format("public class {0} '{'", clazzName)).append(eol);
  229. model.append(eol);
  230. // field declarations
  231. model.append(fields);
  232. // default constructor
  233. model.append("\t" + "public ").append(clazzName).append("() {").append(eol);
  234. model.append("\t}").append(eol);
  235. // end of class body
  236. model.append('}');
  237. model.trimToSize();
  238. return model.toString();
  239. }
  240. /**
  241. * Generates the specified index annotation.
  242. *
  243. * @param ap
  244. */
  245. void generateIndexAnnotations(AnnotationBuilder ap, String parameter, IndexType type) {
  246. List<IndexInspector> list = getIndexes(type);
  247. if (list.size() == 0) {
  248. // no matching indexes
  249. return;
  250. }
  251. if (list.size() == 1) {
  252. ap.addParameter(parameter, list.get(0).getColumnsString());
  253. } else {
  254. List<String> parameters = Utils.newArrayList();
  255. for (IndexInspector index : list) {
  256. parameters.add(index.getColumnsString());
  257. }
  258. ap.addParameter(parameter, parameters);
  259. }
  260. }
  261. private List<IndexInspector> getIndexes(IndexType type) {
  262. List<IndexInspector> list = Utils.newArrayList();
  263. for (IndexInspector index : indexes.values()) {
  264. if (index.type.equals(type)) {
  265. list.add(index);
  266. }
  267. }
  268. return list;
  269. }
  270. private StatementBuilder generateColumn(Set<String> imports, ColumnInspector col, boolean trimStrings) {
  271. StatementBuilder sb = new StatementBuilder();
  272. Class<?> clazz = col.clazz;
  273. String column = ModelUtils.convertColumnToFieldName(col.name.toLowerCase());
  274. sb.append('\t');
  275. if (clazz == null) {
  276. // unsupported type
  277. clazz = Object.class;
  278. sb.append("// unsupported type " + col.type);
  279. } else {
  280. // @IQColumn
  281. imports.add(clazz.getCanonicalName());
  282. sb.append('@').append(IQColumn.class.getSimpleName());
  283. // IQColumn annotation parameters
  284. AnnotationBuilder ap = new AnnotationBuilder();
  285. // IQColumn.name
  286. if (!col.name.equalsIgnoreCase(column)) {
  287. ap.addParameter("name", col.name);
  288. }
  289. // IQColumn.primaryKey
  290. // composite primary keys are annotated on the table
  291. if (col.isPrimaryKey && primaryKeys.size() == 1) {
  292. ap.addParameter("primaryKey=true");
  293. }
  294. // IQColumn.maxLength
  295. if ((clazz == String.class) && (col.size > 0) && (col.size < Integer.MAX_VALUE)) {
  296. ap.addParameter("maxLength", col.size);
  297. // IQColumn.trimStrings
  298. if (trimStrings) {
  299. ap.addParameter("trimString=true");
  300. }
  301. } else {
  302. // IQColumn.AutoIncrement
  303. if (col.isAutoIncrement) {
  304. ap.addParameter("autoIncrement=true");
  305. }
  306. }
  307. // IQColumn.allowNull
  308. if (!col.allowNull) {
  309. ap.addParameter("allowNull=false");
  310. }
  311. // IQColumn.defaultValue
  312. if (!isNullOrEmpty(col.defaultValue)) {
  313. ap.addParameter("defaultValue=\"" + col.defaultValue + "\"");
  314. }
  315. // add leading and trailing ()
  316. if (ap.length() > 0) {
  317. ap.insert(0, '(');
  318. ap.append(')');
  319. }
  320. sb.append(ap);
  321. }
  322. sb.append(eol);
  323. // variable declaration
  324. sb.append("\t" + "public ");
  325. sb.append(clazz.getSimpleName());
  326. sb.append(' ');
  327. sb.append(column);
  328. sb.append(';');
  329. sb.append(eol).append(eol);
  330. return sb;
  331. }
  332. /**
  333. * Validates that a table definition (annotated, interface, or both) matches
  334. * the current state of the table and indexes in the database. Results are
  335. * returned as a list of validation remarks which includes recommendations,
  336. * warnings, and errors about the model. The caller may choose to have
  337. * validate throw an exception on any validation ERROR.
  338. *
  339. * @param def
  340. * the table definition
  341. * @param throwError
  342. * whether or not to throw an exception if an error was found
  343. * @return a list if validation remarks
  344. */
  345. <T> List<ValidationRemark> validate(TableDefinition<T> def, boolean throwError) {
  346. List<ValidationRemark> remarks = Utils.newArrayList();
  347. // model class definition validation
  348. if (!Modifier.isPublic(def.getModelClass().getModifiers())) {
  349. remarks.add(error(table, "SCHEMA",
  350. format("Class {0} MUST BE PUBLIC!", def.getModelClass().getCanonicalName())).throwError(
  351. throwError));
  352. }
  353. // Schema Validation
  354. if (!isNullOrEmpty(schema)) {
  355. if (isNullOrEmpty(def.schemaName)) {
  356. remarks.add(consider(table, "SCHEMA",
  357. format("@{0}(name={1})", IQSchema.class.getSimpleName(), schema)));
  358. } else if (!schema.equalsIgnoreCase(def.schemaName)) {
  359. remarks.add(error(
  360. table,
  361. "SCHEMA",
  362. format("@{0}(name={1}) != {2}", IQSchema.class.getSimpleName(), def.schemaName,
  363. schema)).throwError(throwError));
  364. }
  365. }
  366. // index validation
  367. for (IndexInspector index : indexes.values()) {
  368. validate(remarks, def, index, throwError);
  369. }
  370. // field column validation
  371. for (FieldDefinition fieldDef : def.getFields()) {
  372. validate(remarks, fieldDef, throwError);
  373. }
  374. return remarks;
  375. }
  376. /**
  377. * Validates an inspected index from the database against the
  378. * IndexDefinition within the TableDefinition.
  379. */
  380. private <T> void validate(List<ValidationRemark> remarks, TableDefinition<T> def, IndexInspector index,
  381. boolean throwError) {
  382. List<IndexDefinition> defIndexes = def.getIndexes(IndexType.STANDARD);
  383. List<IndexInspector> dbIndexes = getIndexes(IndexType.STANDARD);
  384. if (defIndexes.size() > dbIndexes.size()) {
  385. remarks.add(warn(table, IndexType.STANDARD.name(), "More model indexes than database indexes"));
  386. } else if (defIndexes.size() < dbIndexes.size()) {
  387. remarks.add(warn(table, IndexType.STANDARD.name(), "Model class is missing indexes"));
  388. }
  389. // TODO complete index validation.
  390. // need to actually compare index types and columns within each index.
  391. }
  392. /**
  393. * Validates a column against the model's field definition. Checks for
  394. * existence, supported type, type mapping, default value, defined lengths,
  395. * primary key, autoincrement.
  396. */
  397. private void validate(List<ValidationRemark> remarks, FieldDefinition fieldDef, boolean throwError) {
  398. // unknown field
  399. String field = forceUpperCase ? fieldDef.columnName.toUpperCase() : fieldDef.columnName;
  400. if (!columns.containsKey(field)) {
  401. // unknown column mapping
  402. remarks.add(error(table, fieldDef, "Does not exist in database!").throwError(throwError));
  403. return;
  404. }
  405. ColumnInspector col = columns.get(field);
  406. Class<?> fieldClass = fieldDef.field.getType();
  407. Class<?> jdbcClass = ModelUtils.getClassForSqlType(col.type, dateTimeClass);
  408. // supported type check
  409. // iciql maps to VARCHAR for unsupported types.
  410. if (fieldDef.dataType.equals("VARCHAR") && (fieldClass != String.class)) {
  411. remarks.add(error(table, fieldDef,
  412. "iciql does not currently implement support for " + fieldClass.getName()).throwError(
  413. throwError));
  414. }
  415. // number types
  416. if (!fieldClass.equals(jdbcClass)) {
  417. if (Number.class.isAssignableFrom(fieldClass)) {
  418. remarks.add(warn(
  419. table,
  420. col,
  421. format("Precision mismatch: ModelObject={0}, ColumnObject={1}",
  422. fieldClass.getSimpleName(), jdbcClass.getSimpleName())));
  423. } else {
  424. if (!Date.class.isAssignableFrom(jdbcClass)) {
  425. remarks.add(warn(
  426. table,
  427. col,
  428. format("Object Mismatch: ModelObject={0}, ColumnObject={1}",
  429. fieldClass.getSimpleName(), jdbcClass.getSimpleName())));
  430. }
  431. }
  432. }
  433. // string types
  434. if (fieldClass == String.class) {
  435. if ((fieldDef.maxLength != col.size) && (col.size < Integer.MAX_VALUE)) {
  436. remarks.add(warn(
  437. table,
  438. col,
  439. format("{0}.maxLength={1}, ColumnMaxLength={2}", IQColumn.class.getSimpleName(),
  440. fieldDef.maxLength, col.size)));
  441. }
  442. if (fieldDef.maxLength > 0 && !fieldDef.trimString) {
  443. remarks.add(consider(table, col,
  444. format("{0}.truncateToMaxLength=true" + " will prevent IciqlExceptions on"
  445. + " INSERT or UPDATE, but will clip data!", IQColumn.class.getSimpleName())));
  446. }
  447. }
  448. // numeric autoIncrement
  449. if (fieldDef.isAutoIncrement != col.isAutoIncrement) {
  450. remarks.add(warn(
  451. table,
  452. col,
  453. format("{0}.isAutoIncrement={1}" + " while Column autoIncrement={2}",
  454. IQColumn.class.getSimpleName(), fieldDef.isAutoIncrement, col.isAutoIncrement)));
  455. }
  456. // default value
  457. if (!col.isAutoIncrement && !col.isPrimaryKey) {
  458. // check Model.defaultValue format
  459. if (!ModelUtils.isProperlyFormattedDefaultValue(fieldDef.defaultValue)) {
  460. remarks.add(error(
  461. table,
  462. col,
  463. format("{0}.defaultValue=\"{1}\"" + " is improperly formatted!",
  464. IQColumn.class.getSimpleName(), fieldDef.defaultValue))
  465. .throwError(throwError));
  466. // next field
  467. return;
  468. }
  469. // compare Model.defaultValue to Column.defaultValue
  470. if (isNullOrEmpty(fieldDef.defaultValue) && !isNullOrEmpty(col.defaultValue)) {
  471. // Model.defaultValue is NULL, Column.defaultValue is NOT NULL
  472. remarks.add(warn(
  473. table,
  474. col,
  475. format("{0}.defaultValue=\"\"" + " while column default=\"{1}\"",
  476. IQColumn.class.getSimpleName(), col.defaultValue)));
  477. } else if (!isNullOrEmpty(fieldDef.defaultValue) && isNullOrEmpty(col.defaultValue)) {
  478. // Column.defaultValue is NULL, Model.defaultValue is NOT NULL
  479. remarks.add(warn(
  480. table,
  481. col,
  482. format("{0}.defaultValue=\"{1}\"" + " while column default=\"\"",
  483. IQColumn.class.getSimpleName(), fieldDef.defaultValue)));
  484. } else if (!isNullOrEmpty(fieldDef.defaultValue) && !isNullOrEmpty(col.defaultValue)) {
  485. if (!fieldDef.defaultValue.equals(col.defaultValue)) {
  486. // Model.defaultValue != Column.defaultValue
  487. remarks.add(warn(
  488. table,
  489. col,
  490. format("{0}.defaultValue=\"{1}\"" + " while column default=\"{2}\"",
  491. IQColumn.class.getSimpleName(), fieldDef.defaultValue, col.defaultValue)));
  492. }
  493. }
  494. // sanity check Model.defaultValue literal value
  495. if (!ModelUtils.isValidDefaultValue(fieldDef.field.getType(), fieldDef.defaultValue)) {
  496. remarks.add(error(
  497. table,
  498. col,
  499. format("{0}.defaultValue=\"{1}\" is invalid!", IQColumn.class.getSimpleName(),
  500. fieldDef.defaultValue)));
  501. }
  502. }
  503. }
  504. /**
  505. * Represents an index as it exists in the database.
  506. */
  507. private static class IndexInspector {
  508. String name;
  509. IndexType type;
  510. private List<String> columns = new ArrayList<String>();
  511. public IndexInspector(ResultSet rs) throws SQLException {
  512. name = rs.getString("INDEX_NAME");
  513. // determine index type
  514. boolean hash = rs.getInt("TYPE") == DatabaseMetaData.tableIndexHashed;
  515. boolean unique = !rs.getBoolean("NON_UNIQUE");
  516. if (!hash && !unique) {
  517. type = IndexType.STANDARD;
  518. } else if (hash && unique) {
  519. type = IndexType.UNIQUE_HASH;
  520. } else if (unique) {
  521. type = IndexType.UNIQUE;
  522. } else if (hash) {
  523. type = IndexType.HASH;
  524. }
  525. columns.add(rs.getString("COLUMN_NAME"));
  526. }
  527. public void addColumn(ResultSet rs) throws SQLException {
  528. columns.add(rs.getString("COLUMN_NAME"));
  529. }
  530. public String getColumnsString() {
  531. StatementBuilder sb = new StatementBuilder();
  532. for (String col : columns) {
  533. sb.appendExceptFirst(", ");
  534. sb.append(col);
  535. }
  536. return sb.toString().trim();
  537. }
  538. }
  539. /**
  540. * Represents a column as it exists in the database.
  541. */
  542. static class ColumnInspector implements Comparable<ColumnInspector> {
  543. String name;
  544. String type;
  545. int size;
  546. boolean allowNull;
  547. Class<?> clazz;
  548. boolean isPrimaryKey;
  549. boolean isAutoIncrement;
  550. String defaultValue;
  551. public int compareTo(ColumnInspector o) {
  552. if (isPrimaryKey && o.isPrimaryKey) {
  553. // both primary sort by name
  554. return name.compareTo(o.name);
  555. } else if (isPrimaryKey && !o.isPrimaryKey) {
  556. // primary first
  557. return -1;
  558. } else if (!isPrimaryKey && o.isPrimaryKey) {
  559. // primary first
  560. return 1;
  561. } else {
  562. // neither primary, sort by name
  563. return name.compareTo(o.name);
  564. }
  565. }
  566. }
  567. /**
  568. * Convenience class based on StatementBuilder for creating the annotation
  569. * parameter list.
  570. */
  571. private static class AnnotationBuilder extends StatementBuilder {
  572. AnnotationBuilder() {
  573. super();
  574. }
  575. void addParameter(String parameter) {
  576. appendExceptFirst(", ");
  577. append(parameter);
  578. }
  579. <T> void addParameter(String parameter, T value) {
  580. appendExceptFirst(", ");
  581. append(parameter);
  582. append('=');
  583. if (value instanceof List) {
  584. append("{ ");
  585. List<?> list = (List<?>) value;
  586. StatementBuilder flat = new StatementBuilder();
  587. for (Object o : list) {
  588. flat.appendExceptFirst(", ");
  589. if (o instanceof String) {
  590. flat.append('\"');
  591. }
  592. // TODO escape string
  593. flat.append(o.toString().trim());
  594. if (o instanceof String) {
  595. flat.append('\"');
  596. }
  597. }
  598. append(flat);
  599. append(" }");
  600. } else {
  601. if (value instanceof String) {
  602. append('\"');
  603. }
  604. // TODO escape
  605. append(value.toString().trim());
  606. if (value instanceof String) {
  607. append('\"');
  608. }
  609. }
  610. }
  611. }
  612. }