3 * Copyright (C) 2009-2024 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.charset;
22 import com.google.common.annotations.VisibleForTesting;
23 import java.sql.Connection;
24 import java.sql.ResultSet;
25 import java.sql.SQLException;
26 import java.util.List;
27 import org.sonar.api.utils.MessageException;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 import static java.lang.String.format;
32 import static org.apache.commons.lang.StringUtils.containsIgnoreCase;
34 class MssqlCharsetHandler extends CharsetHandler {
36 private static final Logger LOGGER = LoggerFactory.getLogger(MssqlCharsetHandler.class);
37 private static final String CASE_SENSITIVE_ACCENT_SENSITIVE = "_CS_AS";
38 private static final String CASE_INSENSITIVE_ACCENT_INSENSITIVE = "_CI_AI";
39 private static final String CASE_INSENSITIVE_ACCENT_SENSITIVE = "_CI_AS";
40 private static final String CASE_SENSITIVE_ACCENT_INSENSITIVE = "_CS_AI";
41 private static final String BIN = "BIN";
42 private static final String BIN2 = "BIN2";
44 private final MssqlMetadataReader metadata;
46 MssqlCharsetHandler(SqlExecutor selectExecutor, MssqlMetadataReader metadataReader) {
47 super(selectExecutor);
48 this.metadata = metadataReader;
52 void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
53 expectCaseSensitiveDefaultCollation(connection);
54 if (state == DatabaseCharsetChecker.State.UPGRADE || state == DatabaseCharsetChecker.State.STARTUP) {
55 repairColumns(connection);
59 private void expectCaseSensitiveDefaultCollation(Connection connection) throws SQLException {
60 LOGGER.info("Verify that database collation is case-sensitive and accent-sensitive");
61 String defaultCollation = metadata.getDefaultCollation(connection);
63 if (!isCollationCorrect(defaultCollation)) {
64 String fixedCollation = toCaseSensitive(defaultCollation);
65 throw MessageException.of(format(
66 "Database collation must be case-sensitive and accent-sensitive. It is %s but should be %s.", defaultCollation, fixedCollation));
70 private void repairColumns(Connection connection) throws SQLException {
71 String defaultCollation = metadata.getDefaultCollation(connection);
73 // All VARCHAR columns are returned. No need to check database general collation.
75 // issues | kee | Latin1_General_CS_AS or Latin1_General_100_CI_AS_KS_WS
76 List<ColumnDef> columns = metadata.getColumnDefs(connection);
77 for (ColumnDef column : columns.stream().filter(ColumnDef::isInSonarQubeTable).toList()) {
78 String collation = column.getCollation();
79 if (!isCollationCorrect(collation)) {
80 repairColumnCollation(connection, column, toCaseSensitive(collation));
81 } else if ("Latin1_General_CS_AS".equals(collation) && !collation.equals(defaultCollation)) {
82 repairColumnCollation(connection, column, defaultCollation);
88 * Collation is correct if contains {@link #CASE_SENSITIVE_ACCENT_SENSITIVE} or {@link #BIN} or {@link #BIN2}.
90 private static boolean isCollationCorrect(String collation) {
91 return containsIgnoreCase(collation, CASE_SENSITIVE_ACCENT_SENSITIVE)
92 || containsIgnoreCase(collation, BIN)
93 || containsIgnoreCase(collation, BIN2);
96 private void repairColumnCollation(Connection connection, ColumnDef column, String expectedCollation) throws SQLException {
97 // 1. select the indices defined on this column
98 List<ColumnIndex> indices = metadata.getColumnIndices(connection, column);
101 for (ColumnIndex index : indices) {
102 getSqlExecutor().executeDdl(connection, format("DROP INDEX %s.%s", column.getTable(), index.name));
105 // 3. alter collation of column
106 String nullability = column.isNullable() ? "NULL" : "NOT NULL";
107 String size = column.getSize() >= 0 ? String.valueOf(column.getSize()) : "max";
108 String alterSql = format("ALTER TABLE %s ALTER COLUMN %s %s(%s) COLLATE %s %s",
109 column.getTable(), column.getColumn(), column.getDataType(), size, expectedCollation, nullability);
110 LOGGER.info("Changing collation of column [{}.{}] from {} to {} | sql=", column.getTable(), column.getColumn(), column.getCollation(), expectedCollation, alterSql);
111 getSqlExecutor().executeDdl(connection, alterSql);
113 // 4. re-create indices
114 for (ColumnIndex index : indices) {
115 String uniqueSql = index.unique ? "UNIQUE" : "";
116 String createIndexSql = format("CREATE %s INDEX %s ON %s (%s)", uniqueSql, index.name, column.getTable(), index.csvColumns);
117 getSqlExecutor().executeDdl(connection, createIndexSql);
122 static String toCaseSensitive(String collation) {
123 // Example: Latin1_General_CI_AI --> Latin1_General_CS_AS or Latin1_General_100_CI_AS_KS_WS --> Latin1_General_100_CS_AS_KS_WS
125 .replace(CASE_INSENSITIVE_ACCENT_INSENSITIVE, CASE_SENSITIVE_ACCENT_SENSITIVE)
126 .replace(CASE_INSENSITIVE_ACCENT_SENSITIVE, CASE_SENSITIVE_ACCENT_SENSITIVE)
127 .replace(CASE_SENSITIVE_ACCENT_INSENSITIVE, CASE_SENSITIVE_ACCENT_SENSITIVE);
131 static class ColumnIndex {
132 private final String name;
133 private final boolean unique;
134 private final String csvColumns;
136 public ColumnIndex(String name, boolean unique, String csvColumns) {
138 this.unique = unique;
139 this.csvColumns = csvColumns;
144 enum ColumnIndexConverter implements SqlExecutor.RowConverter<ColumnIndex> {
147 public ColumnIndex convert(ResultSet rs) throws SQLException {
148 return new ColumnIndex(rs.getString(1), rs.getBoolean(2), rs.getString(3));