How to use mergeNewData method of org.evomaster.client.java.controller.internal.db.SqlHandler class

Best EvoMaster code snippet using org.evomaster.client.java.controller.internal.db.SqlHandler.mergeNewData

Source:SqlHandler.java Github

copy

Full Screen

...70 return;71 }72 buffer.add(sql);73 if (isSelect(sql)) {74 mergeNewData(queriedData, ColumnTableAnalyzer.getSelectReadDataFields(sql));75 } else if(isDelete(sql)){76 deletedData.addAll(ColumnTableAnalyzer.getDeletedTables(sql));77 } else if(isInsert(sql)){78 mergeNewData(insertedData, ColumnTableAnalyzer.getInsertedDataFields(sql));79 } else if(isUpdate(sql)){80 mergeNewData(updatedData, ColumnTableAnalyzer.getUpdatedDataFields(sql));81 }82 numberOfSqlCommands++;83 }84 public ExecutionDto getExecutionDto() {85 if(!calculateHeuristics && !extractSqlExecution){86 return null;87 }88 ExecutionDto executionDto = new ExecutionDto();89 executionDto.queriedData.putAll(queriedData);90 executionDto.failedWhere.putAll(failedWhere);91 executionDto.insertedData.putAll(insertedData);92 executionDto.updatedData.putAll(updatedData);93 executionDto.deletedData.addAll(deletedData);94 executionDto.numberOfSqlCommands = this.numberOfSqlCommands;95 return executionDto;96 }97 public List<PairCommandDistance> getDistances() {98 if (connection == null || !calculateHeuristics) {99 return distances;100 }101 buffer.stream()102 .forEach(sql -> {103 /*104 Note: even if the Connection we got to analyze105 the DB is using P6Spy, that would not be a problem,106 as output SQL would not end up on the buffer instance107 we are iterating on (copy on write), and we clear108 the buffer after this loop.109 */110 if (isSelect(sql) || isDelete(sql) || isUpdate(sql)) {111 double dist = computeDistance(sql);112 distances.add(new PairCommandDistance(sql, dist));113 }114 });115 //side effects on buffer is not important, as it is just a cache116 buffer.clear();117 return distances;118 }119 private Double computeDistance(String command) {120 if (connection == null) {121 throw new IllegalStateException("Trying to calculate SQL distance with no DB connection");122 }123 Statement statement;124 try {125 statement = CCJSqlParserUtil.parse(command);126 } catch (Exception e) {127 SimpleLogger.uniqueWarn("Cannot handle command: " + command + "\n" + e.toString());128 return Double.MAX_VALUE;129 }130 Map<String, Set<String>> columns = extractColumnsInvolvedInWhere(statement);131 /*132 even if columns.isEmpty(), we need to check if any data was present133 */134 double dist;135 if(columns.isEmpty()){136 //TODO check if table(s) not empty, and give >0 otherwise137 dist = 0;138 } else {139 dist = getDistanceForWhere(command, columns);140 }141 if (dist > 0) {142 mergeNewData(failedWhere, columns);143 }144 return dist;145 }146 private double getDistanceForWhere(String command, Map<String, Set<String>> columns) {147 String select;148 /*149 TODO:150 this might be likely unnecessary... we are only interested in the variables used151 in the WHERE. Furthermore, this would not support DELETE/INSERT/UPDATE.152 So, we just need to create a new SELECT based on that.153 But SELECT could be complex with many JOINs... whereas DIP would be simple(r)?154 TODO: we need a general solution155 */156 if(isSelect(command)) {157 select = SelectTransformer.addFieldsToSelect(command);158 select = SelectTransformer.removeConstraints(select);159 select = SelectTransformer.removeOperations(select);160 } else {161 if(columns.size() > 1){162 SimpleLogger.uniqueWarn("Cannot analyze: " + command);163 }164 Map.Entry<String, Set<String>> mapping = columns.entrySet().iterator().next();165 select = createSelectForSingleTable(mapping.getKey(), mapping.getValue());166 }167 QueryResult data;168 try {169 data = SqlScriptRunner.execCommand(connection, select);170 } catch (SQLException e) {171 throw new RuntimeException(e);172 }173 return HeuristicsCalculator.computeDistance(command, data);174 }175 private String createSelectForSingleTable(String tableName, Set<String> columns){176 StringBuilder buffer = new StringBuilder();177 buffer.append("SELECT ");178 String variables = columns.stream().collect(Collectors.joining(", "));179 buffer.append(variables);180 buffer.append(" FROM ");181 buffer.append(tableName);182 return buffer.toString();183 }184 /**185 * Check the fields involved in the WHERE clause (if any).186 * Return a map from table name to column names of the involved fields.187 */188 public static Map<String, Set<String>> extractColumnsInvolvedInWhere(Statement statement) {189 /*190 TODO191 following does not handle the case of sub-selects involving other192 tables... but likely that is not something we need to support right now193 */194 Map<String, Set<String>> data = new HashMap<>();195 SqlNameContext context = new SqlNameContext(statement);196 Expression where = ParserUtils.getWhere(statement);197 if (where == null) {198 return data;199 }200 ExpressionVisitor visitor = new ExpressionVisitorAdapter() {201 @Override202 public void visit(Column column) {203 String cn = column.getColumnName();204 if(cn.equals("false")){205 /*206 This is a bug in the JsqlParser library. Until we upgrade it, or fix it if not fixed yet,207 we use this workaround.208 TODO remove it once library upgraded/fixed209 */210 return;211 }212 String tn = context.getTableName(column);213 if(tn.equalsIgnoreCase(SqlNameContext.UNNAMED_TABLE)){214 // TODO handle it properly when ll have support for sub-selects215 return;216 }217 data.putIfAbsent(tn, new HashSet<>());218 Set<String> set = data.get(tn);219 set.add(cn);220 }221 };222 where.accept(visitor);223 return data;224 }225 private static void mergeNewData(226 Map<String, Set<String>> current,227 Map<String, Set<String>> toAdd228 ) {229 for (Map.Entry<String, Set<String>> e : toAdd.entrySet()) {230 String key = e.getKey();231 Set<String> values = e.getValue();232 Set<String> existing = current.get(key);233 if (existing != null && existing.contains("*")) {234 //nothing to do235 continue;236 }237 if (existing == null) {238 existing = new HashSet<>(values);239 current.put(key, existing);...

Full Screen

Full Screen

mergeNewData

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto2import org.evomaster.client.java.controller.api.dto.database.operations.InsertionEntryDto3import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType4import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto5import org.evomaster.client.java.controller.api.dto.database.schema.TableDto6import org.evomaster.client.java.controller.api.dto.database.schema.TableEntryDto7import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto8import org.evomaster.client.java.controller.api.dto.database.schema.TableForeignKeyDto9import org.evomaster.client.java.controller.api.dto.database.operations.DeleteionDto10import org.evomaster.client.java.controller.api.dto.database.operations.DeleteionEntryDto11import org.evomaster.client.java.controller.api.dto.database.operations.UpdateDto

Full Screen

Full Screen

mergeNewData

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.internal.db.SqlHandler;2import java.sql.Connection;3import java.sql.DriverManager;4import java.sql.SQLException;5import java.util.List;6public class SqlHandlerExample {7 public static void main(String[] args) throws SQLException {8 List<String> sqlLines = List.of("INSERT INTO users (id, name) VALUES (1, 'foo')");9 try (Connection con = DriverManager.getConnection("jdbc:h2:mem:test")) {10 SqlHandler handler = new SqlHandler(con);11 handler.executeSqls(sqlLines);12 handler.mergeNewData();13 }14 }15}16import org.evomaster.client.java.controller.internal.db.SqlHandler;17import java.sql.Connection;18import java.sql.DriverManager;19import java.sql.SQLException;20import java.util.List;21public class SqlHandlerExample {22 public static void main(String[] args) throws SQLException {23 List<String> sqlLines = List.of("INSERT INTO users (id, name) VALUES (1, 'foo')");24 try (Connection con = DriverManager.getConnection("jdbc:h2:mem:test")) {25 SqlHandler handler = new SqlHandler(con);26 handler.executeSqls(sqlLines);27 handler.mergeNewData();28 }29 }30}31import org.evomaster.client.java.controller.internal.db.SqlHandler;32import java.sql.Connection;33import java.sql.DriverManager;34import java.sql.SQLException;35import java.util.List;36public class SqlHandlerExample {37 public static void main(String[] args) throws SQLException {38 List<String> sqlLines = List.of("INSERT INTO users (id, name) VALUES (1, 'foo')");39 try (Connection con = DriverManager.getConnection("jdbc:h2:mem:test")) {40 SqlHandler handler = new SqlHandler(con);41 handler.executeSqls(sqlLines);42 handler.mergeNewData();43 }44 }45}46import org.evomaster.client.java.controller.internal.db.SqlHandler;47import java.sql.Connection;48import java.sql.DriverManager;49import java.sql.SQLException;50import java.util.List;51public class SqlHandlerExample {52 public static void main(String[] args) throws SQLException {53 List<String> sqlLines = List.of("INSERT INTO

Full Screen

Full Screen

mergeNewData

Using AI Code Generation

copy

Full Screen

1 public void testMergeNewData() throws Exception {2 SqlScriptExecutor sqlScriptExecutor = new SqlScriptExecutor();3 sqlScriptExecutor.setDatabaseDriver(Driver.class.getCanonicalName());4 sqlScriptExecutor.setDatabaseUser("postgres");5 sqlScriptExecutor.setDatabasePassword("postgres");6 sqlScriptExecutor.setDatabaseSchema("public");7 sqlScriptExecutor.setSqlInitializationFile("sql/initialization.sql");8 sqlScriptExecutor.setSqlInsertionFile("sql/insertion.sql");9 sqlScriptExecutor.setSqlResetFile("sql/reset.sql");10 sqlScriptExecutor.setSqlDroppingFile("sql/dropping.sql");11 sqlScriptExecutor.setSqlScriptExecutorType(SqlScriptExecutorType.POSTGRES);12 sqlScriptExecutor.setSqlScriptExecutorMode(SqlScriptExecutorMode.CREATE_AND_INSERT);13 sqlScriptExecutor.init();14 String sql = "INSERT INTO public.\"User\" (username, password, email, firstname, lastname) VALUES ('user', 'password', '

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