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

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