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

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

Source:SchemaExtractor.java Github

copy

Full Screen

...122 */123 schemaDto.name = getSchemaName(connection, dt);124 if (dt.equals(DatabaseType.POSTGRES)) {125 Map<String, Set<String>> enumLabels = getPostgresEnumTypes(connection);126 addPostgresEnumTypesToSchema(schemaDto, enumLabels);127 schemaDto.compositeTypes = getPostgresCompositeTypes(connection);128 }129 ResultSet tables = md.getTables(null, schemaDto.name, null, new String[]{"TABLE"});130 Set<String> tableNames = new HashSet<>();131 /*132 Interfaces to deal with DBs are simply awful...133 Here, we first check with schema name in upper case, and, if that gives no results,134 we try with lower case... this is because different databases deal with upper/lower135 cases differently.136 But API does not give you any info on whether result set137 is empty or not, and only way is to call next()138 */139 if (!tables.next()) {140 tables.close();141 schemaDto.name = schemaDto.name.toLowerCase();142 tables = md.getTables(null, schemaDto.name, null, new String[]{"TABLE"});143 if (tables.next()) {144 do {145 handleTableEntry(schemaDto, md, tables, tableNames);146 } while (tables.next());147 }148 } else {149 do {150 handleTableEntry(schemaDto, md, tables, tableNames);151 } while (tables.next());152 }153 tables.close();154 /*155 Mark those columns that are using auto generated values156 */157 addForeignKeyToAutoIncrement(schemaDto);158 /*159 JDBC MetaData is quite limited.160 To check constraints, we need to do SQL queries on the system tables.161 Unfortunately, this is database-dependent162 */163 addConstraints(connection, dt, schemaDto);164 if (dt.equals(DatabaseType.POSTGRES)) {165 List<ColumnAttributes> columnAttributes = getPostgresColumnAttributes(connection);166 addColumnAttributes(schemaDto, columnAttributes);167 }168 assert validate(schemaDto);169 return schemaDto;170 }171 private static void addColumnAttributes(DbSchemaDto schemaDto, List<ColumnAttributes> listOfColumnAttributes) {172 for (ColumnAttributes columnAttributes : listOfColumnAttributes) {173 String tableName = columnAttributes.tableName;174 String columnName = columnAttributes.columnName;175 ColumnDto columnDto = getColumnDto(schemaDto, tableName, columnName);176 columnDto.numberOfDimensions = columnAttributes.numberOfDimensions;177 }178 }179 private static ColumnDto getColumnDto(DbSchemaDto schemaDto, String tableName, String columnName) {180 TableDto tableDto = schemaDto.tables.stream()181 .filter(t -> t.name.equals(tableName.toLowerCase()))182 .findFirst()183 .orElse(null);184 return tableDto.columns.stream()185 .filter(c -> c.name.equals(columnName.toLowerCase()))186 .findFirst()187 .orElse(null);188 }189 private static String getSchemaName(Connection connection, DatabaseType dt) throws SQLException {190 String schemaName;191 if (dt.equals(DatabaseType.MYSQL)) {192 // schema is database name in mysql193 schemaName = connection.getCatalog();194 } else {195 try {196 schemaName = connection.getSchema();197 } catch (Exception | AbstractMethodError e) {198 /*199 In remote sessions, getSchema might fail.200 We do not do much with it anyway (at least for201 now), so not a big deal...202 Furthermore, some drivers might be compiled to Java 6,203 whereas getSchema was introduced in Java 7204 */205 schemaName = "public";206 }207 //see https://www.progress.com/blogs/jdbc-tutorial-extracting-database-metadata-via-jdbc-driver208 schemaName = schemaName.toUpperCase();209 }210 return schemaName;211 }212 private static class ColumnAttributes {213 public String tableName;214 public String columnName;215 public int numberOfDimensions;216 }217 private static List<ColumnAttributes> getPostgresColumnAttributes(Connection connection) throws SQLException {218 String query = "SELECT pg_namespace.nspname as TABLE_NAMESPACE, pg_class.relname as TABLE_NAME, pg_attribute.attname as COLUMN_NAME, pg_attribute.attndims as NUMBER_OF_DIMENSIONS \n" +219 "FROM pg_attribute \n" +220 "INNER JOIN pg_class ON pg_class.oid = pg_attribute.attrelid " +221 "INNER JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace " +222 "WHERE pg_namespace.nspname != 'pg_catalog' ";223 List<ColumnAttributes> listOfColumnAttributes = new LinkedList<>();224 try (Statement stmt = connection.createStatement()) {225 ResultSet columnAttributesResultSet = stmt.executeQuery(query);226 while (columnAttributesResultSet.next()) {227 String tableNamesapce = columnAttributesResultSet.getString("TABLE_NAMESPACE");228 String tableName = columnAttributesResultSet.getString("TABLE_NAME");229 String columnName = columnAttributesResultSet.getString("COLUMN_NAME");230 int numberOfDimensions = columnAttributesResultSet.getInt("NUMBER_OF_DIMENSIONS");231 if (numberOfDimensions == 0) {232 // skip attribute rows when data types are not arrays, matrixes, etc.233 continue;234 }235 ColumnAttributes columnAttributes = new ColumnAttributes();236 columnAttributes.tableName = tableName;237 columnAttributes.columnName = columnName;238 columnAttributes.numberOfDimensions = numberOfDimensions;239 listOfColumnAttributes.add(columnAttributes);240 }241 }242 return listOfColumnAttributes;243 }244 private static List<String> getAllCompositeTypeNames(Connection connection) throws SQLException {245 // Source: https://stackoverflow.com/questions/3660787/how-to-list-custom-types-using-postgres-information-schema246 String listAllCompositeTypesQuery = "SELECT n.nspname as schema, t.typname as typename \n" +247 "FROM pg_type t \n" +248 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace \n" +249 "WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)) \n" +250 "AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)\n" +251 "AND n.nspname NOT IN ('pg_catalog', 'information_schema')" +252 "AND t.typtype ='c';";253 List<String> compositeTypeNames = new ArrayList<>();254 try (Statement listAllCompositeTypesStmt = connection.createStatement()) {255 ResultSet listAllCompositeTypesResultSet = listAllCompositeTypesStmt.executeQuery(listAllCompositeTypesQuery);256 while (listAllCompositeTypesResultSet.next()) {257 compositeTypeNames.add(listAllCompositeTypesResultSet.getString("typename"));258 }259 }260 return compositeTypeNames;261 }262 private static List<CompositeTypeDto> getPostgresCompositeTypes(Connection connection) throws SQLException {263 List<CompositeTypeDto> compositeTypeDtos = new ArrayList<>();264 List<String> compositeTypeNames = getAllCompositeTypeNames(connection);265 for (String compositeTypeName : compositeTypeNames) {266 List<CompositeTypeColumnDto> columnDtos = getAllCompositeTypeColumns(connection, compositeTypeName, compositeTypeNames);267 CompositeTypeDto compositeTypeDto = new CompositeTypeDto();268 compositeTypeDto.name = compositeTypeName;269 compositeTypeDto.columns = columnDtos;270 compositeTypeDtos.add(compositeTypeDto);271 }272 return compositeTypeDtos;273 }274 private static final String TEXT_DATA_TYPE = "text";275 private static final String BIT_DATA_TYPE = "bit";276 private static final String VAR_BIT_DATA_TYPE = "varbit";277 private static final String CHAR_DATA_TYPE = "char";278 private static final String VAR_CHAR_DATA_TYPE = "varchar";279 private static final String BLANK_PADDED_CHAR_DATA_TYPE = "bpchar";280 private static final String NUMERIC_DATA_TYPE = "numeric";281 private static List<CompositeTypeColumnDto> getAllCompositeTypeColumns(Connection connection, String compositeTypeName, List<String> allCompositeTypeNames) throws SQLException {282 // Source: https://stackoverflow.com/questions/6979282/postgresql-find-information-about-user-defined-types283 String listAttributesQuery = String.format(284 "SELECT pg_attribute.attname AS attname, pg_attribute.attlen as attlen, pg_type.typname AS typename " +285 " FROM pg_attribute " +286 " JOIN pg_type ON pg_attribute.atttypid=pg_type.oid " +287 " WHERE pg_attribute.attrelid =\n" +288 " (SELECT typrelid FROM pg_type WHERE typname = '%s') " +289 " ORDER BY pg_attribute.attnum ", compositeTypeName);290 List<CompositeTypeColumnDto> columnDtos = new ArrayList<>();291 try (Statement listAttributesStmt = connection.createStatement()) {292 ResultSet listAttributesResultSet = listAttributesStmt.executeQuery(listAttributesQuery);293 while (listAttributesResultSet.next()) {294 CompositeTypeColumnDto columnDto = new CompositeTypeColumnDto();295 columnDto.name = listAttributesResultSet.getString("attname");296 columnDto.type = listAttributesResultSet.getString("typename");297 int attlen = listAttributesResultSet.getInt("attlen");298 /*299 * Composite type columns can not include constraints (such as NOT NULL).300 * Therefore, all columns in composite types are nullable.301 */302 columnDto.nullable = true;303 columnDto.columnTypeIsComposite = allCompositeTypeNames.stream().anyMatch(t -> t.equalsIgnoreCase(columnDto.type));304 if (columnDto.columnTypeIsComposite) {305 columnDto.size = 0;306 } else {307 switch (columnDto.type) {308 case TEXT_DATA_TYPE: {309 columnDto.size = Integer.MAX_VALUE;310 }311 break;312 case NUMERIC_DATA_TYPE:313 case CHAR_DATA_TYPE:314 case VAR_CHAR_DATA_TYPE:315 case BIT_DATA_TYPE:316 case VAR_BIT_DATA_TYPE:317 case BLANK_PADDED_CHAR_DATA_TYPE: {318 throw new UnsupportedOperationException("cannot get variable length size of type (varchar, char, varbit, bit, numeric) currently not supported for postgres composite types: " + columnDto.name + " with type " + columnDto.type);319 }320 default: {321 columnDto.size = attlen;322 }323 }324 }325 columnDtos.add(columnDto);326 }327 }328 return columnDtos;329 }330 private static Map<String, Set<String>> getPostgresEnumTypes(Connection connection) throws SQLException {331 String query = "SELECT t.typname, e.enumlabel\n" +332 "FROM pg_type AS t\n" +333 " JOIN pg_enum AS e ON t.oid = e.enumtypid\n" +334 "ORDER BY e.enumsortorder;";335 Map<String, Set<String>> enumLabels = new HashMap<>();336 try (Statement stmt = connection.createStatement()) {337 ResultSet enumTypeValues = stmt.executeQuery(query);338 while (enumTypeValues.next()) {339 String typeName = enumTypeValues.getString("typname");340 String enumLabel = enumTypeValues.getString("enumlabel");341 if (!enumLabels.containsKey(typeName)) {342 enumLabels.put(typeName, new HashSet<>());343 }344 enumLabels.get(typeName).add(enumLabel);345 }346 }347 return enumLabels;348 }349 private static void addPostgresEnumTypesToSchema(DbSchemaDto schemaDto, Map<String, Set<String>> enumLabels) {350 enumLabels.forEach(351 (k, v) -> {352 EnumeratedTypeDto enumeratedTypeDto = new EnumeratedTypeDto();353 enumeratedTypeDto.name = k;354 enumeratedTypeDto.values = new ArrayList<>(v);355 schemaDto.enumeraredTypes.add(enumeratedTypeDto);356 }357 );358 }359 /**360 * Adds a unique constraint to the corresponding ColumnDTO for the selected table.column pair.361 * Requires the ColumnDTO to be contained in the TableDTO.362 * If the column DTO is not contained, a IllegalArgumentException is thrown.363 *...

Full Screen

Full Screen

addPostgresEnumTypesToSchema

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.DatabaseSchema;4import org.evomaster.client.java.controller.api.dto.database.schema.Table;5import org.evomaster.client.java.controller.api.dto.database.schema.Column;6import org.evomaster.client.java.controller.api.dto.database.schema.DataType;7import org.evomaster.client.java.controller.api.dto.database.schema.ForeignKey;8import org.evomaster.client.java.controller.api.dto.database.schema.ForeignKeyAction;9import org.evomaster.client.java.controller.api.dto.database.schema.Index;10import org.evomaster.client.java.controller.api.dto.database.schema.IndexColumn;11import org.evomaster.client.java.controller.api.dto.database.schema.TableIndex;12import org.evomaster.client.java.controller.api.dto.database.schema.TableUniqueIndex;13DataType enumType1 = new DataType("enum_type_1");14enumType1.addEnumValue("enum_val_1");15enumType1.addEnumValue("enum_val_2");16enumType1.addEnumValue("enum_val_3");17DataType enumType2 = new DataType("enum_type_2");18enumType2.addEnumValue("enum_val_1");19enumType2.addEnumValue("enum_val_2");20enumType2.addEnumValue("enum_val_3");21SchemaExtractor.addPostgresEnumTypesToSchema(schema, enumType1, enumType2);22System.out.println(schema);23{24 {25 },26 {27 }28}

Full Screen

Full Screen

addPostgresEnumTypesToSchema

Using AI Code Generation

copy

Full Screen

1import graphql.schema.GraphQLSchema2import org.evomaster.client.java.controller.internal.db.PostgresSchema3import org.evomaster.client.java.controller.internal.db.SchemaExtractor4import org.evomaster.client.java.controller.internal.db.schema.Table5import org.evomaster.client.java.controller.internal.db.schema.TableColumn6import org.evomaster.client.java.controller.internal.db.schema.TableIndex7import org.evomaster.client.java.controller.internal.db.schema.TableIndexColumn8import org.evomaster.client.java.controller.internal.db.schema.TableUniqueIndex9import org.evomaster.client.java.controller.internal.db.schema.TableUniqueIndexColumn10import org.evomaster.client.java.controller.schema.GraphQLSchema11import org.evomaster.client.java.controller.schema.GraphQLType12import org.evomaster.client.java.controller.schema.PostgresTable13import org.evomaster.client.java.controller.schema.PostgresTableColumn14import org.evomaster.client.java.controller.schema.PostgresTableIndex15import org.evomaster.client.java.controller.schema.PostgresTableIndexColumn16import org.evomaster.client.java.controller.schema.PostgresTableUniqueIndex17import org.evomaster.client.java.controller.schema.PostgresTableUniqueIndexColumn18import org.evomaster.client.java.controller.schema.PostgresType19import org.evomaster.client.java.controller.schema.TableColumnDataType20import org.evomaster.client.java.controller.schema.TableColumnDataType.*21import org.evomaster.client.java.controller.schema.TableIndexType22import org.evomaster.client.java.controller.schema.TableIndexType.*23val schema: GraphQLSchema = GraphQLSchemaGenerator().generateFromResource("schema.graphqls")24val postgresSchema = PostgresSchema("localhost", 5432, "testdb", "testuser", "testpassword")25val tables = postgresSchema.extractTables()26val schemaWithEnums = SchemaExtractor.addPostgresEnumTypesToSchema(schema, tables)

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