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.

UnionQueryImpl.java 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright (c) 2008 Health Market Science, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl.query;
  14. import java.util.List;
  15. import static com.healthmarketscience.jackcess.impl.query.QueryFormat.*;
  16. import com.healthmarketscience.jackcess.query.UnionQuery;
  17. /**
  18. * Concrete Query subclass which represents a UNION query, e.g.:
  19. * {@code SELECT <query1> UNION SELECT <query2>}
  20. *
  21. * @author James Ahlborn
  22. */
  23. public class UnionQueryImpl extends QueryImpl implements UnionQuery
  24. {
  25. public UnionQueryImpl(String name, List<Row> rows, int objectId,
  26. int objectFlag) {
  27. super(name, rows, objectId, objectFlag, Type.UNION);
  28. }
  29. public String getUnionType() {
  30. return(hasFlag(UNION_FLAG) ? DEFAULT_TYPE : "ALL");
  31. }
  32. public String getUnionString1() {
  33. return getUnionString(UNION_PART1);
  34. }
  35. public String getUnionString2() {
  36. return getUnionString(UNION_PART2);
  37. }
  38. @Override
  39. public List<String> getOrderings() {
  40. return super.getOrderings();
  41. }
  42. private String getUnionString(String id) {
  43. for(Row row : getTableRows()) {
  44. if(id.equals(row.name2)) {
  45. return cleanUnionString(row.expression);
  46. }
  47. }
  48. throw new IllegalStateException(
  49. "Could not find union query with id " + id);
  50. }
  51. @Override
  52. protected void toSQLString(StringBuilder builder)
  53. {
  54. builder.append(getUnionString1()).append(NEWLINE)
  55. .append("UNION ");
  56. String unionType = getUnionType();
  57. if(!DEFAULT_TYPE.equals(unionType)) {
  58. builder.append(unionType).append(' ');
  59. }
  60. builder.append(getUnionString2());
  61. List<String> orderings = getOrderings();
  62. if(!orderings.isEmpty()) {
  63. builder.append(NEWLINE).append("ORDER BY ").append(orderings);
  64. }
  65. }
  66. private static String cleanUnionString(String str)
  67. {
  68. return str.trim().replaceAll("[\r\n]+", NEWLINE);
  69. }
  70. }