How to use validate method of org.evomaster.client.java.controller.internal.db.SchemaExtractor class

Best EvoMaster code snippet using org.evomaster.client.java.controller.internal.db.SchemaExtractor.validate

Source:SutController.java Github

copy

Full Screen

...436 SimpleLogger.error("Problem ("+getProblemInfo().getClass().getSimpleName()+") is not RPC but request RPC schema.");437 return;438 }439 try {440 RPCEndpointsBuilder.validateCustomizedValueInRequests(getCustomizedValueInRequests());441 RPCEndpointsBuilder.validateCustomizedNotNullAnnotationForRPCDto(specifyCustomizedNotNullAnnotation());442 RPCProblem rpcp = (RPCProblem) getProblemInfo();443 for (String interfaceName: rpcp.getMapOfInterfaceAndClient()){444 InterfaceSchema schema = RPCEndpointsBuilder.build(interfaceName, rpcp.getType(), rpcp.getClient(interfaceName),445 rpcp.skipEndpointsByName!=null? rpcp.skipEndpointsByName.get(interfaceName):null,446 rpcp.skipEndpointsByAnnotation!=null?rpcp.skipEndpointsByAnnotation.get(interfaceName):null,447 rpcp.involveEndpointsByName!=null? rpcp.involveEndpointsByName.get(interfaceName):null,448 rpcp.involveEndpointsByAnnotation!=null? rpcp.involveEndpointsByAnnotation.get(interfaceName):null,449 getInfoForAuthentication(),450 getCustomizedValueInRequests(),451 specifyCustomizedNotNullAnnotation());452 rpcInterfaceSchema.put(interfaceName, schema);453 }454 localAuthSetupSchemaMap.clear();455 Map<Integer, LocalAuthSetupSchema> local = RPCEndpointsBuilder.buildLocalAuthSetup(getInfoForAuthentication());...

Full Screen

Full Screen

Source:SchemaExtractor.java Github

copy

Full Screen

...8import java.sql.SQLException;9import java.util.*;10import java.util.stream.Collectors;11public class SchemaExtractor {12 public static boolean validate(DbSchemaDto schema) throws IllegalArgumentException {13 /*14 some checks if the derived schema is consistent15 */16 Objects.requireNonNull(schema);17 for (TableDto table : schema.tables) {18 for (ColumnDto column : table.columns) {19 checkForeignKeyToAutoIncrementPresent(schema, table, column);20 checkForeignKeyToAutoIncrementMissing(schema, table, column);21 }22 }23 return true;24 }25 private static void checkForeignKeyToAutoIncrementMissing(DbSchemaDto schema, TableDto table, ColumnDto column) {26 if (column.foreignKeyToAutoIncrement) {27 return;28 }29 Optional<ForeignKeyDto> fk = table.foreignKeys.stream()30 .filter(it -> it.sourceColumns.contains(column.name))31 .findFirst();32 if (!fk.isPresent()) {33 //not a foreign key34 return;35 }36 //TODO proper handling of multi-column PKs/FKs37 Optional<TableDto> targetTable = schema.tables.stream()38 .filter(t -> t.name.equals(fk.get().targetTable))39 .findFirst();40 if (!targetTable.isPresent()) {41 throw new IllegalArgumentException("Foreign key in table " + table.name +42 " pointing to non-existent table " + fk.get().targetTable);43 }44 List<ColumnDto> pks = targetTable.get().columns.stream()45 .filter(c -> c.primaryKey)46 .collect(Collectors.toList());47 if (pks.isEmpty()) {48 throw new IllegalArgumentException("No PK in table " + targetTable.get().name + " that has FKs pointing to it");49 }50 for (ColumnDto pk : pks) {51 if (pk.autoIncrement || pk.foreignKeyToAutoIncrement) {52 throw new IllegalArgumentException("Column " + pk.name + " in table " +53 pk.table + " is auto-increment, although FK pointing to it does not mark it " +54 "as autoincrement in " + column.name + " in " + table.name55 );56 }57 }58 }59 private static void checkForeignKeyToAutoIncrementPresent(DbSchemaDto schema, TableDto table, ColumnDto column) {60 if (!column.foreignKeyToAutoIncrement) {61 return;62 }63 Optional<ForeignKeyDto> fk = table.foreignKeys.stream()64 .filter(it -> it.sourceColumns.contains(column.name))65 .findFirst();66 if (!fk.isPresent()) {67 throw new IllegalArgumentException("No foreign key constraint for marked column " +68 column.name + " in table " + table.name);69 }70 //TODO proper handling of multi-column PKs/FKs71 Optional<TableDto> targetTable = schema.tables.stream()72 .filter(t -> t.name.equals(fk.get().targetTable))73 .findFirst();74 if (!targetTable.isPresent()) {75 throw new IllegalArgumentException("Foreign key in table " + table.name +76 " pointing to non-existent table " + fk.get().targetTable);77 }78 //there should be only 1 PK, and that must be auto-increment79 List<ColumnDto> pks = targetTable.get().columns.stream()80 .filter(c -> c.primaryKey)81 .collect(Collectors.toList());82 if (pks.size() != 1) {83 throw new IllegalArgumentException("There must be only 1 PK in table " +84 targetTable.get().name + " pointed by the FK-to-autoincrement " +85 column.name + " in " + table.name + ". However, there were: " + pks.size());86 }87 ColumnDto pk = pks.get(0);88 if (!pk.autoIncrement && !pk.foreignKeyToAutoIncrement) {89 throw new IllegalArgumentException("Column " + pk.name + " in table " +90 pk.table + " is not auto-increment, although FK pointing to it does mark it" +91 "as autoincrement in " + column.name + " in " + table.name92 );93 }94 }95 public static DbSchemaDto extract(Connection connection) throws Exception {96 Objects.requireNonNull(connection);97 DbSchemaDto schemaDto = new DbSchemaDto();98 try {99 schemaDto.name = connection.getSchema();100 } catch (Exception | AbstractMethodError e) {101 /*102 In remote sessions, getSchema might fail.103 We do not do much with it anyway (at least for104 now), so not a big deal...105 Furthermore, some drivers might be compiled to Java 6,106 whereas getSchema was introduced in Java 7107 */108 schemaDto.name = "public";109 }110 DatabaseMetaData md = connection.getMetaData();111 String protocol = md.getURL(); //TODO better handling112 DatabaseType dt = DatabaseType.OTHER;113 if (protocol.contains(":h2")) {114 dt = DatabaseType.H2;115 } else if (protocol.contains(":derby")) {116 dt = DatabaseType.DERBY;117 } else if (protocol.contains(":postgresql")) {118 dt = DatabaseType.POSTGRES;119 }120 schemaDto.databaseType = dt;121 //see https://www.progress.com/blogs/jdbc-tutorial-extracting-database-metadata-via-jdbc-driver122 schemaDto.name = schemaDto.name.toUpperCase();123 ResultSet tables = md.getTables(null, schemaDto.name, null, new String[]{"TABLE"});124 Set<String> tableNames = new HashSet<>();125 /*126 Interfaces to deal with DBs are simply awful...127 Here, we first check with schema name in upper case, and, if that gives no results,128 we try with lower case... this is because different databases deal with upper/lower129 cases differently.130 But API does not give you any info on whether result set131 is empty or not, and only way is to call next()132 */133 if (!tables.next()) {134 tables.close();135 schemaDto.name = schemaDto.name.toLowerCase();136 tables = md.getTables(null, schemaDto.name, null, new String[]{"TABLE"});137 if (tables.next()) {138 do {139 handleTableEntry(schemaDto, md, tables, tableNames);140 } while (tables.next());141 }142 } else {143 do {144 handleTableEntry(schemaDto, md, tables, tableNames);145 } while (tables.next());146 }147 tables.close();148 /*149 Mark those columns that are using auto generated values150 */151 addForeignKeyToAutoIncrement(schemaDto);152 /*153 JDBC MetaData is quite limited.154 To check constraints, we need to do SQL queries on the system tables.155 Unfortunately, this is database-dependent156 */157 addConstraints(connection, dt, schemaDto);158 assert validate(schemaDto);159 return schemaDto;160 }161 /**162 * Adds a unique constraint to the corresponding ColumnDTO for the selected table.column pair.163 * Requires the ColumnDTO to be contained in the TableDTO.164 * If the column DTO is not contained, a IllegalArgumentException is thrown.165 *166 * @param tableDto the DTO of the table167 * @param columnName the name of the column to add the unique constraint on168 **/169 public static void addUniqueConstraintToColumn(TableDto tableDto, String columnName) {170 ColumnDto columnDto = tableDto.columns.stream()171 .filter(c -> c.name.equals(columnName)).findAny().orElse(null);172 if (columnDto == null) {...

Full Screen

Full Screen

validate

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.internal.db.SchemaExtractor;2import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;3import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;4import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;5import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;6import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;7import org.evomaster.client.java.controller.api.dto.database.operations.UpdateDto;8import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;9import java.util.ArrayList;10import java.util.List;11public class 3 {12 public static void main(String[] args) {13 SchemaExtractor schemaExtractor = new SchemaExtractor();14 DbSchemaDto schema = schemaExtractor.extract(DatabaseType.H2, "jdbc:h2:mem:default;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;INIT=CREATE SCHEMA IF NOT EXISTS public", "sa", "");15 List<DatabaseCommandDto> commands = new ArrayList<>();16 commands.add(new InsertionDto("public", "table", new ArrayList<>(), new ArrayList<>()));17 commands.add(new SqlScriptDto("SELECT * FROM table"));18 commands.add(new UpdateDto("public", "table", new ArrayList<>(), new ArrayList<>(), new ArrayList<>()));19 boolean valid = schemaExtractor.validate(schema, commands);20 }21}22import org.evomaster.client.java.controller.internal.db.SchemaExtractor;23import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;24import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;25import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto;26import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;27import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;28import org.evomaster.client.java.controller.api.dto.database.operations.UpdateDto;29import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;30import java.util.ArrayList;31import java.util.List;32public class 4 {33 public static void main(String[] args) {34 SchemaExtractor schemaExtractor = new SchemaExtractor();35 DbSchemaDto schema = schemaExtractor.extract(DatabaseType.H2, "jdbc:h2:mem

Full Screen

Full Screen

validate

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller.internal.db;2import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;3import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;4import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;5import java.util.List;6public class SchemaExtractorValidate {7 public static void main(String[] args) {8 DbSchemaDto schema = new DbSchemaDto();9 schema.setDatabaseType(DatabaseType.H2);10 schema.setName("TEST");11 TableDto table = new TableDto();12 table.setName("TEST_TABLE");13 table.setSchema(schema);14 schema.getTables().add(table);15 List<String> errors = SchemaExtractor.validate(schema);16 for (String error : errors) {17 System.out.println(error);18 }19 }20}

Full Screen

Full Screen

validate

Using AI Code Generation

copy

Full Screen

1package org.evomaster.client.java.controller.internal.db;2import java.sql.Connection;3import java.sql.DriverManager;4import java.sql.SQLException;5import java.util.List;6public class SchemaExtractorTest {7 public static void main(String[] args) throws SQLException {8 Connection connection = null;9 try {10 connection = DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "");11 } catch (SQLException e) {12 throw new IllegalStateException("Failed to create connection", e);13 }14 Schema schema = SchemaExtractor.extract(connection);15 List<String> errors = SchemaExtractor.validate(schema);16 if (errors.isEmpty()) {17 System.out.println("Schema is valid");18 } else {19 System.out.println("Schema is invalid");20 }21 }22}23package org.evomaster.client.java.controller.internal.db;24import java.sql.Connection;25import java.sql.DriverManager;26import java.sql.SQLException;27public class SqlScriptRunnerTest {28 public static void main(String[] args) throws SQLException {29 Connection connection = null;30 try {31 connection = DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "");32 } catch (SQLException e) {33 throw new IllegalStateException("Failed to create connection", e);34 }35 SqlScriptRunner.run(connection, "CREATE TABLE Foo (id INT, name VARCHAR(100), PRIMARY KEY (id));");36 SqlScriptRunner.run(connection, "INSERT INTO Foo (id, name) VALUES (1, 'foo');");37 }38}39package org.evomaster.client.java.controller.internal.db;40import java.sql.Connection;41import java.sql.DriverManager;42import java.sql.SQLException;43public class SqlScriptRunnerTest {44 public static void main(String[] args) throws SQLException {45 Connection connection = null;46 try {47 connection = DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "");48 } catch (SQLException e) {49 throw new IllegalStateException("Failed to create connection", e);50 }51 SqlScriptRunner.run(connection, "CREATE TABLE Foo (id INT, name VARCHAR(100), PRIMARY KEY (id));");52 SqlScriptRunner.run(connection, "INSERT

Full Screen

Full Screen

validate

Using AI Code Generation

copy

Full Screen

1import org.evomaster.client.java.controller.internal.db.SchemaExtractor;2import java.io.File;3import java.io.IOException;4import java.nio.file.Files;5import java.nio.file.Paths;6public class 3 {7 public static void main(String[] args) throws IOException {8 String schema = SchemaExtractor.validate("jdbc:hsqldb:mem:testdb", "sa", "");9 System.out.println(schema);10 File file = new File("schema.json");11 Files.write(Paths.get(file.getAbsolutePath()), schema.getBytes());12 String schemaFromFile = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));13 System.out.println(schemaFromFile);14 }15}16{17 "tables" : [ {18 "columns" : [ {19 }, {20 } ]21 } ]22}23{24 "tables" : [ {25 "columns" : [ {26 }, {27 } ]28 } ]29}

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