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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. // SQLite returns pre-closed ResultSets for query results with 0 rows
  228. if (!rs.isClosed()) {
  229. int[] columns = def.mapColumns(db.getDialect(), false, rs);
  230. while (rs.next()) {
  231. T item = from.newObject();
  232. def.readRow(db.getDialect(), item, rs, columns);
  233. result.add(item);
  234. }
  235. }
  236. } catch (SQLException e) {
  237. throw IciqlException.fromSQL(stat.getSQL(), e);
  238. } finally {
  239. JdbcUtils.closeSilently(rs, true);
  240. }
  241. return result;
  242. }
  243. public int delete() {
  244. SQLStatement stat = new SQLStatement(db);
  245. stat.appendSQL("DELETE FROM ");
  246. from.appendSQL(stat);
  247. appendWhere(stat);
  248. IciqlLogger.delete(stat.getSQL());
  249. return stat.executeUpdate();
  250. }
  251. public <A> Query<T> setNull(A field) {
  252. return set(field).to(null);
  253. }
  254. public <A> UpdateColumnSet<T, A> set(A field) {
  255. from.getAliasDefinition().checkMultipleEnums(field);
  256. return new UpdateColumnSet<T, A>(this, field);
  257. }
  258. public UpdateColumnSet<T, Boolean> set(boolean field) {
  259. from.getAliasDefinition().checkMultipleBooleans();
  260. return setPrimitive(field);
  261. }
  262. public UpdateColumnSet<T, Byte> set(byte field) {
  263. return setPrimitive(field);
  264. }
  265. public UpdateColumnSet<T, Short> set(short field) {
  266. return setPrimitive(field);
  267. }
  268. public UpdateColumnSet<T, Integer> set(int field) {
  269. return setPrimitive(field);
  270. }
  271. public UpdateColumnSet<T, Long> set(long field) {
  272. return setPrimitive(field);
  273. }
  274. public UpdateColumnSet<T, Float> set(float field) {
  275. return setPrimitive(field);
  276. }
  277. public UpdateColumnSet<T, Double> set(double field) {
  278. return setPrimitive(field);
  279. }
  280. private <A> UpdateColumnSet<T, A> setPrimitive(A field) {
  281. A alias = getPrimitiveAliasByValue(field);
  282. if (alias == null) {
  283. // this will result in an unmapped field exception
  284. return set(field);
  285. }
  286. return set(alias);
  287. }
  288. public <A> UpdateColumnIncrement<T, A> increment(A field) {
  289. return new UpdateColumnIncrement<T, A>(this, field);
  290. }
  291. public UpdateColumnIncrement<T, Byte> increment(byte field) {
  292. return incrementPrimitive(field);
  293. }
  294. public UpdateColumnIncrement<T, Short> increment(short field) {
  295. return incrementPrimitive(field);
  296. }
  297. public UpdateColumnIncrement<T, Integer> increment(int field) {
  298. return incrementPrimitive(field);
  299. }
  300. public UpdateColumnIncrement<T, Long> increment(long field) {
  301. return incrementPrimitive(field);
  302. }
  303. public UpdateColumnIncrement<T, Float> increment(float field) {
  304. return incrementPrimitive(field);
  305. }
  306. public UpdateColumnIncrement<T, Double> increment(double field) {
  307. return incrementPrimitive(field);
  308. }
  309. private <A> UpdateColumnIncrement<T, A> incrementPrimitive(A field) {
  310. A alias = getPrimitiveAliasByValue(field);
  311. if (alias == null) {
  312. // this will result in an unmapped field exception
  313. return increment(field);
  314. }
  315. return increment(alias);
  316. }
  317. public int update() {
  318. if (updateColumnDeclarations.size() == 0) {
  319. throw new IciqlException("Missing set or increment call.");
  320. }
  321. SQLStatement stat = new SQLStatement(db);
  322. stat.appendSQL("UPDATE ");
  323. from.appendSQL(stat);
  324. stat.appendSQL(" SET ");
  325. int i = 0;
  326. for (UpdateColumn declaration : updateColumnDeclarations) {
  327. if (i++ > 0) {
  328. stat.appendSQL(", ");
  329. }
  330. declaration.appendSQL(stat);
  331. }
  332. appendWhere(stat);
  333. IciqlLogger.update(stat.getSQL());
  334. return stat.executeUpdate();
  335. }
  336. public <X, Z> List<X> selectDistinct(Z x) {
  337. return select(x, true);
  338. }
  339. public <X, Z> List<X> select(Z x) {
  340. return select(x, false);
  341. }
  342. @SuppressWarnings("unchecked")
  343. private <X, Z> List<X> select(Z x, boolean distinct) {
  344. Class<?> clazz = x.getClass();
  345. if (Db.isToken(x)) {
  346. // selecting a function
  347. return selectFunction((X) x, distinct);
  348. } else {
  349. // selecting a column
  350. SelectColumn<T> col = getColumnByReference(x);
  351. if (col == null) {
  352. col = getColumnByReference(getPrimitiveAliasByValue(x));
  353. }
  354. if (col != null) {
  355. return (List<X>) selectColumn(col, clazz, distinct);
  356. }
  357. }
  358. // selecting into a new object type
  359. Class<?> enclosingClass = clazz.getEnclosingClass();
  360. if (enclosingClass != null) {
  361. // anonymous inner class
  362. clazz = clazz.getSuperclass();
  363. }
  364. return select((Class<X>) clazz, (X) x, distinct);
  365. }
  366. private <X> List<X> select(Class<X> clazz, X x, boolean distinct) {
  367. List<X> result = Utils.newArrayList();
  368. TableDefinition<X> def = db.define(clazz);
  369. SQLStatement stat = getSelectStatement(distinct);
  370. def.appendSelectList(stat, this, x);
  371. appendFromWhere(stat);
  372. ResultSet rs = stat.executeQuery();
  373. try {
  374. // SQLite returns pre-closed ResultSets for query results with 0 rows
  375. if (!rs.isClosed()) {
  376. int[] columns = def.mapColumns(db.getDialect(), false, rs);
  377. while (rs.next()) {
  378. X row = Utils.newObject(clazz);
  379. def.readRow(db.getDialect(), row, rs, columns);
  380. result.add(row);
  381. }
  382. }
  383. } catch (SQLException e) {
  384. throw IciqlException.fromSQL(stat.getSQL(), e);
  385. } finally {
  386. JdbcUtils.closeSilently(rs, true);
  387. }
  388. return result;
  389. }
  390. @SuppressWarnings("unchecked")
  391. private <X> List<X> selectFunction(X x, boolean distinct) {
  392. SQLStatement stat = getSelectStatement(distinct);
  393. appendSQL(stat, null, x);
  394. appendFromWhere(stat);
  395. ResultSet rs = stat.executeQuery();
  396. List<X> result = Utils.newArrayList();
  397. try {
  398. // SQLite returns pre-closed ResultSets for query results with 0 rows
  399. if (!rs.isClosed()) {
  400. while (rs.next()) {
  401. X value = (X) rs.getObject(1);
  402. result.add(value);
  403. }
  404. }
  405. } catch (Exception e) {
  406. throw IciqlException.fromSQL(stat.getSQL(), e);
  407. } finally {
  408. JdbcUtils.closeSilently(rs, true);
  409. }
  410. return result;
  411. }
  412. @SuppressWarnings("unchecked")
  413. private <X> List<X> selectColumn(SelectColumn<T> col, Class<X> clazz, boolean distinct) {
  414. SQLStatement stat = getSelectStatement(distinct);
  415. col.appendSQL(stat);
  416. appendFromWhere(stat);
  417. ResultSet rs = stat.executeQuery();
  418. List<X> result = Utils.newArrayList();
  419. Class<? extends DataTypeAdapter<?>> typeAdapter = col.getFieldDefinition().typeAdapter;
  420. try {
  421. // SQLite returns pre-closed ResultSets for query results with 0 rows
  422. if (!rs.isClosed()) {
  423. while (rs.next()) {
  424. X value = (X) db.getDialect().deserialize(rs, 1, clazz, typeAdapter);
  425. result.add(value);
  426. }
  427. }
  428. } catch (Exception e) {
  429. throw IciqlException.fromSQL(stat.getSQL(), e);
  430. } finally {
  431. JdbcUtils.closeSilently(rs, true);
  432. }
  433. return result;
  434. }
  435. private SQLStatement getSelectStatement(boolean distinct) {
  436. SQLStatement stat = new SQLStatement(db);
  437. stat.appendSQL("SELECT ");
  438. if (distinct) {
  439. stat.appendSQL("DISTINCT ");
  440. }
  441. return stat;
  442. }
  443. /**
  444. * Begin a primitive boolean field condition clause.
  445. *
  446. * @param x
  447. * the primitive boolean field to query
  448. * @return a query condition to continue building the condition
  449. */
  450. public QueryCondition<T, Boolean> where(boolean x) {
  451. from.getAliasDefinition().checkMultipleBooleans();
  452. return wherePrimitive(x);
  453. }
  454. /**
  455. * Begin a primitive short field condition clause.
  456. *
  457. * @param x
  458. * the primitive short field to query
  459. * @return a query condition to continue building the condition
  460. */
  461. public QueryCondition<T, Byte> where(byte x) {
  462. return wherePrimitive(x);
  463. }
  464. /**
  465. * Begin a primitive short field condition clause.
  466. *
  467. * @param x
  468. * the primitive short field to query
  469. * @return a query condition to continue building the condition
  470. */
  471. public QueryCondition<T, Short> where(short x) {
  472. return wherePrimitive(x);
  473. }
  474. /**
  475. * Begin a primitive int field condition clause.
  476. *
  477. * @param x
  478. * the primitive int field to query
  479. * @return a query condition to continue building the condition
  480. */
  481. public QueryCondition<T, Integer> where(int x) {
  482. return wherePrimitive(x);
  483. }
  484. /**
  485. * Begin a primitive long field condition clause.
  486. *
  487. * @param x
  488. * the primitive long field to query
  489. * @return a query condition to continue building the condition
  490. */
  491. public QueryCondition<T, Long> where(long x) {
  492. return wherePrimitive(x);
  493. }
  494. /**
  495. * Begin a primitive float field condition clause.
  496. *
  497. * @param x
  498. * the primitive float field to query
  499. * @return a query condition to continue building the condition
  500. */
  501. public QueryCondition<T, Float> where(float x) {
  502. return wherePrimitive(x);
  503. }
  504. /**
  505. * Begin a primitive double field condition clause.
  506. *
  507. * @param x
  508. * the primitive double field to query
  509. * @return a query condition to continue building the condition
  510. */
  511. public QueryCondition<T, Double> where(double x) {
  512. return wherePrimitive(x);
  513. }
  514. /**
  515. * Begins a primitive field condition clause.
  516. *
  517. * @param value
  518. * @return a query condition to continue building the condition
  519. */
  520. private <A> QueryCondition<T, A> wherePrimitive(A value) {
  521. A alias = getPrimitiveAliasByValue(value);
  522. if (alias == null) {
  523. // this will result in an unmapped field exception
  524. return where(value);
  525. }
  526. return where(alias);
  527. }
  528. /**
  529. * Begin an Object field condition clause.
  530. *
  531. * @param x
  532. * the mapped object to query
  533. * @return a query condition to continue building the condition
  534. */
  535. public <A> QueryCondition<T, A> where(A x) {
  536. from.getAliasDefinition().checkMultipleEnums(x);
  537. return new QueryCondition<T, A>(this, x);
  538. }
  539. public <A> QueryWhere<T> where(Filter filter) {
  540. HashMap<String, Object> fieldMap = Utils.newHashMap();
  541. for (Field f : filter.getClass().getDeclaredFields()) {
  542. f.setAccessible(true);
  543. try {
  544. Object obj = f.get(filter);
  545. if (obj == from.getAlias()) {
  546. List<TableDefinition.FieldDefinition> fields = from.getAliasDefinition().getFields();
  547. String name = f.getName();
  548. for (TableDefinition.FieldDefinition field : fields) {
  549. String n = name + "." + field.field.getName();
  550. Object o = field.field.get(obj);
  551. fieldMap.put(n, o);
  552. }
  553. }
  554. fieldMap.put(f.getName(), f.get(filter));
  555. } catch (Exception e) {
  556. throw new IciqlException(e);
  557. }
  558. }
  559. Token filterCode = new ClassReader().decompile(filter, fieldMap, "where");
  560. // String filterQuery = filterCode.toString();
  561. conditions.add(filterCode);
  562. return new QueryWhere<T>(this);
  563. }
  564. public QueryWhere<T> where(String fragment, List<?> args) {
  565. return this.where(fragment, args.toArray());
  566. }
  567. public QueryWhere<T> where(String fragment, Object... args) {
  568. conditions.add(new RuntimeToken(fragment, args));
  569. return new QueryWhere<T>(this);
  570. }
  571. public Query<T> where(And<T> conditions) {
  572. whereTrue();
  573. addConditionToken(conditions.where.query);
  574. return this;
  575. }
  576. public Query<T> where(Or<T> conditions) {
  577. whereFalse();
  578. addConditionToken(conditions.where.query);
  579. return this;
  580. }
  581. public QueryWhere<T> whereTrue() {
  582. return whereTrue(true);
  583. }
  584. public QueryWhere<T> whereFalse() {
  585. return whereTrue(false);
  586. }
  587. public QueryWhere<T> whereTrue(Boolean condition) {
  588. Token token = new Function("", condition);
  589. addConditionToken(token);
  590. return new QueryWhere<T>(this);
  591. }
  592. /**
  593. * Sets the Limit and Offset of a query.
  594. *
  595. * @return the query
  596. */
  597. public Query<T> limit(long limit) {
  598. this.limit = limit;
  599. return this;
  600. }
  601. public Query<T> offset(long offset) {
  602. this.offset = offset;
  603. return this;
  604. }
  605. public Query<T> orderBy(boolean field) {
  606. from.getAliasDefinition().checkMultipleBooleans();
  607. return orderByPrimitive(field);
  608. }
  609. public Query<T> orderBy(byte field) {
  610. return orderByPrimitive(field);
  611. }
  612. public Query<T> orderBy(short field) {
  613. return orderByPrimitive(field);
  614. }
  615. public Query<T> orderBy(int field) {
  616. return orderByPrimitive(field);
  617. }
  618. public Query<T> orderBy(long field) {
  619. return orderByPrimitive(field);
  620. }
  621. public Query<T> orderBy(float field) {
  622. return orderByPrimitive(field);
  623. }
  624. public Query<T> orderBy(double field) {
  625. return orderByPrimitive(field);
  626. }
  627. Query<T> orderByPrimitive(Object field) {
  628. Object alias = getPrimitiveAliasByValue(field);
  629. if (alias == null) {
  630. return orderBy(field);
  631. }
  632. return orderBy(alias);
  633. }
  634. public Query<T> orderBy(Object expr) {
  635. from.getAliasDefinition().checkMultipleEnums(expr);
  636. OrderExpression<T> e = new OrderExpression<T>(this, expr, false, false, false);
  637. addOrderBy(e);
  638. return this;
  639. }
  640. /**
  641. * Order by a number of columns.
  642. *
  643. * @param expressions
  644. * the columns
  645. * @return the query
  646. */
  647. public Query<T> orderBy(Object... expressions) {
  648. for (Object expr : expressions) {
  649. from.getAliasDefinition().checkMultipleEnums(expr);
  650. OrderExpression<T> e = new OrderExpression<T>(this, expr, false, false, false);
  651. addOrderBy(e);
  652. }
  653. return this;
  654. }
  655. public Query<T> orderByDesc(Object expr) {
  656. OrderExpression<T> e = new OrderExpression<T>(this, expr, true, false, false);
  657. addOrderBy(e);
  658. return this;
  659. }
  660. public Query<T> groupBy(boolean field) {
  661. from.getAliasDefinition().checkMultipleBooleans();
  662. return groupByPrimitive(field);
  663. }
  664. public Query<T> groupBy(byte field) {
  665. return groupByPrimitive(field);
  666. }
  667. public Query<T> groupBy(short field) {
  668. return groupByPrimitive(field);
  669. }
  670. public Query<T> groupBy(int field) {
  671. return groupByPrimitive(field);
  672. }
  673. public Query<T> groupBy(long field) {
  674. return groupByPrimitive(field);
  675. }
  676. public Query<T> groupBy(float field) {
  677. return groupByPrimitive(field);
  678. }
  679. public Query<T> groupBy(double field) {
  680. return groupByPrimitive(field);
  681. }
  682. Query<T> groupByPrimitive(Object field) {
  683. Object alias = getPrimitiveAliasByValue(field);
  684. if (alias == null) {
  685. return groupBy(field);
  686. }
  687. return groupBy(alias);
  688. }
  689. public Query<T> groupBy(Object expr) {
  690. from.getAliasDefinition().checkMultipleEnums(expr);
  691. groupByExpressions.add(expr);
  692. return this;
  693. }
  694. public Query<T> groupBy(Object... groupBy) {
  695. this.groupByExpressions.addAll(Arrays.asList(groupBy));
  696. return this;
  697. }
  698. /**
  699. * INTERNAL
  700. *
  701. * @param stat
  702. * the statement
  703. * @param alias
  704. * the alias object (can be null)
  705. * @param value
  706. * the value
  707. */
  708. public void appendSQL(SQLStatement stat, Object alias, Object value) {
  709. if (Function.count() == value) {
  710. stat.appendSQL("COUNT(*)");
  711. return;
  712. }
  713. if (RuntimeParameter.PARAMETER == value) {
  714. stat.appendSQL("?");
  715. addParameter(stat, alias, value);
  716. return;
  717. }
  718. Token token = Db.getToken(value);
  719. if (token != null) {
  720. token.appendSQL(stat, this);
  721. return;
  722. }
  723. if (alias != null && value != null && value.getClass().isEnum()) {
  724. // special case:
  725. // value is first enum constant which is also the alias object.
  726. // the first enum constant is used as the alias because we can not
  727. // instantiate an enum reflectively.
  728. stat.appendSQL("?");
  729. addParameter(stat, alias, value);
  730. return;
  731. }
  732. SelectColumn<T> col = getColumnByReference(value);
  733. if (col != null) {
  734. col.appendSQL(stat);
  735. return;
  736. }
  737. stat.appendSQL("?");
  738. addParameter(stat, alias, value);
  739. }
  740. /**
  741. * INTERNAL
  742. *
  743. * @param stat
  744. * the statement
  745. * @param alias
  746. * the alias object (can be null)
  747. * @param valueLeft
  748. * the value on the left of the compound clause
  749. * @param valueRight
  750. * the value on the right of the compound clause
  751. * @param compareType
  752. * the current compare type (e.g. BETWEEN)
  753. */
  754. public void appendSQL(SQLStatement stat, Object alias, Object valueLeft, Object valueRight,
  755. CompareType compareType) {
  756. stat.appendSQL("?");
  757. stat.appendSQL(" ");
  758. switch (compareType) {
  759. case BETWEEN:
  760. stat.appendSQL("AND");
  761. break;
  762. }
  763. stat.appendSQL(" ");
  764. stat.appendSQL("?");
  765. addParameter(stat, alias, valueLeft);
  766. addParameter(stat, alias, valueRight);
  767. }
  768. public void appendSQL(SQLStatement stat, Object alias, Iterable<Object> values,
  769. CompareType compareType) {
  770. boolean first = true;
  771. stat.appendSQL("(");
  772. for (Object value : values) {
  773. if (first) {
  774. first = false;
  775. } else {
  776. stat.appendSQL(", ");
  777. }
  778. stat.appendSQL("?");
  779. addParameter(stat, alias, value);
  780. }
  781. stat.appendSQL(")");
  782. }
  783. private void addParameter(SQLStatement stat, Object alias, Object value) {
  784. SelectColumn<T> col = getColumnByReference(alias);
  785. if (col != null && value != null && value.getClass().isEnum()) {
  786. // enum
  787. TableDefinition.FieldDefinition field = col.getFieldDefinition();
  788. EnumType type = field.enumType;
  789. Enum<?> anEnum = (Enum<?>) value;
  790. Object y = Utils.convertEnum(anEnum, type);
  791. stat.addParameter(y);
  792. } else if (col != null) {
  793. // object
  794. TableDefinition.FieldDefinition field = col.getFieldDefinition();
  795. Class<? extends DataTypeAdapter<?>> typeAdapter = field.typeAdapter;
  796. if (value != null && value instanceof String) {
  797. if (field.trim && field.length > 0) {
  798. // clip strings (issue-15)
  799. String s = (String) value;
  800. if (s.length() > field.length) {
  801. value = s.substring(0, field.length);
  802. }
  803. }
  804. }
  805. Object parameter = db.getDialect().serialize(value, typeAdapter);
  806. stat.addParameter(parameter);
  807. } else {
  808. // primitive
  809. stat.addParameter(value);
  810. }
  811. }
  812. void addConditionToken(Token condition) {
  813. if (condition == ConditionOpenClose.OPEN) {
  814. conditionDepth ++;
  815. } else if (condition == ConditionOpenClose.CLOSE) {
  816. conditionDepth --;
  817. if (conditionDepth < 0) {
  818. throw new IciqlException("unmatch condition open-close count");
  819. }
  820. }
  821. conditions.add(condition);
  822. }
  823. void addConditionToken(Query<T> other) {
  824. for (Token condition : other.conditions) {
  825. addConditionToken(condition);
  826. }
  827. }
  828. void addUpdateColumnDeclaration(UpdateColumn declaration) {
  829. updateColumnDeclarations.add(declaration);
  830. }
  831. void appendWhere(SQLStatement stat) {
  832. if (conditionDepth != 0) {
  833. throw new IciqlException("unmatch condition open-close count");
  834. }
  835. if (!conditions.isEmpty()) {
  836. stat.appendSQL(" WHERE ");
  837. boolean skipNextConjunction = false;
  838. for (Token token : conditions) {
  839. if (skipNextConjunction && token instanceof ConditionAndOr) {
  840. skipNextConjunction = false;
  841. continue;
  842. }
  843. token.appendSQL(stat, this);
  844. stat.appendSQL(" ");
  845. if (ConditionOpenClose.OPEN == token) {
  846. skipNextConjunction = true;
  847. }
  848. }
  849. }
  850. }
  851. void appendFromWhere(SQLStatement stat) {
  852. appendFromWhere(stat, true);
  853. }
  854. void appendFromWhere(SQLStatement stat, boolean log) {
  855. stat.appendSQL(" FROM ");
  856. from.appendSQL(stat);
  857. for (SelectTable<T> join : joins) {
  858. join.appendSQLAsJoin(stat, this);
  859. }
  860. appendWhere(stat);
  861. if (!groupByExpressions.isEmpty()) {
  862. stat.appendSQL(" GROUP BY ");
  863. int i = 0;
  864. for (Object obj : groupByExpressions) {
  865. if (i++ > 0) {
  866. stat.appendSQL(", ");
  867. }
  868. appendSQL(stat, null, obj);
  869. stat.appendSQL(" ");
  870. }
  871. }
  872. if (!orderByList.isEmpty()) {
  873. stat.appendSQL(" ORDER BY ");
  874. int i = 0;
  875. for (OrderExpression<T> o : orderByList) {
  876. if (i++ > 0) {
  877. stat.appendSQL(", ");
  878. }
  879. o.appendSQL(stat);
  880. stat.appendSQL(" ");
  881. }
  882. }
  883. db.getDialect().appendLimitOffset(stat, limit, offset);
  884. if (log) {
  885. IciqlLogger.select(stat.getSQL());
  886. }
  887. }
  888. /**
  889. * Join another table.
  890. *
  891. * @param alias
  892. * an alias for the table to join
  893. * @return the joined query
  894. */
  895. public <A> QueryJoin<T> innerJoin(A alias) {
  896. return join(alias, false);
  897. }
  898. public <A> QueryJoin<T> leftJoin(A alias) {
  899. return join(alias, true);
  900. }
  901. @SuppressWarnings({ "unchecked", "rawtypes" })
  902. private <A> QueryJoin<T> join(A alias, boolean outerJoin) {
  903. TableDefinition<T> def = (TableDefinition<T>) db.define(alias.getClass());
  904. SelectTable<T> join = new SelectTable(db, this, alias, outerJoin);
  905. def.initSelectObject(join, alias, aliasMap, false);
  906. joins.add(join);
  907. return new QueryJoin(this, join);
  908. }
  909. Db getDb() {
  910. return db;
  911. }
  912. SelectTable<T> getFrom() {
  913. return from;
  914. }
  915. boolean isJoin() {
  916. return !joins.isEmpty();
  917. }
  918. SelectTable<?> getSelectTable(Object alias) {
  919. if (from.getAlias() == alias) {
  920. return from;
  921. } else {
  922. for (SelectTable<?> join : joins) {
  923. if (join.getAlias() == alias) {
  924. return join;
  925. }
  926. }
  927. }
  928. return null;
  929. }
  930. /**
  931. * This method returns a mapped Object field by its reference.
  932. *
  933. * @param obj
  934. * @return
  935. */
  936. private SelectColumn<T> getColumnByReference(Object obj) {
  937. SelectColumn<T> col = aliasMap.get(obj);
  938. return col;
  939. }
  940. /**
  941. * This method returns the alias of a mapped primitive field by its value.
  942. *
  943. * @param obj
  944. * @return
  945. */
  946. @SuppressWarnings("unchecked")
  947. <A> A getPrimitiveAliasByValue(A obj) {
  948. for (Object alias : aliasMap.keySet()) {
  949. if (alias.equals(obj)) {
  950. SelectColumn<T> match = aliasMap.get(alias);
  951. if (match.getFieldDefinition().isPrimitive) {
  952. return (A) alias;
  953. }
  954. }
  955. }
  956. return null;
  957. }
  958. void addOrderBy(OrderExpression<T> expr) {
  959. orderByList.add(expr);
  960. }
  961. }