How to use getDefaultSchema method of org.evomaster.client.java.controller.db.DbCleaner class

Best EvoMaster code snippet using org.evomaster.client.java.controller.db.DbCleaner.getDefaultSchema

Source:DbCleaner.java Github

copy

Full Screen

...16 public static void clearDatabase_H2(Connection connection) {17 clearDatabase_H2(connection, null);18 }19 public static void clearDatabase_H2(Connection connection, List<String> tablesToSkip) {20 clearDatabase_H2(connection, getDefaultSchema(DatabaseType.H2), tablesToSkip);21 }22 public static void clearDatabase_H2(Connection connection, String schemaName, List<String> tablesToSkip) {23 clearDatabase(getDefaultReties(DatabaseType.H2), connection, schemaName, tablesToSkip, DatabaseType.H2, false);24 }25 /*26 [non-determinism-source] Man: retries might lead to non-determinate logs27 */28 private static void clearDatabase(int retries, Connection connection, String schemaName, List<String> tablesToSkip, DatabaseType type, boolean doDropTable) {29 /*30 Code based on31 https://stackoverflow.com/questions/8523423/reset-embedded-h2-database-periodically32 */33 try {34 Statement statement = connection.createStatement();35 /*36 For H2, we have to delete tables one at a time... but, to avoid issues37 with FKs, we must temporarily disable the integrity checks38 */39 disableReferentialIntegrity(statement, type);40 cleanDataInTables(tablesToSkip, statement, type, schemaName, isSingleCleanCommand(type), doDropTable);41 resetSequences(statement, type, schemaName);42 enableReferentialIntegrity(statement, type);43 statement.close();44 } catch (Exception e) {45 /*46 this could happen if there is a current transaction with a lock on any table.47 We could check the content of INFORMATION_SCHEMA.LOCKS, or simply look at error message48 */49 String msg = e.getMessage();50 if(msg != null && msg.toLowerCase().contains("timeout")){51 if(retries > 0) {52 SimpleLogger.warn("Timeout issue with cleaning DB. Trying again.");53 //let's just wait a bit, and retry54 try {55 Thread.sleep(2000);56 } catch (InterruptedException interruptedException) {57 }58 retries--;59 clearDatabase(retries, connection, schemaName, tablesToSkip, type, doDropTable);60 } else {61 SimpleLogger.error("Giving up cleaning the DB. There are still timeouts.");62 }63 }64 throw new RuntimeException(e);65 }66 }67 public static void clearDatabase(Connection connection, List<String> tablesToSkip, DatabaseType type){68 clearDatabase(connection, getDefaultSchema(type), tablesToSkip, type);69 }70 public static void clearDatabase(Connection connection, String schemaName, List<String> tablesToSkip, DatabaseType type){71 clearDatabase(getDefaultReties(type), connection, schemaName, tablesToSkip, type, false);72 }73 public static void dropDatabaseTables(Connection connection, String schemaName, List<String> tablesToSkip, DatabaseType type){74 if (type != DatabaseType.MYSQL && type != DatabaseType.MARIADB)75 throw new IllegalArgumentException("Dropping tables are not supported by "+type);76 clearDatabase(getDefaultReties(type), connection, schemaName, tablesToSkip, type, true);77 }78 public static void clearDatabase_Postgres(Connection connection, String schemaName, List<String> tablesToSkip ) {79 clearDatabase(getDefaultReties(DatabaseType.POSTGRES), connection, schemaName, tablesToSkip, DatabaseType.POSTGRES, false);80 }81 /**82 *83 * @param tablesToSkip are tables to be skipped84 * @param statement is to execute the SQL command85 * @param schema specify the schema of data to clean. if [schema] is empty, all data will be cleaned.86 * @param singleCommand specify whether to execute the SQL commands (e.g., truncate table/tables) by single command87 * @param doDropTable specify whether to drop tables which is only for MySQL and MariaDB now.88 * @throws SQLException are exceptions during sql execution89 */90 private static void cleanDataInTables(List<String> tablesToSkip, Statement statement, DatabaseType type, String schema, boolean singleCommand, boolean doDropTable) throws SQLException {91 // Find all tables and truncate them92 Set<String> tables = new HashSet<>();93 ResultSet rs = statement.executeQuery(getAllTableCommand(type, schema));94 while (rs.next()) {95 tables.add(rs.getString(1));96 }97 rs.close();98 if (tables.isEmpty()) {99 throw new IllegalStateException("Could not find any table");100 }101 if (tablesToSkip != null) {102 for (String skip : tablesToSkip) {103 if (!tables.stream().anyMatch(t -> t.equalsIgnoreCase(skip))) {104 String msg = "Asked to skip table '" + skip + "', but it does not exist.";105 msg += " Existing tables in schema '"+schema+"': [" +106 tables.stream().collect(Collectors.joining(", ")) + "]";107 throw new IllegalStateException(msg);108 }109 }110 }111 Set<String> tablesHaveIdentifies = new HashSet<>();112 if (type == DatabaseType.MS_SQL_SERVER){113 ResultSet rst = statement.executeQuery(getAllTableHasIdentify(type, schema));114 while (rst.next()) {115 tablesHaveIdentifies.add(rst.getString(1));116 }117 rst.close();118 }119 List<String> tablesToClear = tables.stream()120 .filter(n -> tablesToSkip == null || tablesToSkip.isEmpty() ||121 !tablesToSkip.stream().anyMatch(skip -> skip.equalsIgnoreCase(n)))122 .collect(Collectors.toList());123 if (singleCommand) {124 String ts = tablesToClear.stream()125 .sorted()126 .collect(Collectors.joining(","));127 if (type != DatabaseType.POSTGRES)128 throw new IllegalArgumentException("do not support for cleaning all data by one single command for " +type);129 if (doDropTable)130 dropTables(statement, ts);131 else{132 statement.executeUpdate("TRUNCATE TABLE " + ts);133 }134 } else {135 //note: if one at a time, need to make sure to first disable FK checks136 for(String t : tablesToClear){137 if (doDropTable)138 dropTables(statement, t);139 else{140 /*141 for MS_SQL_SERVER, we cannot use truncate tables if there exist fk142 see143 https://docs.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql?view=sql-server-ver15#restrictions144 https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813145 then it will cause a problem to reset identify146 */147 if (type == DatabaseType.MS_SQL_SERVER)148 deleteTables(statement, t, tablesHaveIdentifies);149 else150 truncateTables(statement, t);151 }152 }153 }154 }155 private static void dropTables(Statement statement, String table) throws SQLException {156 statement.executeUpdate("DROP TABLE IF EXISTS " +table);157 }158 private static void deleteTables(Statement statement, String table, Set<String> tableHasIdentify) throws SQLException {159 statement.executeUpdate("DELETE FROM "+table);160// NOTE TAHT ideally we should reseed identify here, but there would case an issue, i.e., does not contain an identity column161 if (tableHasIdentify.contains(table))162 statement.executeUpdate("DBCC CHECKIDENT ('"+table+"', RESEED, 0)");163 }164 private static void truncateTables(Statement statement, String table) throws SQLException {165 statement.executeUpdate("TRUNCATE TABLE " + table);166 }167 private static void resetSequences(Statement s, DatabaseType type, String schemaName) throws SQLException {168 ResultSet rs;// Idem for sequences169 Set<String> sequences = new HashSet<>();170 rs = s.executeQuery(getAllSequenceCommand(type, schemaName));171 while (rs.next()) {172 sequences.add(rs.getString(1));173 }174 rs.close();175 for (String seq : sequences) {176 s.executeUpdate(resetSequenceCommand(seq, type));177 }178 /*179 Note: we reset all sequences from 1. But the original database might180 have used a different value.181 In most cases (99.99%), this should not be a problem.182 We could allow using different values in this API... but, maybe just easier183 for the user to reset it manually if really needed?184 */185 }186 private static void disableReferentialIntegrity(Statement s, DatabaseType type) throws SQLException {187 switch (type)188 {189 case POSTGRES: break;190 case MS_SQL_SERVER:191 //https://stackoverflow.com/questions/159038/how-can-foreign-key-constraints-be-temporarily-disabled-using-t-sql192 //https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813193 //https://docs.microsoft.com/en-us/sql/relational-databases/tables/disable-foreign-key-constraints-with-insert-and-update-statements?view=sql-server-ver15194 s.execute("EXEC sp_MSForEachTable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"");195 break;196 case H2:197 s.execute("SET REFERENTIAL_INTEGRITY FALSE");198 break;199 case MARIADB:200 case MYSQL:201 s.execute("SET @@foreign_key_checks = 0;");202 break;203 case OTHER:204 throw new DbUnsupportedException(type);205 }206 }207 private static void enableReferentialIntegrity(Statement s, DatabaseType type) throws SQLException {208 switch (type)209 {210 case POSTGRES: break;211 case MS_SQL_SERVER:212 s.execute("exec sp_MSForEachTable \"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"");213 break;214 case H2:215 /*216 For H2, we have to delete tables one at a time... but, to avoid issues217 with FKs, we must temporarily disable the integrity checks218 */219 s.execute( "SET REFERENTIAL_INTEGRITY TRUE");220 break;221 case MARIADB:222 case MYSQL:223 s.execute("SET @@foreign_key_checks = 1;");224 break;225 case OTHER:226 throw new DbUnsupportedException(type);227 }228 }229 private static int getDefaultReties(DatabaseType type){230 switch (type){231 case MS_SQL_SERVER:232 case POSTGRES: return 0;233 case H2:234 case MARIADB:235 case MYSQL: return 3;236 }237 throw new DbUnsupportedException(type);238 }239 private static String getDefaultSchema(DatabaseType type){240 switch (type){241 case H2: return "PUBLIC";242 //https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/ownership-and-user-schema-separation-in-sql-server243 case MS_SQL_SERVER: return "dbo";244 case MARIADB:245 case MYSQL: throw new IllegalArgumentException("there is no default schema for "+type+", and you must specify a db name here");246 case POSTGRES: return "public";247 }248 throw new DbUnsupportedException(type);249 }250 private static boolean isSingleCleanCommand(DatabaseType type){251 return type == DatabaseType.POSTGRES;252 }253 private static String getAllTableHasIdentify(DatabaseType type, String schema){...

Full Screen

Full Screen

getDefaultSchema

Using AI Code Generation

copy

Full Screen

1String schema = DbCleaner.getDefaultSchema();2String query = "SELECT * FROM " + schema + ".\"MyTable\"";3ResultSet rs = statement.executeQuery(query);4String schema = DbCleaner.getDefaultSchema();5String query = "SELECT * FROM " + schema + ".\"MyTable\"";6ResultSet rs = statement.execute(query);7String schema = DbCleaner.getDefaultSchema();8String query = "SELECT * FROM " + schema + ".\"MyTable\"";9ResultSet rs = statement.executeUpdate(query);10String schema = DbCleaner.getDefaultSchema();11String query = "SELECT * FROM " + schema + ".\"MyTable\"";12ResultSet rs = statement.executeQuery(query);13String schema = DbCleaner.getDefaultSchema();14String query = "SELECT * FROM " + schema + ".\"MyTable\"";15ResultSet rs = statement.execute(query);

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful