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.

Query.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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 java.lang.reflect.Field;
  19. import java.sql.ResultSet;
  20. import java.sql.SQLException;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.HashMap;
  24. import java.util.IdentityHashMap;
  25. import java.util.List;
  26. import com.iciql.Iciql.DataTypeAdapter;
  27. import com.iciql.Iciql.EnumType;
  28. import com.iciql.NestedConditions.And;
  29. import com.iciql.NestedConditions.Or;
  30. import com.iciql.bytecode.ClassReader;
  31. import com.iciql.util.IciqlLogger;
  32. import com.iciql.util.JdbcUtils;
  33. import com.iciql.util.Utils;
  34. /**
  35. * This class represents a query.
  36. *
  37. * @param <T>
  38. * the return type
  39. */
  40. public class Query<T> {
  41. private Db db;
  42. private SelectTable<T> from;
  43. private ArrayList<Token> conditions = Utils.newArrayList();
  44. private ArrayList<UpdateColumn> updateColumnDeclarations = Utils.newArrayList();
  45. private int conditionDepth = 0;
  46. private ArrayList<SelectTable<T>> joins = Utils.newArrayList();
  47. private final IdentityHashMap<Object, SelectColumn<T>> aliasMap = Utils.newIdentityHashMap();
  48. private ArrayList<OrderExpression<T>> orderByList = Utils.newArrayList();
  49. private ArrayList<Object> groupByExpressions = Utils.newArrayList();
  50. private long limit;
  51. private long offset;
  52. private Query(Db db) {
  53. this.db = db;
  54. }
  55. /**
  56. * from() is a static factory method to build a Query object.
  57. *
  58. * @param db
  59. * @param alias
  60. * @return a query object
  61. */
  62. @SuppressWarnings("unchecked")
  63. static <T> Query<T> from(Db db, T alias) {
  64. Query<T> query = new Query<T>(db);
  65. TableDefinition<T> def = (TableDefinition<T>) db.define(alias.getClass());
  66. query.from = new SelectTable<T>(db, query, alias, false);
  67. def.initSelectObject(query.from, alias, query.aliasMap, false);
  68. return query;
  69. }
  70. @SuppressWarnings("unchecked")
  71. static <T> Query<T> rebuild(Db db, T alias) {
  72. Query<T> query = new Query<T>(db);
  73. TableDefinition<T> def = (TableDefinition<T>) db.define(alias.getClass());
  74. query.from = new SelectTable<T>(db, query, alias, false);
  75. def.initSelectObject(query.from, alias, query.aliasMap, true);
  76. return query;
  77. }
  78. public long selectCount() {
  79. SQLStatement stat = getSelectStatement(false);
  80. stat.appendSQL("COUNT(*) ");
  81. appendFromWhere(stat);
  82. ResultSet rs = stat.executeQuery();
  83. try {
  84. rs.next();
  85. long value = rs.getLong(1);
  86. return value;
  87. } catch (SQLException e) {
  88. throw IciqlException.fromSQL(stat.getSQL(), e);
  89. } finally {
  90. JdbcUtils.closeSilently(rs, true);
  91. }
  92. }
  93. public List<T> select() {
  94. return select(false);
  95. }
  96. public T selectFirst() {
  97. List<T> list = limit(1).select(false);
  98. return list.isEmpty() ? null : list.get(0);
  99. }
  100. public List<T> selectDistinct() {
  101. return select(true);
  102. }
  103. public <X, Z> X selectFirst(Z x) {
  104. List<X> list = limit(1).select(x);
  105. return list.isEmpty() ? null : list.get(0);
  106. }
  107. public <X> void createView(Class<X> viewClass) {
  108. TableDefinition<X> viewDef = db.define(viewClass);
  109. SQLStatement fromWhere = new SQLStatement(db);
  110. appendFromWhere(fromWhere, false);
  111. SQLStatement stat = new SQLStatement(db);
  112. db.getDialect().prepareCreateView(stat, viewDef, fromWhere.toSQL());
  113. IciqlLogger.create(stat.toSQL());
  114. stat.execute();
  115. }
  116. public <X> void replaceView(Class<X> viewClass) {
  117. db.dropView(viewClass);
  118. createView(viewClass);
  119. }
  120. public String getSQL() {
  121. SQLStatement stat = getSelectStatement(false);
  122. stat.appendSQL("*");
  123. appendFromWhere(stat);
  124. return stat.getSQL().trim();
  125. }
  126. /**
  127. * toSQL returns a static string version of the query with runtime variables
  128. * properly encoded. This method is also useful when combined with the where
  129. * clause methods like isParameter() or atLeastParameter() which allows
  130. * iciql to generate re-usable parameterized string statements.
  131. *
  132. * @return the sql query as plain text
  133. */
  134. public String toSQL() {
  135. return toSQL(false);
  136. }
  137. /**
  138. * toSQL returns a static string version of the query with runtime variables
  139. * properly encoded. This method is also useful when combined with the where
  140. * clause methods like isParameter() or atLeastParameter() which allows
  141. * iciql to generate re-usable parameterized string statements.
  142. *
  143. * @param distinct
  144. * if true SELECT DISTINCT is used for the query
  145. * @return the sql query as plain text
  146. */
  147. public String toSQL(boolean distinct) {
  148. return toSQL(distinct, null);
  149. }
  150. /**
  151. * toSQL returns a static string version of the query with runtime variables
  152. * properly encoded. This method is also useful when combined with the where
  153. * clause methods like isParameter() or atLeastParameter() which allows
  154. * iciql to generate re-usable parameterized string statements.
  155. *
  156. * @param distinct
  157. * if true SELECT DISTINCT is used for the query
  158. * @param k
  159. * k is used to select only the columns of the specified alias
  160. * for an inner join statement. An example of a generated
  161. * statement is: SELECT DISTINCT t1.* FROM sometable AS t1 INNER
  162. * JOIN othertable AS t2 ON t1.id = t2.id WHERE t2.flag = true
  163. * without the alias parameter the statement would start with
  164. * SELECT DISTINCT * FROM...
  165. * @return the sql query as plain text
  166. */
  167. public <K> String toSQL(boolean distinct, K k) {
  168. SQLStatement stat = new SQLStatement(getDb());
  169. if (updateColumnDeclarations.size() > 0) {
  170. stat.appendSQL("UPDATE ");
  171. from.appendSQL(stat);
  172. stat.appendSQL(" SET ");
  173. int i = 0;
  174. for (UpdateColumn declaration : updateColumnDeclarations) {
  175. if (i++ > 0) {
  176. stat.appendSQL(", ");
  177. }
  178. declaration.appendSQL(stat);
  179. }
  180. appendWhere(stat);
  181. } else {
  182. stat.appendSQL("SELECT ");
  183. if (distinct) {
  184. stat.appendSQL("DISTINCT ");
  185. }
  186. if (k != null) {
  187. SelectTable<?> sel = getSelectTable(k);
  188. if (sel == null) {
  189. // unknown alias, use wildcard
  190. IciqlLogger.warn("Alias {0} is not defined in the statement!", k.getClass());
  191. stat.appendSQL("*");
  192. } else if (isJoin()) {
  193. // join query, use AS alias
  194. String as = sel.getAs();
  195. stat.appendSQL(as + ".*");
  196. } else {
  197. // schema.table.*
  198. String schema = sel.getAliasDefinition().schemaName;
  199. String table = sel.getAliasDefinition().tableName;
  200. String as = getDb().getDialect().prepareTableName(schema, table);
  201. stat.appendSQL(as + ".*");
  202. }
  203. } else {
  204. // alias unspecified, use wildcard
  205. stat.appendSQL("*");
  206. }
  207. appendFromWhere(stat);
  208. }
  209. return stat.toSQL().trim();
  210. }
  211. <Z> String toSubQuery(Z z) {
  212. SQLStatement stat = getSelectStatement(false);
  213. SelectColumn<T> col = aliasMap.get(z);
  214. String columnName = col.getFieldDefinition().columnName;
  215. stat.appendColumn(columnName);
  216. appendFromWhere(stat);
  217. return stat.toSQL();
  218. }
  219. private List<T> select(boolean distinct) {
  220. List<T> result = Utils.newArrayList();
  221. TableDefinition<T> def = from.getAliasDefinition();
  222. SQLStatement stat = getSelectStatement(distinct);
  223. def.appendSelectList(stat);
  224. appendFromWhere(stat);
  225. ResultSet rs = stat.executeQuery();
  226. try {
  227. int[] columns = def.mapColumns(false, rs);
  228. while (rs.next()) {
  229. T item = from.newObject();
  230. def.readRow(db.getDialect(), item, rs, columns);
  231. result.add(item);
  232. }
  233. } catch (SQLException e) {
  234. throw IciqlException.fromSQL(stat.getSQL(), e);
  235. } finally {
  236. JdbcUtils.closeSilently(rs, true);
  237. }
  238. return result;
  239. }
  240. public int delete() {
  241. SQLStatement stat = new SQLStatement(db);
  242. stat.appendSQL("DELETE FROM ");
  243. from.appendSQL(stat);
  244. appendWhere(stat);
  245. IciqlLogger.delete(stat.getSQL());
  246. return stat.executeUpdate();
  247. }
  248. public <A> UpdateColumnSet<T, A> set(A field) {
  249. from.getAliasDefinition().checkMultipleEnums(field);
  250. return new UpdateColumnSet<T, A>(this, field);
  251. }
  252. public UpdateColumnSet<T, Boolean> set(boolean field) {
  253. from.getAliasDefinition().checkMultipleBooleans();
  254. return setPrimitive(field);
  255. }
  256. public UpdateColumnSet<T, Byte> set(byte field) {
  257. return setPrimitive(field);
  258. }
  259. public UpdateColumnSet<T, Short> set(short field) {
  260. return setPrimitive(field);
  261. }
  262. public UpdateColumnSet<T, Integer> set(int field) {
  263. return setPrimitive(field);
  264. }
  265. public UpdateColumnSet<T, Long> set(long field) {
  266. return setPrimitive(field);
  267. }
  268. public UpdateColumnSet<T, Float> set(float field) {
  269. return setPrimitive(field);
  270. }
  271. public UpdateColumnSet<T, Double> set(double field) {
  272. return setPrimitive(field);
  273. }
  274. private <A> UpdateColumnSet<T, A> setPrimitive(A field) {
  275. A alias = getPrimitiveAliasByValue(field);
  276. if (alias == null) {
  277. // this will result in an unmapped field exception
  278. return set(field);
  279. }
  280. return set(alias);
  281. }
  282. public <A> UpdateColumnIncrement<T, A> increment(A field) {
  283. return new UpdateColumnIncrement<T, A>(this, field);
  284. }
  285. public UpdateColumnIncrement<T, Byte> increment(byte field) {
  286. return incrementPrimitive(field);
  287. }
  288. public UpdateColumnIncrement<T, Short> increment(short field) {
  289. return incrementPrimitive(field);
  290. }
  291. public UpdateColumnIncrement<T, Integer> increment(int field) {
  292. return incrementPrimitive(field);
  293. }
  294. public UpdateColumnIncrement<T, Long> increment(long field) {
  295. return incrementPrimitive(field);
  296. }
  297. public UpdateColumnIncrement<T, Float> increment(float field) {
  298. return incrementPrimitive(field);
  299. }
  300. public UpdateColumnIncrement<T, Double> increment(double field) {
  301. return incrementPrimitive(field);
  302. }
  303. private <A> UpdateColumnIncrement<T, A> incrementPrimitive(A field) {
  304. A alias = getPrimitiveAliasByValue(field);
  305. if (alias == null) {
  306. // this will result in an unmapped field exception
  307. return increment(field);
  308. }
  309. return increment(alias);
  310. }
  311. public int update() {
  312. if (updateColumnDeclarations.size() == 0) {
  313. throw new IciqlException("Missing set or increment call.");
  314. }
  315. SQLStatement stat = new SQLStatement(db);
  316. stat.appendSQL("UPDATE ");
  317. from.appendSQL(stat);
  318. stat.appendSQL(" SET ");
  319. int i = 0;
  320. for (UpdateColumn declaration : updateColumnDeclarations) {
  321. if (i++ > 0) {
  322. stat.appendSQL(", ");
  323. }
  324. declaration.appendSQL(stat);
  325. }
  326. appendWhere(stat);
  327. IciqlLogger.update(stat.getSQL());
  328. return stat.executeUpdate();
  329. }
  330. public <X, Z> List<X> selectDistinct(Z x) {
  331. return select(x, true);
  332. }
  333. public <X, Z> List<X> select(Z x) {
  334. return select(x, false);
  335. }
  336. @SuppressWarnings("unchecked")
  337. private <X, Z> List<X> select(Z x, boolean distinct) {
  338. Class<?> clazz = x.getClass();
  339. if (Utils.isSimpleType(clazz)) {
  340. return selectSimple((X) x, distinct);
  341. }
  342. Class<?> enclosingClass = clazz.getEnclosingClass();
  343. if (enclosingClass != null) {
  344. // anonymous inner class
  345. clazz = clazz.getSuperclass();
  346. }
  347. return select((Class<X>) clazz, (X) x, distinct);
  348. }
  349. private <X> List<X> select(Class<X> clazz, X x, boolean distinct) {
  350. List<X> result = Utils.newArrayList();
  351. TableDefinition<X> def = db.define(clazz);
  352. SQLStatement stat = getSelectStatement(distinct);
  353. def.appendSelectList(stat, this, x);
  354. appendFromWhere(stat);
  355. ResultSet rs = stat.executeQuery();
  356. try {
  357. int[] columns = def.mapColumns(false, rs);
  358. while (rs.next()) {
  359. X row = Utils.newObject(clazz);
  360. def.readRow(db.getDialect(), row, rs, columns);
  361. result.add(row);
  362. }
  363. } catch (SQLException e) {
  364. throw IciqlException.fromSQL(stat.getSQL(), e);
  365. } finally {
  366. JdbcUtils.closeSilently(rs, true);
  367. }
  368. return result;
  369. }
  370. @SuppressWarnings("unchecked")
  371. private <X> List<X> selectSimple(X x, boolean distinct) {
  372. SQLStatement stat = getSelectStatement(distinct);
  373. appendSQL(stat, null, x);
  374. appendFromWhere(stat);
  375. ResultSet rs = stat.executeQuery();
  376. List<X> result = Utils.newArrayList();
  377. Class<? extends DataTypeAdapter<?>> typeAdapter = Utils.getDataTypeAdapter(x.getClass().getAnnotations());
  378. try {
  379. while (rs.next()) {
  380. X value = (X) db.getDialect().deserialize(rs, 1, x.getClass(), typeAdapter);
  381. result.add(value);
  382. }
  383. } catch (Exception e) {
  384. throw IciqlException.fromSQL(stat.getSQL(), e);
  385. } finally {
  386. JdbcUtils.closeSilently(rs, true);
  387. }
  388. return result;
  389. }
  390. private SQLStatement getSelectStatement(boolean distinct) {
  391. SQLStatement stat = new SQLStatement(db);
  392. stat.appendSQL("SELECT ");
  393. if (distinct) {
  394. stat.appendSQL("DISTINCT ");
  395. }
  396. return stat;
  397. }
  398. /**
  399. * Begin a primitive boolean field condition clause.
  400. *
  401. * @param x
  402. * the primitive boolean field to query
  403. * @return a query condition to continue building the condition
  404. */
  405. public QueryCondition<T, Boolean> where(boolean x) {
  406. from.getAliasDefinition().checkMultipleBooleans();
  407. return wherePrimitive(x);
  408. }
  409. /**
  410. * Begin a primitive short field condition clause.
  411. *
  412. * @param x
  413. * the primitive short field to query
  414. * @return a query condition to continue building the condition
  415. */
  416. public QueryCondition<T, Byte> where(byte x) {
  417. return wherePrimitive(x);
  418. }
  419. /**
  420. * Begin a primitive short field condition clause.
  421. *
  422. * @param x
  423. * the primitive short field to query
  424. * @return a query condition to continue building the condition
  425. */
  426. public QueryCondition<T, Short> where(short x) {
  427. return wherePrimitive(x);
  428. }
  429. /**
  430. * Begin a primitive int field condition clause.
  431. *
  432. * @param x
  433. * the primitive int field to query
  434. * @return a query condition to continue building the condition
  435. */
  436. public QueryCondition<T, Integer> where(int x) {
  437. return wherePrimitive(x);
  438. }
  439. /**
  440. * Begin a primitive long field condition clause.
  441. *
  442. * @param x
  443. * the primitive long field to query
  444. * @return a query condition to continue building the condition
  445. */
  446. public QueryCondition<T, Long> where(long x) {
  447. return wherePrimitive(x);
  448. }
  449. /**
  450. * Begin a primitive float field condition clause.
  451. *
  452. * @param x
  453. * the primitive float field to query
  454. * @return a query condition to continue building the condition
  455. */
  456. public QueryCondition<T, Float> where(float x) {
  457. return wherePrimitive(x);
  458. }
  459. /**
  460. * Begin a primitive double field condition clause.
  461. *
  462. * @param x
  463. * the primitive double field to query
  464. * @return a query condition to continue building the condition
  465. */
  466. public QueryCondition<T, Double> where(double x) {
  467. return wherePrimitive(x);
  468. }
  469. /**
  470. * Begins a primitive field condition clause.
  471. *
  472. * @param value
  473. * @return a query condition to continue building the condition
  474. */
  475. private <A> QueryCondition<T, A> wherePrimitive(A value) {
  476. A alias = getPrimitiveAliasByValue(value);
  477. if (alias == null) {
  478. // this will result in an unmapped field exception
  479. return where(value);
  480. }
  481. return where(alias);
  482. }
  483. /**
  484. * Begin an Object field condition clause.
  485. *
  486. * @param x
  487. * the mapped object to query
  488. * @return a query condition to continue building the condition
  489. */
  490. public <A> QueryCondition<T, A> where(A x) {
  491. from.getAliasDefinition().checkMultipleEnums(x);
  492. return new QueryCondition<T, A>(this, x);
  493. }
  494. public <A> QueryWhere<T> where(Filter filter) {
  495. HashMap<String, Object> fieldMap = Utils.newHashMap();
  496. for (Field f : filter.getClass().getDeclaredFields()) {
  497. f.setAccessible(true);
  498. try {
  499. Object obj = f.get(filter);
  500. if (obj == from.getAlias()) {
  501. List<TableDefinition.FieldDefinition> fields = from.getAliasDefinition().getFields();
  502. String name = f.getName();
  503. for (TableDefinition.FieldDefinition field : fields) {
  504. String n = name + "." + field.field.getName();
  505. Object o = field.field.get(obj);
  506. fieldMap.put(n, o);
  507. }
  508. }
  509. fieldMap.put(f.getName(), f.get(filter));
  510. } catch (Exception e) {
  511. throw new IciqlException(e);
  512. }
  513. }
  514. Token filterCode = new ClassReader().decompile(filter, fieldMap, "where");
  515. // String filterQuery = filterCode.toString();
  516. conditions.add(filterCode);
  517. return new QueryWhere<T>(this);
  518. }
  519. public QueryWhere<T> where(String fragment, List<?> args) {
  520. return this.where(fragment, args.toArray());
  521. }
  522. public QueryWhere<T> where(String fragment, Object... args) {
  523. conditions.add(new RuntimeToken(fragment, args));
  524. return new QueryWhere<T>(this);
  525. }
  526. public Query<T> where(And<T> conditions) {
  527. whereTrue();
  528. addConditionToken(conditions.where.query);
  529. return this;
  530. }
  531. public Query<T> where(Or<T> conditions) {
  532. whereFalse();
  533. addConditionToken(conditions.where.query);
  534. return this;
  535. }
  536. public QueryWhere<T> whereTrue() {
  537. return whereTrue(true);
  538. }
  539. public QueryWhere<T> whereFalse() {
  540. return whereTrue(false);
  541. }
  542. public QueryWhere<T> whereTrue(Boolean condition) {
  543. Token token = new Function("", condition);
  544. addConditionToken(token);
  545. return new QueryWhere<T>(this);
  546. }
  547. /**
  548. * Sets the Limit and Offset of a query.
  549. *
  550. * @return the query
  551. */
  552. public Query<T> limit(long limit) {
  553. this.limit = limit;
  554. return this;
  555. }
  556. public Query<T> offset(long offset) {
  557. this.offset = offset;
  558. return this;
  559. }
  560. public Query<T> orderBy(boolean field) {
  561. from.getAliasDefinition().checkMultipleBooleans();
  562. return orderByPrimitive(field);
  563. }
  564. public Query<T> orderBy(byte field) {
  565. return orderByPrimitive(field);
  566. }
  567. public Query<T> orderBy(short field) {
  568. return orderByPrimitive(field);
  569. }
  570. public Query<T> orderBy(int field) {
  571. return orderByPrimitive(field);
  572. }
  573. public Query<T> orderBy(long field) {
  574. return orderByPrimitive(field);
  575. }
  576. public Query<T> orderBy(float field) {
  577. return orderByPrimitive(field);
  578. }
  579. public Query<T> orderBy(double field) {
  580. return orderByPrimitive(field);
  581. }
  582. Query<T> orderByPrimitive(Object field) {
  583. Object alias = getPrimitiveAliasByValue(field);
  584. if (alias == null) {
  585. return orderBy(field);
  586. }
  587. return orderBy(alias);
  588. }
  589. public Query<T> orderBy(Object expr) {
  590. from.getAliasDefinition().checkMultipleEnums(expr);
  591. OrderExpression<T> e = new OrderExpression<T>(this, expr, false, false, false);
  592. addOrderBy(e);
  593. return this;
  594. }
  595. /**
  596. * Order by a number of columns.
  597. *
  598. * @param expressions
  599. * the columns
  600. * @return the query
  601. */
  602. public Query<T> orderBy(Object... expressions) {
  603. for (Object expr : expressions) {
  604. from.getAliasDefinition().checkMultipleEnums(expr);
  605. OrderExpression<T> e = new OrderExpression<T>(this, expr, false, false, false);
  606. addOrderBy(e);
  607. }
  608. return this;
  609. }
  610. public Query<T> orderByDesc(Object expr) {
  611. OrderExpression<T> e = new OrderExpression<T>(this, expr, true, false, false);
  612. addOrderBy(e);
  613. return this;
  614. }
  615. public Query<T> groupBy(boolean field) {
  616. from.getAliasDefinition().checkMultipleBooleans();
  617. return groupByPrimitive(field);
  618. }
  619. public Query<T> groupBy(byte field) {
  620. return groupByPrimitive(field);
  621. }
  622. public Query<T> groupBy(short field) {
  623. return groupByPrimitive(field);
  624. }
  625. public Query<T> groupBy(int field) {
  626. return groupByPrimitive(field);
  627. }
  628. public Query<T> groupBy(long field) {
  629. return groupByPrimitive(field);
  630. }
  631. public Query<T> groupBy(float field) {
  632. return groupByPrimitive(field);
  633. }
  634. public Query<T> groupBy(double field) {
  635. return groupByPrimitive(field);
  636. }
  637. Query<T> groupByPrimitive(Object field) {
  638. Object alias = getPrimitiveAliasByValue(field);
  639. if (alias == null) {
  640. return groupBy(field);
  641. }
  642. return groupBy(alias);
  643. }
  644. public Query<T> groupBy(Object expr) {
  645. from.getAliasDefinition().checkMultipleEnums(expr);
  646. groupByExpressions.add(expr);
  647. return this;
  648. }
  649. public Query<T> groupBy(Object... groupBy) {
  650. this.groupByExpressions.addAll(Arrays.asList(groupBy));
  651. return this;
  652. }
  653. /**
  654. * INTERNAL
  655. *
  656. * @param stat
  657. * the statement
  658. * @param alias
  659. * the alias object (can be null)
  660. * @param value
  661. * the value
  662. */
  663. public void appendSQL(SQLStatement stat, Object alias, Object value) {
  664. if (Function.count() == value) {
  665. stat.appendSQL("COUNT(*)");
  666. return;
  667. }
  668. if (RuntimeParameter.PARAMETER == value) {
  669. stat.appendSQL("?");
  670. addParameter(stat, alias, value);
  671. return;
  672. }
  673. Token token = Db.getToken(value);
  674. if (token != null) {
  675. token.appendSQL(stat, this);
  676. return;
  677. }
  678. if (alias != null && value.getClass().isEnum()) {
  679. // special case:
  680. // value is first enum constant which is also the alias object.
  681. // the first enum constant is used as the alias because we can not
  682. // instantiate an enum reflectively.
  683. stat.appendSQL("?");
  684. addParameter(stat, alias, value);
  685. return;
  686. }
  687. SelectColumn<T> col = getColumnByReference(value);
  688. if (col != null) {
  689. col.appendSQL(stat);
  690. return;
  691. }
  692. stat.appendSQL("?");
  693. addParameter(stat, alias, value);
  694. }
  695. /**
  696. * INTERNAL
  697. *
  698. * @param stat
  699. * the statement
  700. * @param alias
  701. * the alias object (can be null)
  702. * @param valueLeft
  703. * the value on the left of the compound clause
  704. * @param valueRight
  705. * the value on the right of the compound clause
  706. * @param compareType
  707. * the current compare type (e.g. BETWEEN)
  708. */
  709. public void appendSQL(SQLStatement stat, Object alias, Object valueLeft, Object valueRight,
  710. CompareType compareType) {
  711. stat.appendSQL("?");
  712. stat.appendSQL(" ");
  713. switch (compareType) {
  714. case BETWEEN:
  715. stat.appendSQL("AND");
  716. break;
  717. }
  718. stat.appendSQL(" ");
  719. stat.appendSQL("?");
  720. addParameter(stat, alias, valueLeft);
  721. addParameter(stat, alias, valueRight);
  722. }
  723. public void appendSQL(SQLStatement stat, Object alias, Iterable<Object> values,
  724. CompareType compareType) {
  725. boolean first = true;
  726. stat.appendSQL("(");
  727. for (Object value : values) {
  728. if (first) {
  729. first = false;
  730. } else {
  731. stat.appendSQL(", ");
  732. }
  733. stat.appendSQL("?");
  734. addParameter(stat, alias, value);
  735. }
  736. stat.appendSQL(")");
  737. }
  738. private void addParameter(SQLStatement stat, Object alias, Object value) {
  739. SelectColumn<T> col = getColumnByReference(alias);
  740. if (col != null && value.getClass().isEnum()) {
  741. // enum
  742. EnumType type = col.getFieldDefinition().enumType;
  743. Enum<?> anEnum = (Enum<?>) value;
  744. Object y = Utils.convertEnum(anEnum, type);
  745. stat.addParameter(y);
  746. } else if (col != null) {
  747. // object
  748. Class<? extends DataTypeAdapter<?>> typeAdapter = col.getFieldDefinition().typeAdapter;
  749. Object parameter = db.getDialect().serialize(value, typeAdapter);
  750. stat.addParameter(parameter);
  751. } else {
  752. // primitive
  753. stat.addParameter(value);
  754. }
  755. }
  756. void addConditionToken(Token condition) {
  757. if (condition == ConditionOpenClose.OPEN) {
  758. conditionDepth ++;
  759. } else if (condition == ConditionOpenClose.CLOSE) {
  760. conditionDepth --;
  761. if (conditionDepth < 0) {
  762. throw new IciqlException("unmatch condition open-close count");
  763. }
  764. }
  765. conditions.add(condition);
  766. }
  767. void addConditionToken(Query<T> other) {
  768. for (Token condition : other.conditions) {
  769. addConditionToken(condition);
  770. }
  771. }
  772. void addUpdateColumnDeclaration(UpdateColumn declaration) {
  773. updateColumnDeclarations.add(declaration);
  774. }
  775. void appendWhere(SQLStatement stat) {
  776. if (conditionDepth != 0) {
  777. throw new IciqlException("unmatch condition open-close count");
  778. }
  779. if (!conditions.isEmpty()) {
  780. stat.appendSQL(" WHERE ");
  781. boolean skipNextConjunction = false;
  782. for (Token token : conditions) {
  783. if (skipNextConjunction && token instanceof ConditionAndOr) {
  784. skipNextConjunction = false;
  785. continue;
  786. }
  787. token.appendSQL(stat, this);
  788. stat.appendSQL(" ");
  789. if (ConditionOpenClose.OPEN == token) {
  790. skipNextConjunction = true;
  791. }
  792. }
  793. }
  794. }
  795. void appendFromWhere(SQLStatement stat) {
  796. appendFromWhere(stat, true);
  797. }
  798. void appendFromWhere(SQLStatement stat, boolean log) {
  799. stat.appendSQL(" FROM ");
  800. from.appendSQL(stat);
  801. for (SelectTable<T> join : joins) {
  802. join.appendSQLAsJoin(stat, this);
  803. }
  804. appendWhere(stat);
  805. if (!groupByExpressions.isEmpty()) {
  806. stat.appendSQL(" GROUP BY ");
  807. int i = 0;
  808. for (Object obj : groupByExpressions) {
  809. if (i++ > 0) {
  810. stat.appendSQL(", ");
  811. }
  812. appendSQL(stat, null, obj);
  813. stat.appendSQL(" ");
  814. }
  815. }
  816. if (!orderByList.isEmpty()) {
  817. stat.appendSQL(" ORDER BY ");
  818. int i = 0;
  819. for (OrderExpression<T> o : orderByList) {
  820. if (i++ > 0) {
  821. stat.appendSQL(", ");
  822. }
  823. o.appendSQL(stat);
  824. stat.appendSQL(" ");
  825. }
  826. }
  827. db.getDialect().appendLimitOffset(stat, limit, offset);
  828. if (log) {
  829. IciqlLogger.select(stat.getSQL());
  830. }
  831. }
  832. /**
  833. * Join another table.
  834. *
  835. * @param alias
  836. * an alias for the table to join
  837. * @return the joined query
  838. */
  839. public <A> QueryJoin<T> innerJoin(A alias) {
  840. return join(alias, false);
  841. }
  842. public <A> QueryJoin<T> leftJoin(A alias) {
  843. return join(alias, true);
  844. }
  845. @SuppressWarnings({ "unchecked", "rawtypes" })
  846. private <A> QueryJoin<T> join(A alias, boolean outerJoin) {
  847. TableDefinition<T> def = (TableDefinition<T>) db.define(alias.getClass());
  848. SelectTable<T> join = new SelectTable(db, this, alias, outerJoin);
  849. def.initSelectObject(join, alias, aliasMap, false);
  850. joins.add(join);
  851. return new QueryJoin(this, join);
  852. }
  853. Db getDb() {
  854. return db;
  855. }
  856. SelectTable<T> getFrom() {
  857. return from;
  858. }
  859. boolean isJoin() {
  860. return !joins.isEmpty();
  861. }
  862. SelectTable<?> getSelectTable(Object alias) {
  863. if (from.getAlias() == alias) {
  864. return from;
  865. } else {
  866. for (SelectTable<?> join : joins) {
  867. if (join.getAlias() == alias) {
  868. return join;
  869. }
  870. }
  871. }
  872. return null;
  873. }
  874. /**
  875. * This method returns a mapped Object field by its reference.
  876. *
  877. * @param obj
  878. * @return
  879. */
  880. private SelectColumn<T> getColumnByReference(Object obj) {
  881. SelectColumn<T> col = aliasMap.get(obj);
  882. return col;
  883. }
  884. /**
  885. * This method returns the alias of a mapped primitive field by its value.
  886. *
  887. * @param obj
  888. * @return
  889. */
  890. @SuppressWarnings("unchecked")
  891. <A> A getPrimitiveAliasByValue(A obj) {
  892. for (Object alias : aliasMap.keySet()) {
  893. if (alias.equals(obj)) {
  894. SelectColumn<T> match = aliasMap.get(alias);
  895. if (match.getFieldDefinition().isPrimitive) {
  896. return (A) alias;
  897. }
  898. }
  899. }
  900. return null;
  901. }
  902. void addOrderBy(OrderExpression<T> expr) {
  903. orderByList.add(expr);
  904. }
  905. }