3 * Copyright (C) 2009-2020 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 java.util.stream.Collectors;
25 import org.sonar.server.platform.db.migration.def.ColumnDef;
27 import static com.google.common.base.Preconditions.checkArgument;
28 import static java.util.Collections.singletonList;
29 import static java.util.Objects.requireNonNull;
30 import static org.sonar.server.platform.db.migration.def.Validations.validateIndexName;
31 import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
33 public class CreateIndexBuilder {
35 private final List<ColumnDef> columns = new ArrayList<>();
36 private String tableName;
37 private String indexName;
38 private boolean unique = false;
41 * Required name of table on which index is created
43 public CreateIndexBuilder setTable(String s) {
49 * Required name of index. Name must be unique among all the tables
52 public CreateIndexBuilder setName(String s) {
58 * By default index is NOT UNIQUE (value {@code false}).
60 public CreateIndexBuilder setUnique(boolean b) {
66 * Add a column to the scope of index. Order of calls to this
67 * method is important and is kept as-is when creating the index.
68 * The attributes used from {@link ColumnDef} are the name, the type
69 * and the length (in case of VARCHAR). Other attributes are ignored.
71 public CreateIndexBuilder addColumn(ColumnDef column) {
72 columns.add(requireNonNull(column, "Column cannot be null"));
76 public List<String> build() {
77 validateTableName(tableName);
78 validateIndexName(indexName);
79 checkArgument(!columns.isEmpty(), "at least one column must be specified");
80 return singletonList(createSqlStatement());
83 private String createSqlStatement() {
84 StringBuilder sql = new StringBuilder("CREATE ");
86 sql.append("UNIQUE ");
89 sql.append(indexName);
91 sql.append(tableName);
93 sql.append(columns.stream().map(ColumnDef::getName).collect(Collectors.joining(", ")));
95 return sql.toString();