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.

DropColumnsBuilder.java 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * SonarQube, open source software quality management tool.
  3. * Copyright (C) 2008-2014 SonarSource
  4. * mailto:contact AT sonarsource DOT com
  5. *
  6. * SonarQube is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * SonarQube is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.db.migrations;
  21. import org.sonar.db.dialect.Dialect;
  22. import org.sonar.db.dialect.MsSql;
  23. import org.sonar.db.dialect.MySql;
  24. import org.sonar.db.dialect.Oracle;
  25. import org.sonar.db.dialect.PostgreSql;
  26. public class DropColumnsBuilder {
  27. private final Dialect dialect;
  28. private final String tableName;
  29. private final String[] columns;
  30. public DropColumnsBuilder(Dialect dialect, String tableName, String... columns) {
  31. this.tableName = tableName;
  32. this.dialect = dialect;
  33. this.columns = columns;
  34. }
  35. public String build() {
  36. StringBuilder sql = new StringBuilder().append("ALTER TABLE ").append(tableName).append(" ");
  37. switch (dialect.getId()) {
  38. case PostgreSql.ID:
  39. case MySql.ID:
  40. dropColumns(sql, "DROP COLUMN ");
  41. break;
  42. case MsSql.ID:
  43. sql.append("DROP COLUMN ");
  44. dropColumns(sql, "");
  45. break;
  46. case Oracle.ID:
  47. sql.append("DROP (");
  48. dropColumns(sql, "");
  49. sql.append(")");
  50. break;
  51. default:
  52. throw new IllegalStateException(String.format("Unsupported database '%s'", dialect.getId()));
  53. }
  54. return sql.toString();
  55. }
  56. private void dropColumns(StringBuilder sql, String columnPrefix) {
  57. for (int i = 0; i < columns.length; i++) {
  58. sql.append(columnPrefix);
  59. sql.append(columns[i]);
  60. if (i < columns.length - 1) {
  61. sql.append(", ");
  62. }
  63. }
  64. }
  65. }