Best EvoMaster code snippet using org.evomaster.client.java.controller.internal.db.ParserUtils
Source:HeuristicsCalculator.java
...15import java.time.format.DateTimeFormatterBuilder;16import java.time.format.DateTimeParseException;17import java.util.Locale;18import java.util.Objects;19import static org.evomaster.client.java.controller.internal.db.ParserUtils.getWhere;20public class HeuristicsCalculator {21 private final SqlNameContext context;22 public HeuristicsCalculator(SqlNameContext context) {23 this.context = Objects.requireNonNull(context);24 }25 public static double computeDistance(String statement, QueryResult data) {26 if (data.isEmpty()) {27 //if no data, we have no info whatsoever28 return Double.MAX_VALUE;29 }30 Statement stmt = ParserUtils.asStatement(statement);31 Expression where = getWhere(stmt);32 if (where == null) {33 //no constraint, and at least one data point34 return 0;35 }36 SqlNameContext context = new SqlNameContext(stmt);37 HeuristicsCalculator calculator = new HeuristicsCalculator(context);38 double min = Double.MAX_VALUE;39 for (DataRow row : data.seeRows()) {40 double dist = calculator.computeExpression(where, row);41 if (dist == 0) {42 return 0;43 }44 if (dist < min) {...
Source:SqlHandler.java
...14import java.util.*;15import java.util.concurrent.ConcurrentHashMap;16import java.util.concurrent.CopyOnWriteArrayList;17import java.util.stream.Collectors;18import static org.evomaster.client.java.controller.internal.db.ParserUtils.*;19/**20 * Class used to act upon SQL commands executed by the SUT21 */22public class SqlHandler {23 /**24 * Computing heuristics on SQL is expensive, as we need to run25 * further queries. So, we buffer them, and execute them only26 * if needed (ie, lazy initialization)27 */28 private final List<String> buffer;29 /**30 * The heuristics based on the SQL execution31 */32 private final List<PairCommandDistance> distances;33 //see ExecutionDto34 private final Map<String, Set<String>> queriedData;35 private final Map<String, Set<String>> updatedData;36 private final Map<String, Set<String>> insertedData;37 private final Map<String, Set<String>> failedWhere;38 private final List<String> deletedData;39 private int numberOfSqlCommands;40 private volatile Connection connection;41 private volatile boolean calculateHeuristics;42 private volatile boolean extractSqlExecution;43 public SqlHandler() {44 buffer = new CopyOnWriteArrayList<>();45 distances = new ArrayList<>();46 queriedData = new ConcurrentHashMap<>();47 updatedData = new ConcurrentHashMap<>();48 insertedData = new ConcurrentHashMap<>();49 failedWhere = new ConcurrentHashMap<>();50 deletedData = new CopyOnWriteArrayList<>();51 calculateHeuristics = true;52 numberOfSqlCommands = 0;53 }54 public void reset() {55 buffer.clear();56 distances.clear();57 queriedData.clear();58 updatedData.clear();59 insertedData.clear();60 failedWhere.clear();61 deletedData.clear();62 numberOfSqlCommands = 0;63 }64 public void setConnection(Connection connection) {65 this.connection = connection;66 }67 public void handle(String sql) {68 Objects.requireNonNull(sql);69 if(!calculateHeuristics && !extractSqlExecution){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 private 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 String tn = context.getTableName(column);205 if(tn.equalsIgnoreCase(SqlNameContext.UNNAMED_TABLE)){206 // TODO handle it properly when ll have support for sub-selects207 return;208 }209 data.putIfAbsent(tn, new HashSet<>());210 Set<String> set = data.get(tn);...
ParserUtils
Using AI Code Generation
1import org.evomaster.client.java.controller.internal.db.ParserUtils;2import org.evomaster.client.java.controller.internal.db.SqlScriptRunner;3import org.evomaster.client.java.controller.internal.db.SqlScriptRunnerException;4import org.evomaster.client.java.controller.internal.db.SqlScriptRunnerResult;5import org.evomaster.client.java.controller.internal.db.schema.Table;6import org.evomaster.client.java.controller.internal.db.schema.TableColumn;7import org.evomaster.client.java.controller.internal.db.schema.TableIndex;8import org.evomaster.client.java.controller.internal.db.schema.TableUniqueIndex;9import org.evomaster.client.java.controller.internal.db.schema.TableForeignKey;10import org.evomaster.client.java.controller.internal.db.schema.TableCheck;11import org.evomaster.client.java.controller.internal.db.schema.TableTrigger;12import org.evomaster.client.java.controller.internal.db.schema.TableSchema;13import org.evomaster.client.java.controller.internal.db.schema.TableSchemaException;14import org.evomaster.client.java.controller.internal.db.h2.H2Table;15import org.evomaster.client.java.controller.internal.db.h2.H2TableColumn;16import org.evomaster.client.java.controller.internal.db.h2.H2TableIndex;17import org.evomaster.client.java.controller.internal.db.h2.H2TableUniqueIndex;18import org.evomaster.client.java.controller.internal.db.h2.H2TableForeignKey;19import org.evomaster.client.java.controller.internal.db.h2.H2TableCheck;20import org.evomaster.client.java.controller.internal.db.h2.H2TableTrigger;21import org.evomaster.client.java.controller.internal.db.h2.H2TableSchema;22import org.evomaster.client.java.controller.internal.db.h2.H2TableSchemaException;23import org.evomaster.client.java.controller.internal.db.h2.H2TableSchemaParser;24import org.evomaster.client.java.controller.internal.db.h2.H2TableSchemaParserException;25import org.evomaster.client.java.controller.internal.db.h2.H2TableSchemaParserResult;26import org.evomaster.client.java.controller.internal.db.h2.H2TableSchemaParserUtils;27import org.evomaster.client.java.controller.internal.db.h2.H2TableSchemaParserUtilsException;28import org.evomaster.client.java.controller.internal.db.h2.H2TableSchemaParserUtilsResult;29import java.sql.Connection;30import java.sql.DriverManager;31import java.sql.SQLException;32import java.sql.Statement;33import java.util.List;34import
ParserUtils
Using AI Code Generation
1import org.evomaster.client.java.controller.internal.db.ParserUtils;2public class 3 {3 public static void main(String[] args) throws Exception {4 ParserUtils utils = new ParserUtils();5 String sql = "SELECT * FROM users WHERE id = ? AND name = ? AND surname = ? AND age = ? AND email = ? AND password = ?";6 List<String> parameters = Arrays.asList("1", "John", "Smith", "18", "
ParserUtils
Using AI Code Generation
1import org.evomaster.client.java.controller.internal.db.ParserUtils;2public class 3 {3 public static void main(String[] args) {4 String s = "2018-01-01";5 ParserUtils.parseDate(s);6 }7}8import org.evomaster.client.java.controller.internal.db.ParserUtils;9public class 4 {10 public static void main(String[] args) {11 String s = "2018-01-01";12 ParserUtils.parseTime(s);13 }14}15import org.evomaster.client.java.controller.internal.db.ParserUtils;16public class 5 {17 public static void main(String[] args) {18 String s = "2018-01-01";19 ParserUtils.parseDateTime(s);20 }21}22import org.evomaster.client.java.controller.internal.db.ParserUtils;23public class 6 {24 public static void main(String[] args) {25 String s = "2018-01-01";26 ParserUtils.parseTimestamp(s);27 }28}29import org.evomaster.client.java.controller.internal.db.ParserUtils;30public class 7 {31 public static void main(String[] args) {32 String s = "2018-01-01";33 ParserUtils.parseTimestamp(s);34 }35}36import org.evomaster.client.java.controller.internal.db.ParserUtils;37public class 8 {38 public static void main(String[] args) {39 String s = "2018-01-01";40 ParserUtils.parseTimestamp(s);41 }42}43import org.evomaster.client.java.controller.internal.db.ParserUtils;44public class 9 {45 public static void main(String[] args) {46 String s = "2018-01-01";
ParserUtils
Using AI Code Generation
1import org.evomaster.client.java.controller.internal.db.ParserUtils;2import java.sql.ResultSet;3import java.sql.SQLException;4public class 3 {5 public static void main(String[] args) throws SQLException {6 String input = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";7 ResultSet rs = ParserUtils.parseResultSet(input);8 while(rs.next()) {9 System.out.println(rs.getString(1));10 }11 }12}13import org.evomaster.client.java.controller.internal.db.ParserUtils;14import java.sql.ResultSet;15import java.sql.SQLException;16public class 4 {17 public static void main(String[] args) throws SQLException {18 String input = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";19 ResultSet rs = ParserUtils.parseResultSet(input);20 while(rs.next()) {21 System.out.println(rs.getString(1));22 }23 }24}25import org.evomaster.client.java.controller.internal.db.ParserUtils;26import java.sql.ResultSet;27import java.sql.SQLException;28public class 5 {29 public static void main(String[] args) throws SQLException {30 String input = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";31 ResultSet rs = ParserUtils.parseResultSet(input);32 while(rs.next()) {33 System.out.println(rs.getString(1));34 }35 }36}37import org.evomaster.client.java.controller.internal.db.ParserUtils;38import java.sql.ResultSet;39import java.sql.SQLException;40public class 6 {41 public static void main(String[] args) throws SQLException {
ParserUtils
Using AI Code Generation
1public class 3 {2 public static void main(String[] args) {3 ParserUtils parser = new ParserUtils();4 parser.parse("select * from table1");5 }6}7package org.evomaster.client.java.controller.internal.db;8import java.util.ArrayList;9import java.util.Arrays;10import java.util.List;11import java.util.regex.Matcher;12import java.util.regex.Pattern;13public class ParserUtils {14 public ParserUtils() {15 }16 public void parse(String query){17 String selectRegEx = "(?i)select\\s+((?:\\*|\\s*\\w+\\s*(?:,\\s*\\w+\\s*)*))\\s+(?:from\\s+((?:\\s*\\w+\\s*(?:,\\s*\\w+\\s*)*)))";18 String insertRegEx = "(?i)insert\\s+into\\s+((?:\\s*\\w+\\s*(?:,\\s*\\w+\\s*)*))\\s+values\\s+((?:\\s*\\w+\\s*(?:,\\s*\\w+\\s*)*))";19 String updateRegEx = "(?i)update\\s+((?:\\s*\\w+\\s*(?:,\\s*\\w+\\s*)*))\\s+set\\s+((?:\\s*\\w+\\s*(?:,\\s*\\w+\\s*)*))";20 String deleteRegEx = "(?i)delete\\s+(?:from\\s+((?:\\s*\\w+\\s*(?:,\\s*\\w+\\s*)*)))";21 List<String> regexList = new ArrayList<>(Arrays.asList(selectRegEx, insertRegEx, updateRegEx, deleteRegEx));22 List<String> queryTypeList = new ArrayList<>(Arrays.asList("select", "insert", "update", "delete"));
ParserUtils
Using AI Code Generation
1public class 3 {2 public static void main(String[] args) {3 String sql = "SELECT * FROM table1 WHERE id = 1";4 ParserUtils parserUtils = new ParserUtils();5 List<String> tables = parserUtils.extractTables(sql);6 System.out.println(tables);7 }8}9public class 4 {10 public static void main(String[] args) {11 String sql = "SELECT * FROM table1 WHERE id = 1";12 ParserUtils parserUtils = new ParserUtils();13 List<String> columns = parserUtils.extractColumns(sql);14 System.out.println(columns);15 }16}17public class 5 {18 public static void main(String[] args) {19 String sql = "SELECT * FROM table1 WHERE id = 1";20 ParserUtils parserUtils = new ParserUtils();21 List<String> conditions = parserUtils.extractConditions(sql);22 System.out.println(conditions);23 }24}25public class 6 {26 public static void main(String[] args) {
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!!