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

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

Source:DbCleaner.java Github

copy

Full Screen

...89 */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){254 if(type != DatabaseType.MS_SQL_SERVER)255 throw new IllegalArgumentException("getAllTableHasIdentify only supports for MS_SQL_SERVER, not for "+type);256 return getAllTableCommand(type, schema) + " AND OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1";257 }258 private static String getAllTableCommand(DatabaseType type, String schema) {259 String command = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where (TABLE_TYPE='TABLE' OR TABLE_TYPE='BASE TABLE')";260 switch (type){261 // https://stackoverflow.com/questions/175415/how-do-i-get-list-of-all-tables-in-a-database-using-tsql, TABLE_CATALOG='"+dbname+"'"262 case MS_SQL_SERVER:263 // for MySQL, schema is dbname264 case MYSQL:265 case MARIADB:266 case H2:267 case POSTGRES:268 if (schema.isEmpty())269 return command;270 return command + " AND TABLE_SCHEMA='" + schema +"'";271 }272 throw new DbUnsupportedException(type);273// case MS_SQL_SERVER_2000:274// return "SELECT sobjects.name FROM sysobjects sobjects WHERE sobjects.xtype = '"+schema+"'"; // shcema can be 'U'275 }276 private static String getAllSequenceCommand(DatabaseType type, String schemaName) {277 String command = "SELECT SEQUENCE_NAME FROM INFORMATION_SCHEMA.SEQUENCES";278 switch (type){279 case MYSQL:280 case MARIADB: return getAllTableCommand(type, schemaName);281 case H2:282 case POSTGRES:283 //https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/sequences-transact-sql?view=sql-server-ver15284 case MS_SQL_SERVER:285 if (schemaName.isEmpty())286 return command;287 else288 return command + " WHERE SEQUENCE_SCHEMA='" + schemaName + "'";289 }290 throw new DbUnsupportedException(type);291 }292 private static String resetSequenceCommand(String sequence, DatabaseType type) {293 switch (type){294 case MARIADB:...

Full Screen

Full Screen

getAllTableCommand

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.db.DbCleaner2import org.evomaster.client.java.controller.db.SqlScriptRunner3import org.evomaster.client.java.controller.db.SqlScriptRunnerImpl4import org.evomaster.client.java.controller.db.TableCommand5import org.evomaster.client.java.controller.internal.db.h2.H2Controller6val dbController = H2Controller()7fun init() {8 val runner: SqlScriptRunner = SqlScriptRunnerImpl(dbController)9 runner.executeSqlScript("CREATE TABLE IF NOT EXISTS test_table (id INT, name VARCHAR(100), PRIMARY KEY(id))")10 runner.executeSqlScript("INSERT INTO test_table VALUES (1, 'John')")11 runner.executeSqlScript("INSERT INTO test_table VALUES (2, 'Mary')")12 runner.executeSqlScript("INSERT INTO test_table VALUES (3, 'Peter')")13}14fun test() {15 val cleaner = DbCleaner(dbController)16 val commands = cleaner.getAllTableCommand("test_table")17 assertEquals(3, commands.size)18 val command1 = TableCommand("test_table", "DELETE FROM test_table WHERE id = 1")19 val command2 = TableCommand("test_table", "DELETE FROM test_table WHERE id = 2")20 val command3 = TableCommand("test_table", "DELETE FROM test_table WHERE id = 3")21 assertTrue(commands.contains(command1))22 assertTrue(commands.contains(command2))23 assertTrue(commands.contains(command3))24}25fun tearDown() {26 val runner: SqlScriptRunner = SqlScriptRunnerImpl(dbController)27 runner.executeSqlScript("DROP TABLE test_table")28}

Full Screen

Full Screen

getAllTableCommand

Using AI Code Generation

copy

Full Screen

1@DisplayName("Test for getAllTableCommand method of DbCleaner class")2class DbCleanerTest {3 @DisplayName("Test for getAllTableCommand method")4 void getAllTableCommandTest() {5 String expected = "SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'";6 String actual = DbCleaner.getAllTableCommand();7 assertEquals(expected, actual);8 }9}10@DisplayName("Test for getDeleteAllCommand method of DbCleaner class")11class DbCleanerTest {12 @DisplayName("Test for getDeleteAllCommand method")13 void getDeleteAllCommandTest() {14 String expected = "DELETE FROM ";15 String actual = DbCleaner.getDeleteAllCommand();16 assertEquals(expected, actual);17 }18}19@DisplayName("Test for getDropTableCommand method of DbCleaner class")20class DbCleanerTest {21 @DisplayName("Test for getDropTableCommand method")22 void getDropTableCommandTest() {23 String expected = "DROP TABLE ";24 String actual = DbCleaner.getDropTableCommand();25 assertEquals(expected, actual);26 }27}28@DisplayName("Test for getDeleteTableCommand method of DbCleaner class")29class DbCleanerTest {30 @DisplayName("Test for getDeleteTableCommand method")31 void getDeleteTableCommandTest() {32 String expected = "DELETE FROM ";33 String actual = DbCleaner.getDeleteTableCommand();34 assertEquals(expected, actual);35 }36}37@DisplayName("Test for getTruncateTableCommand method of DbCleaner class")38class DbCleanerTest {39 @DisplayName("Test for getTruncateTableCommand method")40 void getTruncateTableCommandTest() {41 String expected = "TRUNCATE TABLE ";42 String actual = DbCleaner.getTruncateTableCommand();43 assertEquals(expected, actual);44 }45}

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