Best EvoMaster code snippet using org.evomaster.client.java.controller.db.DbCleaner.getDefaultRetries
Source:DbCleaner.java
...34 * The SQL command "TRUNCATE TABLE my_table RESTART IDENTITY"35 * is not supported by H2 version 1.4.199 or lower36 */37 final boolean restartIdentitiyWhenTruncating = H2VersionUtils.isVersionGreaterOrEqual(h2Version, H2VersionUtils.H2_VERSION_2_0_0);38 clearDatabase(getDefaultRetries(DatabaseType.H2), connection, schemaName, tableToSkip, tableToClean, DatabaseType.H2,39 false, true, restartIdentitiyWhenTruncating);40 }41 /*42 [non-determinism-source] Man: retries might lead to non-determinate logs43 */44 private static void clearDatabase(int retries,45 Connection connection,46 String schemaName,47 List<String> tableToSkip,48 List<String> tableToClean,49 DatabaseType type,50 boolean doDropTable,51 boolean doResetSequence,52 boolean restartIdentityWhenTruncating) {53 /*54 Code based on55 https://stackoverflow.com/questions/8523423/reset-embedded-h2-database-periodically56 */57 try {58 Statement statement = connection.createStatement();59 /*60 For H2, we have to delete tables one at a time... but, to avoid issues61 with FKs, we must temporarily disable the integrity checks62 */63 disableReferentialIntegrity(statement, type);64 List<String> cleanedTable = cleanDataInTables(tableToSkip,65 tableToClean,66 statement,67 type,68 schemaName,69 isSingleCleanCommand(type),70 doDropTable,71 restartIdentityWhenTruncating);72 if (doResetSequence) {73 List<String> sequenceToClean = null;74 if (type == DatabaseType.MYSQL || type == DatabaseType.MARIADB)75 sequenceToClean = cleanedTable;76 resetSequences(statement, type, schemaName, sequenceToClean);77 }78 enableReferentialIntegrity(statement, type);79 statement.close();80 } catch (Exception e) {81 /*82 this could happen if there is a current transaction with a lock on any table.83 We could check the content of INFORMATION_SCHEMA.LOCKS, or simply look at error message84 */85 String msg = e.getMessage();86 if (msg != null && msg.toLowerCase().contains("timeout")) {87 if (retries > 0) {88 SimpleLogger.warn("Timeout issue with cleaning DB. Trying again.");89 //let's just wait a bit, and retry90 try {91 Thread.sleep(2000);92 } catch (InterruptedException interruptedException) {93 // empty block94 }95 retries--;96 clearDatabase(retries, connection, schemaName, tableToSkip, tableToClean, type, doDropTable, doResetSequence, restartIdentityWhenTruncating);97 } else {98 SimpleLogger.error("Giving up cleaning the DB. There are still timeouts.");99 }100 }101 throw new RuntimeException(e);102 }103 }104 public static void clearDatabase(Connection connection, List<String> tablesToSkip, DatabaseType type, boolean doResetSequence) {105 clearDatabase(connection, getDefaultSchema(type), tablesToSkip, type, doResetSequence);106 }107 public static void clearDatabase(Connection connection, List<String> tablesToSkip, DatabaseType type) {108 clearDatabase(connection, tablesToSkip, type, true);109 }110 public static void clearDatabase(Connection connection, List<String> tableToSkip, List<String> tableToClean, DatabaseType type) {111 clearDatabase(connection, tableToSkip, tableToClean, type, true);112 }113 public static void clearDatabase(Connection connection, List<String> tableToSkip, List<String> tableToClean, DatabaseType type, boolean doResetSequence) {114 clearDatabase(connection, getDefaultSchema(type), tableToSkip, tableToClean, type, doResetSequence);115 }116 public static void clearDatabase(Connection connection, String schemaName, List<String> tablesToSkip, DatabaseType type) {117 clearDatabase(connection, getSchemaName(schemaName, type), tablesToSkip, type, true);118 }119 public static void clearDatabase(Connection connection, String schemaName, List<String> tablesToSkip, DatabaseType type, boolean doResetSequence) {120 clearDatabase(connection, getSchemaName(schemaName, type), tablesToSkip, null, type, doResetSequence);121 }122 public static void clearDatabase(Connection connection, String schemaName, List<String> tableToSkip, List<String> tableToClean, DatabaseType type) {123 clearDatabase(connection, getSchemaName(schemaName, type), tableToSkip, tableToClean, type, true);124 }125 public static void clearDatabase(Connection connection, String schemaName, List<String> tableToSkip, List<String> tableToClean, DatabaseType type, boolean doResetSequence) {126 /*127 * Enable the restarting of Identity fields only if sequences are to be restarted128 * and the database type is H2129 */130 boolean restartIdentityWhenTruncating;131 if (doResetSequence && type.equals(DatabaseType.H2)) {132 try {133 String h2Version = H2VersionUtils.getH2Version(connection);134 restartIdentityWhenTruncating = H2VersionUtils.isVersionGreaterOrEqual(h2Version, H2VersionUtils.H2_VERSION_2_0_0);135 } catch (SQLException ex) {136 throw new RuntimeException("Unexpected SQL exception while getting H2 version", ex);137 }138 } else {139 restartIdentityWhenTruncating = false;140 }141 clearDatabase(getDefaultRetries(type), connection, getSchemaName(schemaName, type), tableToSkip, tableToClean, type, false, doResetSequence, restartIdentityWhenTruncating);142 }143 public static void dropDatabaseTables(Connection connection, String schemaName, List<String> tablesToSkip, DatabaseType type) {144 if (type != DatabaseType.MYSQL && type != DatabaseType.MARIADB)145 throw new IllegalArgumentException("Dropping tables are not supported by " + type);146 clearDatabase(getDefaultRetries(type), connection, getSchemaName(schemaName, type), tablesToSkip, null, type, true, true, false);147 }148 public static void clearDatabase_Postgres(Connection connection, String schemaName, List<String> tablesToSkip) {149 clearDatabase_Postgres(connection, getSchemaName(schemaName, DatabaseType.POSTGRES), tablesToSkip, null);150 }151 public static void clearDatabase_Postgres(Connection connection, String schemaName, List<String> tableToSkip, List<String> tableToClean) {152 clearDatabase(getDefaultRetries(DatabaseType.POSTGRES), connection, getSchemaName(schemaName, DatabaseType.POSTGRES), tableToSkip, tableToClean, DatabaseType.POSTGRES, false, true, false);153 }154 private static String getSchemaName(String schemaName, DatabaseType type) {155 if (schemaName != null) return schemaName;156 return getDefaultSchema(type);157 }158 /**159 * @param tableToSkip are tables to skip160 * @param tableToClean are tables to clean161 * @param statement is to execute the SQL command162 * @param schema specify the schema of data to clean. if [schema] is empty, all data will be cleaned.163 * @param singleCommand specify whether to execute the SQL commands (e.g., truncate table/tables) by single command164 * @param doDropTable specify whether to drop tables which is only for MySQL and MariaDB now.165 * @return a list of tables which have been cleaned166 * @throws SQLException are exceptions during sql execution167 */168 private static List<String> cleanDataInTables(List<String> tableToSkip,169 List<String> tableToClean,170 Statement statement,171 DatabaseType type,172 String schema,173 boolean singleCommand,174 boolean doDropTable,175 boolean restartIdentityWhenTruncating) throws SQLException {176 if (tableToSkip != null && (!tableToSkip.isEmpty()) && tableToClean != null && (!tableToClean.isEmpty()))177 throw new IllegalArgumentException("tableToSkip and tableToClean cannot be configured at the same time.");178 // Find all tables and truncate them179 Set<String> tables = new HashSet<>();180 ResultSet rs = statement.executeQuery(getAllTableCommand(type, schema));181 while (rs.next()) {182 tables.add(rs.getString(1));183 }184 rs.close();185 if (tables.isEmpty()) {186 throw new IllegalStateException("Could not find any table");187 }188 final List<String> tableToHandle;189 boolean toskip = tableToSkip != null;190 if (tableToClean != null) {191 tableToHandle = tableToClean;192 } else {193 tableToHandle = tableToSkip;194 }195 if (tableToHandle != null) {196 for (String skip : tableToHandle) {197 if (tables.stream().noneMatch(t -> t.equalsIgnoreCase(skip))) {198 String msg = "Asked to skip/clean table '" + skip + "', but it does not exist.";199 msg += " Existing tables in schema '" + schema + "': [" +200 String.join(", ", tables) + "]";201 throw new IllegalStateException(msg);202 }203 }204 }205 Set<String> tablesHaveIdentifies = new HashSet<>();206 if (type == DatabaseType.MS_SQL_SERVER) {207 ResultSet rst = statement.executeQuery(getAllTableHasIdentify(type, schema));208 while (rst.next()) {209 tablesHaveIdentifies.add(rst.getString(1));210 }211 rst.close();212 }213 List<String> tablesToClear = tables.stream()214 .filter(n -> tableToHandle == null ||215 (toskip && (tableToHandle.isEmpty() || tableToHandle.stream().noneMatch(skip -> skip.equalsIgnoreCase(n)))) ||216 (!toskip && tableToHandle.stream().anyMatch(clean -> clean.equalsIgnoreCase(n)))217 )218 .collect(Collectors.toList());219 if (singleCommand) {220 String ts = tablesToClear.stream()221 .sorted()222 .collect(Collectors.joining(","));223 if (type != DatabaseType.POSTGRES)224 throw new IllegalArgumentException("do not support for cleaning all data by one single command for " + type);225 if (doDropTable) {226 dropTableIfExists(statement, ts);227 } else {228 truncateTable(statement, ts, restartIdentityWhenTruncating);229 }230 } else {231 //note: if one at a time, need to make sure to first disable FK checks232 for (String t : tablesToClear) {233 if (doDropTable)234 dropTableIfExists(statement, t);235 else {236 /*237 for MS_SQL_SERVER, we cannot use truncate tables if there exist fk238 see239 https://docs.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql?view=sql-server-ver15#restrictions240 https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813241 then it will cause a problem to reset identify242 */243 if (type == DatabaseType.MS_SQL_SERVER)244 deleteTables(statement, t, schema, tablesHaveIdentifies);245 else246 truncateTable(statement, t, restartIdentityWhenTruncating);247 }248 }249 }250 return tablesToClear;251 }252 private static void dropTableIfExists(Statement statement, String table) throws SQLException {253 statement.executeUpdate("DROP TABLE IF EXISTS " + table);254 }255 private static void deleteTables(Statement statement, String table, String schema, Set<String> tableHasIdentify) throws SQLException {256 String tableWithSchema = table;257 /*258 for MS SQL, the delete command should consider its schema,259 but such schema info is not returned when retrieving table name with select command, see [getAllTableCommand]260 then here, we need to reformat the table name with schema261 */262 if (!schema.isEmpty() && !schema.equals(getDefaultSchema(DatabaseType.MS_SQL_SERVER)))263 tableWithSchema = schema + "." + schema;264 statement.executeUpdate("DELETE FROM " + tableWithSchema);265// NOTE TAHT ideally we should reseed identify here, but there would case an issue, i.e., does not contain an identity column266 if (tableHasIdentify.contains(table))267 statement.executeUpdate("DBCC CHECKIDENT ('" + tableWithSchema + "', RESEED, 0)");268 }269 private static void truncateTable(Statement statement, String table, boolean restartIdentityWhenTruncating) throws SQLException {270 if (restartIdentityWhenTruncating) {271 statement.executeUpdate("TRUNCATE TABLE " + table + " RESTART IDENTITY");272 } else {273 statement.executeUpdate("TRUNCATE TABLE " + table);274 }275 }276 private static void resetSequences(Statement s, DatabaseType type, String schemaName, List<String> sequenceToClean) throws SQLException {277 ResultSet rs;// Idem for sequences278 Set<String> sequences = new HashSet<>();279 rs = s.executeQuery(getAllSequenceCommand(type, schemaName));280 while (rs.next()) {281 sequences.add(rs.getString(1));282 }283 rs.close();284 for (String seq : sequences) {285 if (sequenceToClean == null || sequenceToClean.isEmpty() || sequenceToClean.stream().anyMatch(x -> x.equalsIgnoreCase(seq)))286 s.executeUpdate(resetSequenceCommand(seq, type));287 }288 /*289 Note: we reset all sequences from 1. But the original database might290 have used a different value.291 In most cases (99.99%), this should not be a problem.292 We could allow using different values in this API... but, maybe just easier293 for the user to reset it manually if really needed?294 */295 }296 private static void disableReferentialIntegrity(Statement s, DatabaseType type) throws SQLException {297 switch (type) {298 case POSTGRES:299 break;300 case MS_SQL_SERVER:301 //https://stackoverflow.com/questions/159038/how-can-foreign-key-constraints-be-temporarily-disabled-using-t-sql302 //https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813303 //https://docs.microsoft.com/en-us/sql/relational-databases/tables/disable-foreign-key-constraints-with-insert-and-update-statements?view=sql-server-ver15304 s.execute("EXEC sp_MSForEachTable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"");305 break;306 case H2:307 s.execute("SET REFERENTIAL_INTEGRITY FALSE");308 break;309 case MARIADB:310 case MYSQL:311 s.execute("SET @@foreign_key_checks = 0;");312 break;313 case OTHER:314 throw new DbUnsupportedException(type);315 }316 }317 private static void enableReferentialIntegrity(Statement s, DatabaseType type) throws SQLException {318 switch (type) {319 case POSTGRES:320 break;321 case MS_SQL_SERVER:322 s.execute("exec sp_MSForEachTable \"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"");323 break;324 case H2:325 /*326 For H2, we have to delete tables one at a time... but, to avoid issues327 with FKs, we must temporarily disable the integrity checks328 */329 s.execute("SET REFERENTIAL_INTEGRITY TRUE");330 break;331 case MARIADB:332 case MYSQL:333 s.execute("SET @@foreign_key_checks = 1;");334 break;335 case OTHER:336 throw new DbUnsupportedException(type);337 }338 }339 private static int getDefaultRetries(DatabaseType type) {340 switch (type) {341 case MS_SQL_SERVER:342 case POSTGRES:343 return 0;344 case H2:345 case MARIADB:346 case MYSQL:347 return 3;348 }349 throw new DbUnsupportedException(type);350 }351 private static String getDefaultSchema(DatabaseType type) {352 switch (type) {353 case H2:...
getDefaultRetries
Using AI Code Generation
1package org.evomaster.client.java.controller.db;2import com.foo.Bar;3import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;4import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;5import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;6import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;7import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;8import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;9import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;10import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexType;11import org.evomaster.client.java.controller.api.dto.database.schema.TableType;12import java.util.Arrays;13import java.util.Collections;14import java.util.List;15public class DbCleaner {16 private static final String DEFAULT_SCHEMA_NAME = "public";17 private static final String[] DEFAULT_TABLES_TO_IGNORE = new String[]{"flyway_schema_history"};18 private static final String[] DEFAULT_VIEWS_TO_IGNORE = new String[]{};19 private static final String[] DEFAULT_FUNCTIONS_TO_IGNORE = new String[]{};20 private static final String[] DEFAULT_SEQUENCES_TO_IGNORE = new String[]{};21 private static final String[] DEFAULT_TABLES_TO_KEEP = new String[]{};22 private static final String[] DEFAULT_VIEWS_TO_KEEP = new String[]{};23 private static final String[] DEFAULT_FUNCTIONS_TO_KEEP = new String[]{};24 private static final String[] DEFAULT_SEQUENCES_TO_KEEP = new String[]{};25 private static final String[] DEFAULT_TABLES_TO_TRUNCATE = new String[]{};26 private static final String[] DEFAULT_VIEWS_TO_TRUNCATE = new String[]{};27 private static final String[] DEFAULT_FUNCTIONS_TO_TRUNCATE = new String[]{};28 private static final String[] DEFAULT_SEQUENCES_TO_TRUNCATE = new String[]{};29 private static final String[] DEFAULT_TABLES_TO_DELETE = new String[]{};30 private static final String[] DEFAULT_VIEWS_TO_DELETE = new String[]{};31 private static final String[] DEFAULT_FUNCTIONS_TO_DELETE = new String[]{};32 private static final String[] DEFAULT_SEQUENCES_TO_DELETE = new String[]{};33 private static final String[] DEFAULT_TABLES_TO_CLEAR = new String[]{};34 private static final String[] DEFAULT_VIEWS_TO_CLEAR = new String[]{};
getDefaultRetries
Using AI Code Generation
1 public void test_0() throws Exception {2 final DbCleaner instance = new DbCleaner();3 final int result = instance.getDefaultRetries();4 Assert.assertEquals(0, result);5 }6 public void test_1() throws Exception {7 final DbCleaner instance = new DbCleaner();8 final int result = instance.getDefaultRetries();9 Assert.assertEquals(0, result);10 }11 public void test_2() throws Exception {12 final DbCleaner instance = new DbCleaner();13 final int result = instance.getDefaultRetries();14 Assert.assertEquals(0, result);15 }16 public void test_3() throws Exception {17 final DbCleaner instance = new DbCleaner();18 final int result = instance.getDefaultRetries();19 Assert.assertEquals(0, result);20 }21 public void test_4() throws Exception {22 final DbCleaner instance = new DbCleaner();23 final int result = instance.getDefaultRetries();24 Assert.assertEquals(0, result);25 }26 public void test_5() throws Exception {27 final DbCleaner instance = new DbCleaner();28 final int result = instance.getDefaultRetries();29 Assert.assertEquals(0, result);30 }31 public void test_6() throws Exception {32 final DbCleaner instance = new DbCleaner();33 final int result = instance.getDefaultRetries();34 Assert.assertEquals(0, result);35 }36 public void test_7() throws Exception {37 final DbCleaner instance = new DbCleaner();38 final int result = instance.getDefaultRetries();39 Assert.assertEquals(0, result);40 }41 public void test_8() throws Exception {
getDefaultRetries
Using AI Code Generation
1int retries = DbCleaner.getDefaultRetries();2DbCleaner.setDefaultRetries(2);3int retries = DbCleaner.getRetries();4DbCleaner.setRetries(2);5int waitTime = DbCleaner.getWaitTime();6DbCleaner.setWaitTime(1000);7DbCleaner.cleanDatabase();8DbCleaner.cleanDatabaseAndTables();9DbCleaner.cleanDatabaseAndTables("table1", "table2");10DbCleaner.cleanDatabaseAndTables(List.of("table1", "table2"));11DbCleaner.cleanDatabaseAndTables("table1", "table2", "table3");
getDefaultRetries
Using AI Code Generation
1int retries = DbCleaner.getDefaultRetries();2DbCleaner.setDefaultRetries(5);3DbCleaner.setMaxSqlLength(1000);4DbCleaner.setMaxSqlExecutionTime(1000);5DbCleaner.setMaxSqlExecutionTime(1000);6DbCleaner.setMaxSqlExecutionTime(1000);7DbCleaner.setMaxSqlExecutionTime(1000);8DbCleaner.setMaxSqlExecutionTime(1000);9DbCleaner.setMaxSqlExecutionTime(1000);10DbCleaner.setMaxSqlExecutionTime(1000);11DbCleaner.setMaxSqlExecutionTime(1000);12DbCleaner.setMaxSqlExecutionTime(
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!