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.

QueryTest.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /*
  2. Copyright (c) 2007 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess.query;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;
  29. import com.healthmarketscience.jackcess.DataType;
  30. import com.healthmarketscience.jackcess.Database;
  31. import com.healthmarketscience.jackcess.DatabaseTest;
  32. import com.healthmarketscience.jackcess.query.Query.Row;
  33. import junit.framework.TestCase;
  34. import org.apache.commons.lang.StringUtils;
  35. import static org.apache.commons.lang.SystemUtils.LINE_SEPARATOR;
  36. import static com.healthmarketscience.jackcess.query.QueryFormat.*;
  37. import static com.healthmarketscience.jackcess.JetFormatTest.*;
  38. /**
  39. * @author James Ahlborn
  40. */
  41. public class QueryTest extends TestCase
  42. {
  43. public QueryTest(String name) throws Exception {
  44. super(name);
  45. }
  46. public void testUnionQuery() throws Exception
  47. {
  48. String expr1 = "Select * from Table1";
  49. String expr2 = "Select * from Table2";
  50. UnionQuery query = (UnionQuery)newQuery(
  51. Query.Type.UNION,
  52. newRow(TABLE_ATTRIBUTE, expr1, null, UNION_PART1),
  53. newRow(TABLE_ATTRIBUTE, expr2, null, UNION_PART2));
  54. setFlag(query, 3);
  55. assertEquals(multiline("Select * from Table1",
  56. "UNION Select * from Table2;"),
  57. query.toSQLString());
  58. setFlag(query, 1);
  59. assertEquals(multiline("Select * from Table1",
  60. "UNION ALL Select * from Table2;"),
  61. query.toSQLString());
  62. addRows(query, newRow(ORDERBY_ATTRIBUTE, "Table1.id",
  63. null, null));
  64. assertEquals(multiline("Select * from Table1",
  65. "UNION ALL Select * from Table2",
  66. "ORDER BY Table1.id;"),
  67. query.toSQLString());
  68. removeRows(query, TABLE_ATTRIBUTE);
  69. try {
  70. query.toSQLString();
  71. fail("IllegalStateException should have been thrown");
  72. } catch(IllegalStateException e) {
  73. // success
  74. }
  75. }
  76. public void testPassthroughQuery() throws Exception
  77. {
  78. String expr = "Select * from Table1";
  79. String constr = "ODBC;";
  80. PassthroughQuery query = (PassthroughQuery)newQuery(
  81. Query.Type.PASSTHROUGH, expr, constr);
  82. assertEquals(expr, query.toSQLString());
  83. assertEquals(constr, query.getConnectionString());
  84. }
  85. public void testDataDefinitionQuery() throws Exception
  86. {
  87. String expr = "Drop table Table1";
  88. DataDefinitionQuery query = (DataDefinitionQuery)newQuery(
  89. Query.Type.DATA_DEFINITION, expr, null);
  90. assertEquals(expr, query.toSQLString());
  91. }
  92. public void testUpdateQuery() throws Exception
  93. {
  94. UpdateQuery query = (UpdateQuery)newQuery(
  95. Query.Type.UPDATE,
  96. newRow(TABLE_ATTRIBUTE, null, "Table1", null),
  97. newRow(COLUMN_ATTRIBUTE, "\"some string\"", null, "Table1.id"),
  98. newRow(COLUMN_ATTRIBUTE, "42", null, "Table1.col1"));
  99. assertEquals(
  100. multiline("UPDATE Table1",
  101. "SET Table1.id = \"some string\", Table1.col1 = 42;"),
  102. query.toSQLString());
  103. addRows(query, newRow(WHERE_ATTRIBUTE, "(Table1.col2 < 13)",
  104. null, null));
  105. assertEquals(
  106. multiline("UPDATE Table1",
  107. "SET Table1.id = \"some string\", Table1.col1 = 42",
  108. "WHERE (Table1.col2 < 13);"),
  109. query.toSQLString());
  110. }
  111. public void testSelectQuery() throws Exception
  112. {
  113. SelectQuery query = (SelectQuery)newQuery(
  114. Query.Type.SELECT,
  115. newRow(TABLE_ATTRIBUTE, null, "Table1", null));
  116. setFlag(query, 1);
  117. assertEquals(multiline("SELECT *",
  118. "FROM Table1;"),
  119. query.toSQLString());
  120. doTestColumns(query);
  121. doTestSelectFlags(query);
  122. doTestParameters(query);
  123. doTestTables(query);
  124. doTestRemoteDb(query);
  125. doTestJoins(query);
  126. doTestWhereExpression(query);
  127. doTestGroupings(query);
  128. doTestHavingExpression(query);
  129. doTestOrderings(query);
  130. }
  131. public void testBadQueries() throws Exception
  132. {
  133. List<Row> rowList = new ArrayList<Row>();
  134. rowList.add(newRow(TYPE_ATTRIBUTE, null, -1, null, null));
  135. Query query = Query.create(-1, "TestQuery", rowList, 13);
  136. try {
  137. query.toSQLString();
  138. fail("UnsupportedOperationException should have been thrown");
  139. } catch(UnsupportedOperationException e) {
  140. // success
  141. }
  142. addRows(query, newRow(TYPE_ATTRIBUTE, null, -1, null, null));
  143. try {
  144. query.getTypeRow();
  145. fail("IllegalStateException should have been thrown");
  146. } catch(IllegalStateException e) {
  147. // success
  148. }
  149. try {
  150. new Query("TestQuery", rowList, 13, Query.Type.UNION) {
  151. @Override protected void toSQLString(StringBuilder builder) {
  152. throw new UnsupportedOperationException();
  153. }};
  154. fail("IllegalStateException should have been thrown");
  155. } catch(IllegalStateException e) {
  156. // success
  157. }
  158. }
  159. public void testReadQueries() throws Exception
  160. {
  161. for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.QUERY)) {
  162. Map<String,String> expectedQueries = new HashMap<String,String>();
  163. expectedQueries.put(
  164. "SelectQuery", multiline(
  165. "SELECT DISTINCT Table1.*, Table2.col1, Table2.col2, Table3.col3",
  166. "FROM (Table1 LEFT JOIN Table3 ON Table1.col1 = Table3.col1) INNER JOIN Table2 ON (Table3.col1 = Table2.col1) AND (Table3.col1 = Table2.col2)",
  167. "WHERE (((Table2.col2)=\"foo\" Or (Table2.col2) In (\"buzz\",\"bazz\")))",
  168. "ORDER BY Table2.col1;"));
  169. expectedQueries.put(
  170. "DeleteQuery", multiline(
  171. "DELETE Table1.col1, Table1.col2, Table1.col3",
  172. "FROM Table1",
  173. "WHERE (((Table1.col1)>\"blah\"));"));
  174. expectedQueries.put(
  175. "AppendQuery",multiline(
  176. "INSERT INTO Table3",
  177. "SELECT [Table1].[col2], [Table2].[col2], [Table2].[col3]",
  178. "FROM Table3, Table1 INNER JOIN Table2 ON [Table1].[col1]=[Table2].[col1];"));
  179. expectedQueries.put(
  180. "UpdateQuery",multiline(
  181. "PARAMETERS User Name Text;",
  182. "UPDATE Table1",
  183. "SET Table1.col1 = \"foo\", Table1.col2 = [Table2].[col3], [[Table2]].[[col1]] = [User Name]",
  184. "WHERE ((([Table2].[col1]) Is Not Null));"));
  185. expectedQueries.put(
  186. "MakeTableQuery",multiline(
  187. "SELECT Max(Table2.col1) AS MaxOfcol1, Table2.col2, Table3.col2 INTO Table4",
  188. "FROM (Table2 INNER JOIN Table1 ON Table2.col1 = Table1.col2) RIGHT JOIN Table3 ON Table1.col2 = Table3.col3",
  189. "GROUP BY Table2.col2, Table3.col2",
  190. "HAVING (((Max(Table2.col1))=\"buzz\") AND ((Table2.col2)<>\"blah\"));"));
  191. expectedQueries.put(
  192. "CrosstabQuery", multiline(
  193. "TRANSFORM Count([Table2].[col2]) AS CountOfcol2",
  194. "SELECT Table2_1.col1, [Table2].[col3], Avg(Table2_1.col2) AS AvgOfcol2",
  195. "FROM (Table1 INNER JOIN Table2 ON [Table1].[col1]=[Table2].[col1]) INNER JOIN Table2 AS Table2_1 ON [Table2].[col1]=Table2_1.col3",
  196. "WHERE ((([Table1].[col1])>\"10\") And ((Table2_1.col1) Is Not Null) And ((Avg(Table2_1.col2))>\"10\"))",
  197. "GROUP BY Table2_1.col1, [Table2].[col3]",
  198. "ORDER BY [Table2].[col3]",
  199. "PIVOT [Table1].[col1];"));
  200. expectedQueries.put(
  201. "UnionQuery", multiline(
  202. "Select Table1.col1, Table1.col2",
  203. "where Table1.col1 = \"foo\"",
  204. "UNION",
  205. "Select Table2.col1, Table2.col2",
  206. "UNION ALL Select Table3.col1, Table3.col2",
  207. "where Table3.col3 > \"blah\";"));
  208. expectedQueries.put(
  209. "PassthroughQuery", multiline(
  210. "ALTER TABLE Table4 DROP COLUMN col5;\0"));
  211. expectedQueries.put(
  212. "DataDefinitionQuery", multiline(
  213. "CREATE TABLE Table5 (col1 CHAR, col2 CHAR);\0"));
  214. Database db = DatabaseTest.open(testDB);
  215. for(Query q : db.getQueries()) {
  216. assertEquals(expectedQueries.remove(q.getName()), q.toSQLString());
  217. }
  218. assertTrue(expectedQueries.isEmpty());
  219. db.close();
  220. }
  221. }
  222. private void doTestColumns(SelectQuery query) throws Exception
  223. {
  224. addRows(query, newRow(COLUMN_ATTRIBUTE, "Table1.id", null, null));
  225. addRows(query, newRow(COLUMN_ATTRIBUTE, "Table1.col", "Some.Alias", null));
  226. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias], *",
  227. "FROM Table1;"),
  228. query.toSQLString());
  229. }
  230. private void doTestSelectFlags(SelectQuery query) throws Exception
  231. {
  232. setFlag(query, 3);
  233. assertEquals(multiline("SELECT DISTINCT Table1.id, Table1.col AS [Some.Alias], *",
  234. "FROM Table1;"),
  235. query.toSQLString());
  236. setFlag(query, 9);
  237. assertEquals(multiline("SELECT DISTINCTROW Table1.id, Table1.col AS [Some.Alias], *",
  238. "FROM Table1;"),
  239. query.toSQLString());
  240. setFlag(query, 7);
  241. assertEquals(multiline("SELECT DISTINCT Table1.id, Table1.col AS [Some.Alias], *",
  242. "FROM Table1",
  243. "WITH OWNERACCESS OPTION;"),
  244. query.toSQLString());
  245. replaceRows(query,
  246. newRow(FLAG_ATTRIBUTE, null, 49, null, "5", null));
  247. assertEquals(multiline("SELECT TOP 5 PERCENT Table1.id, Table1.col AS [Some.Alias], *",
  248. "FROM Table1;"),
  249. query.toSQLString());
  250. setFlag(query, 0);
  251. }
  252. private void doTestParameters(SelectQuery query) throws Exception
  253. {
  254. addRows(query, newRow(PARAMETER_ATTRIBUTE, null, DataType.INT.getValue(), "INT_VAL", null));
  255. assertEquals(multiline("PARAMETERS INT_VAL Short;",
  256. "SELECT Table1.id, Table1.col AS [Some.Alias]",
  257. "FROM Table1;"),
  258. query.toSQLString());
  259. addRows(query, newRow(PARAMETER_ATTRIBUTE, null, DataType.TEXT.getValue(), 50, "TextVal", null),
  260. newRow(PARAMETER_ATTRIBUTE, null, 0, 50, "[Some Value]", null));
  261. assertEquals(multiline("PARAMETERS INT_VAL Short, TextVal Text(50), [Some Value] Value;",
  262. "SELECT Table1.id, Table1.col AS [Some.Alias]",
  263. "FROM Table1;"),
  264. query.toSQLString());
  265. addRows(query, newRow(PARAMETER_ATTRIBUTE, null, -1, "BadVal", null));
  266. try {
  267. query.toSQLString();
  268. fail("IllegalStateException should have been thrown");
  269. } catch(IllegalStateException e) {
  270. // success
  271. }
  272. removeRows(query, PARAMETER_ATTRIBUTE);
  273. }
  274. private void doTestTables(SelectQuery query) throws Exception
  275. {
  276. addRows(query, newRow(TABLE_ATTRIBUTE, null, "Table2", "Another Table"));
  277. addRows(query, newRow(TABLE_ATTRIBUTE, "Select val from Table3", "val", "Table3Val"));
  278. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  279. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val;"),
  280. query.toSQLString());
  281. }
  282. private void doTestRemoteDb(SelectQuery query) throws Exception
  283. {
  284. addRows(query, newRow(REMOTEDB_ATTRIBUTE, null, 2, "other_db.mdb", null));
  285. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  286. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val IN 'other_db.mdb';"),
  287. query.toSQLString());
  288. replaceRows(query, newRow(REMOTEDB_ATTRIBUTE, "MDB_FILE;", 2, "other_db.mdb", null));
  289. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  290. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val IN 'other_db.mdb' [MDB_FILE;];"),
  291. query.toSQLString());
  292. replaceRows(query, newRow(REMOTEDB_ATTRIBUTE, "MDB_FILE;", 2, null, null));
  293. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  294. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val IN '' [MDB_FILE;];"),
  295. query.toSQLString());
  296. removeRows(query, REMOTEDB_ATTRIBUTE);
  297. }
  298. private void doTestJoins(SelectQuery query) throws Exception
  299. {
  300. addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = [Another Table].id)", 1, "Table1", "Another Table"));
  301. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  302. "FROM [Select val from Table3].val AS Table3Val, Table1 INNER JOIN Table2 AS [Another Table] ON (Table1.id = [Another Table].id);"),
  303. query.toSQLString());
  304. addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = Table3Val.id)", 2, "Table1", "Table3Val"));
  305. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  306. "FROM (Table1 INNER JOIN Table2 AS [Another Table] ON (Table1.id = [Another Table].id)) LEFT JOIN [Select val from Table3].val AS Table3Val ON (Table1.id = Table3Val.id);"),
  307. query.toSQLString());
  308. addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = Table3Val.id)", 5, "Table1", "Table3Val"));
  309. try {
  310. query.toSQLString();
  311. fail("IllegalStateException should have been thrown");
  312. } catch(IllegalStateException e) {
  313. // success
  314. }
  315. removeLastRows(query, 1);
  316. query.toSQLString();
  317. addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = Table3Val.id)", 1, "BogusTable", "Table3Val"));
  318. try {
  319. query.toSQLString();
  320. fail("IllegalStateException should have been thrown");
  321. } catch(IllegalStateException e) {
  322. // success
  323. }
  324. removeRows(query, JOIN_ATTRIBUTE);
  325. }
  326. private void doTestWhereExpression(SelectQuery query) throws Exception
  327. {
  328. addRows(query, newRow(WHERE_ATTRIBUTE, "(Table1.col2 < 13)",
  329. null, null));
  330. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  331. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val",
  332. "WHERE (Table1.col2 < 13);"),
  333. query.toSQLString());
  334. }
  335. private void doTestGroupings(SelectQuery query) throws Exception
  336. {
  337. addRows(query, newRow(GROUPBY_ATTRIBUTE, "Table1.id", null, null),
  338. newRow(GROUPBY_ATTRIBUTE, "SUM(Table1.val)", null, null));
  339. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  340. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val",
  341. "WHERE (Table1.col2 < 13)",
  342. "GROUP BY Table1.id, SUM(Table1.val);"),
  343. query.toSQLString());
  344. }
  345. private void doTestHavingExpression(SelectQuery query) throws Exception
  346. {
  347. addRows(query, newRow(HAVING_ATTRIBUTE, "(SUM(Table1.val) = 500)", null, null));
  348. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  349. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val",
  350. "WHERE (Table1.col2 < 13)",
  351. "GROUP BY Table1.id, SUM(Table1.val)",
  352. "HAVING (SUM(Table1.val) = 500);"),
  353. query.toSQLString());
  354. }
  355. private void doTestOrderings(SelectQuery query) throws Exception
  356. {
  357. addRows(query, newRow(ORDERBY_ATTRIBUTE, "Table1.id", null, null),
  358. newRow(ORDERBY_ATTRIBUTE, "Table2.val", "D", null));
  359. assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]",
  360. "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val",
  361. "WHERE (Table1.col2 < 13)",
  362. "GROUP BY Table1.id, SUM(Table1.val)",
  363. "HAVING (SUM(Table1.val) = 500)",
  364. "ORDER BY Table1.id, Table2.val DESC;"),
  365. query.toSQLString());
  366. }
  367. private static Query newQuery(Query.Type type, Row... rows)
  368. {
  369. return newQuery(type, null, null, rows);
  370. }
  371. private static Query newQuery(Query.Type type, String typeExpr,
  372. String typeName1, Row... rows)
  373. {
  374. List<Row> rowList = new ArrayList<Row>();
  375. rowList.add(newRow(TYPE_ATTRIBUTE, typeExpr, type.getValue(),
  376. null, typeName1, null));
  377. rowList.addAll(Arrays.asList(rows));
  378. return Query.create(type.getObjectFlag(), "TestQuery", rowList, 13);
  379. }
  380. private static Row newRow(Byte attr, String expr, String name1, String name2)
  381. {
  382. return newRow(attr, expr, null, null, name1, name2);
  383. }
  384. private static Row newRow(Byte attr, String expr, Number flagNum,
  385. String name1, String name2)
  386. {
  387. return newRow(attr, expr, flagNum, null, name1, name2);
  388. }
  389. private static Row newRow(Byte attr, String expr, Number flagNum,
  390. Number extraNum, String name1, String name2)
  391. {
  392. Short flag = ((flagNum != null) ? flagNum.shortValue() : null);
  393. Integer extra = ((extraNum != null) ? extraNum.intValue() : null);
  394. return new Row(attr, expr, flag, extra, name1, name2, null, null);
  395. }
  396. private static void setFlag(Query query, Number newFlagNum)
  397. {
  398. replaceRows(query,
  399. newRow(FLAG_ATTRIBUTE, null, newFlagNum, null, null, null));
  400. }
  401. private static void addRows(Query query, Row... rows)
  402. {
  403. query.getRows().addAll(Arrays.asList(rows));
  404. }
  405. private static void replaceRows(Query query, Row... rows)
  406. {
  407. removeRows(query, rows[0].attribute);
  408. addRows(query, rows);
  409. }
  410. private static void removeRows(Query query, Byte attr)
  411. {
  412. for(Iterator<Row> iter = query.getRows().iterator(); iter.hasNext(); ) {
  413. if(attr.equals(iter.next().attribute)) {
  414. iter.remove();
  415. }
  416. }
  417. }
  418. private static void removeLastRows(Query query, int num)
  419. {
  420. List<Row> rows = query.getRows();
  421. int size = rows.size();
  422. rows.subList(size - num, size).clear();
  423. }
  424. private static String multiline(String... strs)
  425. {
  426. return StringUtils.join(strs, LINE_SEPARATOR);
  427. }
  428. }