repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/DropTableProjectMappings.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v102;
import java.sql.Connection;
import java.sql.SQLException;
import org.sonar.db.Database;
import org.sonar.db.DatabaseUtils;
import org.sonar.server.platform.db.migration.sql.DropTableBuilder;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropTableProjectMappings extends DdlChange {
private static final String TABLE_NAME = "project_mappings";
public DropTableProjectMappings(Database db) {
super(db);
}
@Override
public void execute(Context context) throws SQLException {
try (Connection c = getDatabase().getDataSource().getConnection()) {
if (DatabaseUtils.tableExists(TABLE_NAME, c)) {
context.execute(new DropTableBuilder(getDialect(), TABLE_NAME).build());
}
}
}
}
| 1,652 | 34.934783 | 80 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInGroupRoles.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v102;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange;
public class RenameComponentUuidInGroupRoles extends RenameVarcharColumnChange {
private static final String TABLE_NAME = "group_roles";
private static final String OLD_COLUMN_NAME = "component_uuid";
private static final String NEW_COLUMN_NAME = "entity_uuid";
public RenameComponentUuidInGroupRoles(Database db) {
super(db, TABLE_NAME, OLD_COLUMN_NAME, NEW_COLUMN_NAME);
}
}
| 1,408 | 38.138889 | 80 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInSnapshots.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v102;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange;
public class RenameComponentUuidInSnapshots extends RenameVarcharColumnChange {
private static final String TABLE_NAME = "snapshots";
private static final String OLD_COLUMN_NAME = "component_uuid";
private static final String NEW_COLUMN_NAME = "root_component_uuid";
public RenameComponentUuidInSnapshots(Database db) {
super(db, TABLE_NAME, OLD_COLUMN_NAME, NEW_COLUMN_NAME);
}
} | 1,411 | 39.342857 | 79 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInUserRoles.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v102;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange;
public class RenameComponentUuidInUserRoles extends RenameVarcharColumnChange {
private static final String TABLE_NAME = "user_roles";
private static final String OLD_COLUMN_NAME = "component_uuid";
private static final String NEW_COLUMN_NAME = "entity_uuid";
public RenameComponentUuidInUserRoles(Database db) {
super(db, TABLE_NAME, OLD_COLUMN_NAME, NEW_COLUMN_NAME);
}
}
| 1,404 | 39.142857 | 79 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInWebhookDeliveries.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v102;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange;
public class RenameComponentUuidInWebhookDeliveries extends RenameVarcharColumnChange {
private static final String TABLE_NAME = "webhook_deliveries";
private static final String OLD_COLUMN_NAME = "component_uuid";
private static final String NEW_COLUMN_NAME = "project_uuid";
public RenameComponentUuidInWebhookDeliveries(Database db) {
super(db, TABLE_NAME, OLD_COLUMN_NAME, NEW_COLUMN_NAME);
}
}
| 1,429 | 39.857143 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/RenameMainComponentUuidInCeActivity.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v102;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange;
public class RenameMainComponentUuidInCeActivity extends RenameVarcharColumnChange {
private static final String TABLE_NAME = "ce_activity";
private static final String OLD_COLUMN_NAME = "main_component_uuid";
private static final String NEW_COLUMN_NAME = "entity_uuid";
public RenameMainComponentUuidInCeActivity(Database db) {
super(db, TABLE_NAME, OLD_COLUMN_NAME, NEW_COLUMN_NAME);
}
}
| 1,420 | 39.6 | 84 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/RenameMainComponentUuidInCeQueue.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v102;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange;
public class RenameMainComponentUuidInCeQueue extends RenameVarcharColumnChange {
private static final String TABLE_NAME = "ce_queue";
private static final String OLD_COLUMN_NAME = "main_component_uuid";
private static final String NEW_COLUMN_NAME = "entity_uuid";
public RenameMainComponentUuidInCeQueue(Database db) {
super(db, TABLE_NAME, OLD_COLUMN_NAME, NEW_COLUMN_NAME);
}
}
| 1,411 | 39.342857 | 81 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v102/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.platform.db.migration.version.v102;
import javax.annotation.ParametersAreNonnullByDefault;
| 991 | 40.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/DatabaseMigrationStateImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration;
import java.util.Date;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class DatabaseMigrationStateImplTest {
private DatabaseMigrationStateImpl underTest = new DatabaseMigrationStateImpl();
@Test
public void getStatus_returns_NONE_when_component_is_created() {
assertThat(underTest.getStatus()).isEqualTo(DatabaseMigrationState.Status.NONE);
}
@Test
public void getStatus_returns_argument_of_setStatus() {
for (DatabaseMigrationState.Status status : DatabaseMigrationState.Status.values()) {
underTest.setStatus(status);
assertThat(underTest.getStatus()).isEqualTo(status);
}
}
@Test
public void getStartedAt_returns_null_when_component_is_created() {
assertThat(underTest.getStartedAt()).isNull();
}
@Test
public void getStartedAt_returns_argument_of_setStartedAt() {
Date expected = new Date();
underTest.setStartedAt(expected);
assertThat(underTest.getStartedAt()).isSameAs(expected);
}
@Test
public void getError_returns_null_when_component_is_created() {
assertThat(underTest.getError()).isNull();
}
@Test
public void getError_returns_argument_of_setError() {
RuntimeException expected = new RuntimeException();
underTest.setError(expected);
assertThat(underTest.getError()).isSameAs(expected);
}
}
| 2,243 | 30.605634 | 89 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/MigrationConfigurationModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class MigrationConfigurationModuleTest {
private final MigrationConfigurationModule underTest = new MigrationConfigurationModule();
@Test
public void verify_component_count() {
ListContainer container = new ListContainer();
underTest.configure(container);
assertThat(container.getAddedObjects()).isNotEmpty();
}
}
| 1,366 | 33.175 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/MigrationEngineModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class MigrationEngineModuleTest {
private MigrationEngineModule underTest = new MigrationEngineModule();
@Test
public void verify_component_count() {
ListContainer container = new ListContainer();
underTest.configure(container);
assertThat(container.getAddedObjects()).hasSize(2);
}
}
| 1,336 | 33.282051 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/NoopDatabaseMigrationImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration;
import org.junit.Test;
public class NoopDatabaseMigrationImplTest {
@Test
public void startIt_does_nothing() {
new NoopDatabaseMigrationImpl().startIt();
}
}
| 1,061 | 34.4 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/ColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ColumnDefTest {
@Test
public void isInSonarQubeTable_returns_false_if_sqlazure_system_table() {
ColumnDef underTest = new ColumnDef("sys.sysusers", "login", "charset", "collation", "NVARCHAR", 100L, false);
assertThat(underTest.isInSonarQubeTable()).isFalse();
underTest = new ColumnDef("SYS.SYSUSERS", "login", "charset", "collation", "NVARCHAR", 100L, false);
assertThat(underTest.isInSonarQubeTable()).isFalse();
}
@Test
public void isInSonarQubeTable_returns_true_if_table_created_by_sonarqube() {
ColumnDef underTest = new ColumnDef("project_measures", "text_value", "charset", "collation", "NVARCHAR", 100L, false);
assertThat(underTest.isInSonarQubeTable()).isTrue();
underTest = new ColumnDef("PROJECT_MEASURES", "text_value", "charset", "collation", "NVARCHAR", 100L, false);
assertThat(underTest.isInSonarQubeTable()).isTrue();
}
}
| 1,887 | 39.170213 | 123 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/DatabaseCharsetCheckerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.db.Database;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class DatabaseCharsetCheckerTest {
private Database db = mock(Database.class, Mockito.RETURNS_MOCKS);
private CharsetHandler handler = mock(CharsetHandler.class);
private DatabaseCharsetChecker underTest = spy(new DatabaseCharsetChecker(db));
@Test
public void executes_handler() throws Exception {
Oracle dialect = new Oracle();
when(underTest.getHandler(dialect)).thenReturn(handler);
when(db.getDialect()).thenReturn(dialect);
underTest.check(DatabaseCharsetChecker.State.UPGRADE);
verify(handler).handle(any(Connection.class), eq(DatabaseCharsetChecker.State.UPGRADE));
}
@Test
public void throws_ISE_if_handler_fails() throws Exception {
Oracle dialect = new Oracle();
when(underTest.getHandler(dialect)).thenReturn(handler);
when(db.getDialect()).thenReturn(dialect);
doThrow(new SQLException("failure")).when(handler).handle(any(Connection.class), any(DatabaseCharsetChecker.State.class));
assertThatThrownBy(() -> underTest.check(DatabaseCharsetChecker.State.UPGRADE))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("failure");
}
@Test
public void does_nothing_if_h2() {
assertThat(underTest.getHandler(new H2())).isNull();
}
@Test
public void getHandler_returns_MssqlCharsetHandler_if_mssql() {
assertThat(underTest.getHandler(new MsSql())).isInstanceOf(MssqlCharsetHandler.class);
}
@Test
public void getHandler_returns_OracleCharsetHandler_if_oracle() {
assertThat(underTest.getHandler(new Oracle())).isInstanceOf(OracleCharsetHandler.class);
}
@Test
public void getHandler_returns_PostgresCharsetHandler_if_postgres() {
assertThat(underTest.getHandler(new PostgreSql())).isInstanceOf(PostgresCharsetHandler.class);
}
@Test
public void getHandler_throws_IAE_if_unsupported_db() {
Dialect unsupportedDialect = mock(Dialect.class);
when(unsupportedDialect.getId()).thenReturn("foo");
assertThatThrownBy(() -> underTest.getHandler(unsupportedDialect))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Database not supported: foo");
}
}
| 3,775 | 36.019608 | 126 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.utils.MessageException;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class MssqlCharsetHandlerTest {
private static final String TABLE_ISSUES = "issues";
private static final String TABLE_PROJECTS = "projects";
private static final String COLUMN_KEE = "kee";
private static final String COLUMN_NAME = "name";
private SqlExecutor sqlExecutor = mock(SqlExecutor.class);
private MssqlMetadataReader metadata = mock(MssqlMetadataReader.class);
private MssqlCharsetHandler underTest = new MssqlCharsetHandler(sqlExecutor, metadata);
private Connection connection = mock(Connection.class);
@Test
public void fresh_install_verifies_that_default_collation_is_CS_AS() throws SQLException {
answerDefaultCollation("Latin1_General_CS_AS");
underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL);
verify(metadata).getDefaultCollation(connection);
}
@Test
public void fresh_install_fails_if_default_collation_is_not_CS_AS() throws SQLException {
answerDefaultCollation("Latin1_General_CI_AI");
assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL))
.isInstanceOf(MessageException.class)
.hasMessage("Database collation must be case-sensitive and accent-sensitive. It is Latin1_General_CI_AI but should be Latin1_General_CS_AS.");
}
@Test
public void upgrade_fails_if_default_collation_is_not_CS_AS() throws SQLException {
answerDefaultCollation("Latin1_General_CI_AI");
assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE))
.isInstanceOf(MessageException.class)
.hasMessage("Database collation must be case-sensitive and accent-sensitive. It is Latin1_General_CI_AI but should be Latin1_General_CS_AS.");
}
@Test
public void upgrade_checks_that_columns_are_CS_AS() throws SQLException {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(
new ColumnDef(TABLE_ISSUES, COLUMN_KEE, "Latin1_General", "Latin1_General_CS_AS", "varchar", 10, false),
new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Latin1_General", "Latin1_General_CS_AS", "varchar", 10, false));
// do not fail
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
}
@Test
public void upgrade_repairs_CI_AI_columns() throws SQLException {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(
new ColumnDef(TABLE_ISSUES, COLUMN_KEE, "Latin1_General", "Latin1_General_CS_AS", "varchar", 10, false),
new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Latin1_General", "Latin1_General_CI_AI", "varchar", 10, false));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor).executeDdl(connection, "ALTER TABLE projects ALTER COLUMN name varchar(10) COLLATE Latin1_General_CS_AS NOT NULL");
}
@Test
public void upgrade_repairs_indexed_CI_AI_columns() throws SQLException {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(
new ColumnDef(TABLE_ISSUES, COLUMN_KEE, "Latin1_General", "Latin1_General_CS_AS", "varchar", 10, false),
new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Latin1_General", "Latin1_General_CI_AI", "varchar", 10, false));
answerIndices(
new MssqlCharsetHandler.ColumnIndex("projects_name", false, "name"),
// This index is on two columns. Note that it does not make sense for table "projects" !
new MssqlCharsetHandler.ColumnIndex("projects_login_and_name", true, "login,name"));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor).executeDdl(connection, "DROP INDEX projects.projects_name");
verify(sqlExecutor).executeDdl(connection, "DROP INDEX projects.projects_login_and_name");
verify(sqlExecutor).executeDdl(connection, "ALTER TABLE projects ALTER COLUMN name varchar(10) COLLATE Latin1_General_CS_AS NOT NULL");
verify(sqlExecutor).executeDdl(connection, "CREATE INDEX projects_name ON projects (name)");
verify(sqlExecutor).executeDdl(connection, "CREATE UNIQUE INDEX projects_login_and_name ON projects (login,name)");
}
@Test
@UseDataProvider("combinationsOfCsAsAndSuffix")
public void repair_case_insensitive_accent_insensitive_combinations_with_or_without_suffix(String collation, String expectedCollation)
throws Exception {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(new ColumnDef(TABLE_ISSUES, COLUMN_KEE, "Latin1_General", collation, "varchar", 10, false));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor).executeDdl(connection, "ALTER TABLE issues ALTER COLUMN kee varchar(10) COLLATE " + expectedCollation + " NOT NULL");
}
@DataProvider
public static Object[][] combinationsOfCsAsAndSuffix() {
List<String[]> res = new ArrayList<>();
for (String sensitivity : asList("CI_AI", "CI_AS", "CS_AI")) {
for (String suffix : asList("", "_KS_WS")) {
res.add(new String[] {
format("Latin1_General_%s%s", sensitivity, suffix),
format("Latin1_General_CS_AS%s", suffix)
});
}
}
return res.toArray(new Object[0][]);
}
@Test
public void support_the_max_size_of_varchar_column() throws Exception {
answerDefaultCollation("Latin1_General_CS_AS");
// returned size is -1
answerColumnDefs(new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Latin1_General", "Latin1_General_CI_AI", "nvarchar", -1, false));
answerIndices();
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor).executeDdl(connection, "ALTER TABLE projects ALTER COLUMN name nvarchar(max) COLLATE Latin1_General_CS_AS NOT NULL");
}
@Test
public void do_not_repair_system_tables_of_sql_azure() throws Exception {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(new ColumnDef("sys.sysusers", COLUMN_NAME, "Latin1_General", "Latin1_General_CI_AI", "varchar", 10, false));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor, never()).executeDdl(any(Connection.class), anyString());
}
@Test
@UseDataProvider("combinationOfBinAndSuffix")
public void do_not_repair_if_collation_contains_BIN(String collation) throws Exception {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Latin1_General", collation, "varchar", 10, false));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor, never()).executeDdl(any(Connection.class), anyString());
}
@DataProvider
public static Object[][] combinationOfBinAndSuffix() {
return Stream.of("", "_KS_WS")
.map(suffix -> new String[] {format("Latin1_General_BIN%s", suffix)})
.toArray(Object[][]::new);
}
@Test
@UseDataProvider("combinationOfBin2AndSuffix")
public void do_not_repair_if_collation_contains_BIN2(String collation) throws Exception {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Latin1_General", collation, "varchar", 10, false));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor, never()).executeDdl(any(Connection.class), anyString());
}
@DataProvider
public static Object[][] combinationOfBin2AndSuffix() {
return Stream.of("", "_KS_WS")
.map(suffix -> new String[] {format("Latin1_General_BIN2%s", suffix)})
.toArray(Object[][]::new);
}
/**
* SONAR-7988
*/
@Test
public void fix_Latin1_CS_AS_columns_created_in_5_x() throws SQLException {
answerDefaultCollation("SQL_Latin1_General_CP1_CS_AS");
answerColumnDefs(new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Latin1_General", "Latin1_General_CS_AS", "nvarchar", 10, false));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verify(sqlExecutor).executeDdl(connection, "ALTER TABLE projects ALTER COLUMN name nvarchar(10) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL");
}
private void answerColumnDefs(ColumnDef... columnDefs) throws SQLException {
when(metadata.getColumnDefs(connection)).thenReturn(asList(columnDefs));
}
private void answerDefaultCollation(String defaultCollation) throws SQLException {
when(metadata.getDefaultCollation(connection)).thenReturn(defaultCollation);
}
private void answerIndices(MssqlCharsetHandler.ColumnIndex... indices) throws SQLException {
when(metadata.getColumnIndices(same(connection), any(ColumnDef.class))).thenReturn(asList(indices));
}
}
| 10,393 | 42.672269 | 148 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/MssqlMetadataReaderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MssqlMetadataReaderTest {
private SqlExecutor sqlExecutor = mock(SqlExecutor.class);
private Connection connection = mock(Connection.class);
private MssqlMetadataReader underTest = new MssqlMetadataReader(sqlExecutor);
@Test
public void test_getDefaultCollation() throws SQLException {
answerSelect("Latin1_General_CS_AS");
assertThat(underTest.getDefaultCollation(connection)).isEqualTo("Latin1_General_CS_AS");
}
private void answerSelect(String charset) throws SQLException {
when(sqlExecutor.selectSingleString(same(connection), anyString())).thenReturn(charset);
}
}
| 1,841 | 36.591837 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/OracleCharsetHandlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class OracleCharsetHandlerTest {
private SqlExecutor sqlExecutor = mock(SqlExecutor.class);
private Connection connection = mock(Connection.class);
private OracleCharsetHandler underTest = new OracleCharsetHandler(sqlExecutor);
@Test
public void fresh_install_verifies_utf8_charset() throws Exception {
answerCharset("UTF8");
underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL);
}
@Test
public void upgrade_does_not_verify_utf8_charset() throws Exception {
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
verifyNoInteractions(sqlExecutor);
}
@Test
public void fresh_install_supports_al32utf8() throws Exception {
answerCharset("AL32UTF8");
underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL);
}
@Test
public void fresh_install_fails_if_charset_is_not_utf8() throws Exception {
answerCharset("LATIN");
assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL))
.isInstanceOf(MessageException.class)
.hasMessage("Oracle NLS_CHARACTERSET does not support UTF8: LATIN");
}
@Test
public void fails_if_can_not_get_charset() throws Exception {
answerCharset(null);
assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL))
.isInstanceOf(MessageException.class);
}
@Test
public void does_nothing_if_regular_startup() throws Exception {
underTest.handle(connection, DatabaseCharsetChecker.State.STARTUP);
verifyNoInteractions(sqlExecutor);
}
private void answerCharset(@Nullable String charset) throws SQLException {
when(sqlExecutor.selectSingleString(any(Connection.class), anyString()))
.thenReturn(charset);
}
}
| 3,159 | 33.725275 | 102 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/PostgresCharsetHandlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
import org.sonar.db.version.SqTables;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class PostgresCharsetHandlerTest {
private static final String TABLE_ISSUES = "issues";
private static final String TABLE_PROJECTS = "projects";
private static final String COLUMN_KEE = "kee";
private static final String COLUMN_NAME = "name";
private final SqlExecutor sqlExecutor = mock(SqlExecutor.class);
private final Connection connection = mock(Connection.class);
private final PostgresMetadataReader metadata = mock(PostgresMetadataReader.class);
private final PostgresCharsetHandler underTest = new PostgresCharsetHandler(sqlExecutor, metadata);
@Test
public void fresh_install_verifies_that_default_charset_is_utf8() throws SQLException {
answerDefaultCharset("utf8");
underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL);
// no errors, charset has been verified
verify(metadata).getDefaultCharset(same(connection));
verifyNoInteractions(sqlExecutor);
}
@Test
public void upgrade_verifies_that_default_charset_and_columns_are_utf8() throws Exception {
answerDefaultCharset("utf8");
answerColumns(asList(
new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"},
new String[] {TABLE_PROJECTS, COLUMN_NAME, "utf8"}));
underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE);
// no errors, charsets have been verified
verify(metadata).getDefaultCharset(same(connection));
}
@Test
public void regular_startup_verifies_that_default_charset_and_columns_are_utf8() throws Exception {
answerDefaultCharset("utf8");
answerColumns(asList(
new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"},
new String[] {TABLE_PROJECTS, COLUMN_NAME, "utf8"}));
underTest.handle(connection, DatabaseCharsetChecker.State.STARTUP);
// no errors, charsets have been verified
verify(metadata).getDefaultCharset(same(connection));
}
@Test
public void column_charset_can_be_empty() throws Exception {
answerDefaultCharset("utf8");
answerColumns(asList(
new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"},
new String[] {TABLE_PROJECTS, COLUMN_NAME, "" /* unset -> uses db collation */}));
// no error
assertThatCode(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE))
.doesNotThrowAnyException();
verify(sqlExecutor).select(same(connection), eq("select table_name, column_name,"
+ " collation_name "
+ "from information_schema.columns "
+ "where table_schema='public' "
+ "and table_name in (" + SqTables.TABLES.stream().map(s -> "'" + s + "'").collect(Collectors.joining(",")) + ") "
+ "and udt_name='varchar' order by table_name, column_name"), any(SqlExecutor.StringsConverter.class));
}
@Test
public void schema_is_taken_into_account_when_selecting_columns() throws Exception {
answerDefaultCharset("utf8");
answerSchema("test-schema");
answerColumns(asList(
new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"},
new String[] {TABLE_PROJECTS, COLUMN_NAME, "" /* unset -> uses db collation */}));
// no error
assertThatCode(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE))
.doesNotThrowAnyException();
verify(sqlExecutor).select(same(connection), eq("select table_name, column_name,"
+ " collation_name "
+ "from information_schema.columns "
+ "where table_schema='test-schema' "
+ "and table_name in (" + SqTables.TABLES.stream().map(s -> "'" + s + "'").collect(Collectors.joining(",")) + ") "
+ "and udt_name='varchar' order by table_name, column_name"), any(SqlExecutor.StringsConverter.class));
}
@Test
public void upgrade_fails_if_non_utf8_column() throws Exception {
// default charset is ok but two columns are not
answerDefaultCharset("utf8");
answerColumns(asList(
new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"},
new String[] {TABLE_PROJECTS, COLUMN_KEE, "latin"},
new String[] {TABLE_PROJECTS, COLUMN_NAME, "latin"}));
assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE))
.isInstanceOf(MessageException.class)
.hasMessage("Database columns [projects.kee, projects.name] must have UTF8 charset.");
}
@Test
public void upgrade_fails_if_default_charset_is_not_utf8() throws Exception {
answerDefaultCharset("latin");
answerColumns(
List.<String[]>of(new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"}));
assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE))
.isInstanceOf(MessageException.class)
.hasMessage("Database charset is latin. It must support UTF8.");
}
private void answerDefaultCharset(String defaultCollation) throws SQLException {
when(metadata.getDefaultCharset(same(connection))).thenReturn(defaultCollation);
}
private void answerSchema(String schema) throws SQLException {
when(connection.getSchema()).thenReturn(schema);
}
private void answerColumns(List<String[]> firstRequest) throws SQLException {
when(sqlExecutor.select(same(connection), anyString(), any(SqlExecutor.StringsConverter.class))).thenReturn(firstRequest);
}
}
| 6,844 | 40.737805 | 126 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/PostgresMetadataReaderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PostgresMetadataReaderTest {
private SqlExecutor sqlExecutor = mock(SqlExecutor.class);
private Connection connection = mock(Connection.class);
private PostgresMetadataReader underTest = new PostgresMetadataReader(sqlExecutor);
@Test
public void test_getDefaultCharset() throws SQLException {
answerSelect("latin");
assertThat(underTest.getDefaultCharset(connection)).isEqualTo("latin");
}
private void answerSelect(String charset) throws SQLException {
when(sqlExecutor.selectSingleString(same(connection), anyString())).thenReturn(charset);
}
}
| 1,817 | 35.36 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/SelectExecutorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import java.sql.Connection;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThat;
public class SelectExecutorTest {
@Rule
public CoreDbTester dbTester = CoreDbTester.createForSchema(SelectExecutorTest.class, "users_table.sql");
SqlExecutor underTest = new SqlExecutor();
@Test
public void testExecuteQuery() throws Exception {
insertUser("him", "Him");
insertUser("her", "Her");
try (Connection connection = dbTester.openConnection()) {
List<String[]> rows = underTest.select(connection, "select login, name from users order by login", new SqlExecutor.StringsConverter(2));
assertThat(rows).hasSize(2);
assertThat(rows.get(0)[0]).isEqualTo("her");
assertThat(rows.get(0)[1]).isEqualTo("Her");
assertThat(rows.get(1)[0]).isEqualTo("him");
assertThat(rows.get(1)[1]).isEqualTo("Him");
}
}
private void insertUser(String login, String name) {
dbTester.executeInsert("users",
"LOGIN", login,
"NAME", name);
}
}
| 2,005 | 33.586207 | 142 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/SqlExecutorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.charset;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThat;
public class SqlExecutorTest {
private static final String LOGIN_DB_COLUMN = "login";
private static final String NAME_DB_COLUMN = "name";
private static final String USERS_DB_TABLE = "users";
private static final String IS_ROOT_DB_COLUMN = "is_root";
private SqlExecutor underTest = new SqlExecutor();
@Rule
public CoreDbTester dbTester = CoreDbTester.createForSchema(SqlExecutorTest.class, "users_table.sql");
@Test
public void executeSelect_executes_PreparedStatement() throws Exception {
dbTester.executeInsert(USERS_DB_TABLE, LOGIN_DB_COLUMN, "login1", NAME_DB_COLUMN, "name one", IS_ROOT_DB_COLUMN, false);
dbTester.executeInsert(USERS_DB_TABLE, LOGIN_DB_COLUMN, "login2", NAME_DB_COLUMN, "name two", IS_ROOT_DB_COLUMN, false);
try (Connection connection = dbTester.openConnection()) {
List<String[]> users = underTest.select(connection, "select " + LOGIN_DB_COLUMN + ", " + NAME_DB_COLUMN + " from users order by login", new SqlExecutor.StringsConverter(
2));
assertThat(users).hasSize(2);
assertThat(users.get(0)[0]).isEqualTo("login1");
assertThat(users.get(0)[1]).isEqualTo("name one");
assertThat(users.get(1)[0]).isEqualTo("login2");
assertThat(users.get(1)[1]).isEqualTo("name two");
}
}
@Test
public void executeUpdate_executes_PreparedStatement() throws Exception {
dbTester.executeInsert(USERS_DB_TABLE, LOGIN_DB_COLUMN, "the_login", NAME_DB_COLUMN, "the name", IS_ROOT_DB_COLUMN, false);
try (Connection connection = dbTester.openConnection()) {
underTest.executeDdl(connection, "update users set " + NAME_DB_COLUMN + "='new name' where " + LOGIN_DB_COLUMN + "='the_login'");
}
Map<String, Object> row = dbTester.selectFirst("select " + NAME_DB_COLUMN + " from users where " + LOGIN_DB_COLUMN + "='the_login'");
assertThat(row)
.isNotEmpty()
.containsEntry("NAME", "new name");
}
}
| 3,044 | 40.712329 | 175 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BigIntegerColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class BigIntegerColumnDefTest {
@Test
public void build_string_column_def() {
BigIntegerColumnDef def = new BigIntegerColumnDef.Builder()
.setColumnName("issues")
.setIsNullable(true)
.build();
assertThat(def.getName()).isEqualTo("issues");
assertThat(def.isNullable()).isTrue();
}
@Test
public void build_string_column_def_with_default_values() {
BigIntegerColumnDef def = new BigIntegerColumnDef.Builder()
.setColumnName("issues")
.build();
assertThat(def.getName()).isEqualTo("issues");
assertThat(def.isNullable()).isTrue();
}
@Test
public void generate_sql_type() {
BigIntegerColumnDef def = new BigIntegerColumnDef.Builder()
.setColumnName("issues")
.setIsNullable(true)
.build();
assertThat(def.generateSqlType(new H2())).isEqualTo("BIGINT");
assertThat(def.generateSqlType(new PostgreSql())).isEqualTo("BIGINT");
assertThat(def.generateSqlType(new MsSql())).isEqualTo("BIGINT");
assertThat(def.generateSqlType(new Oracle())).isEqualTo("NUMBER (38)");
}
@Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> {
new BigIntegerColumnDef.Builder()
.setColumnName(null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_with_NPE_if_no_name() {
assertThatThrownBy(() -> {
new BigIntegerColumnDef.Builder()
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
}
| 2,789 | 31.068966 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BlobColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.platform.db.migration.def.BlobColumnDef.newBlobColumnDefBuilder;
public class BlobColumnDefTest {
private BlobColumnDef underTest = newBlobColumnDefBuilder().setColumnName("a").build();
@Test
public void builder_setColumnName_throws_IAE_if_name_is_not_lowercase() {
BlobColumnDef.Builder builder = newBlobColumnDefBuilder();
assertThatThrownBy(() -> builder.setColumnName("T"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'T'");
}
@Test
public void builder_build_throws_NPE_if_no_name_was_set() {
BlobColumnDef.Builder builder = newBlobColumnDefBuilder();
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void blobColumDef_is_nullable_by_default() {
assertThat(newBlobColumnDefBuilder().setColumnName("a").build().isNullable()).isTrue();
}
@Test
public void builder_setNullable_sets_nullable_field_of_BlobColumnDef() {
assertThat(newBlobColumnDefBuilder().setColumnName("a").setIsNullable(true).build().isNullable()).isTrue();
assertThat(newBlobColumnDefBuilder().setColumnName("a").setIsNullable(false).build().isNullable()).isFalse();
}
@Test
public void builder_setColumnName_sets_name_field_of_BlobColumnDef() {
assertThat(newBlobColumnDefBuilder().setColumnName("a").build().getName()).isEqualTo("a");
}
@Test
public void generateSqlType_for_MsSql() {
assertThat(underTest.generateSqlType(new MsSql())).isEqualTo("VARBINARY(MAX)");
}
@Test
public void generateSqlType_for_Oracle() {
assertThat(underTest.generateSqlType(new Oracle())).isEqualTo("BLOB");
}
@Test
public void generateSqlType_for_H2() {
assertThat(underTest.generateSqlType(new H2())).isEqualTo("BLOB");
}
@Test
public void generateSqlType_for_PostgreSql() {
assertThat(underTest.generateSqlType(new PostgreSql())).isEqualTo("BYTEA");
}
@Test
public void generateSqlType_thows_IAE_for_unknown_dialect() {
Dialect dialect = mock(Dialect.class);
when(dialect.getId()).thenReturn("AAA");
assertThatThrownBy(() -> underTest.generateSqlType(dialect))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unsupported dialect id AAA");
}
}
| 3,696 | 34.893204 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BooleanColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class BooleanColumnDefTest {
@Test
public void build_column_def() {
BooleanColumnDef def = new BooleanColumnDef.Builder()
.setColumnName("enabled")
.setIsNullable(false)
.setDefaultValue(true)
.build();
assertThat(def.getName()).isEqualTo("enabled");
assertThat(def.isNullable()).isFalse();
assertThat(def.getDefaultValue()).isEqualTo(true);
}
@Test
public void build_column_def_with_only_required_attributes() {
BooleanColumnDef def = new BooleanColumnDef.Builder()
.setColumnName("enabled")
.build();
assertThat(def.getName()).isEqualTo("enabled");
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void generate_sql_type() {
BooleanColumnDef def = new BooleanColumnDef.Builder()
.setColumnName("enabled")
.setIsNullable(true)
.build();
assertThat(def.generateSqlType(new H2())).isEqualTo("BOOLEAN");
assertThat(def.generateSqlType(new PostgreSql())).isEqualTo("BOOLEAN");
assertThat(def.generateSqlType(new MsSql())).isEqualTo("BIT");
assertThat(def.generateSqlType(new Oracle())).isEqualTo("NUMBER(1)");
}
@Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> new BooleanColumnDef.Builder().setColumnName(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_with_NPE_if_no_name() {
assertThatThrownBy(() -> new BooleanColumnDef.Builder().build())
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
}
| 2,845 | 33.289157 | 80 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ClobColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ClobColumnDefTest {
private final ClobColumnDef underTest = new ClobColumnDef.Builder()
.setColumnName("issues")
.setIsNullable(true)
.build();
@Test
public void build_string_column_def() {
assertThat(underTest.getName()).isEqualTo("issues");
assertThat(underTest.isNullable()).isTrue();
assertThat(underTest.getDefaultValue()).isNull();
}
@Test
public void build_string_column_def_with_only_required_attributes() {
ClobColumnDef def = new ClobColumnDef.Builder()
.setColumnName("issues")
.build();
assertThat(def.getName()).isEqualTo("issues");
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void generate_sql_type_on_mssql() {
assertThat(underTest.generateSqlType(new MsSql())).isEqualTo("NVARCHAR (MAX)");
}
@Test
public void generate_sql_type_on_h2() {
assertThat(underTest.generateSqlType(new H2())).isEqualTo("CLOB");
}
@Test
public void generate_sql_type_on_oracle() {
assertThat(underTest.generateSqlType(new Oracle())).isEqualTo("CLOB");
}
@Test
public void generate_sql_type_on_postgre() {
assertThat(underTest.generateSqlType(new PostgreSql())).isEqualTo("TEXT");
}
@Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> {
new ClobColumnDef.Builder()
.setColumnName(null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_with_NPE_if_no_name() {
assertThatThrownBy(() -> {
new ClobColumnDef.Builder()
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
}
| 2,948 | 29.71875 | 83 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/DecimalColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DecimalColumnDefTest {
@Test
public void build_string_column_def() {
DecimalColumnDef def = new DecimalColumnDef.Builder()
.setColumnName("issues")
.setPrecision(30)
.setScale(20)
.setIsNullable(true)
.build();
assertThat(def.getName()).isEqualTo("issues");
assertThat(def.getPrecision()).isEqualTo(30);
assertThat(def.getScale()).isEqualTo(20);
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> {
new DecimalColumnDef.Builder()
.setColumnName(null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_with_NPE_if_no_name() {
assertThatThrownBy(() -> {
new DecimalColumnDef.Builder()
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void default_precision_is_38() {
DecimalColumnDef def = new DecimalColumnDef.Builder()
.setColumnName("issues")
.setScale(20)
.setIsNullable(true)
.build();
assertThat(def.getPrecision()).isEqualTo(38);
}
@Test
public void default_precision_is_20() {
DecimalColumnDef def = new DecimalColumnDef.Builder()
.setColumnName("issues")
.setPrecision(30)
.setIsNullable(true)
.build();
assertThat(def.getScale()).isEqualTo(20);
}
@Test
public void create_builder_with_only_required_attributes() {
DecimalColumnDef def = new DecimalColumnDef.Builder()
.setColumnName("issues")
.build();
assertThat(def.getPrecision()).isEqualTo(38);
assertThat(def.getScale()).isEqualTo(20);
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void generate_sql_type() {
DecimalColumnDef def = new DecimalColumnDef.Builder()
.setColumnName("issues")
.setPrecision(30)
.setScale(20)
.setIsNullable(true)
.build();
assertThat(def.generateSqlType(new H2())).isEqualTo("DOUBLE");
assertThat(def.generateSqlType(new PostgreSql())).isEqualTo("NUMERIC (30,20)");
assertThat(def.generateSqlType(new MsSql())).isEqualTo("DECIMAL (30,20)");
assertThat(def.generateSqlType(new Oracle())).isEqualTo("NUMERIC (30,20)");
}
@Test
public void fail_with_UOE_to_generate_sql_type_when_unknown_dialect() {
assertThatThrownBy(() -> {
DecimalColumnDef def = new DecimalColumnDef.Builder()
.setColumnName("issues")
.setPrecision(30)
.setScale(20)
.setIsNullable(true)
.build();
Dialect dialect = mock(Dialect.class);
when(dialect.getId()).thenReturn("unknown");
def.generateSqlType(dialect);
})
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("Unknown dialect 'unknown'");
}
}
| 4,294 | 29.899281 | 83 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/IntegerColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.platform.db.migration.def.IntegerColumnDef.newIntegerColumnDefBuilder;
public class IntegerColumnDefTest {
private IntegerColumnDef underTest = newIntegerColumnDefBuilder().setColumnName("a").build();
@Test
public void builder_setColumnName_throws_IAE_if_name_is_not_lowercase() {
IntegerColumnDef.Builder builder = newIntegerColumnDefBuilder();
assertThatThrownBy(() -> builder.setColumnName("T"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'T'");
}
@Test
public void builder_build_throws_NPE_if_no_name_was_set() {
IntegerColumnDef.Builder builder = newIntegerColumnDefBuilder();
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void integerColumDef_is_nullable_by_default() {
assertThat(newIntegerColumnDefBuilder().setColumnName("a").build().isNullable()).isTrue();
}
@Test
public void builder_setNullable_sets_nullable_field_of_IntegerColumnDef() {
assertThat(newIntegerColumnDefBuilder().setColumnName("a").setIsNullable(true).build().isNullable()).isTrue();
assertThat(newIntegerColumnDefBuilder().setColumnName("a").setIsNullable(false).build().isNullable()).isFalse();
}
@Test
public void builder_setColumnName_sets_name_field_of_IntegerColumnDef() {
assertThat(newIntegerColumnDefBuilder().setColumnName("a").build().getName()).isEqualTo("a");
}
@Test
public void builder_setDefaultValue_sets_default_value_field_of_IntegerColumnDef() {
assertThat(newIntegerColumnDefBuilder().setColumnName("a").setDefaultValue(42).build().getDefaultValue()).isEqualTo(42);
}
@Test
public void default_value_is_null_by_default() {
assertThat(newIntegerColumnDefBuilder().setColumnName("a").build().getDefaultValue()).isNull();
}
@Test
public void generateSqlType_for_MsSql() {
assertThat(underTest.generateSqlType(new MsSql())).isEqualTo("INT");
}
@Test
public void generateSqlType_for_Oracle() {
assertThat(underTest.generateSqlType(new Oracle())).isEqualTo("NUMBER(38,0)");
}
@Test
public void generateSqlType_for_H2() {
assertThat(underTest.generateSqlType(new H2())).isEqualTo("INTEGER");
}
@Test
public void generateSqlType_for_PostgreSql() {
assertThat(underTest.generateSqlType(new PostgreSql())).isEqualTo("INTEGER");
}
@Test
public void generateSqlType_thows_IAE_for_unknown_dialect() {
Dialect dialect = mock(Dialect.class);
when(dialect.getId()).thenReturn("AAA");
assertThatThrownBy(() -> underTest.generateSqlType(dialect))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unsupported dialect id AAA");
}
}
| 4,136 | 35.289474 | 124 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TimestampColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.platform.db.migration.def.TimestampColumnDef.newTimestampColumnDefBuilder;
@SuppressWarnings("deprecation")
public class TimestampColumnDefTest {
@Test
public void build_column_def() {
TimestampColumnDef def = newTimestampColumnDefBuilder()
.setColumnName("created_at")
.setIsNullable(false)
.build();
assertThat(def.getName()).isEqualTo("created_at");
assertThat(def.isNullable()).isFalse();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void build_column_def_with_only_required_attributes() {
TimestampColumnDef def = newTimestampColumnDefBuilder()
.setColumnName("created_at")
.build();
assertThat(def.getName()).isEqualTo("created_at");
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void generate_sql_type() {
TimestampColumnDef def = newTimestampColumnDefBuilder()
.setColumnName("created_at")
.build();
assertThat(def.generateSqlType(new H2())).isEqualTo("TIMESTAMP");
assertThat(def.generateSqlType(new PostgreSql())).isEqualTo("TIMESTAMP");
assertThat(def.generateSqlType(new MsSql())).isEqualTo("DATETIME");
assertThat(def.generateSqlType(new Oracle())).isEqualTo("TIMESTAMP (6)");
}
@Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> newTimestampColumnDefBuilder().setColumnName(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_with_NPE_if_no_name() {
assertThatThrownBy(() -> newTimestampColumnDefBuilder().build())
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
}
| 2,957 | 34.638554 | 105 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TinyIntColumnDefTest {
@Test
public void build_string_column_def() {
TinyIntColumnDef def = new TinyIntColumnDef.Builder()
.setColumnName("foo")
.setIsNullable(true)
.build();
assertThat(def.getName()).isEqualTo("foo");
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void generate_sql_type() {
TinyIntColumnDef def = new TinyIntColumnDef.Builder()
.setColumnName("foo")
.setIsNullable(true)
.build();
assertThat(def.generateSqlType(new H2())).isEqualTo("TINYINT");
assertThat(def.generateSqlType(new PostgreSql())).isEqualTo("SMALLINT");
assertThat(def.generateSqlType(new MsSql())).isEqualTo("TINYINT");
assertThat(def.generateSqlType(new Oracle())).isEqualTo("NUMBER(3)");
}
@Test
public void fail_with_UOE_to_generate_sql_type_when_unknown_dialect() {
assertThatThrownBy(() -> {
TinyIntColumnDef def = new TinyIntColumnDef.Builder()
.setColumnName("foo")
.setIsNullable(true)
.build();
Dialect dialect = mock(Dialect.class);
when(dialect.getId()).thenReturn("unknown");
def.generateSqlType(dialect);
})
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("Unknown dialect 'unknown'");
}
}
| 2,635 | 33.684211 | 76 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ValidationsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
import static org.sonar.server.platform.db.migration.def.Validations.validateIndexName;
import static org.sonar.server.platform.db.migration.def.Validations.validateIndexNameIgnoreCase;
public class ValidationsTest {
@Test
public void accept_valid_table_name() {
validateColumnName("date_in_ms");
validateColumnName("date_in_ms_1");
}
@Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> validateColumnName(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_when_column_name_is_an_SQL_reserved_keyword() {
assertThatThrownBy(() -> validateColumnName("values"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Column name must not be an SQL reserved keyword, got 'values'");
}
@Test
public void accept_allowed_identifier_for_column_name_that_is_SQL_reserved_keyword() {
assertThatCode(() -> validateColumnName("value"))
.doesNotThrowAnyException();
}
@Test
public void fail_when_index_name_is_an_SQL_reserved_keyword_ignoring_case() {
assertThatThrownBy(() -> validateIndexNameIgnoreCase("VALUES"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must not be an SQL reserved keyword, got 'VALUES'");
assertThatThrownBy(() -> validateIndexNameIgnoreCase("values"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must not be an SQL reserved keyword, got 'values'");
}
@Test
public void accept_allowed_identifier_for_index_name_that_is_SQL_reserved_keyword_ignoring_case() {
assertThatCode(() -> validateIndexNameIgnoreCase("value"))
.doesNotThrowAnyException();
assertThatCode(() -> validateIndexNameIgnoreCase("VALUE"))
.doesNotThrowAnyException();
}
@Test
public void fail_when_column_name_is_in_upper_case() {
assertThatThrownBy(() -> validateColumnName("DATE_IN_MS"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'DATE_IN_MS'");
}
@Test
public void fail_when_column_name_contains_invalid_character() {
assertThatThrownBy(() -> validateColumnName("date-in/ms"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'date-in/ms'");
}
@Test
public void validateIndexName_throws_IAE_when_index_name_contains_invalid_characters() {
assertThatThrownBy(() -> validateIndexName("(not/valid)"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must be lower case and contain only alphanumeric chars or '_', got '(not/valid)'");
}
@Test
public void validateIndexName_throws_NPE_when_index_name_is_null() {
assertThatThrownBy(() -> validateIndexName(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Index name can't be null");
}
@Test
public void validateIndexName_returns_valid_name() {
assertThat(validateIndexName("foo")).isEqualTo("foo");
}
}
| 4,339 | 38.099099 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/VarcharColumnDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.def;
import org.junit.Test;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class VarcharColumnDefTest {
@Test
public void build_string_column_def() {
VarcharColumnDef def = new VarcharColumnDef.Builder()
.setColumnName("issues")
.setLimit(10)
.setIsNullable(true)
.setDefaultValue("foo")
.build();
assertThat(def.getName()).isEqualTo("issues");
assertThat(def.getColumnSize()).isEqualTo(10);
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isEqualTo("foo");
}
@Test
public void build_string_column_def_with_only_required_attributes() {
VarcharColumnDef def = new VarcharColumnDef.Builder()
.setColumnName("issues")
.setLimit(10)
.build();
assertThat(def.getName()).isEqualTo("issues");
assertThat(def.getColumnSize()).isEqualTo(10);
assertThat(def.isNullable()).isTrue();
assertThat(def.getDefaultValue()).isNull();
}
@Test
public void generate_sql_type() {
VarcharColumnDef def = new VarcharColumnDef.Builder()
.setColumnName("issues")
.setLimit(10)
.setIsNullable(true)
.build();
assertThat(def.generateSqlType(new H2())).isEqualTo("VARCHAR (10)");
assertThat(def.generateSqlType(new PostgreSql())).isEqualTo("VARCHAR (10)");
assertThat(def.generateSqlType(new MsSql())).isEqualTo("NVARCHAR (10)");
assertThat(def.generateSqlType(new Oracle())).isEqualTo("VARCHAR2 (10 CHAR)");
}
@Test
public void generateSqlType_does_not_set_unit_on_oracle_if_legacy_mode() {
VarcharColumnDef def = new VarcharColumnDef.Builder()
.setColumnName("issues")
.setLimit(10)
.setIsNullable(true)
.setIgnoreOracleUnit(true)
.build();
assertThat(def.generateSqlType(new Oracle())).isEqualTo("VARCHAR2 (10)");
}
@Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> {
new VarcharColumnDef.Builder()
.setColumnName(null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_with_NPE_if_no_name() {
assertThatThrownBy(() -> {
new VarcharColumnDef.Builder()
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
}
@Test
public void fail_with_NPE_if_size_is_null() {
assertThatThrownBy(() -> {
new VarcharColumnDef.Builder()
.setColumnName("issues")
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Limit cannot be null");
}
}
| 3,725 | 30.846154 | 82 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/engine/MigrationContainerImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.engine;
import java.sql.SQLException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.Startable;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.server.platform.db.migration.step.InternalMigrationStepRegistry;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationStepRegistryImpl;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static org.assertj.core.api.Assertions.assertThat;
public class MigrationContainerImplTest {
private final SpringComponentContainer parent = new SpringComponentContainer();
private MigrationContainerImpl underTest;
@Before
public void setUp() {
InternalMigrationStepRegistry registry = new MigrationStepRegistryImpl();
registry.add(1, "test", NoOpMigrationStep.class);
parent.add(registry.build());
parent.startComponents();
underTest = new MigrationContainerImpl(parent, NoOpExecutor.class);
underTest.add(StartCallCounter.class);
}
@Test
public void adds_migration_steps_to_migration_container() {
assertThat(underTest.getComponentByType(MigrationStep.class)).isInstanceOf(NoOpMigrationStep.class);
}
@Test
public void context_of_migration_container_has_specified_context_as_parent() {
assertThat(underTest.context().getParent()).isEqualTo(parent.context());
}
@Test
public void context_of_migration_container_is_started_in_constructor() {
assertThat(underTest.context().isActive()).isTrue();
}
@Test
public void add_duplicate_steps_has_no_effect() {
InternalMigrationStepRegistry registry = new MigrationStepRegistryImpl();
registry.add(1, "test", NoOpMigrationStep.class);
registry.add(2, "test2", NoOpMigrationStep.class);
SpringComponentContainer parent = new SpringComponentContainer();
parent.add(registry.build());
parent.startComponents();
MigrationContainerImpl underTest = new MigrationContainerImpl(parent, NoOpExecutor.class);
assertThat(underTest.getComponentsByType(MigrationStep.class)).hasSize(1);
}
@Test
public void migration_container_lazily_instance_components() {
assertThat(StartCallCounter.startCalls).isZero();
StartCallCounter startCallCounter = underTest.getComponentByType(StartCallCounter.class);
assertThat(startCallCounter).isNotNull();
assertThat(StartCallCounter.startCalls).isOne();
}
@Test
public void cleanup_does_not_fail_even_if_stop_of_component_fails() {
parent.add(StopFailing.class);
MigrationContainerImpl underTest = new MigrationContainerImpl(parent, NoOpExecutor.class);
underTest.cleanup();
}
private static class NoOpExecutor implements MigrationStepsExecutor {
@Override
public void execute(List<RegisteredMigrationStep> steps) {
}
}
private static class NoOpMigrationStep implements MigrationStep {
@Override
public void execute() throws SQLException {
}
}
public static final class StartCallCounter implements Startable {
private static int startCalls = 0;
@Override
public void start() {
startCalls++;
}
@Override
public void stop() {
// do nothing
}
}
public static final class StopFailing implements Startable {
@Override
public void start() {
// do nothing
}
@Override
public void stop() {
throw new RuntimeException("Faking stop call failing");
}
}
}
| 4,462 | 31.576642 | 104 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/engine/MigrationContainerPopulatorImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.engine;
import org.junit.Before;
import org.junit.Test;
import org.sonar.server.platform.db.migration.history.MigrationHistory;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MigrationContainerPopulatorImplTest {
private final SimpleMigrationContainer migrationContainer = new SimpleMigrationContainer();
private final MigrationSteps migrationSteps = mock(MigrationSteps.class);
private final MigrationContainerPopulatorImpl underTest = new MigrationContainerPopulatorImpl();
@Before
public void setUp() {
migrationContainer.add(migrationSteps);
}
@Test
public void populateContainer_adds_MigrationStepsExecutorImpl() {
when(migrationSteps.readAll()).thenReturn(emptyList());
// add MigrationStepsExecutorImpl's dependencies
migrationContainer.add(mock(MigrationHistory.class));
migrationContainer.startComponents();
underTest.populateContainer(migrationContainer);
assertThat(migrationContainer.getComponentByType(MigrationStepsExecutorImpl.class)).isNotNull();
}
@Test
public void populateContainer_adds_classes_of_all_steps_defined_in_MigrationSteps() {
when(migrationSteps.readAll()).thenReturn(asList(
new RegisteredMigrationStep(1, "foo", MigrationStep1.class),
new RegisteredMigrationStep(2, "bar", MigrationStep2.class),
new RegisteredMigrationStep(3, "dor", MigrationStep3.class)));
migrationContainer.startComponents();
underTest.populateContainer(migrationContainer);
assertThat(migrationContainer.getComponentsByType(MigrationStep1.class)).isNotNull();
assertThat(migrationContainer.getComponentsByType(MigrationStep2.class)).isNotNull();
assertThat(migrationContainer.getComponentsByType(MigrationStep3.class)).isNotNull();
}
@Test
public void populateCotnainer_does_not_fail_if_same_class_is_used_for_more_than_one_migration() {
when(migrationSteps.readAll()).thenReturn(asList(
new RegisteredMigrationStep(1, "foo", MigrationStep1.class),
new RegisteredMigrationStep(2, "bar", MigrationStep2.class),
new RegisteredMigrationStep(3, "bar2", MigrationStep2.class),
new RegisteredMigrationStep(4, "foo2", MigrationStep1.class),
new RegisteredMigrationStep(5, "dor", MigrationStep3.class)));
migrationContainer.startComponents();
underTest.populateContainer(migrationContainer);
assertThat(migrationContainer.getComponentsByType(MigrationStep1.class)).isNotNull();
assertThat(migrationContainer.getComponentsByType(MigrationStep2.class)).isNotNull();
assertThat(migrationContainer.getComponentsByType(MigrationStep3.class)).isNotNull();
}
private static abstract class NoopMigrationStep implements MigrationStep {
@Override
public void execute() {
throw new UnsupportedOperationException("execute not implemented");
}
}
public static final class MigrationStep1 extends NoopMigrationStep {
}
public static final class MigrationStep2 extends NoopMigrationStep {
}
public static final class MigrationStep3 extends NoopMigrationStep {
}
public static final class Clazz1 {
}
public static final class Clazz2 {
}
public static final class Clazz3 {
}
}
| 4,551 | 36.311475 | 100 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/engine/MigrationEngineImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.engine;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.server.platform.db.migration.SupportsBlueGreen;
import org.sonar.server.platform.db.migration.history.MigrationHistory;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MigrationEngineImplTest {
private final MigrationHistory migrationHistory = mock(MigrationHistory.class);
private final SpringComponentContainer serverContainer = new SpringComponentContainer();
private final MigrationSteps migrationSteps = mock(MigrationSteps.class);
private final StepRegistry stepRegistry = new StepRegistry();
private final MapSettings settings = new MapSettings();
private final MigrationEngineImpl underTest = new MigrationEngineImpl(migrationHistory, serverContainer, migrationSteps);
@Before
public void before() {
serverContainer.add(migrationSteps);
serverContainer.add(migrationHistory);
serverContainer.add(stepRegistry);
serverContainer.startComponents();
}
@Test
public void execute_execute_all_steps_of_there_is_no_last_migration_number() {
when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.empty());
List<RegisteredMigrationStep> steps = singletonList(new RegisteredMigrationStep(1, "doo", TestMigrationStep.class));
when(migrationSteps.readAll()).thenReturn(steps);
underTest.execute();
verify(migrationSteps, times(2)).readAll();
assertThat(stepRegistry.stepRan).isTrue();
}
@Test
public void execute_execute_steps_from_last_migration_number_plus_1() {
when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.of(50L));
List<RegisteredMigrationStep> steps = singletonList(new RegisteredMigrationStep(1, "doo", TestMigrationStep.class));
when(migrationSteps.readFrom(51)).thenReturn(steps);
when(migrationSteps.readAll()).thenReturn(steps);
underTest.execute();
verify(migrationSteps).readFrom(51);
assertThat(stepRegistry.stepRan).isTrue();
}
private static class NoOpExecutor implements MigrationStepsExecutor {
@Override
public void execute(List<RegisteredMigrationStep> steps) {
// no op
}
}
private static class StepRegistry {
boolean stepRan = false;
}
private static class TestMigrationStep implements MigrationStep {
private final StepRegistry registry;
public TestMigrationStep(StepRegistry registry) {
this.registry = registry;
}
@Override
public void execute() throws SQLException {
registry.stepRan = true;
}
}
@SupportsBlueGreen
private static class TestBlueGreenMigrationStep implements MigrationStep {
private final StepRegistry registry;
public TestBlueGreenMigrationStep(StepRegistry registry) {
this.registry = registry;
}
@Override
public void execute() throws SQLException {
registry.stepRan = true;
}
}
}
| 4,454 | 36.125 | 123 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/engine/SimpleMigrationContainer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.engine;
import org.sonar.core.platform.SpringComponentContainer;
public final class SimpleMigrationContainer extends SpringComponentContainer implements MigrationContainer {
@Override
public void cleanup() {
stopComponents();
}
}
| 1,133 | 35.580645 | 108 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.history;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class MigrationHistoryImplTest {
@Rule
public CoreDbTester dbTester = CoreDbTester.createForSchema(MigrationHistoryImplTest.class, "schema_migration.sql");
private MigrationHistoryMeddler migrationHistoryMeddler = mock(MigrationHistoryMeddler.class);
private MigrationHistoryImpl underTest = new MigrationHistoryImpl(dbTester.database(), migrationHistoryMeddler);
@Test
public void start_does_not_fail_if_table_history_exists_and_calls_meddler() {
underTest.start();
verify(migrationHistoryMeddler).meddle(underTest);
}
@Test
public void getLastMigrationNumber_returns_empty_if_history_table_is_empty() {
assertThat(underTest.getLastMigrationNumber()).isEmpty();
}
@Test
public void getLastMigrationNumber_returns_last_version_assuming_version_are_only_number() throws SQLException {
insert(12, 5, 30, 8);
assertThat(underTest.getLastMigrationNumber()).contains(30L);
}
@Test
public void done_fails_with_NPE_if_argument_is_null() {
assertThatThrownBy(() -> underTest.done(null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void done_adds_migration_number_to_table() {
underTest.done(new RegisteredMigrationStep(12, "aa", MigrationStep.class));
assertThat(underTest.getLastMigrationNumber()).contains(12L);
}
private void insert(int... versions) throws SQLException {
try (Connection connection = dbTester.database().getDataSource().getConnection()) {
Arrays.stream(versions).forEach(version -> insert(connection, version));
}
}
private void insert(Connection connection, long version) {
try (PreparedStatement statement = connection.prepareStatement("insert into schema_migrations(version) values (?)")) {
statement.setString(1, String.valueOf(version));
statement.execute();
connection.commit();
} catch (SQLException e) {
throw new IllegalStateException(String.format("Failed to insert row with value %s", version), e);
}
}
}
| 3,442 | 36.423913 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryMeddlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.history;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.IntStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class MigrationHistoryMeddlerTest {
private static final long OLD_VERSION_70_LAST_MIGRATION_NUMBER = 1_923L;
private static final long NEW_VERSION_70_LAST_MIGRATION_NUMBER = 1_959L;
private MigrationSteps migrationSteps = mock(MigrationSteps.class);
private MigrationHistory migrationHistory = mock(MigrationHistory.class);
private MigrationHistoryMeddler underTest = new MigrationHistoryMeddler(migrationSteps);
@Test
public void no_effect_if_no_last_migration_number() {
when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.empty());
underTest.meddle(migrationHistory);
verify(migrationHistory).getLastMigrationNumber();
verifyNoMoreInteractions(migrationHistory, migrationSteps);
}
@Test
@UseDataProvider("non_old_70_last_migration_number")
public void no_history_meddling_if_last_migration_number_is_not_old_70_last_migration_number(long lastMigrationNumber) {
when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.of(lastMigrationNumber));
underTest.meddle(migrationHistory);
verify(migrationHistory).getLastMigrationNumber();
verifyNoMoreInteractions(migrationHistory, migrationSteps);
}
@Test
public void update_last_migration_number_if_last_migration_number_is_old_70_last_migration_number() {
verifyUpdateLastMigrationNumber(OLD_VERSION_70_LAST_MIGRATION_NUMBER, NEW_VERSION_70_LAST_MIGRATION_NUMBER);
}
public void verifyUpdateLastMigrationNumber(long oldVersion, long expectedNewVersion) {
when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.of(oldVersion));
List<RegisteredMigrationStep> stepsFromNewLastMigrationNumber = IntStream.range(0, 1 + new Random().nextInt(30))
.mapToObj(i -> new RegisteredMigrationStep(i, "desc_" + i, MigrationStep.class))
.toList();
when(migrationSteps.readFrom(expectedNewVersion)).thenReturn(stepsFromNewLastMigrationNumber);
underTest.meddle(migrationHistory);
verify(migrationHistory).getLastMigrationNumber();
verify(migrationSteps).readFrom(expectedNewVersion);
verify(migrationHistory).done(stepsFromNewLastMigrationNumber.get(0));
verifyNoMoreInteractions(migrationHistory, migrationSteps);
}
@DataProvider
public static Object[][] non_old_70_last_migration_number() {
return new Object[][] {
{1L},
{OLD_VERSION_70_LAST_MIGRATION_NUMBER - 1 - new Random().nextInt(12)},
{OLD_VERSION_70_LAST_MIGRATION_NUMBER + 1 + new Random().nextInt(12)}
};
}
}
| 4,182 | 40.83 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryTableImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.history;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThat;
public class MigrationHistoryTableImplTest {
private static final String TABLE_SCHEMA_MIGRATIONS = "schema_migrations";
@Rule
public CoreDbTester dbTester = CoreDbTester.createEmpty();
private MigrationHistoryTableImpl underTest = new MigrationHistoryTableImpl(dbTester.database());
@Test
public void start_creates_table_on_empty_schema() {
underTest.start();
verifyTable();
}
@Test
public void start_does_not_fail_if_table_exists() throws SQLException {
executeDdl("create table " + TABLE_SCHEMA_MIGRATIONS + " (version varchar(255) not null)");
verifyTable();
underTest.start();
verifyTable();
}
private void executeDdl(String sql) throws SQLException {
try (Connection connection = dbTester.database().getDataSource().getConnection()) {
connection.setAutoCommit(false);
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
connection.commit();
}
}
}
private void verifyTable() {
assertThat(dbTester.countRowsOfTable(TABLE_SCHEMA_MIGRATIONS)).isZero();
dbTester.assertColumnDefinition(TABLE_SCHEMA_MIGRATIONS, "version", Types.VARCHAR, 255, false);
}
}
| 2,344 | 31.569444 | 99 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/NoTableMigrationHistoryImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.history;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
public class NoTableMigrationHistoryImplTest {
@Rule
public CoreDbTester dbTester = CoreDbTester.createEmpty();
private MigrationHistoryMeddler migrationHistoryMeddler = mock(MigrationHistoryMeddler.class);
private MigrationHistoryImpl underTest = new MigrationHistoryImpl(dbTester.database(), migrationHistoryMeddler);
@Test
public void start_fails_with_ISE_if_table_history_does_not_exist() {
assertThatThrownBy(() -> {
underTest.start();
verifyNoInteractions(migrationHistoryMeddler);
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Migration history table is missing");
}
}
| 1,781 | 36.914894 | 114 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AddColumnsBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.BigIntegerColumnDef;
import org.sonar.server.platform.db.migration.def.VarcharColumnDef;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.platform.db.migration.def.BooleanColumnDef.newBooleanColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder;
public class AddColumnsBuilderTest {
private static final String TABLE_NAME = "issues";
@Test
public void add_columns_on_h2() {
assertThat(createSampleBuilder(new H2()).build())
.isEqualTo("ALTER TABLE issues ADD (date_in_ms BIGINT NULL, name VARCHAR (10) NOT NULL, col_with_default BOOLEAN DEFAULT false NOT NULL, varchar_col_with_default VARCHAR (3) DEFAULT 'foo' NOT NULL)");
}
@Test
public void add_columns_on_oracle() {
assertThat(createSampleBuilder(new Oracle()).build())
.isEqualTo("ALTER TABLE issues ADD (date_in_ms NUMBER (38) NULL, name VARCHAR2 (10 CHAR) NOT NULL, col_with_default NUMBER(1) DEFAULT 0 NOT NULL, varchar_col_with_default VARCHAR2 (3 CHAR) DEFAULT 'foo' NOT NULL)");
}
@Test
public void add_columns_on_postgresql() {
assertThat(createSampleBuilder(new PostgreSql()).build())
.isEqualTo("ALTER TABLE issues ADD COLUMN date_in_ms BIGINT NULL, ADD COLUMN name VARCHAR (10) NOT NULL, ADD COLUMN col_with_default BOOLEAN DEFAULT false NOT NULL, ADD COLUMN varchar_col_with_default VARCHAR (3) DEFAULT 'foo' NOT NULL");
}
@Test
public void add_columns_on_mssql() {
assertThat(createSampleBuilder(new MsSql()).build())
.isEqualTo("ALTER TABLE issues ADD date_in_ms BIGINT NULL, name NVARCHAR (10) NOT NULL, col_with_default BIT DEFAULT 0 NOT NULL, varchar_col_with_default NVARCHAR (3) DEFAULT 'foo' NOT NULL");
}
@Test
public void fail_with_ISE_if_no_column() {
assertThatThrownBy(() -> new AddColumnsBuilder(new H2(), TABLE_NAME).build())
.isInstanceOf(IllegalStateException.class)
.hasMessage("No column has been defined");
}
private AddColumnsBuilder createSampleBuilder(Dialect dialect) {
return new AddColumnsBuilder(dialect, TABLE_NAME)
.addColumn(new BigIntegerColumnDef.Builder().setColumnName("date_in_ms").setIsNullable(true).build())
.addColumn(new VarcharColumnDef.Builder().setColumnName("name").setLimit(10).setIsNullable(false).build())
// columns with default values
.addColumn(newBooleanColumnDefBuilder().setColumnName("col_with_default").setDefaultValue(false).setIsNullable(false).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("varchar_col_with_default").setLimit(3).setDefaultValue("foo").setIsNullable(false).build());
}
}
| 3,886 | 46.987654 | 244 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AddPrimaryKeyBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AddPrimaryKeyBuilderTest {
private static final String TABLE_NAME = "issues";
@Test
public void generate() {
String sql = new AddPrimaryKeyBuilder(TABLE_NAME, "id").build();
assertThat(sql).isEqualTo("ALTER TABLE issues ADD CONSTRAINT pk_issues PRIMARY KEY (id)");
}
@Test
public void fail_when_table_name_is_invalid() {
assertThatThrownBy(() -> new AddPrimaryKeyBuilder("abcdefghijklmnopqrstuvwxyz", "id"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_when_primary_key_column_is_invalid() {
AddPrimaryKeyBuilder builder = new AddPrimaryKeyBuilder("my_table", null);
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalStateException.class);
}
}
| 1,794 | 34.196078 | 94 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AlterColumnsBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.BooleanColumnDef;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.platform.db.migration.def.BooleanColumnDef.newBooleanColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.DecimalColumnDef.newDecimalColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder;
public class AlterColumnsBuilderTest {
private static final String TABLE_NAME = "issues";
@Test
public void update_columns_on_h2() {
assertThat(createSampleBuilder(new H2()).build())
.containsOnly(
"ALTER TABLE issues ALTER COLUMN value DOUBLE NULL",
"ALTER TABLE issues ALTER COLUMN name VARCHAR (10) NULL");
}
@Test
public void update_not_nullable_column_on_h2() {
assertThat(createNotNullableBuilder(new H2()).build())
.containsOnly("ALTER TABLE issues ALTER COLUMN name VARCHAR (10) NOT NULL");
}
@Test
public void update_columns_on_mssql() {
assertThat(createSampleBuilder(new MsSql()).build())
.containsOnly(
"ALTER TABLE issues ALTER COLUMN value DECIMAL (30,20) NULL",
"ALTER TABLE issues ALTER COLUMN name NVARCHAR (10) NULL");
}
@Test
public void update_not_nullable_column_on_mssql() {
assertThat(createNotNullableBuilder(new MsSql()).build())
.containsOnly("ALTER TABLE issues ALTER COLUMN name NVARCHAR (10) NOT NULL");
}
@Test
public void update_columns_on_postgres() {
assertThat(createSampleBuilder(new PostgreSql()).build())
.containsOnly("ALTER TABLE issues " +
"ALTER COLUMN value TYPE NUMERIC (30,20), ALTER COLUMN value DROP NOT NULL, " +
"ALTER COLUMN name TYPE VARCHAR (10), ALTER COLUMN name DROP NOT NULL");
}
@Test
public void update_not_nullable_column_on_postgres() {
assertThat(createNotNullableBuilder(new PostgreSql()).build())
.containsOnly("ALTER TABLE issues ALTER COLUMN name TYPE VARCHAR (10), ALTER COLUMN name SET NOT NULL");
}
@Test
public void update_columns_on_oracle() {
assertThat(createSampleBuilder(new Oracle()).build())
.containsOnly(
"ALTER TABLE issues MODIFY (value NUMERIC (30,20) NULL)",
"ALTER TABLE issues MODIFY (name VARCHAR2 (10 CHAR) NULL)");
}
@Test
public void update_not_nullable_column_on_oracle() {
assertThat(createNotNullableBuilder(new Oracle()).build())
.containsOnly("ALTER TABLE issues MODIFY (name VARCHAR2 (10 CHAR) NOT NULL)");
}
@Test
public void fail_with_ISE_if_no_column() {
assertThatThrownBy(() -> new AlterColumnsBuilder(new H2(), TABLE_NAME).build())
.isInstanceOf(IllegalStateException.class)
.hasMessage("No column has been defined");
}
/**
* As we want DEFAULT value to be removed from all tables, it is supported
* only on creation of tables and columns, not on alter.
*/
@Test
public void updateColumn_throws_IAE_if_default_value_is_defined() {
BooleanColumnDef column = newBooleanColumnDefBuilder()
.setColumnName("enabled")
.setIsNullable(false)
.setDefaultValue(false)
.build();
AlterColumnsBuilder alterColumnsBuilder = new AlterColumnsBuilder(new H2(), TABLE_NAME);
assertThatThrownBy(() -> alterColumnsBuilder.updateColumn(column))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Default value is not supported on alter of column 'enabled'");
}
private AlterColumnsBuilder createSampleBuilder(Dialect dialect) {
return new AlterColumnsBuilder(dialect, TABLE_NAME)
.updateColumn(
newDecimalColumnDefBuilder()
.setColumnName("value")
.setPrecision(30)
.setScale(20)
.setIsNullable(true)
.build())
.updateColumn(
newVarcharColumnDefBuilder()
.setColumnName("name")
.setLimit(10)
.setIsNullable(true)
.build());
}
private AlterColumnsBuilder createNotNullableBuilder(Dialect dialect) {
return new AlterColumnsBuilder(dialect, TABLE_NAME)
.updateColumn(
newVarcharColumnDefBuilder()
.setColumnName("name")
.setLimit(10)
.setIsNullable(false)
.build());
}
}
| 5,437 | 35.496644 | 110 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateIndexBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder;
public class CreateIndexBuilderTest {
@Test
public void create_index_on_single_column() {
verifySql(new CreateIndexBuilder()
.setTable("issues")
.setName("issues_key")
.addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build()),
"CREATE INDEX issues_key ON issues (kee)");
}
@Test
public void create_unique_index_on_single_column() {
verifySql(new CreateIndexBuilder()
.setTable("issues")
.setName("issues_key")
.addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build())
.setUnique(true),
"CREATE UNIQUE INDEX issues_key ON issues (kee)");
}
@Test
public void create_index_on_multiple_columns() {
verifySql(new CreateIndexBuilder()
.setTable("rules")
.setName("rules_key")
.addColumn(newVarcharColumnDefBuilder().setColumnName("repository").setLimit(10).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("rule_key").setLimit(50).build()),
"CREATE INDEX rules_key ON rules (repository, rule_key)");
}
@Test
public void create_unique_index_on_multiple_columns() {
verifySql(new CreateIndexBuilder()
.setTable("rules")
.setName("rules_key")
.addColumn(newVarcharColumnDefBuilder().setColumnName("repository").setLimit(10).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("rule_key").setLimit(50).build())
.setUnique(true),
"CREATE UNIQUE INDEX rules_key ON rules (repository, rule_key)");
}
@Test
public void index_length_is_not_specified_on_big_varchar_columns() {
verifySql(new CreateIndexBuilder()
.setTable("issues")
.setName("issues_key")
.addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(4000).build()),
"CREATE INDEX issues_key ON issues (kee)");
}
@Test
public void throw_NPE_if_table_is_missing() {
assertThatThrownBy(() -> {
new CreateIndexBuilder()
.setName("issues_key")
.addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build())
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Table name can't be null");
}
@Test
public void throw_NPE_if_index_name_is_missing() {
assertThatThrownBy(() -> {
new CreateIndexBuilder()
.setTable("issues")
.addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build())
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Index name can't be null");
}
@Test
public void throw_IAE_if_columns_are_missing() {
assertThatThrownBy(() -> {
new CreateIndexBuilder()
.setTable("issues")
.setName("issues_key")
.build();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("at least one column must be specified");
}
@Test
public void throw_IAE_if_table_name_is_not_valid() {
assertThatThrownBy(() -> {
new CreateIndexBuilder()
.setTable("(not valid)")
.setName("issues_key")
.addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build())
.build();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'");
}
@Test
public void throw_NPE_when_adding_null_column() {
assertThatThrownBy(() -> {
new CreateIndexBuilder()
.setTable("issues")
.setName("issues_key")
.addColumn((String) null)
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Column cannot be null");
}
private static void verifySql(CreateIndexBuilder builder, String expectedSql) {
List<String> actual = builder.build();
assertThat(actual).containsExactly(expectedSql);
}
}
| 5,068 | 33.482993 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableAsBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.util.List;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder;
public class CreateTableAsBuilderTest {
@Test
public void create_table() {
String createTableAs = "CREATE TABLE issues_copy (rule_uuid) AS (SELECT rule_uuid FROM issues)";
String selectInto = "SELECT rule_uuid INTO issues_copy FROM issues";
verifySql(new H2(), createTableAs, "ALTER TABLE issues_copy ALTER COLUMN rule_uuid VARCHAR (40) NOT NULL");
verifySql(new MsSql(), selectInto, "ALTER TABLE issues_copy ALTER COLUMN rule_uuid NVARCHAR (40) NOT NULL");
verifySql(new Oracle(), createTableAs, "ALTER TABLE issues_copy MODIFY (rule_uuid VARCHAR2 (40 CHAR) NOT NULL)");
verifySql(new PostgreSql(), createTableAs, "ALTER TABLE issues_copy ALTER COLUMN rule_uuid TYPE VARCHAR (40), ALTER COLUMN rule_uuid SET NOT NULL");
}
@Test
public void create_table_with_cast() {
verifySqlWithCast(new H2(), "CREATE TABLE issues_copy (rule_uuid) AS (SELECT CAST (rule_id AS VARCHAR (40)) AS rule_uuid FROM issues)",
"ALTER TABLE issues_copy ALTER COLUMN rule_uuid VARCHAR (40) NOT NULL");
verifySqlWithCast(new MsSql(), "SELECT CAST (rule_id AS NVARCHAR (40)) AS rule_uuid INTO issues_copy FROM issues",
"ALTER TABLE issues_copy ALTER COLUMN rule_uuid NVARCHAR (40) NOT NULL");
verifySqlWithCast(new Oracle(), "CREATE TABLE issues_copy (rule_uuid) AS (SELECT CAST (rule_id AS VARCHAR2 (40 CHAR)) AS rule_uuid FROM issues)",
"ALTER TABLE issues_copy MODIFY (rule_uuid VARCHAR2 (40 CHAR) NOT NULL)");
verifySqlWithCast(new PostgreSql(), "CREATE TABLE issues_copy (rule_uuid) AS (SELECT CAST (rule_id AS VARCHAR (40)) AS rule_uuid FROM issues)",
"ALTER TABLE issues_copy ALTER COLUMN rule_uuid TYPE VARCHAR (40), ALTER COLUMN rule_uuid SET NOT NULL");
}
@Test
public void fail_if_columns_not_set() {
assertThatThrownBy(() -> new CreateTableAsBuilder(new H2(), "issues_copy", "issues")
.build())
.isInstanceOf(IllegalStateException.class);
}
@Test
public void fail_if_table_not_set() {
assertThatThrownBy(() -> new CreateTableAsBuilder(new H2(), null, "issues")
.build())
.isInstanceOf(NullPointerException.class);
}
private static void verifySqlWithCast(Dialect dialect, String... expectedSql) {
List<String> actual = new CreateTableAsBuilder(dialect, "issues_copy", "issues")
.addColumnWithCast(newVarcharColumnDefBuilder().setColumnName("rule_uuid").setIsNullable(false).setLimit(40).build(), "rule_id")
.build();
assertThat(actual).containsExactly(expectedSql);
}
private static void verifySql(Dialect dialect, String... expectedSql) {
List<String> actual = new CreateTableAsBuilder(dialect, "issues_copy", "issues")
.addColumn(newVarcharColumnDefBuilder().setColumnName("rule_uuid").setIsNullable(false).setLimit(40).build())
.build();
assertThat(actual).containsExactly(expectedSql);
}
}
| 4,203 | 47.321839 | 152 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableBuilderDbTesterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.util.Map;
import org.junit.ClassRule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.db.dialect.Dialect;
import org.sonar.server.platform.db.migration.def.TinyIntColumnDef;
import org.sonar.server.platform.db.migration.def.VarcharColumnDef;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.sonar.server.platform.db.migration.def.BigIntegerColumnDef.newBigIntegerColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.BlobColumnDef.newBlobColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.BooleanColumnDef.newBooleanColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.ClobColumnDef.newClobColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.DecimalColumnDef.newDecimalColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.IntegerColumnDef.newIntegerColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder;
import static org.sonar.server.platform.db.migration.sql.CreateTableBuilder.ColumnFlag.AUTO_INCREMENT;
public class CreateTableBuilderDbTesterTest {
@ClassRule
public static final CoreDbTester dbTester = CoreDbTester.createEmpty();
private Dialect dialect = dbTester.database().getDialect();
private static int tableNameGenerator = 0;
@Test
public void create_no_primary_key_table() {
newCreateTableBuilder()
.addColumn(newBooleanColumnDefBuilder().setColumnName("bool_col_1").build())
.addColumn(newBooleanColumnDefBuilder().setColumnName("bool_col_2").setIsNullable(false).build())
.addColumn(newIntegerColumnDefBuilder().setColumnName("i_col_1").build())
.addColumn(newIntegerColumnDefBuilder().setColumnName("i_col_2").setIsNullable(false).build())
.addColumn(newBigIntegerColumnDefBuilder().setColumnName("bi_col_1").build())
.addColumn(newBigIntegerColumnDefBuilder().setColumnName("bi_col_2").setIsNullable(false).build())
.addColumn(newClobColumnDefBuilder().setColumnName("clob_col_1").build())
.addColumn(newClobColumnDefBuilder().setColumnName("clob_col_2").setIsNullable(false).build())
.addColumn(newDecimalColumnDefBuilder().setColumnName("dec_col_1").build())
.addColumn(newDecimalColumnDefBuilder().setColumnName("dec_col_2").setIsNullable(false).build())
.addColumn(new TinyIntColumnDef.Builder().setColumnName("tiny_col_1").build())
.addColumn(new TinyIntColumnDef.Builder().setColumnName("tiny_col_2").setIsNullable(false).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("varchar_col_1").setLimit(40).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("varchar_col_2").setLimit(40).setIsNullable(false).build())
.addColumn(newBlobColumnDefBuilder().setColumnName("blob_col_1").build())
.addColumn(newBlobColumnDefBuilder().setColumnName("blob_col_2").setIsNullable(false).build())
.build()
.forEach(dbTester::executeDdl);
}
@Test
public void create_single_column_primary_key_table() {
newCreateTableBuilder()
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col_1").setIsNullable(false).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("varchar_col_2").setLimit(40).setIsNullable(false).build())
.build()
.forEach(dbTester::executeDdl);
}
@Test
public void create_multi_column_primary_key_table() {
newCreateTableBuilder()
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col_1").setIsNullable(false).build())
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col_2").setIsNullable(false).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("varchar_col_2").setLimit(40).setIsNullable(false).build())
.build()
.forEach(dbTester::executeDdl);
}
@Test
public void create_autoincrement_notnullable_integer_primary_key_table() {
String tableName = createTableName();
new CreateTableBuilder(dialect, tableName)
.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)
.addColumn(valColumnDef())
.build()
.forEach(dbTester::executeDdl);
verifyAutoIncrementIsWorking(tableName);
}
@Test
public void create_autoincrement_notnullable_biginteger_primary_key_table() {
String tableName = createTableName();
new CreateTableBuilder(dialect, tableName)
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)
.addColumn(valColumnDef())
.build()
.forEach(dbTester::executeDdl);
verifyAutoIncrementIsWorking(tableName);
}
private static VarcharColumnDef valColumnDef() {
return newVarcharColumnDefBuilder().setColumnName("val").setLimit(10).setIsNullable(false).build();
}
private void verifyAutoIncrementIsWorking(String tableName) {
dbTester.executeInsert(tableName, "val", "toto");
Map<String, Object> row = dbTester.selectFirst("select id as \"id\", val as \"val\" from " + tableName);
assertThat(row.get("id")).isNotNull();
assertThat(row).containsEntry("val", "toto");
}
private CreateTableBuilder newCreateTableBuilder() {
return new CreateTableBuilder(dialect, createTableName());
}
private static String createTableName() {
return "table_" + tableNameGenerator++;
}
}
| 6,381 | 46.984962 | 119 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import org.sonar.server.platform.db.migration.def.TinyIntColumnDef;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.sonar.server.platform.db.migration.def.BigIntegerColumnDef.newBigIntegerColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.BlobColumnDef.newBlobColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.BooleanColumnDef.newBooleanColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.ClobColumnDef.newClobColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.DecimalColumnDef.newDecimalColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.IntegerColumnDef.newIntegerColumnDefBuilder;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder;
import static org.sonar.server.platform.db.migration.sql.CreateTableBuilder.ColumnFlag.AUTO_INCREMENT;
@RunWith(DataProviderRunner.class)
public class CreateTableBuilderTest {
private static final H2 H2 = new H2();
private static final Oracle ORACLE = new Oracle();
private static final PostgreSql POSTGRESQL = new PostgreSql();
private static final MsSql MS_SQL = new MsSql();
private static final Dialect[] ALL_DIALECTS = {H2, MS_SQL, POSTGRESQL, ORACLE};
private static final String TABLE_NAME = "table_42";
private CreateTableBuilder underTest = new CreateTableBuilder(mock(Dialect.class), TABLE_NAME);
@Test
public void constructor_fails_with_NPE_if_dialect_is_null() {
assertThatThrownBy(() -> new CreateTableBuilder(null, TABLE_NAME))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("dialect can't be null");
}
@Test
public void constructor_fails_with_NPE_if_tablename_is_null() {
assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("Table name can't be null");
}
@Test
public void constructor_throws_IAE_if_table_name_is_not_lowercase() {
assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), "Tooo"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Table name must be lower case and contain only alphanumeric chars or '_', got 'Tooo");
}
@Test
public void constructor_throws_IAE_if_table_name_is_26_chars_long() {
assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), "abcdefghijklmnopqrstuvwxyz"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Table name length can't be more than 25");
}
@Test
public void constructor_does_not_fail_if_table_name_is_25_chars_long() {
new CreateTableBuilder(mock(Dialect.class), "abcdefghijklmnopqrstuvwxy");
}
@Test
public void constructor_does_not_fail_if_table_name_contains_ascii_letters() {
new CreateTableBuilder(mock(Dialect.class), "abcdefghijklmnopqrstuvwxy");
new CreateTableBuilder(mock(Dialect.class), "z");
}
@Test
public void constructor_throws_IAE_if_table_name_starts_with_underscore() {
assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), "_a"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Table name must not start by a number or '_', got '_a'");
}
@Test
@UseDataProvider("digitCharsDataProvider")
public void constructor_throws_IAE_if_table_name_starts_with_number(char number) {
assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), number + "a"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Table name must not start by a number or '_', got '" + number + "a'");
}
@DataProvider
public static Object[][] digitCharsDataProvider() {
return new Object[][]{
{'0'},
{'1'},
{'2'},
{'3'},
{'4'},
{'5'},
{'6'},
{'7'},
{'8'},
{'9'},
};
}
@Test
public void constructor_does_not_fail_if_table_name_contains_underscore_or_numbers() {
new CreateTableBuilder(mock(Dialect.class), "a1234567890");
new CreateTableBuilder(mock(Dialect.class), "a_");
}
@Test
public void build_throws_ISE_if_no_column_has_been_set() {
assertThatThrownBy(() -> underTest.build())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("at least one column must be specified");
}
@Test
public void addColumn_throws_NPE_if_ColumnDef_is_null() {
assertThatThrownBy(() -> underTest.addColumn(null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("column def can't be null");
}
@Test
public void addPkColumn_throws_NPE_if_ColumnDef_is_null() {
assertThatThrownBy(() -> underTest.addPkColumn(null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("column def can't be null");
}
@Test
public void addPkColumn_throws_IAE_when_AUTO_INCREMENT_flag_is_provided_with_column_name_other_than_id() {
assertThatThrownBy(() -> underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("toto").build(), AUTO_INCREMENT))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Auto increment column name must be id");
}
@Test
public void addPkColumn_throws_ISE_when_adding_multiple_autoincrement_columns() {
underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT);
assertThatThrownBy(() -> underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("There can't be more than one auto increment column");
}
@Test
public void addPkColumn_throws_IAE_when_AUTO_INCREMENT_flag_is_provided_with_def_other_than_Integer_and_BigInteger() {
ColumnDef[] columnDefs = {
newBooleanColumnDefBuilder().setColumnName("id").build(),
newClobColumnDefBuilder().setColumnName("id").build(),
newDecimalColumnDefBuilder().setColumnName("id").build(),
new TinyIntColumnDef.Builder().setColumnName("id").build(),
newVarcharColumnDefBuilder().setColumnName("id").setLimit(40).build(),
newBlobColumnDefBuilder().setColumnName("id").build()
};
Arrays.stream(columnDefs)
.forEach(columnDef -> {
try {
underTest.addPkColumn(columnDef, AUTO_INCREMENT);
fail("A IllegalArgumentException should have been raised");
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Auto increment column must either be BigInteger or Integer");
}
});
}
@Test
public void addPkColumn_throws_IAE_when_AUTO_INCREMENT_flag_is_provided_and_column_is_nullable() {
ColumnDef[] columnDefs = {
newIntegerColumnDefBuilder().setColumnName("id").build(),
newBigIntegerColumnDefBuilder().setColumnName("id").build()
};
Arrays.stream(columnDefs)
.forEach(columnDef -> {
try {
underTest.addPkColumn(columnDef, AUTO_INCREMENT);
fail("A IllegalArgumentException should have been raised");
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Auto increment column can't be nullable");
}
});
}
@Test
public void build_sets_type_SERIAL_for_autoincrement_integer_pk_column_on_Postgresql() {
List<String> stmts = new CreateTableBuilder(POSTGRESQL, TABLE_NAME)
.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.isEqualTo(
"CREATE TABLE table_42 (id SERIAL NOT NULL, CONSTRAINT pk_table_42 PRIMARY KEY (id))");
}
@Test
public void build_sets_type_BIGSERIAL_for_autoincrement_biginteger_pk_column_on_Postgresql() {
List<String> stmts = new CreateTableBuilder(POSTGRESQL, TABLE_NAME)
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.isEqualTo(
"CREATE TABLE table_42 (id BIGSERIAL NOT NULL, CONSTRAINT pk_table_42 PRIMARY KEY (id))");
}
@Test
public void build_generates_a_create_trigger_statement_when_an_autoincrement_pk_column_is_specified_and_on_Oracle() {
List<String> stmts = new CreateTableBuilder(ORACLE, TABLE_NAME)
.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)
.build();
assertThat(stmts).hasSize(3);
assertThat(stmts.get(0))
.isEqualTo("CREATE TABLE table_42 (id NUMBER(38,0) NOT NULL, CONSTRAINT pk_table_42 PRIMARY KEY (id))");
assertThat(stmts.get(1))
.isEqualTo("CREATE SEQUENCE table_42_seq START WITH 1 INCREMENT BY 1");
assertThat(stmts.get(2))
.isEqualTo("CREATE OR REPLACE TRIGGER table_42_idt" +
" BEFORE INSERT ON table_42" +
" FOR EACH ROW" +
" BEGIN" +
" IF :new.id IS null THEN" +
" SELECT table_42_seq.nextval INTO :new.id FROM dual;" +
" END IF;" +
" END;");
}
@Test
public void build_adds_IDENTITY_clause_on_MsSql() {
List<String> stmts = new CreateTableBuilder(MS_SQL, TABLE_NAME)
.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.isEqualTo(
"CREATE TABLE table_42 (id INT NOT NULL IDENTITY (1,1), CONSTRAINT pk_table_42 PRIMARY KEY (id))");
}
@Test
public void build_adds_AUTO_INCREMENT_clause_on_H2() {
List<String> stmts = new CreateTableBuilder(H2, TABLE_NAME)
.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.isEqualTo(
"CREATE TABLE table_42 (id INTEGER NOT NULL AUTO_INCREMENT (1,1), CONSTRAINT pk_table_42 PRIMARY KEY (id))");
}
@Test
public void withPkConstraintName_throws_NPE_if_name_is_null() {
assertThatThrownBy(() -> underTest.withPkConstraintName(null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("Constraint name can't be null");
}
@Test
public void withPkConstraintName_throws_IAE_if_name_is_not_lowercase() {
assertThatThrownBy(() -> underTest.withPkConstraintName("Too"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Constraint name must be lower case and contain only alphanumeric chars or '_', got 'Too'");
}
@Test
public void withPkConstraintName_throws_IAE_if_name_is_more_than_30_char_long() {
assertThatThrownBy(() -> underTest.withPkConstraintName("abcdefghijklmnopqrstuvwxyzabcdf"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Constraint name length can't be more than 30");
}
@Test
public void withPkConstraintName_throws_IAE_if_name_starts_with_underscore() {
assertThatThrownBy(() -> underTest.withPkConstraintName("_a"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Constraint name must not start by a number or '_', got '_a'");
}
@Test
@UseDataProvider("digitCharsDataProvider")
public void withPkConstraintName_throws_IAE_if_name_starts_with_number(char number) {
assertThatThrownBy(() -> underTest.withPkConstraintName(number + "a"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Constraint name must not start by a number or '_', got '" + number + "a'");
}
@Test
public void withPkConstraintName_does_not_fail_if_name_is_30_char_long() {
underTest.withPkConstraintName("abcdefghijklmnopqrstuvwxyzabcd");
}
@Test
public void withPkConstraintName_does_not_fail_if_name_contains_ascii_letters() {
underTest.withPkConstraintName("abcdefghijklmnopqrstuvwxyz");
}
@Test
public void withPkConstraintName_does_not_fail_if_name_contains_underscore() {
underTest.withPkConstraintName("a_");
}
@Test
public void withPkConstraintName_does_not_fail_if_name_contains_numbers() {
underTest.withPkConstraintName("a0123456789");
}
@Test
public void build_adds_NULL_when_column_is_nullable_for_all_DBs() {
Arrays.stream(ALL_DIALECTS)
.forEach(dialect -> {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col").build())
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.startsWith("CREATE TABLE " + TABLE_NAME + " (" +
"bg_col " +
bigIntSqlType(dialect) + " NULL" +
")");
});
}
@Test
public void build_adds_NOT_NULL_when_column_is_not_nullable_for_all_DBs() {
Arrays.stream(ALL_DIALECTS)
.forEach(dialect -> {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col").setIsNullable(false).build())
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.startsWith("CREATE TABLE " + TABLE_NAME + " (" +
"bg_col " +
bigIntSqlType(dialect) +
" NOT NULL" +
")");
});
}
@Test
public void build_of_single_column_table() {
List<String> stmts = new CreateTableBuilder(H2, TABLE_NAME)
.addColumn(newBooleanColumnDefBuilder().setColumnName("bool_col_1").build())
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next()).isEqualTo("CREATE TABLE table_42 (bool_col_1 BOOLEAN NULL)");
}
@Test
public void build_table_with_pk() {
List<String> stmts = new CreateTableBuilder(H2, TABLE_NAME)
.addPkColumn(newBooleanColumnDefBuilder().setColumnName("bool_col").build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("varchar_col").setLimit(40).build())
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.isEqualTo("CREATE TABLE " + TABLE_NAME + " (" +
"bool_col BOOLEAN NULL," +
"varchar_col VARCHAR (40) NULL," +
" CONSTRAINT pk_" + TABLE_NAME + " PRIMARY KEY (bool_col)" +
")");
}
@Test
public void build_adds_PRIMARY_KEY_constraint_on_single_column_with_name_computed_from_tablename() {
Arrays.asList(ALL_DIALECTS)
.forEach(dialect -> {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col").setIsNullable(false).build())
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.startsWith("CREATE TABLE " + TABLE_NAME + " (" +
"bg_col " + bigIntSqlType(dialect) + " NOT NULL," +
" CONSTRAINT pk_" + TABLE_NAME + " PRIMARY KEY (bg_col)" +
")");
});
}
@Test
public void build_adds_PRIMARY_KEY_constraint_on_single_column_with_lower_case_of_specified_name() {
Arrays.asList(ALL_DIALECTS)
.forEach(dialect -> {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col").setIsNullable(false).build())
.withPkConstraintName("my_pk")
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.startsWith("CREATE TABLE " + TABLE_NAME + " (" +
"bg_col " +
bigIntSqlType(dialect) +
" NOT NULL," +
" CONSTRAINT my_pk PRIMARY KEY (bg_col)" +
")");
});
}
@Test
public void build_adds_PRIMARY_KEY_constraint_on_multiple_columns_with_name_computed_from_tablename() {
Arrays.asList(ALL_DIALECTS)
.forEach(dialect -> {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col_1").setIsNullable(false).build())
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col_2").setIsNullable(false).build())
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.startsWith("CREATE TABLE " + TABLE_NAME + " (" +
"bg_col_1 " + bigIntSqlType(dialect) + " NOT NULL," +
"bg_col_2 " + bigIntSqlType(dialect) + " NOT NULL," +
" CONSTRAINT pk_" + TABLE_NAME + " PRIMARY KEY (bg_col_1,bg_col_2)" +
")");
});
}
@Test
public void build_adds_PRIMARY_KEY_constraint_on_multiple_columns_with_lower_case_of_specified_name() {
Arrays.asList(ALL_DIALECTS)
.forEach(dialect -> {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col_1").setIsNullable(false).build())
.addPkColumn(newBigIntegerColumnDefBuilder().setColumnName("bg_col_2").setIsNullable(false).build())
.withPkConstraintName("my_pk")
.build();
assertThat(stmts).hasSize(1);
assertThat(stmts.iterator().next())
.startsWith("CREATE TABLE " + TABLE_NAME + " (" +
"bg_col_1 " + bigIntSqlType(dialect) + " NOT NULL," +
"bg_col_2 " + bigIntSqlType(dialect) + " NOT NULL," +
" CONSTRAINT my_pk PRIMARY KEY (bg_col_1,bg_col_2)" +
")");
});
}
@Test
public void build_adds_DEFAULT_clause_on_varchar_column_on_H2() {
verifyDefaultClauseOnVarcharColumn(H2, "CREATE TABLE table_42 (status VARCHAR (1) DEFAULT 'P' NOT NULL)");
}
@Test
public void build_adds_DEFAULT_clause_on_varchar_column_on_MSSQL() {
verifyDefaultClauseOnVarcharColumn(MS_SQL, "CREATE TABLE table_42 (status NVARCHAR (1) DEFAULT 'P' NOT NULL)");
}
@Test
public void build_adds_DEFAULT_clause_on_varchar_column_on_Oracle() {
verifyDefaultClauseOnVarcharColumn(ORACLE, "CREATE TABLE table_42 (status VARCHAR2 (1 CHAR) DEFAULT 'P' NOT NULL)");
}
@Test
public void build_adds_DEFAULT_clause_on_varchar_column_on_PostgreSQL() {
verifyDefaultClauseOnVarcharColumn(POSTGRESQL, "CREATE TABLE table_42 (status VARCHAR (1) DEFAULT 'P' NOT NULL)");
}
private static void verifyDefaultClauseOnVarcharColumn(Dialect dialect, String expectedSql) {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addColumn(newVarcharColumnDefBuilder().setColumnName("status").setLimit(1).setIsNullable(false).setDefaultValue("P").build())
.build();
assertThat(stmts).containsExactly(expectedSql);
}
@Test
public void build_adds_DEFAULT_clause_on_boolean_column_on_H2() {
verifyDefaultClauseOnBooleanColumn(H2, "CREATE TABLE table_42 (enabled BOOLEAN DEFAULT true NOT NULL)");
}
@Test
public void build_adds_DEFAULT_clause_on_boolean_column_on_MSSQL() {
verifyDefaultClauseOnBooleanColumn(MS_SQL, "CREATE TABLE table_42 (enabled BIT DEFAULT 1 NOT NULL)");
}
@Test
public void build_adds_DEFAULT_clause_on_boolean_column_on_Oracle() {
verifyDefaultClauseOnBooleanColumn(ORACLE, "CREATE TABLE table_42 (enabled NUMBER(1) DEFAULT 1 NOT NULL)");
}
@Test
public void build_adds_DEFAULT_clause_on_boolean_column_on_PostgreSQL() {
verifyDefaultClauseOnBooleanColumn(POSTGRESQL, "CREATE TABLE table_42 (enabled BOOLEAN DEFAULT true NOT NULL)");
}
private static void verifyDefaultClauseOnBooleanColumn(Dialect dialect, String expectedSql) {
List<String> stmts = new CreateTableBuilder(dialect, TABLE_NAME)
.addColumn(newBooleanColumnDefBuilder().setColumnName("enabled").setIsNullable(false).setDefaultValue(true).build())
.build();
assertThat(stmts).containsExactly(expectedSql);
}
private static String bigIntSqlType(Dialect dialect) {
return Oracle.ID.equals(dialect.getId()) ? "NUMBER (38)" : "BIGINT";
}
}
| 21,743 | 40.10397 | 146 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DbPrimaryKeyConstraintFinderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;
import javax.sql.DataSource;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.db.Database;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DbPrimaryKeyConstraintFinderTest {
@Rule
public CoreDbTester db = CoreDbTester.createForSchema(DbPrimaryKeyConstraintFinderTest.class, "schema.sql");
private final Database dbMock = mock(Database.class);
private final DbPrimaryKeyConstraintFinder underTest = new DbPrimaryKeyConstraintFinder(dbMock);
private static final PostgreSql POSTGRESQL = new PostgreSql();
private static final MsSql MS_SQL = new MsSql();
private static final Oracle ORACLE = new Oracle();
private static final org.sonar.db.dialect.H2 H2 = new H2();
@Test
public void findConstraintName_constraint_exists() throws SQLException {
DbPrimaryKeyConstraintFinder underTest = new DbPrimaryKeyConstraintFinder(db.database());
Optional<String> constraintName = underTest.findConstraintName("TEST_PRIMARY_KEY");
assertThat(constraintName).isPresent();
assertThat(constraintName.get()).contains("PK_TEST_PRIMARY_KEY");
}
@Test
public void findConstraintName_constraint_not_exist_fails_silently() throws SQLException {
DbPrimaryKeyConstraintFinder underTest = new DbPrimaryKeyConstraintFinder(db.database());
assertThat(underTest.findConstraintName("NOT_EXISTING_TABLE")).isNotPresent();
}
@Test
public void getDbVendorSpecificQuery_mssql() {
when(dbMock.getDialect()).thenReturn(MS_SQL);
assertThat(underTest.getDbVendorSpecificQuery("my_table"))
.isEqualTo("SELECT name FROM sys.key_constraints WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = 'my_table'");
}
@Test
public void getDbVendorSpecificQuery_postgresql() throws SQLException {
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class);
when(dataSource.getConnection()).thenReturn(connection);
when(connection.getSchema()).thenReturn("SonarQube");
when(dbMock.getDialect()).thenReturn(POSTGRESQL);
when(dbMock.getDataSource()).thenReturn(dataSource);
assertThat(underTest.getDbVendorSpecificQuery("my_table"))
.isEqualTo("SELECT conname FROM pg_constraint c JOIN pg_namespace n on c.connamespace = n.oid JOIN pg_class cls on c.conrelid = cls.oid WHERE cls.relname = 'my_table' AND n.nspname = 'SonarQube'");
}
@Test
public void getDbVendorSpecificQuery_oracle() {
when(dbMock.getDialect()).thenReturn(ORACLE);
assertThat(underTest.getDbVendorSpecificQuery("my_table"))
.isEqualTo("SELECT constraint_name FROM user_constraints WHERE table_name = UPPER('my_table') AND constraint_type='P'");
}
@Test
public void getDbVendorSpecificQuery_h2() {
when(dbMock.getDialect()).thenReturn(H2);
assertThat(underTest.getDbVendorSpecificQuery("my_table"))
.isEqualTo("SELECT constraint_name FROM information_schema.table_constraints WHERE table_name = 'MY_TABLE' and constraint_type = 'PRIMARY KEY'");
}
}
| 4,241 | 40.184466 | 203 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropColumnsBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import org.junit.Test;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
public class DropColumnsBuilderTest {
@Test
public void drop_columns_on_oracle() {
assertThat(new DropColumnsBuilder(new Oracle(), "issues", "date_in_ms", "name").build())
.containsOnly("ALTER TABLE issues SET UNUSED (date_in_ms, name)");
}
@Test
public void drop_columns_on_postgresql() {
assertThat(new DropColumnsBuilder(new PostgreSql(), "issues", "date_in_ms", "name").build())
.containsOnly("ALTER TABLE issues DROP COLUMN date_in_ms, DROP COLUMN name");
}
@Test
public void drop_columns_on_mssql() {
assertThat(new DropColumnsBuilder(new MsSql(), "issues", "date_in_ms", "name").build())
.containsOnly("ALTER TABLE issues DROP COLUMN date_in_ms, name");
}
@Test
public void drop_columns_on_h2() {
assertThat(new DropColumnsBuilder(new H2(), "issues", "date_in_ms", "name").build())
.containsOnly(
"ALTER TABLE issues DROP COLUMN date_in_ms",
"ALTER TABLE issues DROP COLUMN name");
}
}
| 2,100 | 34.610169 | 96 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropConstraintBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.sonar.db.dialect.Oracle;
import static org.assertj.core.api.Assertions.assertThat;
public class DropConstraintBuilderTest {
@Test
public void fail_if_constraint_name_starts_with_pk() {
DropConstraintBuilder builder = new DropConstraintBuilder(new Oracle());
Assert.assertThrows("This builder should not be used with primary keys", IllegalArgumentException.class, () -> builder.setName("pk_constraint"));
}
@Test
public void succeeds_for_oracle() {
DropConstraintBuilder builder = new DropConstraintBuilder(new Oracle());
List<String> queries = builder.setName("constraint1").setTable("table1").build();
assertThat(queries).containsOnly("ALTER TABLE table1 DROP CONSTRAINT constraint1");
}
}
| 1,704 | 38.651163 | 149 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropMsSQLDefaultConstraintsBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.junit.Test;
import org.sonar.db.Database;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DropMsSQLDefaultConstraintsBuilderTest {
private final Database db = mock(Database.class);
@Test
public void fail_if_oracle() throws Exception {
when(db.getDialect()).thenReturn(new Oracle());
assertThatThrownBy(() -> {
new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_h2() throws Exception {
when(db.getDialect()).thenReturn(new H2());
assertThatThrownBy(() -> {
new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_postgres() throws Exception {
when(db.getDialect()).thenReturn(new PostgreSql());
assertThatThrownBy(() -> {
new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void generate_queries_for_mssql() throws Exception {
when(db.getDialect()).thenReturn(new MsSql());
DataSource dataSource = mock(DataSource.class);
when(db.getDataSource()).thenReturn(dataSource);
Connection connection = mock(Connection.class);
when(dataSource.getConnection()).thenReturn(connection);
PreparedStatement statement = mock(PreparedStatement.class);
when(connection.prepareStatement(anyString())).thenReturn(statement);
ResultSet rsMock = mock(ResultSet.class);
when(statement.executeQuery()).thenReturn(rsMock);
when(rsMock.next()).thenReturn(true, true, false);
when(rsMock.getString(1)).thenReturn("DF__A1", "DF__A2");
assertThat(new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build())
.containsExactly("ALTER TABLE snapshots DROP CONSTRAINT DF__A1", "ALTER TABLE snapshots DROP CONSTRAINT DF__A2");
}
}
| 3,559 | 39.454545 | 141 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropPrimaryKeySqlGeneratorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import org.sonar.db.Database;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DropPrimaryKeySqlGeneratorTest {
private static final String TABLE_NAME = "issues";
private static final String PK_COLUMN = "id";
private static final String CONSTRAINT = "pk_id";
private static final PostgreSql POSTGRESQL = new PostgreSql();
private static final MsSql MS_SQL = new MsSql();
private static final Oracle ORACLE = new Oracle();
private static final org.sonar.db.dialect.H2 H2 = new H2();
private final Database db = mock(Database.class);
private final DbPrimaryKeyConstraintFinder dbConstraintFinder = mock(DbPrimaryKeyConstraintFinder.class);
private final DropPrimaryKeySqlGenerator underTest = new DropPrimaryKeySqlGenerator(db, dbConstraintFinder);
@Test
public void generate_unknown_dialect() throws SQLException {
Dialect mockDialect = mock(Dialect.class);
when(mockDialect.getId()).thenReturn("unknown-db-vendor");
when(db.getDialect()).thenReturn(mockDialect);
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
assertThatThrownBy(() -> underTest.generate(TABLE_NAME, PK_COLUMN, true))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void generate_for_postgres_sql() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(dbConstraintFinder.getPostgresSqlSequence(TABLE_NAME, "id")).thenReturn(TABLE_NAME + "_id_seq");
when(db.getDialect()).thenReturn(POSTGRESQL);
List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, true);
assertThat(sqls).containsExactly("ALTER TABLE issues ALTER COLUMN id DROP DEFAULT",
"DROP SEQUENCE issues_id_seq",
"ALTER TABLE issues DROP CONSTRAINT pk_id");
}
@Test
public void generate_for_postgres_sql_no_seq() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(dbConstraintFinder.getPostgresSqlSequence(TABLE_NAME, "id")).thenReturn(null);
when(db.getDialect()).thenReturn(POSTGRESQL);
List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, true);
assertThat(sqls).containsExactly("ALTER TABLE issues ALTER COLUMN id DROP DEFAULT",
"ALTER TABLE issues DROP CONSTRAINT pk_id");
}
@Test
public void generate_for_ms_sql() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(db.getDialect()).thenReturn(MS_SQL);
List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, true);
assertThat(sqls).containsExactly("ALTER TABLE issues DROP CONSTRAINT pk_id");
}
@Test
public void generate_for_oracle_autogenerated_true() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(db.getDialect()).thenReturn(ORACLE);
List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, true);
assertThat(sqls).containsExactly("DROP TRIGGER issues_IDT",
"DROP SEQUENCE issues_SEQ",
"ALTER TABLE issues DROP CONSTRAINT pk_id DROP INDEX");
}
@Test
public void generate_for_oracle_autogenerated_false() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(db.getDialect()).thenReturn(ORACLE);
List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, false);
assertThat(sqls).containsExactly("ALTER TABLE issues DROP CONSTRAINT pk_id DROP INDEX");
}
@Test
public void generate_for_h2() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(db.getDialect()).thenReturn(H2);
List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, true);
assertThat(sqls).containsExactly("ALTER TABLE issues DROP CONSTRAINT pk_id");
}
}
| 5,304 | 39.189394 | 110 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropTableBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import org.junit.Test;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DropTableBuilderTest {
@Test
public void drop_tables_on_postgresql() {
assertThat(new DropTableBuilder(new PostgreSql(), "issues")
.build()).containsOnly("drop table if exists issues");
}
@Test
public void drop_tables_on_mssql() {
assertThat(new DropTableBuilder(new MsSql(), "issues")
.build()).containsOnly("drop table issues");
}
@Test
public void drop_tables_on_h2() {
assertThat(new DropTableBuilder(new H2(), "issues")
.build()).containsOnly("drop table if exists issues");
}
@Test
public void drop_columns_on_oracle() {
assertThat(new DropTableBuilder(new Oracle(), "issues")
.build()).containsExactly(
"BEGIN\n" +
"EXECUTE IMMEDIATE 'DROP SEQUENCE issues_seq';\n" +
"EXCEPTION\n" +
"WHEN OTHERS THEN\n" +
" IF SQLCODE != -2289 THEN\n" +
" RAISE;\n" +
" END IF;\n" +
"END;",
"BEGIN\n" +
"EXECUTE IMMEDIATE 'DROP TRIGGER issues_idt';\n" +
"EXCEPTION\n" +
"WHEN OTHERS THEN\n" +
" IF SQLCODE != -4080 THEN\n" +
" RAISE;\n" +
" END IF;\n" +
"END;",
"BEGIN\n" +
"EXECUTE IMMEDIATE 'DROP TABLE issues';\n" +
"EXCEPTION\n" +
"WHEN OTHERS THEN\n" +
" IF SQLCODE != -942 THEN\n" +
" RAISE;\n" +
" END IF;\n" +
"END;");
}
@Test
public void fail_when_dialect_is_null() {
assertThatThrownBy(() -> new DropTableBuilder(null, "issues"))
.isInstanceOf(NullPointerException.class);
}
@Test
public void fail_when_table_is_null() {
assertThatThrownBy(() -> new DropTableBuilder(new PostgreSql(), null))
.isInstanceOf(NullPointerException.class);
}
}
| 2,937 | 30.934783 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.text.StrSubstitutor;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.FromDataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.BigIntegerColumnDef;
import org.sonar.server.platform.db.migration.def.BlobColumnDef;
import org.sonar.server.platform.db.migration.def.BooleanColumnDef;
import org.sonar.server.platform.db.migration.def.ClobColumnDef;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import org.sonar.server.platform.db.migration.def.DecimalColumnDef;
import org.sonar.server.platform.db.migration.def.IntegerColumnDef;
import org.sonar.server.platform.db.migration.def.TinyIntColumnDef;
import org.sonar.server.platform.db.migration.def.VarcharColumnDef;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(Theories.class)
public class RenameColumnsBuilderTest {
private static final String NEW_COLUMN_NAME = "new_" + randomAlphabetic(6).toLowerCase();
@DataPoints("database")
public static final DatabaseAndResult[] DATABASES = {
new DatabaseAndResult(new H2(), "ALTER TABLE ${table_name} ALTER COLUMN ${old_column_name} RENAME TO ${new_column_name}"),
new DatabaseAndResult(new PostgreSql(), "ALTER TABLE ${table_name} RENAME COLUMN ${old_column_name} TO ${new_column_name}"),
new DatabaseAndResult(new MsSql(), "EXEC sp_rename '${table_name}.${old_column_name}', '${new_column_name}', 'COLUMN'"),
new DatabaseAndResult(new Oracle(), "ALTER TABLE ${table_name} RENAME COLUMN ${old_column_name} TO ${new_column_name}")
};
@DataPoints("columnDef")
public static final ColumnDef[] COLUMN_DEFS = {
BigIntegerColumnDef.newBigIntegerColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).build(),
BigIntegerColumnDef.newBigIntegerColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).build(),
BlobColumnDef.newBlobColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).build(),
BlobColumnDef.newBlobColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).build(),
BooleanColumnDef.newBooleanColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).build(),
BooleanColumnDef.newBooleanColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).build(),
ClobColumnDef.newClobColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).build(),
ClobColumnDef.newClobColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).build(),
DecimalColumnDef.newDecimalColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).build(),
DecimalColumnDef.newDecimalColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).build(),
IntegerColumnDef.newIntegerColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).build(),
IntegerColumnDef.newIntegerColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).build(),
TinyIntColumnDef.newTinyIntColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).build(),
TinyIntColumnDef.newTinyIntColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).build(),
VarcharColumnDef.newVarcharColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(false).setLimit(10).build(),
VarcharColumnDef.newVarcharColumnDefBuilder().setColumnName(NEW_COLUMN_NAME).setIsNullable(true).setLimit(10).build(),
};
@DataPoints("illegalColumnName")
public static final String[] ILLEGAL_COLUMN_NAME = {
"",
"AA",
"A.A",
"_A",
"1A",
"\uD801\uDC8B\uD801\uDC8C\uD801\uDC8D"
};
@Theory
public void checkSQL_results(
@FromDataPoints("database") DatabaseAndResult database,
@FromDataPoints("columnDef") ColumnDef columnDef) {
String oldColumnName = "old_" + randomAlphabetic(6).toLowerCase();
String tableName = "table_" + randomAlphabetic(6).toLowerCase();
List<String> result = new RenameColumnsBuilder(database.getDialect(), tableName)
.renameColumn(oldColumnName, columnDef)
.build();
Map<String, String> parameters = new HashMap<>();
parameters.put("table_name", tableName);
parameters.put("old_column_name", oldColumnName);
parameters.put("new_column_name", NEW_COLUMN_NAME);
parameters.put("column_def", columnDef.generateSqlType(database.getDialect()));
String expectedResult = StrSubstitutor.replace(database.getTemplateSql(), parameters);
assertThat(result).containsExactlyInAnyOrder(expectedResult);
}
@Theory
public void when_old_column_is_same_as_new_column_ISA_is_thrown(
@FromDataPoints("database") DatabaseAndResult database,
@FromDataPoints("columnDef") ColumnDef columnDef) {
String tableName = "table_" + randomAlphabetic(6).toLowerCase();
assertThatThrownBy(() -> new RenameColumnsBuilder(database.getDialect(), tableName)
.renameColumn(NEW_COLUMN_NAME, columnDef)
.build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Column names must be different");
}
@Theory
public void when_new_column_contains_illegal_character_ISA_is_thrown(
@FromDataPoints("database") DatabaseAndResult database,
@FromDataPoints("columnDef") ColumnDef columnDef,
@FromDataPoints("illegalColumnName") String illegalColumnName) {
String tableName = "table_" + randomAlphabetic(6).toLowerCase();
assertThatThrownBy(() -> new RenameColumnsBuilder(database.getDialect(), tableName)
.renameColumn(illegalColumnName, columnDef)
.build())
.isInstanceOf(IllegalArgumentException.class);
}
private static class DatabaseAndResult {
private final Dialect dialect;
private final String templateSql;
private DatabaseAndResult(Dialect dialect, String templateSql) {
this.dialect = dialect;
this.templateSql = templateSql;
}
public Dialect getDialect() {
return dialect;
}
public String getTemplateSql() {
return templateSql;
}
}
}
| 7,426 | 45.710692 | 128 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameTableBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.sql;
import java.util.List;
import org.junit.Test;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class RenameTableBuilderTest {
@Test
public void rename_table_on_h2() {
verifySql(new H2(), "ALTER TABLE foo RENAME TO bar");
}
@Test
public void rename_table_on_mssql() {
verifySql(new MsSql(), "EXEC sp_rename 'foo', 'bar'");
}
@Test
public void rename_table_on_oracle() {
verifySql(new Oracle(),
"DROP TRIGGER foo_idt",
"RENAME foo TO bar",
"RENAME foo_seq TO bar_seq",
"CREATE OR REPLACE TRIGGER bar_idt BEFORE INSERT ON bar FOR EACH ROW BEGIN IF :new.id IS null THEN SELECT bar_seq.nextval INTO :new.id FROM dual; END IF; END;");
}
@Test
public void rename_table_on_oracle_when_auto_generated_id_is_false() {
verifySqlWhenAutoGeneratedIdIsFalse(new Oracle(), "RENAME foo TO bar");
}
@Test
public void rename_table_on_postgresql() {
verifySql(new PostgreSql(), "ALTER TABLE foo RENAME TO bar");
}
@Test
public void throw_IAE_if_name_is_not_valid() {
assertThatThrownBy(() -> new RenameTableBuilder(new H2()).setName("(not valid)").build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'");
}
@Test
public void throw_IAE_if_new_name_is_not_valid() {
assertThatThrownBy(() -> new RenameTableBuilder(new H2()).setName("foo").setNewName("(not valid)").build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'");
}
private static void verifySql(Dialect dialect, String... expectedSql) {
List<String> actual = new RenameTableBuilder(dialect)
.setName("foo")
.setNewName("bar")
.build();
assertThat(actual).containsExactly(expectedSql);
}
private static void verifySqlWhenAutoGeneratedIdIsFalse(Dialect dialect, String... expectedSql) {
List<String> actual = new RenameTableBuilder(dialect)
.setName("foo")
.setNewName("bar")
.setAutoGeneratedId(false)
.build();
assertThat(actual).containsExactly(expectedSql);
}
}
| 3,366 | 34.819149 | 167 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DataChangeTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.Select.Row;
import org.sonar.server.platform.db.migration.step.Select.RowReader;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
public class DataChangeTest {
private static final int MAX_BATCH_SIZE = 250;
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Rule
public CoreDbTester db = CoreDbTester.createForSchema(DataChangeTest.class, "schema.sql");
@Before
public void setUp() {
db.executeUpdateSql("truncate table persons");
}
@Test
public void query() throws Exception {
insertPersons();
AtomicBoolean executed = new AtomicBoolean(false);
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
assertThat(context.prepareSelect("select id from persons order by id desc").list(Select.LONG_READER))
.containsExactly(3L, 2L, 1L);
assertThat(context.prepareSelect("select id from persons where id=?").setLong(1, 2L).get(Select.LONG_READER))
.isEqualTo(2L);
assertThat(context.prepareSelect("select id from persons where id=?").setLong(1, 12345L).get(Select.LONG_READER))
.isNull();
executed.set(true);
}
}.execute();
assertThat(executed.get()).isTrue();
}
@Test
public void read_column_types() throws Exception {
insertPersons();
List<Object[]> persons = new ArrayList<>();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
persons.addAll(context
.prepareSelect("select id,login,age,enabled,updated_at,coeff from persons where id=2")
.list(new UserReader()));
}
}.execute();
assertThat(persons).hasSize(1);
assertThat(persons.get(0)[0]).isEqualTo(2L);
assertThat(persons.get(0)[1]).isEqualTo("emmerik");
assertThat(persons.get(0)[2]).isEqualTo(14);
assertThat(persons.get(0)[3]).isEqualTo(true);
assertThat(persons.get(0)[4]).isNotNull();
assertThat(persons.get(0)[5]).isEqualTo(5.2);
}
@Test
public void parameterized_query() throws Exception {
insertPersons();
final List<Long> ids = new ArrayList<>();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
ids.addAll(context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).list(Select.LONG_READER));
}
}.execute();
assertThat(ids).containsOnly(2L, 3L);
}
@Test
public void display_current_row_details_if_error_during_get() throws Exception {
insertPersons();
assertThatThrownBy(() -> {
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).get((RowReader<Long>) row -> {
throw new IllegalStateException("Unexpected error");
});
}
}.execute();
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Error during processing of row: [id=2]");
}
@Test
public void display_current_row_details_if_error_during_list() throws Exception {
insertPersons();
assertThatThrownBy(() -> {
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).list((RowReader<Long>) row -> {
throw new IllegalStateException("Unexpected error");
});
}
}.execute();
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Error during processing of row: [id=2]");
}
@Test
public void bad_parameterized_query() throws Exception {
insertPersons();
DataChange change = new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
// parameter value is not set
context.prepareSelect("select id from persons where id>=?").list(Select.LONG_READER);
}
};
assertThatThrownBy(() -> change.execute())
.isInstanceOf(SQLException.class);
}
@Test
public void scroll() throws Exception {
insertPersons();
final List<Long> ids = new ArrayList<>();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
context.prepareSelect("select id from persons order by id desc").scroll(row -> ids.add(row.getNullableLong(1)));
}
}.execute();
assertThat(ids).containsExactly(3L, 2L, 1L);
}
@Test
public void insert() throws Exception {
insertPersons();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
context.prepareUpsert("insert into persons(id,login,age,enabled,coeff) values (?,?,?,?,?)")
.setLong(1, 10L)
.setString(2, "kurt")
.setInt(3, 27)
.setBoolean(4, true)
.setDouble(5, 2.2)
.execute().commit().close();
}
}.execute();
assertThat(db.select("select id as \"ID\" from persons"))
.extracting(t -> t.get("ID"))
.containsOnly(1L, 2L, 3L, 10L);
assertInitialPersons();
assertPerson(10L, "kurt", 27L, true, null, 2.2d);
}
@Test
public void batch_inserts() throws Exception {
insertPersons();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
Upsert upsert = context.prepareUpsert("insert into persons(id,login,age,enabled,coeff) values (?,?,?,?,?)");
boolean committed = upsert
.setLong(1, 10L)
.setString(2, "kurt")
.setInt(3, 27)
.setBoolean(4, true)
.setDouble(5, 2.2)
.addBatch();
assertThat(committed).isFalse();
committed = upsert
.setLong(1, 11L)
.setString(2, "courtney")
.setInt(3, 25)
.setBoolean(4, false)
.setDouble(5, 2.3)
.addBatch();
assertThat(committed).isFalse();
upsert.execute().commit().close();
}
}.execute();
assertThat(db.select("select id as \"ID\" from persons"))
.extracting(t -> t.get("ID"))
.containsOnly(1L, 2L, 3L, 10L, 11L);
assertInitialPersons();
assertPerson(10L, "kurt", 27L, true, null, 2.2d);
assertPerson(11L, "courtney", 25L, false, null, 2.3d);
}
@Test
public void override_size_of_batch_inserts() throws Exception {
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
Upsert upsert = context.prepareUpsert("insert into persons(id,login,age,enabled,coeff) values (?,?,?,?,?)")
.setBatchSize(3);
long id = 100L;
assertThat(addBatchInsert(upsert, id++)).isFalse();
assertThat(addBatchInsert(upsert, id++)).isFalse();
assertThat(addBatchInsert(upsert, id++)).isTrue();
assertThat(addBatchInsert(upsert, id++)).isFalse();
assertThat(addBatchInsert(upsert, id++)).isFalse();
assertThat(addBatchInsert(upsert, id++)).isTrue();
assertThat(addBatchInsert(upsert, id)).isFalse();
upsert.execute().commit().close();
}
}.execute();
assertThat(db.countRowsOfTable("persons")).isEqualTo(7);
for (int i = 100; i < 107; i++) {
assertPerson(i, "kurt", 27L, true, null, 2.2d);
}
}
private boolean addBatchInsert(Upsert upsert, long id) throws SQLException {
return upsert
.setLong(1, id)
.setString(2, "kurt")
.setInt(3, 27)
.setBoolean(4, true)
.setDouble(5, 2.2)
.addBatch();
}
@Test
public void update_null() throws Exception {
insertPersons();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
Upsert upsert = context.prepareUpsert("update persons set login=?,age=?,enabled=?, updated_at=?, coeff=? where id=?");
upsert
.setString(1, null)
.setInt(2, null)
.setBoolean(3, null)
.setDate(4, null)
.setDouble(5, null)
.setLong(6, 2L)
.execute()
.commit()
.close();
}
}.execute();
assertPerson(1L, "barbara", 56L, false, "2014-01-25", 1.5d);
assertPerson(2L, null, null, null, null, null);
assertPerson(3L, "morgan", 3L, true, "2014-01-25", 5.4d);
}
@Test
public void mass_batch_insert() throws Exception {
db.executeUpdateSql("truncate table persons");
final int count = MAX_BATCH_SIZE + 10;
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
Upsert upsert = context.prepareUpsert("insert into persons(id,login,age,enabled,coeff) values (?,?,?,?,?)");
for (int i = 0; i < count; i++) {
upsert
.setLong(1, 10L + i)
.setString(2, "login" + i)
.setInt(3, 10 + i)
.setBoolean(4, true)
.setDouble(5, i + 0.5)
.addBatch();
}
upsert.execute().commit().close();
}
}.execute();
assertThat(db.countRowsOfTable("persons")).isEqualTo(count);
}
@Test
public void scroll_and_update() throws Exception {
insertPersons();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
final Upsert upsert = context.prepareUpsert("update persons set login=?, age=? where id=?");
context.prepareSelect("select id from persons").scroll(new Select.RowHandler() {
@Override
public void handle(Row row) throws SQLException {
long id = row.getNullableLong(1);
upsert.setString(1, "login" + id).setInt(2, 10 + (int) id).setLong(3, id);
upsert.execute();
}
});
upsert.commit().close();
}
}.execute();
assertPerson(1L, "login1", 11L, false, "2014-01-25", 1.5d);
assertPerson(2L, "login2", 12L, true, "2014-01-25", 5.2d);
assertPerson(3L, "login3", 13L, true, "2014-01-25", 5.4d);
}
@Test
public void display_current_row_details_if_error_during_scroll() throws Exception {
insertPersons();
assertThatThrownBy(() -> {
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
final Upsert upsert = context.prepareUpsert("update persons set login=?, age=? where id=?");
context.prepareSelect("select id from persons").scroll(row -> {
throw new IllegalStateException("Unexpected error");
});
upsert.commit().close();
}
}.execute();
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Error during processing of row: [id=1]");
}
@Test
public void mass_update() throws Exception {
insertPersons();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
MassUpdate massUpdate = context.prepareMassUpdate();
massUpdate.select("select id from persons where id>=?").setLong(1, 2L);
massUpdate.update("update persons set login=?, age=? where id=?");
massUpdate.execute((row, update) -> {
long id = row.getNullableLong(1);
update
.setString(1, "login" + id)
.setInt(2, 10 + (int) id)
.setLong(3, id);
return true;
});
}
}.execute();
assertPerson(1L, "barbara", 56L, false, "2014-01-25", 1.5d);
assertPerson(2L, "login2", 12L, true, "2014-01-25", 5.2d);
assertPerson(3L, "login3", 13L, true, "2014-01-25", 5.4d);
}
@Test
public void row_splitter_should_split_correctly() throws Exception {
insertPersons();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
MassRowSplitter<PhoneNumberRow> massRowSplitter = context.prepareMassRowSplitter();
massRowSplitter.select("select id, phone_numbers from persons where id>?").setLong(1, -2L);
massRowSplitter.splitRow(row -> {
try {
int personId = row.getInt(1);
String phoneNumbers = row.getString(2);
if (phoneNumbers == null) {
return emptySet();
}
return Arrays.stream(StringUtils.split(phoneNumbers, '\n'))
.map(number -> new PhoneNumberRow(personId, number))
.collect(toSet());
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
massRowSplitter.insert("insert into phone_numbers (person_id, phone_number) values (?, ?)");
massRowSplitter.execute((row, insert) -> {
insert.setLong(1, row.personId())
.setString(2, row.phoneNumber());
return true;
});
}
}.execute();
Set<PhoneNumberRow> actualRows = getPhoneNumberRows();
assertThat(actualRows)
.containsExactlyInAnyOrder(
new PhoneNumberRow(1, "1"),
new PhoneNumberRow(1, "32234"),
new PhoneNumberRow(1, "42343"),
new PhoneNumberRow(2, "432423")
);
}
private Set<PhoneNumberRow> getPhoneNumberRows() {
return db
.select("select person_id as personId, phone_number as phoneNumber from phone_numbers")
.stream()
.map(row -> new PhoneNumberRow((long) row.get("PERSONID"), (String) row.get("PHONENUMBER")))
.collect(toSet());
}
private record PhoneNumberRow(long personId, String phoneNumber){}
@Test
public void display_current_row_details_if_error_during_mass_update() throws Exception {
insertPersons();
assertThatThrownBy(() -> {
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
MassUpdate massUpdate = context.prepareMassUpdate();
massUpdate.select("select id from persons where id>=?").setLong(1, 2L);
massUpdate.update("update persons set login=?, age=? where id=?");
massUpdate.execute((row, update) -> {
throw new IllegalStateException("Unexpected error");
});
}
}.execute();
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Error during processing of row: [id=2]");
}
@Test
public void mass_update_nothing() throws Exception {
insertPersons();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
MassUpdate massUpdate = context.prepareMassUpdate();
massUpdate.select("select id from persons where id>=?").setLong(1, 2L);
massUpdate.update("update persons set login=?, age=? where id=?");
massUpdate.execute((row, update) -> false);
}
}.execute();
assertInitialPersons();
}
@Test
public void bad_mass_update() throws Exception {
insertPersons();
DataChange change = new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
MassUpdate massUpdate = context.prepareMassUpdate();
massUpdate.select("select id from persons where id>=?").setLong(1, 2L);
// update is not set
massUpdate.execute((row, update) -> false);
}
};
try {
change.execute();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("SELECT or UPDATE requests are not defined");
}
}
@Test
public void read_not_null_fields() throws Exception {
insertPersons();
List<Object[]> persons = new ArrayList<>();
new DataChange(db.database()) {
@Override
public void execute(Context context) throws SQLException {
persons.addAll(context
.prepareSelect("select id,login,age,enabled,updated_at,coeff from persons where id=2")
.list(row -> new Object[] {
// id, login, age, enabled
row.getLong(1),
row.getString(2),
row.getInt(3),
row.getBoolean(4),
row.getDate(5),
row.getDouble(6),
}));
}
}.execute();
assertThat(persons).hasSize(1);
assertThat(persons.get(0)[0]).isEqualTo(2L);
assertThat(persons.get(0)[1]).isEqualTo("emmerik");
assertThat(persons.get(0)[2]).isEqualTo(14);
assertThat(persons.get(0)[3]).isEqualTo(true);
assertThat(persons.get(0)[4]).isNotNull();
assertThat(persons.get(0)[5]).isEqualTo(5.2);
}
static class UserReader implements RowReader<Object[]> {
@Override
public Object[] read(Row row) throws SQLException {
return new Object[] {
// id, login, age, enabled
row.getNullableLong(1),
row.getNullableString(2),
row.getNullableInt(3),
row.getNullableBoolean(4),
row.getNullableDate(5),
row.getNullableDouble(6),
};
}
}
private void insertPersons() throws ParseException {
insertPerson(1, "barbara", 56, false, "2014-01-25", 1.5d, "\n1\n32234\n42343\n");
insertPerson(2, "emmerik", 14, true, "2014-01-25", 5.2d, "432423");
insertPerson(3, "morgan", 3, true, "2014-01-25", 5.4d, null);
}
private void assertInitialPersons() throws ParseException {
assertPerson(1L, "barbara", 56L, false, "2014-01-25", 1.5d);
assertPerson(2L, "emmerik", 14L, true, "2014-01-25", 5.2d);
assertPerson(3L, "morgan", 3L, true, "2014-01-25", 5.4d);
}
private void insertPerson(int id, String login, int age, boolean enabled, String updatedAt, double coeff, @Nullable String newLineSeparatedPhoneNumbers) throws ParseException {
db.executeInsert("persons",
"ID", id,
"LOGIN", login,
"AGE", age,
"ENABLED", enabled,
"UPDATED_AT", dateFormat.parse(updatedAt),
"COEFF", coeff,
"PHONE_NUMBERS", newLineSeparatedPhoneNumbers);
}
private void assertPerson(long id, @Nullable String login, @Nullable Long age, @Nullable Boolean enabled, @Nullable String updatedAt, @Nullable Double coeff)
throws ParseException {
List<Map<String, Object>> rows = db
.select("select id as \"ID\", login as \"LOGIN\", age as \"AGE\", enabled as \"ENABLED\", coeff as \"COEFF\", updated_at as \"UPDATED\" from persons where id=" + id);
assertThat(rows).describedAs("id=" + id).hasSize(1);
Map<String, Object> row = rows.get(0);
assertThat(row).containsEntry("ID", id);
assertThat(row).containsEntry("LOGIN", login);
assertThat(row).containsEntry("AGE", age);
assertThat(row).containsEntry("ENABLED", enabled);
assertThat(row).containsEntry("UPDATED", updatedAt == null ? null : dateFormat.parse(updatedAt));
assertThat(row).containsEntry("COEFF", coeff);
}
}
| 20,504 | 33.462185 | 178 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DropIndexChangeTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.sonar.db.Database;
import org.sonar.db.DatabaseUtils;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.Validations;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DropIndexChangeTest {
private static final String TABLE_NAME = "components";
private static final String INDEX_NAME = "projects_module_uuid";
@Test
public void execute_whenCalledWithH2_shouldGenerateProperSql() throws SQLException {
Assertions.assertThat(runExecute(H2.ID, TABLE_NAME, INDEX_NAME, INDEX_NAME))
.contains(INDEX_NAME);
}
@Test
public void execute_whenCalledWithOracle_shouldGenerateProperSql() throws SQLException {
Assertions.assertThat(runExecute(Oracle.ID, TABLE_NAME, INDEX_NAME, INDEX_NAME))
.contains(INDEX_NAME);
}
@Test
public void execute_whenCalledWithPg_shouldGenerateProperSql() throws SQLException {
Assertions.assertThat(runExecute(PostgreSql.ID, TABLE_NAME, INDEX_NAME, INDEX_NAME))
.contains(INDEX_NAME);
}
@Test
public void execute_whenCalledWithMsSql_shouldGenerateProperSql() throws SQLException {
Assertions.assertThat(runExecute(MsSql.ID, TABLE_NAME, INDEX_NAME, INDEX_NAME))
.contains(INDEX_NAME);
}
@Test
public void execute_whenCalledWithWrongDbId_shouldFail() throws SQLException {
final String invalidDialectId = "invalid_dialect_id";
Assertions.assertThatThrownBy(() -> runExecute(invalidDialectId, TABLE_NAME, INDEX_NAME, INDEX_NAME))
.isInstanceOf(IllegalStateException.class)
.hasMessageStartingWith("Unsupported dialect for drop of index:");
}
@Test
public void execute_whenNoIndexFound_shouldSkipExecution() throws SQLException {
Assertions.assertThat(runExecute(H2.ID, TABLE_NAME, INDEX_NAME, INDEX_NAME))
.contains(INDEX_NAME);
}
@Test
public void execute_whenActualIndexIsLongerThanMax_shouldGenerateProperSql() throws SQLException {
final String actualIndexName = "idx_123456789123456789123456789_" + INDEX_NAME;
Assertions.assertThat(runExecute(H2.ID, TABLE_NAME, INDEX_NAME, actualIndexName))
.contains(actualIndexName);
}
@Test
public void execute_whenDifferentIndexName_shouldFindFromDb() throws SQLException {
final String actualIndexName = "idx_123_" + INDEX_NAME;
Assertions.assertThat(runExecute(H2.ID, TABLE_NAME, INDEX_NAME, actualIndexName))
.contains(actualIndexName);
}
@Test
public void execute_whenNoIndexFound_shouldSkip() throws SQLException {
Assertions.assertThat(runExecute(H2.ID, TABLE_NAME, INDEX_NAME, null, false))
.isEmpty();
}
private String runExecute(String dialectId, String tableName, String knownIndexName, String actualIndexName) throws SQLException {
return runExecute(dialectId, tableName, knownIndexName, actualIndexName, true).get();
}
private Optional<String> runExecute(String dialectId, String tableName, String knownIndexName, String actualIndexName, boolean expectResult) throws SQLException {
Dialect dialect = mock(Dialect.class);
when(dialect.getId()).thenReturn(dialectId);
Database db = Mockito.mock(Database.class, Mockito.withSettings().defaultAnswer(RETURNS_MOCKS));
when(db.getDialect()).thenReturn(dialect);
DdlChange.Context con = mock(DdlChange.Context.class);
try (MockedStatic<DatabaseUtils> dbUtils = Mockito.mockStatic(DatabaseUtils.class); MockedStatic<Validations> validationsUtil = Mockito.mockStatic(Validations.class)) {
validationsUtil.when(() -> Validations.validateTableName(any(String.class))).thenCallRealMethod();
validationsUtil.when(() -> Validations.validateIndexName(any(String.class))).thenCallRealMethod();
dbUtils.when(() -> DatabaseUtils.findExistingIndex(any(Connection.class), eq(tableName), eq(knownIndexName))).thenReturn(Optional.ofNullable(actualIndexName));
DropIndexChange underTest = new DropIndexChange(db, knownIndexName, tableName) {
};
underTest.execute(con);
// validate that the validations are called
validationsUtil.verify(() -> Validations.validateTableName(eq(tableName)));
validationsUtil.verify(() -> Validations.validateIndexName(eq(knownIndexName)));
}
if (expectResult) {
ArgumentCaptor<String> sqlCaptor = ArgumentCaptor.forClass(String.class);
Mockito.verify(con).execute(sqlCaptor.capture());
return Optional.of(sqlCaptor.getValue());
} else {
Mockito.verify(con, Mockito.never()).execute(any(String.class));
return Optional.empty();
}
}
}
| 6,000 | 40.673611 | 172 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/ForceReloadingOfAllPluginsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.CoreDbTester;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.platform.db.migration.step.ForceReloadingOfAllPlugins.OVERWRITE_HASH;
public class ForceReloadingOfAllPluginsTest {
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
@Rule
public CoreDbTester db = CoreDbTester.createForSchema(ForceReloadingOfAllPluginsTest.class, "schema.sql");
private final DataChange underTest = new ForceReloadingOfAllPlugins(db.database());
@Test
public void migration_overwrite_file_hash_on_all_plugins() throws SQLException {
String pluginUuid1 = insertPlugin();
String pluginUuid2 = insertPlugin();
underTest.execute();
assertPluginFileHashOverwrite(pluginUuid1);
assertPluginFileHashOverwrite(pluginUuid2);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
String pluginUuid1 = insertPlugin();
String pluginUuid2 = insertPlugin();
underTest.execute();
// re-entrant
underTest.execute();
assertPluginFileHashOverwrite(pluginUuid1);
assertPluginFileHashOverwrite(pluginUuid2);
}
private void assertPluginFileHashOverwrite(String pluginUuid) {
String selectSql = String.format("select file_hash from plugins where uuid='%s'", pluginUuid);
var selectResult = db.select(selectSql);
assertThat(selectResult.get(0)).containsEntry("FILE_HASH", OVERWRITE_HASH);
}
private String insertPlugin() {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
map.put("KEE", randomAlphabetic(20));
map.put("FILE_HASH", randomAlphabetic(32));
map.put("CREATED_AT", System.currentTimeMillis());
map.put("UPDATED_AT", System.currentTimeMillis());
map.put("TYPE", "EXTERNAL");
map.put("REMOVED", false);
db.executeInsert("plugins", map);
return uuid;
}
}
| 3,099 | 33.831461 | 108 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationNumberTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.util.Random;
import org.junit.Test;
import org.sonar.test.TestUtils;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class MigrationNumberTest {
@Test
public void constructor_is_private() {
TestUtils.hasOnlyPrivateConstructors(MigrationNumber.class);
}
@Test
public void validate_throws_IAE_if_argument_is_less_then_0() {
assertThatThrownBy(() -> MigrationNumber.validate(-(Math.abs(new Random().nextInt()) + 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Migration number must be >= 0");
}
@Test
public void validate_accepts_0() {
MigrationNumber.validate(0);
}
@Test
public void validate_accepts_any_positive_long() {
MigrationNumber.validate(Math.abs(new Random().nextInt()));
}
}
| 1,693 | 31.576923 | 95 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepExecutionExceptionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class MigrationStepExecutionExceptionTest {
private RegisteredMigrationStep step = new RegisteredMigrationStep(1, "foo", MigrationStep.class);
private MigrationStepExecutionException underTest = new MigrationStepExecutionException(
step, new IllegalArgumentException("some cause"));
@Test
public void MigrationStepExecutionException_is_unchecked() {
assertThat(RuntimeException.class.isAssignableFrom(MigrationStepExecutionException.class)).isTrue();
}
@Test
public void constructor_throws_NPE_if_step_is_null() {
assertThatThrownBy(() -> {
new MigrationStepExecutionException(null, new NullPointerException("Some cause"));
})
.isInstanceOf(NullPointerException.class)
.hasMessage("RegisteredMigrationStep can't be null");
}
@Test
public void constructor_throws_NPE_if_cause_is_null() {
assertThatThrownBy(() -> {
new MigrationStepExecutionException(new RegisteredMigrationStep(1, "foo", MigrationStep.class), null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("cause can't be null");
}
@Test
public void constructor_sets_exception_message_from_step_argument() {
assertThat(underTest.getMessage()).isEqualTo("Execution of migration step #1 'foo' failed");
}
@Test
public void getFailingStep_returns_constructor_argument() {
assertThat(underTest.getFailingStep()).isSameAs(step);
}
}
| 2,459 | 36.272727 | 108 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepRegistryImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class MigrationStepRegistryImplTest {
private MigrationStepRegistryImpl underTest = new MigrationStepRegistryImpl();
@Test
public void add_fails_with_IAE_if_migrationNumber_is_less_than_0() {
assertThatThrownBy(() -> {
underTest.add(-Math.abs(new Random().nextLong() + 1), "sdsd", MigrationStep.class);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Migration number must be >= 0");
}
@Test
public void add_fails_with_NPE_if_description_is_null() {
assertThatThrownBy(() -> {
underTest.add(12, null, MigrationStep.class);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("description can't be null");
}
@Test
public void add_fails_with_IAE_if_description_is_empty() {
assertThatThrownBy(() -> {
underTest.add(12, "", MigrationStep.class);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("description can't be empty");
}
@Test
public void add_fails_with_NPE_is_migrationstep_class_is_null() {
assertThatThrownBy(() -> {
underTest.add(12, "sdsd", null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("MigrationStep class can't be null");
}
@Test
public void add_fails_with_ISE_when_called_twice_with_same_migration_number() {
underTest.add(12, "dsd", MigrationStep.class);
assertThatThrownBy(() -> underTest.add(12, "dfsdf", MigrationStep.class))
.isInstanceOf(IllegalStateException.class)
.hasMessage("A migration is already registered for migration number '12'");
}
@Test
public void build_fails_with_ISE_if_registry_is_empty() {
assertThatThrownBy(() -> underTest.build())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Registry is empty");
}
@Test
public void build_returns_a_MigrationStepsImpl_with_all_steps_added_to_registry_ordered_by_migration_number() {
underTest.add(343, "sss", MigrationStep2.class);
underTest.add(5, "aazsa", MigrationStep1.class);
underTest.add(66, "bbb", MigrationStep3.class);
underTest.add(2, "aaaa", MigrationStep4.class);
MigrationSteps migrationSteps = underTest.build();
assertThat(migrationSteps).isInstanceOf(MigrationStepsImpl.class);
List<RegisteredMigrationStep> registeredMigrationSteps = migrationSteps.readAll();
assertThat(registeredMigrationSteps).hasSize(4);
verify(registeredMigrationSteps.get(0), 2, "aaaa", MigrationStep4.class);
verify(registeredMigrationSteps.get(1), 5, "aazsa", MigrationStep1.class);
verify(registeredMigrationSteps.get(2), 66, "bbb", MigrationStep3.class);
verify(registeredMigrationSteps.get(3), 343, "sss", MigrationStep2.class);
}
private static void verify(RegisteredMigrationStep step, int migrationNUmber, String description, Class<? extends MigrationStep> stepClass) {
assertThat(step.getMigrationNumber()).isEqualTo(migrationNUmber);
assertThat(step.getDescription()).isEqualTo(description);
assertThat(step.getStepClass()).isEqualTo(stepClass);
}
private static abstract class NoopMigrationStep implements MigrationStep {
@Override
public void execute() {
throw new IllegalStateException("execute is not implemented");
}
}
private static class MigrationStep1 extends NoopMigrationStep {
}
private static class MigrationStep2 extends NoopMigrationStep {
}
private static class MigrationStep3 extends NoopMigrationStep {
}
private static class MigrationStep4 extends NoopMigrationStep {
}
}
| 4,633 | 34.374046 | 143 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsExecutorImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.server.platform.db.migration.engine.MigrationContainer;
import org.sonar.server.platform.db.migration.engine.SimpleMigrationContainer;
import org.sonar.server.platform.db.migration.history.MigrationHistory;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
public class MigrationStepsExecutorImplTest {
@Rule
public LogTester logTester = new LogTester();
private MigrationContainer migrationContainer = new SimpleMigrationContainer();
private MigrationHistory migrationHistor = mock(MigrationHistory.class);
private MigrationStepsExecutorImpl underTest = new MigrationStepsExecutorImpl(migrationContainer, migrationHistor);
@Test
public void execute_does_not_fail_when_stream_is_empty_and_log_start_stop_INFO() {
underTest.execute(Collections.emptyList());
assertThat(logTester.logs()).hasSize(2);
assertLogLevel(Level.INFO, "Executing DB migrations...", "Executed DB migrations: success | time=");
}
@Test
public void execute_fails_with_ISE_if_no_instance_of_computation_step_exist_in_container() {
List<RegisteredMigrationStep> steps = asList(registeredStepOf(1, MigrationStep1.class));
((SpringComponentContainer) migrationContainer).startComponents();
try {
underTest.execute(steps);
fail("execute should have thrown a IllegalStateException");
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Unable to load component " + MigrationStep1.class);
} finally {
assertThat(logTester.logs()).hasSize(2);
assertLogLevel(Level.INFO, "Executing DB migrations...");
assertLogLevel(Level.ERROR, "Executed DB migrations: failure | time=");
}
}
private void assertLogLevel(Level level, String... expected) {
List<String> logs = logTester.logs(level);
assertThat(logs).hasSize(expected.length);
Iterator<String> iterator = logs.iterator();
Arrays.stream(expected).forEachOrdered(log -> {
if (log.endsWith(" | time=")) {
assertThat(iterator.next()).startsWith(log);
} else {
assertThat(iterator.next()).isEqualTo(log);
}
});
}
@Test
public void execute_execute_the_instance_of_type_specified_in_step_in_stream_order() {
migrationContainer.add(MigrationStep1.class, MigrationStep2.class, MigrationStep3.class);
((SpringComponentContainer) migrationContainer).startComponents();
underTest.execute(asList(
registeredStepOf(1, MigrationStep2.class),
registeredStepOf(2, MigrationStep1.class),
registeredStepOf(3, MigrationStep3.class)));
assertThat(SingleCallCheckerMigrationStep.calledSteps)
.containsExactly(MigrationStep2.class, MigrationStep1.class, MigrationStep3.class);
assertThat(logTester.logs()).hasSize(8);
assertLogLevel(Level.INFO,
"Executing DB migrations...",
"#1 '1-MigrationStep2'...",
"#1 '1-MigrationStep2': success | time=",
"#2 '2-MigrationStep1'...",
"#2 '2-MigrationStep1': success | time=",
"#3 '3-MigrationStep3'...",
"#3 '3-MigrationStep3': success | time=",
"Executed DB migrations: success | time=");
assertThat(migrationContainer.getComponentByType(MigrationStep1.class).isCalled()).isTrue();
assertThat(migrationContainer.getComponentByType(MigrationStep2.class).isCalled()).isTrue();
assertThat(migrationContainer.getComponentByType(MigrationStep3.class).isCalled()).isTrue();
}
@Test
public void execute_throws_MigrationStepExecutionException_on_first_failing_step_execution_throws_SQLException() {
migrationContainer.add(MigrationStep2.class, SqlExceptionFailingMigrationStep.class, MigrationStep3.class);
List<RegisteredMigrationStep> steps = asList(
registeredStepOf(1, MigrationStep2.class),
registeredStepOf(2, SqlExceptionFailingMigrationStep.class),
registeredStepOf(3, MigrationStep3.class));
((SpringComponentContainer) migrationContainer).startComponents();
try {
underTest.execute(steps);
fail("a MigrationStepExecutionException should have been thrown");
} catch (MigrationStepExecutionException e) {
assertThat(e).hasMessage("Execution of migration step #2 '2-SqlExceptionFailingMigrationStep' failed");
assertThat(e).hasCause(SqlExceptionFailingMigrationStep.THROWN_EXCEPTION);
} finally {
assertThat(logTester.logs()).hasSize(6);
assertLogLevel(Level.INFO,
"Executing DB migrations...",
"#1 '1-MigrationStep2'...",
"#1 '1-MigrationStep2': success | time=",
"#2 '2-SqlExceptionFailingMigrationStep'...");
assertLogLevel(Level.ERROR,
"#2 '2-SqlExceptionFailingMigrationStep': failure | time=",
"Executed DB migrations: failure | time=");
}
}
@Test
public void execute_throws_MigrationStepExecutionException_on_first_failing_step_execution_throws_any_exception() {
migrationContainer.add(MigrationStep2.class, RuntimeExceptionFailingMigrationStep.class, MigrationStep3.class);
List<RegisteredMigrationStep> steps = asList(
registeredStepOf(1, MigrationStep2.class),
registeredStepOf(2, RuntimeExceptionFailingMigrationStep.class),
registeredStepOf(3, MigrationStep3.class));
((SpringComponentContainer) migrationContainer).startComponents();
try {
underTest.execute(steps);
fail("should throw MigrationStepExecutionException");
} catch (MigrationStepExecutionException e) {
assertThat(e).hasMessage("Execution of migration step #2 '2-RuntimeExceptionFailingMigrationStep' failed");
assertThat(e.getCause()).isSameAs(RuntimeExceptionFailingMigrationStep.THROWN_EXCEPTION);
}
}
private static RegisteredMigrationStep registeredStepOf(int migrationNumber, Class<? extends MigrationStep> migrationStep1Class) {
return new RegisteredMigrationStep(migrationNumber, migrationNumber + "-" + migrationStep1Class.getSimpleName(), migrationStep1Class);
}
private static abstract class SingleCallCheckerMigrationStep implements MigrationStep {
private static List<Class<? extends MigrationStep>> calledSteps = new ArrayList<>();
private boolean called = false;
@Override
public void execute() {
checkState(!called, "execute must not be called twice");
this.called = true;
calledSteps.add(getClass());
}
public boolean isCalled() {
return called;
}
public static List<Class<? extends MigrationStep>> getCalledSteps() {
return calledSteps;
}
}
public static final class MigrationStep1 extends SingleCallCheckerMigrationStep {
}
public static final class MigrationStep2 extends SingleCallCheckerMigrationStep {
}
public static final class MigrationStep3 extends SingleCallCheckerMigrationStep {
}
public static class SqlExceptionFailingMigrationStep implements MigrationStep {
private static final SQLException THROWN_EXCEPTION = new SQLException("Faking SQL exception in MigrationStep#execute()");
@Override
public void execute() throws SQLException {
throw THROWN_EXCEPTION;
}
}
public static class RuntimeExceptionFailingMigrationStep implements MigrationStep {
private static final RuntimeException THROWN_EXCEPTION = new RuntimeException("Faking failing migration step");
@Override
public void execute() {
throw THROWN_EXCEPTION;
}
}
}
| 8,784 | 39.114155 | 138 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class MigrationStepsImplTest {
private MigrationStepsImpl underTest = new MigrationStepsImpl(Arrays.asList(
new RegisteredMigrationStep(1, "mmmmmm", MigrationStep.class),
new RegisteredMigrationStep(2, "sds", MigrationStep.class),
new RegisteredMigrationStep(8, "ss", MigrationStep.class)));
private MigrationStepsImpl unorderedSteps = new MigrationStepsImpl(Arrays.asList(
new RegisteredMigrationStep(2, "sds", MigrationStep.class),
new RegisteredMigrationStep(8, "ss", MigrationStep.class),
new RegisteredMigrationStep(1, "mmmmmm", MigrationStep.class)));
@Test
public void constructor_fails_with_NPE_if_argument_is_null() {
assertThatThrownBy(() -> new MigrationStepsImpl(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("steps can't be null");
}
@Test
public void constructor_fails_with_IAE_if_argument_is_empty() {
assertThatThrownBy(() -> new MigrationStepsImpl(Collections.emptyList()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("steps can't be empty");
}
@Test
public void constructor_fails_with_NPE_if_argument_contains_a_null() {
assertThatThrownBy(() -> {
new MigrationStepsImpl(Arrays.asList(
new RegisteredMigrationStep(12, "sdsd", MigrationStep.class),
null,
new RegisteredMigrationStep(88, "q", MigrationStep.class)));
})
.isInstanceOf(NullPointerException.class);
}
@Test
public void getMaxMigrationNumber_returns_migration_of_last_step_in_constructor_list_argument() {
assertThat(underTest.getMaxMigrationNumber()).isEqualTo(8L);
assertThat(unorderedSteps.getMaxMigrationNumber()).isOne();
}
@Test
public void readAll_iterates_over_all_steps_in_constructor_list_argument() {
verifyContainsNumbers(underTest.readAll(), 1L, 2L, 8L);
}
@Test
public void readFrom_throws_IAE_if_number_is_less_than_0() {
assertThatThrownBy(() -> underTest.readFrom(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Migration number must be >= 0");
}
@Test
public void readFrom_returns_stream_of_sublist_from_the_first_migration_with_number_greater_or_equal_to_argument() {
verifyContainsNumbers(underTest.readFrom(1), 1L, 2L, 8L);
verifyContainsNumbers(underTest.readFrom(2), 2L, 8L);
verifyContainsNumbers(underTest.readFrom(3), 8L);
verifyContainsNumbers(underTest.readFrom(4), 8L);
verifyContainsNumbers(underTest.readFrom(5), 8L);
verifyContainsNumbers(underTest.readFrom(6), 8L);
verifyContainsNumbers(underTest.readFrom(7), 8L);
verifyContainsNumbers(underTest.readFrom(8), 8L);
}
@Test
public void readFrom_returns_an_empty_stream_if_argument_is_greater_than_biggest_migration_number() {
verifyContainsNumbers(underTest.readFrom(9));
verifyContainsNumbers(unorderedSteps.readFrom(9));
}
private static void verifyContainsNumbers(List<RegisteredMigrationStep> steps, Long... expectedMigrationNumbers) {
assertThat(steps).hasSize(expectedMigrationNumbers.length);
Iterator<RegisteredMigrationStep> iterator = steps.iterator();
Arrays.stream(expectedMigrationNumbers).forEach(expected -> assertThat(iterator.next().getMigrationNumber()).isEqualTo(expected));
}
}
| 4,416 | 39.522936 | 134 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import org.junit.Test;
import org.mockito.InOrder;
import org.sonar.server.platform.db.migration.version.DbVersion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MigrationStepsProviderTest {
private final InternalMigrationStepRegistry internalMigrationStepRegistry = mock(InternalMigrationStepRegistry.class);
private final MigrationStepsProvider underTest = new MigrationStepsProvider();
@Test
public void provide_throws_ISE_with_registry_build_throws_ISE_because_it_is_empty() {
IllegalStateException expected = new IllegalStateException("faking ISE because registry is empty");
when(internalMigrationStepRegistry.build()).thenThrow(expected);
assertThatThrownBy(() -> underTest.provide(internalMigrationStepRegistry))
.isInstanceOf(expected.getClass())
.hasMessage(expected.getMessage());
}
@Test
public void provide_calls_DbVersion_addStep_in_order() {
DbVersion dbVersion1 = newMockFailingOnSecondBuildCall();
DbVersion dbVersion2 = newMockFailingOnSecondBuildCall();
DbVersion dbVersion3 = newMockFailingOnSecondBuildCall();
InOrder inOrder = inOrder(dbVersion1, dbVersion2, dbVersion3);
MigrationSteps expected = mock(MigrationSteps.class);
when(internalMigrationStepRegistry.build()).thenReturn(expected);
assertThat(underTest.provide(internalMigrationStepRegistry, dbVersion1, dbVersion2, dbVersion3))
.isSameAs(expected);
inOrder.verify(dbVersion1).addSteps(internalMigrationStepRegistry);
inOrder.verify(dbVersion2).addSteps(internalMigrationStepRegistry);
inOrder.verify(dbVersion3).addSteps(internalMigrationStepRegistry);
inOrder.verifyNoMoreInteractions();
}
private static DbVersion newMockFailingOnSecondBuildCall() {
DbVersion res = mock(DbVersion.class);
doNothing()
.doThrow(new RuntimeException("addStep should not be called twice"))
.when(res)
.addSteps(any(MigrationStepRegistry.class));
return res;
}
}
| 3,164 | 40.644737 | 120 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/RegisteredMigrationStepTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class RegisteredMigrationStepTest {
@Test
public void constructor_throws_NPE_if_description_is_null() {
assertThatThrownBy(() -> new RegisteredMigrationStep(1, null, MigrationStep.class))
.isInstanceOf(NullPointerException.class)
.hasMessage("description can't be null");
}
@Test
public void constructor_throws_NPE_if_MigrationStep_class_is_null() {
assertThatThrownBy(() -> new RegisteredMigrationStep(1, "", null))
.isInstanceOf(NullPointerException.class)
.hasMessage("MigrationStep class can't be null");
}
@Test
public void verify_getters() {
RegisteredMigrationStep underTest = new RegisteredMigrationStep(3, "foo", MyMigrationStep.class);
assertThat(underTest.getMigrationNumber()).isEqualTo(3L);
assertThat(underTest.getDescription()).isEqualTo("foo");
assertThat(underTest.getStepClass()).isEqualTo(MyMigrationStep.class);
}
private static abstract class MyMigrationStep implements MigrationStep {
}
}
| 2,039 | 36.090909 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/UpsertImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.step;
import java.sql.Connection;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.mockito.Mockito.mock;
public class UpsertImplTest {
@Test
public void setBatchSize_throws_IAE_if_value_is_negative() throws Exception {
UpsertImpl underTest = create();
assertThatThrownBy(() -> underTest.setBatchSize(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("size must be positive. Got -1");
}
@Test
public void setBatchSize_accepts_zero() throws Exception {
UpsertImpl underTest = create();
underTest.setBatchSize(0);
assertThat(underTest.getMaxBatchSize()).isZero();
}
@Test
public void setBatchSize_accepts_strictly_positive_value() throws Exception {
UpsertImpl underTest = create();
underTest.setBatchSize(42);
assertThat(underTest.getMaxBatchSize()).isEqualTo(42);
}
@Test
public void maxBatchSize_is_250_by_default() throws Exception {
UpsertImpl underTest = create();
assertThat(underTest.getMaxBatchSize()).isEqualTo(250);
}
private UpsertImpl create() throws Exception {
return UpsertImpl.create(mock(Connection.class), "sql");
}
}
| 2,169 | 30 | 79 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/DatabaseVersionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.server.platform.db.migration.history.MigrationHistory;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Status.FRESH_INSTALL;
import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Status.REQUIRES_DOWNGRADE;
import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Status.REQUIRES_UPGRADE;
import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Status.UP_TO_DATE;
public class DatabaseVersionTest {
private MigrationHistory migrationHistory = mock(MigrationHistory.class);
private MigrationSteps migrationSteps = mock(MigrationSteps.class);
private DatabaseVersion underTest = new DatabaseVersion(migrationSteps, migrationHistory);
@Test
public void getStatus_returns_FRESH_INSTALL_when_table_is_empty() {
mockMaxMigrationNumberInDb(null);
mockMaxMigrationNumberInConfig(150L);
assertThat(underTest.getStatus()).isEqualTo(FRESH_INSTALL);
}
@Test
public void getStatus_returns_REQUIRES_UPGRADE_when_max_migration_number_in_table_is_less_than_max_migration_number_in_configuration() {
mockMaxMigrationNumberInDb(123L);
mockMaxMigrationNumberInConfig(150L);
assertThat(underTest.getStatus()).isEqualTo(REQUIRES_UPGRADE);
}
@Test
public void getStatus_returns_UP_TO_DATE_when_max_migration_number_in_table_is_equal_to_max_migration_number_in_configuration() {
mockMaxMigrationNumberInDb(150L);
mockMaxMigrationNumberInConfig(150L);
assertThat(underTest.getStatus()).isEqualTo(UP_TO_DATE);
}
@Test
public void getStatus_returns_REQUIRES_DOWNGRADE_when_max_migration_number_in_table_is_greater_than_max_migration_number_in_configuration() {
mockMaxMigrationNumberInDb(200L);
mockMaxMigrationNumberInConfig(150L);
assertThat(underTest.getStatus()).isEqualTo(REQUIRES_DOWNGRADE);
}
private void mockMaxMigrationNumberInDb(@Nullable Long value1) {
when(migrationHistory.getLastMigrationNumber()).thenReturn(Optional.ofNullable(value1));
}
private void mockMaxMigrationNumberInConfig(long value) {
when(migrationSteps.getMaxMigrationNumber()).thenReturn(value);
}
}
| 3,360 | 40.493827 | 143 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/DbVersionTestUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version;
import java.util.HashSet;
import java.util.Set;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationStepRegistry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.platform.db.migration.step.MigrationNumber.validate;
public class DbVersionTestUtils {
public static void verifyMinimumMigrationNumber(DbVersion underTest, int minimumMigrationNumber) {
TestMigrationStepRegistry registry = new TestMigrationStepRegistry() {
@Override
public <T extends MigrationStep> MigrationStepRegistry add(long migrationNumber, String description, Class<T> stepClass) {
super.add(migrationNumber, description, MigrationStep.class);
assertThat(migrationNumber).isGreaterThanOrEqualTo(minimumMigrationNumber);
return this;
}
};
underTest.addSteps(registry);
assertThat(registry.migrationNumbers).describedAs("No migration added to registry").isNotEmpty();
assertThat(registry.migrationNumbers.stream().sorted().findFirst().get()).isEqualTo(minimumMigrationNumber);
}
public static void verifyMigrationCount(DbVersion underTest, int migrationCount) {
TestMigrationStepRegistry registry = new TestMigrationStepRegistry();
underTest.addSteps(registry);
assertThat(registry.migrationNumbers).hasSize(migrationCount);
}
public static void verifyMigrationNotEmpty(DbVersion underTest) {
TestMigrationStepRegistry registry = new TestMigrationStepRegistry();
underTest.addSteps(registry);
assertThat(registry.migrationNumbers).isNotEmpty();
}
private static class TestMigrationStepRegistry implements MigrationStepRegistry {
private Set<Long> migrationNumbers = new HashSet<>();
@Override
public <T extends MigrationStep> MigrationStepRegistry add(long migrationNumber, String description, Class<T> stepClass) {
validate(migrationNumber);
assertThat(description).isNotEmpty();
assertThat(stepClass).isNotNull();
assertThat(migrationNumbers.add(migrationNumber)).isTrue();
return this;
}
}
}
| 3,036 | 40.040541 | 128 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/RenameVarcharColumnAbstractTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version;
import java.sql.SQLException;
import org.junit.Rule;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange;
import static java.sql.Types.VARCHAR;
public abstract class RenameVarcharColumnAbstractTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(getClass(), "schema.sql");
private final String tableName;
private final String columnName;
private final boolean isNullable;
public RenameVarcharColumnAbstractTest(String tableName, String columnName, boolean isNullable) {
this.tableName = tableName;
this.columnName = columnName;
this.isNullable = isNullable;
}
protected void verifyMigrationIsReentrant() throws SQLException {
db.assertColumnDoesNotExist(tableName, columnName);
getClassUnderTest().execute();
getClassUnderTest().execute();
db.assertColumnDefinition(tableName, columnName, VARCHAR, 40, isNullable);
}
protected void verifyColumnIsRenamed() throws SQLException {
db.assertColumnDoesNotExist(tableName, columnName);
getClassUnderTest().execute();
db.assertColumnDefinition(tableName, columnName, VARCHAR, 40, isNullable);
}
protected abstract RenameVarcharColumnChange getClassUnderTest();
}
| 2,157 | 35.576271 | 99 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v00/CreateInitialSchemaTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v00;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThat;
public class CreateInitialSchemaTest {
@Rule
public final CoreDbTester dbTester = CoreDbTester.createForSchema(CreateInitialSchemaTest.class, "empty.sql");
private final CreateInitialSchema underTest = new CreateInitialSchema(dbTester.database());
@Test
public void creates_tables_on_empty_db() throws Exception {
underTest.execute();
List<String> tables = new ArrayList<>();
try (Connection connection = dbTester.openConnection();
ResultSet rs = connection.getMetaData().getTables(null, null, null, new String[] {"TABLE"})) {
while (rs.next()) {
String schema = rs.getString("TABLE_SCHEM");
if (!"INFORMATION_SCHEMA".equalsIgnoreCase(schema)) {
tables.add(rs.getString("TABLE_NAME").toLowerCase(Locale.ENGLISH));
}
}
}
assertThat(tables).containsOnly(
"active_rules",
"active_rule_parameters",
"app_branch_project_branch",
"alm_pats",
"app_projects",
"alm_settings",
"audits",
"project_alm_settings",
"analysis_properties",
"ce_activity",
"ce_queue",
"ce_scanner_context",
"ce_task_characteristics",
"ce_task_input",
"ce_task_message",
"components",
"default_qprofiles",
"deprecated_rule_keys",
"duplications_index",
"es_queue",
"events",
"event_component_changes",
"file_sources",
"groups",
"groups_users",
"group_roles",
"internal_component_props",
"internal_properties",
"issues",
"issue_changes",
"live_measures",
"metrics",
"new_code_periods",
"new_code_reference_issues",
"notifications",
"org_qprofiles",
"permission_templates",
"perm_templates_groups",
"perm_templates_users",
"perm_tpl_characteristics",
"plugins",
"portfolios",
"portfolio_projects",
"portfolio_proj_branches",
"portfolio_references",
"projects",
"project_badge_token",
"project_branches",
"project_links",
"project_mappings",
"project_measures",
"project_qprofiles",
"project_qgates",
"properties",
"push_events",
"qgate_group_permissions",
"qgate_user_permissions",
"qprofile_changes",
"qprofile_edit_groups",
"qprofile_edit_users",
"quality_gates",
"quality_gate_conditions",
"rules",
"rules_parameters",
"rules_profiles",
"rule_repositories",
"rule_desc_sections",
"saml_message_ids",
"scanner_analysis_cache",
"scim_users",
"session_tokens",
"snapshots",
"users",
"user_dismissed_messages",
"user_roles",
"user_tokens",
"webhooks",
"webhook_deliveries");
}
}
| 3,975 | 27.811594 | 112 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v00/DbVersion00Test.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v00;
import org.junit.Test;
import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMigrationCount;
import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMinimumMigrationNumber;
public class DbVersion00Test {
private DbVersion00 underTest = new DbVersion00();
@Test
public void migrationNumber_starts_at_1153() {
verifyMinimumMigrationNumber(underTest, 1);
}
@Test
public void verify_migration_count() {
verifyMigrationCount(underTest, 2);
}
}
| 1,433 | 33.142857 | 109 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v00/PopulateInitialSchemaTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v00;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PopulateInitialSchemaTest {
private static final long NOW = 1_500L;
private final Random random = new Random();
private final Version version = Version.create(1 + random.nextInt(10), 1 + random.nextInt(10), random.nextInt(10));
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
private final System2 system2 = mock(System2.class);
private final SonarQubeVersion sonarQubeVersion = mock(SonarQubeVersion.class);
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(PopulateInitialSchemaTest.class, "v99.sql");
private final PopulateInitialSchema underTest = new PopulateInitialSchema(db.database(), system2, uuidFactory, sonarQubeVersion);
@Before
public void setUp() {
when(sonarQubeVersion.get()).thenReturn(version);
}
@Test
public void migration_inserts_users_and_groups() throws SQLException {
when(system2.now()).thenReturn(NOW);
underTest.execute();
verifyAdminUser();
verifyGroup("sonar-users", "Every authenticated user automatically belongs to this group");
verifyGroup("sonar-administrators", "System administrators");
String qualityGateUuid = verifyQualityGate();
verifyInternalProperties();
verifyProperties(qualityGateUuid);
verifyRolesOfAdminsGroup();
verifyRolesOfUsersGroup();
verifyRolesOfAnyone();
verifyMembershipOfAdminUser();
}
private void verifyAdminUser() {
Map<String, Object> cols = db.selectFirst("select " +
"login as \"LOGIN\", " +
"name as \"NAME\", " +
"email as \"EMAIL\", " +
"external_id as \"EXTERNAL_ID\", " +
"external_login as \"EXTERNAL_LOGIN\", " +
"external_identity_provider as \"EXT_IDENT_PROVIDER\", " +
"user_local as \"USER_LOCAL\", " +
"crypted_password as \"CRYPTED_PASSWORD\", " +
"salt as \"SALT\", " +
"hash_method as \"HASH_METHOD\", " +
"created_at as \"CREATED_AT\", " +
"updated_at as \"UPDATED_AT\", " +
"reset_password as \"RESET_PASSWORD\" " +
"from users where login='admin'");
assertThat(cols)
.containsEntry("LOGIN", "admin")
.containsEntry("NAME", "Administrator")
.containsEntry("EXTERNAL_ID", "admin")
.containsEntry("EXTERNAL_LOGIN", "admin")
.containsEntry("EXT_IDENT_PROVIDER", "sonarqube")
.containsEntry("USER_LOCAL", true)
.containsEntry("CRYPTED_PASSWORD", "$2a$12$uCkkXmhW5ThVK8mpBvnXOOJRLd64LJeHTeCkSuB3lfaR2N0AYBaSi")
.containsEntry("HASH_METHOD", "BCRYPT")
.containsEntry("CREATED_AT", NOW)
.containsEntry("RESET_PASSWORD", true)
.containsEntry("UPDATED_AT", NOW);
assertThat(cols.get("EMAIL")).isNull();
assertThat(cols.get("SALT")).isNull();
}
private void verifyGroup(String expectedName, String expectedDescription) {
List<Map<String, Object>> rows = db.select("select " +
"uuid as \"UUID\"," +
"name as \"name\", " +
"description as \"description\", " +
"created_at as \"CREATED_AT\", " +
"updated_at as \"UPDATED_AT\" " +
"from groups where name='" + expectedName + "'");
assertThat(rows).hasSize(1);
Map<String, Object> row = rows.get(0);
assertThat(row).containsEntry("name", expectedName);
assertThat(row).containsEntry("description", expectedDescription);
assertThat(((Date) row.get("CREATED_AT")).getTime()).isEqualTo(NOW);
assertThat(((Date) row.get("UPDATED_AT")).getTime()).isEqualTo(NOW);
}
private String verifyQualityGate() {
List<Map<String, Object>> rows = db.select("select " +
"uuid as \"UUID\", " +
"name as \"NAME\", " +
"is_built_in as \"BUILTIN\"," +
"created_at as \"CREATED_AT\", " +
"updated_at as \"UPDATED_AT\"" +
" from quality_gates");
assertThat(rows).hasSize(1);
Map<String, Object> row = rows.get(0);
assertThat(row).containsEntry("NAME", "Sonar way");
assertThat(row).containsEntry("BUILTIN", true);
assertThat(((Date) row.get("CREATED_AT")).getTime()).isEqualTo(NOW);
assertThat(((Date) row.get("UPDATED_AT")).getTime()).isEqualTo(NOW);
return (String) row.get("UUID");
}
private void verifyInternalProperties() {
List<Map<String, Object>> rows = db.select("select " +
"kee as \"KEE\", " +
"is_empty as \"EMPTY\", " +
"text_value as \"VAL\"," +
"created_at as \"CREATED_AT\" " +
" from internal_properties");
assertThat(rows).hasSize(2);
Map<String, Map<String, Object>> rowsByKey = rows.stream().collect(Collectors.toMap(t -> (String) t.get("KEE"), Function.identity()));
verifyInternalProperty(rowsByKey, "installation.date", String.valueOf(system2.now()));
verifyInternalProperty(rowsByKey, "installation.version", version.toString());
}
private static void verifyInternalProperty(Map<String, Map<String, Object>> rowsByKey, String key, String val) {
Map<String, Object> row = rowsByKey.get(key);
assertThat(row)
.containsEntry("KEE", key)
.containsEntry("EMPTY", false)
.containsEntry("VAL", val)
.containsEntry("CREATED_AT", NOW);
}
private void verifyProperties(String qualityGateUuid) {
List<Map<String, Object>> rows = db.select("select " +
"prop_key as \"PROP_KEY\", " +
"is_empty as \"EMPTY\", " +
"text_value as \"VAL\"," +
"created_at as \"CREATED_AT\" " +
" from properties");
assertThat(rows).hasSize(3);
Map<String, Map<String, Object>> rowsByKey = rows.stream().collect(Collectors.toMap(t -> (String) t.get("PROP_KEY"), Function.identity()));
verifyProperty(rowsByKey, "sonar.forceAuthentication", "true");
verifyProperty(rowsByKey, "projects.default.visibility", "public");
verifyProperty(rowsByKey, "qualitygate.default", qualityGateUuid);
}
private static void verifyProperty(Map<String, Map<String, Object>> rowsByKey, String key, String val) {
Map<String, Object> row = rowsByKey.get(key);
assertThat(row)
.containsEntry("PROP_KEY", key)
.containsEntry("EMPTY", false)
.containsEntry("VAL", val)
.containsEntry("CREATED_AT", NOW);
}
private void verifyRolesOfAdminsGroup() {
assertThat(selectRoles("sonar-administrators")).containsOnly("admin", "profileadmin", "gateadmin", "provisioning", "applicationcreator", "portfoliocreator");
}
private void verifyRolesOfUsersGroup() {
assertThat(selectRoles("sonar-users")).containsOnly("provisioning", "scan");
}
private void verifyRolesOfAnyone() {
List<Map<String, Object>> rows = db.select("select gr.role as \"role\" " +
"from group_roles gr where gr.group_uuid is null");
Stream<String> roles = rows.stream()
.map(row -> (String) row.get("role"));
assertThat(roles).isEmpty();
}
private Stream<String> selectRoles(String groupName) {
List<Map<String, Object>> rows = db.select("select gr.role as \"role\" " +
"from group_roles gr " +
"inner join groups g on gr.group_uuid = g.uuid " +
"where g.name='" + groupName + "'");
return rows.stream()
.map(row -> (String) row.get("role"));
}
private void verifyMembershipOfAdminUser() {
List<Map<String, Object>> rows = db.select("select g.name as \"groupName\" from groups g " +
"inner join groups_users gu on gu.group_uuid = g.uuid " +
"inner join users u on gu.user_uuid = u.uuid " +
"where u.login='admin'");
List<String> groupNames = rows.stream()
.map(row -> (String) row.get("groupName"))
.toList();
assertThat(groupNames).containsOnly("sonar-administrators", "sonar-users");
}
}
| 9,167 | 37.847458 | 161 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/AddNclocToProjectsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class AddNclocToProjectsTest {
private static final String TABLE_NAME = "projects";
private static final String COLUMN_NAME = "ncloc";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(AddNclocToProjectsTest.class, "schema.sql");
private final DdlChange underTest = new AddNclocToProjects(db.database());
@Test
public void add_column() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.BIGINT, null, true);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.BIGINT, null, true);
}
} | 1,992 | 35.907407 | 106 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/CreateScimGroupsTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonar.server.platform.db.migration.version.v100.CreateScimGroupsTable.TABLE_NAME;
public class CreateScimGroupsTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createEmpty();
private final DdlChange underTest = new CreateScimGroupsTable(db.database());
@Test
public void migration_should_create_a_table() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
underTest.execute();
db.assertTableExists(TABLE_NAME);
db.assertColumnDefinition(TABLE_NAME, "scim_uuid", Types.VARCHAR, UUID_SIZE, false);
db.assertColumnDefinition(TABLE_NAME, "group_uuid", Types.VARCHAR, UUID_SIZE, false);
db.assertPrimaryKey(TABLE_NAME, "pk_scim_groups", "scim_uuid");
}
@Test
public void migration_should_be_reentrant() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
underTest.execute();
// re-entrant
underTest.execute();
db.assertTableExists(TABLE_NAME);
}
}
| 2,152 | 34.295082 | 99 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/CreateUniqueIndexForScimGroupsUuidTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
import static org.sonar.server.platform.db.migration.version.v100.CreateScimGroupsTable.TABLE_NAME;
import static org.sonar.server.platform.db.migration.version.v100.CreateUniqueIndexForScimGroupsUuid.COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v100.CreateUniqueIndexForScimGroupsUuid.INDEX_NAME;
public class CreateUniqueIndexForScimGroupsUuidTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(CreateUniqueIndexForScimGroupsUuidTest.class, "schema.sql");
private final DdlChange underTest = new CreateUniqueIndexForScimGroupsUuid(db.database());
@Test
public void migration_should_create_index() throws SQLException {
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
underTest.execute();
db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
underTest.execute();
underTest.execute();
db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
}
}
| 2,166 | 37.017544 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DbVersion100Test.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import org.junit.Test;
import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMigrationNotEmpty;
import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMinimumMigrationNumber;
public class DbVersion100Test {
private final DbVersion100 underTest = new DbVersion100();
@Test
public void migrationNumber_starts_at_10_0_000() {
verifyMinimumMigrationNumber(underTest, 10_0_000);
}
@Test
public void verify_migration_is_not_empty() {
verifyMigrationNotEmpty(underTest);
}
}
| 1,463 | 34.707317 | 109 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropBModuleUuidInComponentsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropBModuleUuidInComponentsTest {
private static final String TABLE_NAME = "components";
private static final String COLUMN_NAME = "b_module_uuid";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropBModuleUuidInComponentsTest.class, "schema.sql");
private final DdlChange underTest = new DropBModuleUuidInComponents(db.database());
@Test
public void drops_column() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, true);
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, true);
underTest.execute();
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
}
| 1,970 | 36.903846 | 115 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropBModuleUuidPathInComponentsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropBModuleUuidPathInComponentsTest {
private static final String TABLE_NAME = "components";
private static final String COLUMN_NAME = "b_module_uuid_path";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropBModuleUuidPathInComponentsTest.class, "schema.sql");
private final DdlChange underTest = new DropBModuleUuidPathInComponents(db.database());
@Test
public void drops_column() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 1500, true);
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 1500, true);
underTest.execute();
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
}
| 1,991 | 37.307692 | 119 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropIndexProjectsModuleUuidInComponentsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropIndexProjectsModuleUuidInComponentsTest {
private static final String TABLE_NAME = "components";
private static final String COLUMN_NAME = "module_uuid";
private static final String INDEX_NAME = "projects_module_uuid";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexProjectsModuleUuidInComponentsTest.class, "schema.sql");
private final DdlChange underTest = new DropIndexProjectsModuleUuidInComponents(db.database());
@Test
public void drops_index() throws SQLException {
db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
underTest.execute();
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
}
@Test
public void execute_whenIndexNameWithPrefix_shouldStillDelete() throws SQLException {
String alteredIndexName = "idx_1234567891345678916456789_" + INDEX_NAME;
db.executeUpdateSql(String.format("ALTER INDEX %s RENAME TO %s;", INDEX_NAME, alteredIndexName));
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
db.assertIndex(TABLE_NAME, alteredIndexName, COLUMN_NAME);
underTest.execute();
db.assertIndexDoesNotExist(TABLE_NAME, alteredIndexName);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
underTest.execute();
underTest.execute();
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
}
}
| 2,481 | 39.032258 | 127 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropIndexProjectsRootUuidInComponentsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropIndexProjectsRootUuidInComponentsTest {
private static final String TABLE_NAME = "components";
private static final String COLUMN_NAME = "root_uuid";
private static final String INDEX_NAME = "projects_root_uuid";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexProjectsRootUuidInComponentsTest.class, "schema.sql");
private final DdlChange underTest = new DropIndexProjectsRootUuidInComponents(db.database());
@Test
public void drops_index() throws SQLException {
db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
underTest.execute();
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
underTest.execute();
underTest.execute();
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
}
}
| 1,985 | 37.192308 | 125 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropModuleUuidInComponentsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropModuleUuidInComponentsTest {
private static final String TABLE_NAME = "components";
private static final String COLUMN_NAME = "module_uuid";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropModuleUuidInComponentsTest.class, "schema.sql");
private final DdlChange underTest = new DropModuleUuidInComponents(db.database());
@Test
public void drops_column() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, true);
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, true);
underTest.execute();
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
}
| 1,965 | 36.807692 | 114 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropModuleUuidPathInComponentsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropModuleUuidPathInComponentsTest {
private static final String TABLE_NAME = "components";
private static final String COLUMN_NAME = "module_uuid_path";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropModuleUuidPathInComponentsTest.class, "schema.sql");
private final DdlChange underTest = new DropModuleUuidPathInComponents(db.database());
@Test
public void drops_column() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 1500, true);
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 1500, true);
underTest.execute();
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
}
| 1,986 | 37.211538 | 118 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropRootUuidInComponentsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
public class DropRootUuidInComponentsTest {
private static final String TABLE_NAME = "components";
private static final String COLUMN_NAME = "root_uuid";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropRootUuidInComponentsTest.class, "schema.sql");
private final DdlChange underTest = new DropRootUuidInComponents(db.database());
@Test
public void drops_column() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, false);
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, false);
underTest.execute();
underTest.execute();
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
}
}
| 1,959 | 36.692308 | 112 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropScimUserProvisioningTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
import static org.assertj.core.api.Assertions.assertThat;
public class DropScimUserProvisioningTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropScimUserProvisioningTest.class, "schema.sql");
private final DataChange underTest = new DropScimUserProvisioning(db.database());
@Test
public void migration_should_truncate_scim_users_table() throws SQLException {
insertScimUser(1);
insertScimUser(2);
underTest.execute();
assertThat(db.select("select * from scim_users")).isEmpty();
}
private void insertScimUser(long id) {
db.executeInsert("scim_users",
"scim_uuid", "any-scim-uuid-" + id,
"user_uuid", "any-user-uuid-" + id
);
}
@Test
public void migration_is_reentrant() throws SQLException {
insertScimUser(1);
insertScimUser(2);
underTest.execute();
underTest.execute();
assertThat(db.select("select * from scim_users")).isEmpty();
}
} | 2,029 | 31.222222 | 112 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/DropSonarScimEnabledPropertyTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
public class DropSonarScimEnabledPropertyTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(DropSonarScimEnabledPropertyTest.class, "schema.sql");
private final DataChange underTest = new DropSonarScimEnabledProperty(db.database());
@Test
public void migration_should_remove_scim_property() throws SQLException {
insertScimProperty(db);
underTest.execute();
Assertions.assertThat(db.select("select * from properties")).isEmpty();
}
@Test
public void migration_is_reentrant() throws SQLException {
insertScimProperty(db);
underTest.execute();
underTest.execute();
Assertions.assertThat(db.select("select * from properties")).isEmpty();
}
private void insertScimProperty(CoreDbTester db) {
db.executeInsert("properties ",
"prop_key", "sonar.scim.enabled",
"is_empty", false,
"text_value", "true",
"created_at", 100_000L,
"uuid", "some-random-uuid"
);
}
} | 2,089 | 32.174603 | 116 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/LogMessageIfSonarScimEnabledPresentPropertyTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.platform.db.migration.version.v100.LogMessageIfSonarScimEnabledPresentProperty.SONAR_SCIM_ENABLED;
public class LogMessageIfSonarScimEnabledPresentPropertyTest {
@Rule
public LogTester logger = new LogTester();
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(LogMessageIfSonarScimEnabledPresentPropertyTest.class, "schema.sql");
private final DataChange underTest = new LogMessageIfSonarScimEnabledPresentProperty(db.database());
@Before
public void before() {
logger.clear();
}
@Test
public void migration_should_log_message_when_scim_property() throws SQLException {
db.executeInsert("properties ",
"prop_key", "sonar.scim.enabled",
"is_empty", false,
"text_value", "true",
"created_at", 100_000L,
"uuid", "some-random-uuid"
);
underTest.execute();
assertThat(logger.logs(Level.WARN))
.hasSize(1)
.containsExactly("'" + SONAR_SCIM_ENABLED + "' property is defined but not read anymore. Please read the upgrade notes" +
" for the instruction to upgrade. User provisioning is deactivated until reactivated from the SonarQube" +
" Administration Interface (\"General->Authentication\"). "
+ "See documentation: https://docs.sonarqube.org/10.1/instance-administration/authentication/saml/scim/overview/");
}
@Test
public void migration_should_not_log_if_no_scim_property() throws SQLException {
underTest.execute();
assertThat(logger.logs(Level.WARN)).isEmpty();
}
@Test
public void migration_is_reentrant() throws SQLException {
db.executeInsert("properties ",
"prop_key", "sonar.scim.enabled",
"is_empty", false,
"text_value", "true",
"created_at", 100_000L,
"uuid", "some-random-uuid"
);
underTest.execute();
underTest.execute();
assertThat(logger.logs(Level.WARN)).hasSize(2);
}
}
| 3,164 | 33.402174 | 131 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/MakeColumnUserLocalNotNullableInUsersTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static java.sql.Types.BOOLEAN;
public class MakeColumnUserLocalNotNullableInUsersTest {
private static final String TABLE_NAME = "users";
private static final String COLUMN_NAME = "user_local";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(MakeColumnUserLocalNotNullableInUsersTest.class, "schema.sql");
private final MakeColumnUserLocalNotNullableInUsers underTest = new MakeColumnUserLocalNotNullableInUsers(db.database());
@Test
public void user_local_column_is_not_null() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, true);
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, false);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, true);
underTest.execute();
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, false);
}
}
| 2,024 | 37.207547 | 125 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/PopulateNclocForForProjectsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
public class PopulateNclocForForProjectsTest {
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
@Rule
public CoreDbTester db = CoreDbTester.createForSchema(PopulateNclocForForProjectsTest.class, "schema.sql");
private final DataChange underTest = new PopulateNclocForForProjects(db.database());
@Test
public void migration_populates_ncloc_for_projects() throws SQLException {
Map<String, Long> expectedNclocByProjectUuid = populateData();
underTest.execute();
verifyNclocCorrectlyPopulatedForProjects(expectedNclocByProjectUuid);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
Map<String, Long> expectedNclocByProjectUuid = populateData();
underTest.execute();
// re-entrant
underTest.execute();
verifyNclocCorrectlyPopulatedForProjects(expectedNclocByProjectUuid);
}
private Map<String, Long> populateData() {
String nclocMetricUuid = insertMetric("ncloc");
String projectUuid1 = insertProject();
String project1Branch1 = insertProjectBranch(projectUuid1);
String project1Branch2 = insertProjectBranch(projectUuid1);
long project1maxNcloc = 100;
insertLiveMeasure(nclocMetricUuid, projectUuid1, project1Branch1, 80L);
insertLiveMeasure(nclocMetricUuid, projectUuid1, project1Branch2, project1maxNcloc);
String otherMetricUuid = insertMetric("other");
insertLiveMeasure(otherMetricUuid, projectUuid1, project1Branch1, 5000L);
insertLiveMeasure(otherMetricUuid, projectUuid1, project1Branch2, 6000L);
String projectUuid2 = insertProject();
String project2Branch1 = insertProjectBranch(projectUuid2);
String project2Branch2 = insertProjectBranch(projectUuid2);
String project2Branch3 = insertProjectBranch(projectUuid2);
long project2maxNcloc = 60;
insertLiveMeasure(nclocMetricUuid, projectUuid2, project2Branch1, 20L);
insertLiveMeasure(nclocMetricUuid, projectUuid2, project2Branch2, 50L);
insertLiveMeasure(nclocMetricUuid, projectUuid2, project2Branch3, project2maxNcloc);
return Map.of(projectUuid1, project1maxNcloc, projectUuid2, project2maxNcloc);
}
private void verifyNclocCorrectlyPopulatedForProjects(Map<String, Long> expectedNclocByProjectUuid) {
for (Map.Entry<String, Long> entry : expectedNclocByProjectUuid.entrySet()) {
String query = String.format("select ncloc from projects where uuid='%s'", entry.getKey());
Long nclocFromProject = (Long) db.selectFirst(query).get("NCLOC");
assertThat(nclocFromProject).isEqualTo(entry.getValue());
}
}
private String insertMetric(String name) {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
map.put("NAME", name);
db.executeInsert("metrics", map);
return uuid;
}
private String insertProject() {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
map.put("KEE", randomAlphabetic(20));
map.put("QUALIFIER", "TRK");
map.put("PRIVATE", true);
map.put("UPDATED_AT", System.currentTimeMillis());
db.executeInsert("projects", map);
return uuid;
}
private String insertProjectBranch(String projectUuid) {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
map.put("PROJECT_UUID", projectUuid);
map.put("KEE", randomAlphabetic(20));
map.put("BRANCH_TYPE", "PULL_REQUEST");
map.put("UPDATED_AT", System.currentTimeMillis());
map.put("CREATED_AT", System.currentTimeMillis());
map.put("NEED_ISSUE_SYNC", false);
db.executeInsert("project_branches", map);
return uuid;
}
private void insertLiveMeasure(String metricUuid, String projectUuid, String componentUuid, Long value) {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
map.put("PROJECT_UUID", projectUuid);
map.put("COMPONENT_UUID", componentUuid);
map.put("METRIC_UUID", metricUuid);
map.put("VALUE", value);
map.put("UPDATED_AT", System.currentTimeMillis());
map.put("CREATED_AT", System.currentTimeMillis());
db.executeInsert("live_measures", map);
}
}
| 5,602 | 37.641379 | 109 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/RemoveOrphanRulesFromQualityProfilesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RemoveOrphanRulesFromQualityProfilesTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(RemoveOrphanRulesFromQualityProfilesTest.class, "schema.sql");
private final System2 system2 = mock(System2.class);
private final UuidFactory instance = new SequenceUuidFactory();
private final DataChange underTest = new RemoveOrphanRulesFromQualityProfiles(db.database(), instance, system2);
@Before
public void before() {
when(system2.now()).thenReturn(1L);
}
@Test
public void migration_should_remove_orphans() throws SQLException {
insertData();
underTest.execute();
assertOrphanRuleRemoved();
assertQualityProfileChanges();
}
@Test
public void migration_should_be_reentrant() throws SQLException {
insertData();
// re-entrant
underTest.execute();
underTest.execute();
assertOrphanRuleRemoved();
assertQualityProfileChanges();
}
private void insertData() {
insertRule("uuid-rule-1", "language-1", "rule1");
insertRule("uuid-rule-2", "language-2", "rule2");
insertProfile("uuid-profile-1", "language-1");
insertProfile("uuid-profile-2", "language-2");
activateRule("uuid-active-rule-1", "uuid-profile-1", "uuid-rule-1");
activateRule("uuid-active-rule-2", "uuid-profile-1", "uuid-rule-2");
activateRule("uuid-active-rule-3", "uuid-profile-2", "uuid-rule-2");
}
private void insertRule(String uuid, String language, String ruleKey) {
Map<String, Object> rule = new HashMap<>();
rule.put("uuid", uuid);
rule.put("plugin_rule_key", language + ":" + ruleKey);
rule.put("plugin_name", "plugin-name-1");
rule.put("scope", "MAIN");
rule.put("language", language);
rule.put("is_template", false);
rule.put("is_ad_hoc", false);
rule.put("is_external", false);
db.executeInsert("rules", rule);
}
private void insertProfile(String uuid, String language) {
Map<String, Object> profile = new HashMap<>();
profile.put("uuid", uuid);
profile.put("name", "profile-name-1");
profile.put("language", language);
profile.put("is_built_in", false);
db.executeInsert("rules_profiles", profile);
}
private void activateRule(String activeRuleUuid, String profileUuid, String ruleUuid) {
Map<String, Object> active_rule = new HashMap<>();
active_rule.put("uuid", activeRuleUuid);
active_rule.put("failure_level", 3);
active_rule.put("profile_uuid", profileUuid);
active_rule.put("rule_uuid", ruleUuid);
db.executeInsert("active_rules", active_rule);
}
private void assertOrphanRuleRemoved() {
assertThat(db.select("SELECT * from active_rules"))
.extracting(r -> r.get("UUID"))
.containsExactly("uuid-active-rule-1", "uuid-active-rule-3");
}
private void assertQualityProfileChanges() {
assertThat(db.select("SELECT * from qprofile_changes"))
.extracting(r -> r.get("KEE"), r -> r.get("RULES_PROFILE_UUID"), r -> r.get("CHANGE_TYPE"), r -> r.get("USER_UUID"), r -> r.get("CHANGE_DATA"), r -> r.get("CREATED_AT"))
.containsExactly(tuple("1", "uuid-profile-1", "DEACTIVATED", null, "ruleUuid=uuid-rule-2", 1L));
}
}
| 4,641 | 34.984496 | 175 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v100/UpdateUserLocalValueInUsersTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v100;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomNumeric;
import static org.assertj.core.api.Assertions.assertThat;
public class UpdateUserLocalValueInUsersTest {
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
@Rule
public CoreDbTester db = CoreDbTester.createForSchema(UpdateUserLocalValueInUsersTest.class, "schema.sql");
private final DataChange underTest = new UpdateUserLocalValueInUsers(db.database());
@Test
public void migration_updates_user_local_if_null() throws SQLException {
String userUuid1 = insertUser(true);
String userUuid2 = insertUser(false);
String userUuid3 = insertUser(null);
underTest.execute();
assertUserLocalIsUpdatedCorrectly(userUuid1, true);
assertUserLocalIsUpdatedCorrectly(userUuid2, false);
assertUserLocalIsUpdatedCorrectly(userUuid3, true);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
String userUuid1 = insertUser(true);
String userUuid2 = insertUser(false);
String userUuid3 = insertUser(null);
underTest.execute();
// re-entrant
underTest.execute();
assertUserLocalIsUpdatedCorrectly(userUuid1, true);
assertUserLocalIsUpdatedCorrectly(userUuid2, false);
assertUserLocalIsUpdatedCorrectly(userUuid3, true);
}
private void assertUserLocalIsUpdatedCorrectly(String userUuid, boolean expected) {
String selectSql = String.format("select USER_LOCAL from users where uuid='%s'", userUuid);
assertThat(db.select(selectSql).stream()
.map(row -> row.get("USER_LOCAL"))
.toList())
.containsExactlyInAnyOrder(expected);
}
private String insertUser(Boolean userLocal) {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
map.put("LOGIN", randomAlphabetic(20));
map.put("EXTERNAL_LOGIN", randomAlphabetic(20));
map.put("EXTERNAL_IDENTITY_PROVIDER", "sonarqube");
map.put("EXTERNAL_ID", randomNumeric(5));
map.put("CREATED_AT", System.currentTimeMillis());
map.put("USER_LOCAL", userLocal);
map.put("RESET_PASSWORD", false);
db.executeInsert("users", map);
return uuid;
}
}
| 3,482 | 35.28125 | 109 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/AddCodeVariantsColumnInIssuesTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static java.sql.Types.VARCHAR;
public class AddCodeVariantsColumnInIssuesTableTest {
private static final String TABLE_NAME = "issues";
private static final String COLUMN_NAME = "code_variants";
private static final int COLUMN_SIZE = 4000;
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(AddCodeVariantsColumnInIssuesTableTest.class, "schema.sql");
private final AddCodeVariantsColumnInIssuesTable underTest = new AddCodeVariantsColumnInIssuesTable(db.database());
@Test
public void migration_should_add_column() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, COLUMN_SIZE, true);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, COLUMN_SIZE, true);
}
}
| 2,043 | 36.163636 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/AddIsMainColumnInProjectBranchesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static java.sql.Types.BOOLEAN;
public class AddIsMainColumnInProjectBranchesTest {
private static final String TABLE_NAME = "project_branches";
private static final String COLUMN_NAME = "is_main";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(AddIsMainColumnInProjectBranchesTest.class, "schema.sql");
private final AddIsMainColumnInProjectBranches underTest = new AddIsMainColumnInProjectBranches(db.database());
@Test
public void is_main_column_exists_with_null_value() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, null);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, null);
}
}
| 1,981 | 35.703704 | 120 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/AddReportSchedulesTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonar.server.platform.db.migration.version.v101.AddReportSchedulesTable.TABLE_NAME;
public class AddReportSchedulesTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createEmpty();
private final DdlChange underTest = new AddReportSchedulesTable(db.database());
@Test
public void migration_should_create_a_table() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
underTest.execute();
db.assertTableExists(TABLE_NAME);
db.assertColumnDefinition(TABLE_NAME, "uuid", Types.VARCHAR, UUID_SIZE, false);
db.assertColumnDefinition(TABLE_NAME, "portfolio_uuid", Types.VARCHAR, UUID_SIZE, true);
db.assertColumnDefinition(TABLE_NAME, "branch_uuid", Types.VARCHAR, UUID_SIZE, true);
db.assertColumnDefinition(TABLE_NAME, "last_send_time_in_ms", Types.BIGINT, null, false);
db.assertPrimaryKey(TABLE_NAME, "pk_report_schedules", "uuid");
}
@Test
public void migration_should_be_reentrant() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
underTest.execute();
// re-entrant
underTest.execute();
db.assertTableExists(TABLE_NAME);
}
}
| 2,343 | 34.515152 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/AddReportSubscriptionsTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonar.server.platform.db.migration.version.v101.AddReportSubscriptionsTable.TABLE_NAME;
public class AddReportSubscriptionsTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createEmpty();
private final DdlChange underTest = new AddReportSubscriptionsTable(db.database());
@Test
public void migration_should_create_a_table() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
underTest.execute();
db.assertTableExists(TABLE_NAME);
db.assertColumnDefinition(TABLE_NAME, "uuid", Types.VARCHAR, UUID_SIZE, false);
db.assertColumnDefinition(TABLE_NAME, "portfolio_uuid", Types.VARCHAR, UUID_SIZE, true);
db.assertColumnDefinition(TABLE_NAME, "branch_uuid", Types.VARCHAR, UUID_SIZE, true);
db.assertColumnDefinition(TABLE_NAME, "user_uuid", Types.VARCHAR, UUID_SIZE, false);
db.assertPrimaryKey(TABLE_NAME, "pk_report_subscriptions", "uuid");
}
@Test
public void migration_should_be_reentrant() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
underTest.execute();
// re-entrant
underTest.execute();
db.assertTableExists(TABLE_NAME);
}
}
| 2,352 | 35.765625 | 105 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/AlterIsMainColumnInProjectBranchesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static java.sql.Types.BOOLEAN;
public class AlterIsMainColumnInProjectBranchesTest {
private static final String TABLE_NAME = "project_branches";
private static final String COLUMN_NAME = "is_main";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(AlterIsMainColumnInProjectBranchesTest.class, "schema.sql");
private final AlterIsMainColumnInProjectBranches underTest = new AlterIsMainColumnInProjectBranches(db.database());
@Test
public void execute_shouldNotBeNullable() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, true);
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, false);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, true);
underTest.execute();
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, BOOLEAN, null, false);
}
}
| 2,019 | 36.407407 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateExternalGroupsTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonar.server.platform.db.migration.version.v101.CreateExternalGroupsTable.EXTERNAL_GROUP_ID_COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateExternalGroupsTable.EXTERNAL_IDENTITY_PROVIDER_COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateExternalGroupsTable.GROUP_UUID_COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateExternalGroupsTable.TABLE_NAME;
public class CreateExternalGroupsTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createEmpty();
private final DdlChange createExternalGroupsTable = new CreateExternalGroupsTable(db.database());
@Test
public void migration_should_create_a_table() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
createExternalGroupsTable.execute();
db.assertTableExists(TABLE_NAME);
db.assertColumnDefinition(TABLE_NAME, GROUP_UUID_COLUMN_NAME, Types.VARCHAR, UUID_SIZE, false);
db.assertColumnDefinition(TABLE_NAME, EXTERNAL_GROUP_ID_COLUMN_NAME, Types.VARCHAR, 255, false);
db.assertColumnDefinition(TABLE_NAME, EXTERNAL_IDENTITY_PROVIDER_COLUMN_NAME, Types.VARCHAR, 100, false);
db.assertPrimaryKey(TABLE_NAME, "pk_external_groups", GROUP_UUID_COLUMN_NAME);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
db.assertTableDoesNotExist(TABLE_NAME);
createExternalGroupsTable.execute();
// re-entrant
createExternalGroupsTable.execute();
db.assertTableExists(TABLE_NAME);
}
}
| 2,748 | 40.029851 | 131 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateIndexForEmailOnUsersTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.sonar.server.platform.db.migration.version.v101.CreateIndexForEmailOnUsersTable.COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateIndexForEmailOnUsersTable.INDEX_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateIndexForEmailOnUsersTable.TABLE_NAME;
public class CreateIndexForEmailOnUsersTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexForEmailOnUsersTableTest.class, "schema.sql");
private final CreateIndexForEmailOnUsersTable createIndexForEmailOnUsersTable = new CreateIndexForEmailOnUsersTable(db.database());
@Test
public void migration_should_create_index() throws SQLException {
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
createIndexForEmailOnUsersTable.execute();
db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
createIndexForEmailOnUsersTable.execute();
createIndexForEmailOnUsersTable.execute();
db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME);
}
}
| 2,140 | 38.648148 | 133 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateIndexForScmAccountOnScmAccountsTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.sonar.server.platform.db.migration.version.v101.CreateIndexForScmAccountOnScmAccountsTable.INDEX_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateScmAccountsTable.SCM_ACCOUNT_COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateScmAccountsTable.SCM_ACCOUNTS_TABLE_NAME;
public class CreateIndexForScmAccountOnScmAccountsTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexForScmAccountOnScmAccountsTableTest.class, "schema.sql");
private final CreateIndexForScmAccountOnScmAccountsTable createIndexForScmAccountOnScmAccountsTable = new CreateIndexForScmAccountOnScmAccountsTable(db.database());
@Test
public void migration_should_create_index() throws SQLException {
db.assertIndexDoesNotExist(SCM_ACCOUNTS_TABLE_NAME, INDEX_NAME);
createIndexForScmAccountOnScmAccountsTable.execute();
db.assertIndex(SCM_ACCOUNTS_TABLE_NAME, INDEX_NAME, SCM_ACCOUNT_COLUMN_NAME);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
createIndexForScmAccountOnScmAccountsTable.execute();
createIndexForScmAccountOnScmAccountsTable.execute();
db.assertIndex(SCM_ACCOUNTS_TABLE_NAME, INDEX_NAME, SCM_ACCOUNT_COLUMN_NAME);
}
}
| 2,309 | 41.777778 | 166 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateIndexOnExternalIdAndIdentityOnExternalGroupsTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static org.sonar.server.platform.db.migration.version.v101.CreateExternalGroupsTable.EXTERNAL_GROUP_ID_COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateExternalGroupsTable.EXTERNAL_IDENTITY_PROVIDER_COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateExternalGroupsTable.TABLE_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateIndexOnExternalIdAndIdentityOnExternalGroupsTable.INDEX_NAME;
public class CreateIndexOnExternalIdAndIdentityOnExternalGroupsTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexOnExternalIdAndIdentityOnExternalGroupsTableTest.class, "schema.sql");
private final CreateIndexOnExternalIdAndIdentityOnExternalGroupsTable createIndexOnExternalIdAndIdentityOnExternalGroupsTable = new CreateIndexOnExternalIdAndIdentityOnExternalGroupsTable(
db.database());
@Test
public void migration_should_create_index() throws SQLException {
db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME);
createIndexOnExternalIdAndIdentityOnExternalGroupsTable.execute();
db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, EXTERNAL_IDENTITY_PROVIDER_COLUMN_NAME, EXTERNAL_GROUP_ID_COLUMN_NAME);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
createIndexOnExternalIdAndIdentityOnExternalGroupsTable.execute();
createIndexOnExternalIdAndIdentityOnExternalGroupsTable.execute();
db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, EXTERNAL_IDENTITY_PROVIDER_COLUMN_NAME, EXTERNAL_GROUP_ID_COLUMN_NAME);
}
}
| 2,629 | 44.344828 | 190 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateProjectUuidInUserTokensTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import static java.sql.Types.VARCHAR;
public class CreateProjectUuidInUserTokensTest {
private static final String TABLE_NAME = "user_tokens";
private static final String COLUMN_NAME = "project_uuid";
@Rule
public final CoreDbTester db = CoreDbTester.createForSchema(CreateProjectUuidInUserTokensTest.class, "schema.sql");
private final CreateProjectUuidInUserTokens underTest = new CreateProjectUuidInUserTokens(db.database());
@Test
public void migration_creates_new_column() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 40, null);
}
@Test
public void migration_is_reentrant() throws SQLException {
db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME);
underTest.execute();
underTest.execute();
db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 40, null);
}
} | 1,954 | 36.596154 | 117 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateScmAccountsTableTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v101;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DdlChange;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.USER_UUID_SIZE;
import static org.sonar.server.platform.db.migration.version.v101.CreateScmAccountsTable.SCM_ACCOUNT_COLUMN_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateScmAccountsTable.SCM_ACCOUNT_SIZE;
import static org.sonar.server.platform.db.migration.version.v101.CreateScmAccountsTable.SCM_ACCOUNTS_TABLE_NAME;
import static org.sonar.server.platform.db.migration.version.v101.CreateScmAccountsTable.USER_UUID_COLUMN_NAME;
public class CreateScmAccountsTableTest {
@Rule
public final CoreDbTester db = CoreDbTester.createEmpty();
private final DdlChange createScmAccountsTable = new CreateScmAccountsTable(db.database());
@Test
public void migration_should_create_a_table() throws SQLException {
db.assertTableDoesNotExist(SCM_ACCOUNTS_TABLE_NAME);
createScmAccountsTable.execute();
db.assertTableExists(SCM_ACCOUNTS_TABLE_NAME);
db.assertColumnDefinition(SCM_ACCOUNTS_TABLE_NAME, USER_UUID_COLUMN_NAME, Types.VARCHAR, USER_UUID_SIZE, false);
db.assertColumnDefinition(SCM_ACCOUNTS_TABLE_NAME, SCM_ACCOUNT_COLUMN_NAME, Types.VARCHAR, SCM_ACCOUNT_SIZE, false);
db.assertPrimaryKey(SCM_ACCOUNTS_TABLE_NAME, "pk_scm_accounts", USER_UUID_COLUMN_NAME, SCM_ACCOUNT_COLUMN_NAME);
}
@Test
public void migration_should_be_reentrant() throws SQLException {
db.assertTableDoesNotExist(SCM_ACCOUNTS_TABLE_NAME);
createScmAccountsTable.execute();
// re-entrant
createScmAccountsTable.execute();
db.assertTableExists(SCM_ACCOUNTS_TABLE_NAME);
}
}
| 2,718 | 41.484375 | 120 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.