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 34KB

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