3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program 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.
11 * This program 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.
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.
20 package org.sonar.server.platform.db.migration.sql;
22 import java.util.ArrayList;
23 import java.util.List;
24 import org.sonar.server.platform.db.migration.def.ColumnDef;
26 import static com.google.common.base.Preconditions.checkArgument;
27 import static java.util.Collections.singletonList;
28 import static java.util.Objects.requireNonNull;
29 import static org.sonar.server.platform.db.migration.def.Validations.validateIndexName;
30 import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
32 public class CreateIndexBuilder {
34 private final List<String> columns = new ArrayList<>();
35 private String tableName;
36 private String indexName;
37 private boolean unique = false;
40 * Required name of table on which index is created
42 public CreateIndexBuilder setTable(String s) {
48 * Required name of index. Name must be unique among all the tables
51 public CreateIndexBuilder setName(String s) {
57 * By default index is NOT UNIQUE (value {@code false}).
59 public CreateIndexBuilder setUnique(boolean b) {
65 * Add a column to the scope of index. Order of calls to this
66 * method is important and is kept as-is when creating the index.
67 * The attribute used from {@link ColumnDef} is the name.
68 * Other attributes are ignored.
70 public CreateIndexBuilder addColumn(ColumnDef column) {
71 columns.add(requireNonNull(column, "Column cannot be null").getName());
76 * Add a column to the scope of index. Order of calls to this
77 * method is important and is kept as-is when creating the index.
79 public CreateIndexBuilder addColumn(String column) {
80 columns.add(requireNonNull(column, "Column cannot be null"));
84 public List<String> build() {
85 validateTableName(tableName);
86 validateIndexName(indexName);
87 checkArgument(!columns.isEmpty(), "at least one column must be specified");
88 return singletonList(createSqlStatement());
91 private String createSqlStatement() {
92 StringBuilder sql = new StringBuilder("CREATE ");
94 sql.append("UNIQUE ");
97 sql.append(indexName);
99 sql.append(tableName);
101 sql.append(String.join(", ", columns));
103 return sql.toString();