diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java index 0c14d5c8b24..1fd26dcc2cd 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java @@ -32,6 +32,7 @@ import org.grails.orm.hibernate.cfg.ColumnConfig; import org.grails.orm.hibernate.cfg.PersistentEntityNamingStrategy; import org.grails.orm.hibernate.cfg.PropertyConfig; +import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateBasicProperty; import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateEnumProperty; import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher; import org.grails.orm.hibernate.cfg.domainbinding.util.CreateKeyForProps; @@ -49,6 +50,7 @@ public class EnumTypeBinder { private final ColumnConfigToColumnBinder columnConfigToColumnBinder; private final PersistentEntityNamingStrategy namingStrategy; private final CreateKeyForProps createKeyForProps; + private final StringColumnConstraintsBinder stringColumnConstraintsBinder = new StringColumnConstraintsBinder(); public EnumTypeBinder( MetadataBuildingContext metadataBuildingContext, @@ -98,10 +100,12 @@ public BasicValue bindEnumType(@Nonnull HibernateEnumProperty property, String p Class propertyType = property.getEnumType(); PropertyConfig pc = property.getHibernateMappedForm(); String typeName = property.getTypeName(propertyType); + GrailsEnumType enumType = null; if (typeName != null) { simpleValue.setTypeName(typeName); } else { - GrailsEnumType.fromString(pc.getEnumType()).configure(simpleValue, propertyType); + enumType = GrailsEnumType.fromString(pc.getEnumType()); + enumType.configure(simpleValue, propertyType); } Properties enumProperties = new Properties(); enumProperties.put(ENUM_CLASS_PROP, propertyType.getName()); @@ -118,6 +122,20 @@ public BasicValue bindEnumType(@Nonnull HibernateEnumProperty property, String p Table t = simpleValue.getTable(); t.addColumn(column); simpleValue.addColumn(column); + // on a collection of enum values the constraints are those of the collection: maxSize is the number of its values, + // and an allowed value is a whole collection, so neither is the length of the column of one value + if ((enumType == GrailsEnumType.DEFAULT || enumType == GrailsEnumType.STRING) && !(property instanceof HibernateBasicProperty)) { + stringColumnConstraintsBinder.bindStringColumnConstraints(column, pc, null); + // maxSize does not validate an enum value, so a value whose name is longer than the column would pass validation and + // fail in the database: the column holds the longest name of the enum at least + int longestName = 0; + for (Object constant : propertyType.getEnumConstants()) { + longestName = Math.max(longestName, ((Enum) constant).name().length()); + } + if (column.getLength() != null && column.getLength() < longestName) { + column.setLength((long) longestName); + } + } createKeyForProps.createKeyForProps(property, path, t, columnName); if (!pc.getColumns().isEmpty()) { diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/StringColumnConstraintsBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/StringColumnConstraintsBinder.java index 00c8d4a2140..9f6d61a6708 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/StringColumnConstraintsBinder.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/StringColumnConstraintsBinder.java @@ -55,7 +55,11 @@ private static boolean isUnboundedTextType(String typeName) { } private Optional getMax(Property mappedForm) { - return Optional.ofNullable(mappedForm.getInList()).flatMap(list -> list.stream() + // an allowed value is a string only when the property is one: an enum property lists its constants, and a + // collection lists whole collections, which have no text to read + return Optional.ofNullable(mappedForm.getInList()).flatMap(list -> ((java.util.List) list).stream() + .filter(String.class::isInstance) + .map(String.class::cast) .map(this::parseInt) .filter(Objects::nonNull) .reduce(Integer::max)); diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumMaxSizeColumnSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumMaxSizeColumnSpec.groovy new file mode 100644 index 00000000000..64fb3ece664 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumMaxSizeColumnSpec.groovy @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package grails.gorm.tests + +import grails.gorm.annotation.Entity +import spock.lang.Issue + +@Issue('https://github.com/apache/grails-core/issues/14505') +class EnumMaxSizeColumnSpec extends HibernateGormDatastoreSpec { + + void setupSpec() { + manager.registerDomainClasses(EnumSizedThing, EnumListedThing, EnumCollectionThing) + } + + void "an enum property with maxSize still stores and reads its value"() { + given: + new EnumSizedThing(stringField: 'x', enumField: EnumSizedKind.TWO).save(flush: true, failOnError: true) + session.clear() + + expect: + EnumSizedThing.findByEnumField(EnumSizedKind.TWO).enumField == EnumSizedKind.TWO + EnumSizedThing.count() == 1 + } + + void "the string property keeps the length from maxSize"() { + when: + Map lengths = [:] + manager.sessionFactory.currentSession.doWork { conn -> + def rs = conn.createStatement().executeQuery( + "select column_name, character_maximum_length from information_schema.columns " + + "where lower(table_name) = 'enum_sized_thing'") + while (rs.next()) { + lengths[rs.getString(1).toLowerCase()] = rs.getInt(2) + } + } + + then: + lengths['string_field'] == 100 + } + + void "an enum property with an inList of enum values stores and reads its value"() { + given: + new EnumListedThing(kind: EnumSizedKind.ONE).save(flush: true, failOnError: true) + session.clear() + + expect: + EnumListedThing.findByKind(EnumSizedKind.ONE).kind == EnumSizedKind.ONE + EnumListedThing.count() == 1 + } + + void "a maxSize on a collection of enum values limits the number of values and not the length of one"() { + given: 'a collection with maxSize 2 of values that are longer than two characters' + new EnumCollectionThing(kinds: [EnumLongKind.FIRST_VALUE, EnumLongKind.SECOND_VALUE]).save(flush: true, failOnError: true) + session.clear() + + expect: 'both values are stored and read back' + EnumCollectionThing.list()[0].kinds as Set == [EnumLongKind.FIRST_VALUE, EnumLongKind.SECOND_VALUE] as Set + + and: 'a third value is refused by the constraint of the collection' + !new EnumCollectionThing(kinds: [EnumLongKind.FIRST_VALUE, EnumLongKind.SECOND_VALUE, EnumLongKind.THIRD_VALUE]).validate() + } + + void "an enum inList that does not allow a value rejects it"() { + expect: + !new EnumListedThing(kind: EnumSizedKind.TWO).validate() + } +} + +enum EnumSizedKind { ONE, TWO } + +@Entity +class EnumSizedThing { + String stringField + EnumSizedKind enumField + + static constraints = { + stringField nullable: true, maxSize: 100 + enumField nullable: true, maxSize: 100 + } +} + +@Entity +class EnumListedThing { + EnumSizedKind kind + + static constraints = { + kind inList: [EnumSizedKind.ONE] + } +} + +enum EnumLongKind { FIRST_VALUE, SECOND_VALUE, THIRD_VALUE } + +@Entity +class EnumCollectionThing { + Set kinds + + static hasMany = [kinds: EnumLongKind] + + static constraints = { + kinds maxSize: 2 + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/EnumMaxSizeColumnIntegrationSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/EnumMaxSizeColumnIntegrationSpec.groovy new file mode 100644 index 00000000000..9ccd377a007 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/EnumMaxSizeColumnIntegrationSpec.groovy @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.grails.orm.hibernate + +import grails.gorm.annotation.Entity +import grails.gorm.tests.HibernateGormDatastoreSpec +import org.testcontainers.mariadb.MariaDBContainer +import org.testcontainers.mysql.MySQLContainer +import org.testcontainers.postgresql.PostgreSQLContainer +import org.testcontainers.spock.Testcontainers +import spock.lang.Issue +import spock.lang.Requires +import spock.lang.Shared + +@Issue('https://github.com/apache/grails-core/issues/14505') +@Testcontainers +@Requires({ isDockerAvailable() }) +class EnumMaxSizeColumnIntegrationSpec extends HibernateGormDatastoreSpec { + + @Shared PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:16") + @Shared MySQLContainer mysql = new MySQLContainer("mysql:8.0") + @Shared MariaDBContainer mariadb = new MariaDBContainer("mariadb:10.11") + + void setupSpec() { + manager.registerDomainClasses(EnumDdlThing) + } + + void "the enum column honours maxSize on #db"() { + given: + if (!container.isRunning()) { + container.start() + } + manager.destroy() + manager.grailsConfig = [ + 'dataSource.url' : container.jdbcUrl, + 'dataSource.driverClassName' : container.driverClassName, + 'dataSource.username' : container.username, + 'dataSource.password' : container.password, + 'dataSource.dbCreate' : 'create-drop', + 'hibernate.hbm2ddl.auto' : 'create', + ] + manager.setup(this.class) + + when: + Map column = [:] + datastore.dataSource.connection.withCloseable { conn -> + conn.createStatement().withCloseable { stmt -> + stmt.executeQuery("select data_type, character_maximum_length from information_schema.columns " + + "where lower(table_name) = 'enum_ddl_thing' and lower(column_name) = 'enum_field'").with { rs -> + rs.next() + column = [type: rs.getString(1), maxLength: rs.getObject(2)] + } + } + } + + then: 'a native enum has no length, any other column is as long as maxSize says' + column.type == 'enum' || (column.maxLength as Integer) == 100 + + where: + db | container + 'postgres' | postgres + 'mysql' | mysql + 'mariadb' | mariadb + } +} + +enum EnumDdlKind { ONE, TWO } + +@Entity +class EnumDdlThing { + EnumDdlKind enumField + + static constraints = { + enumField nullable: true, maxSize: 100 + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy index 27ba192c413..c3aabddd657 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/EnumTypeBinderSpec.groovy @@ -120,6 +120,38 @@ class EnumTypeBinderSpec extends HibernateGormDatastoreSpec { Person05 | UserTypeEnumType | UserTypeEnumType.class.getName() | null | false } + def "a maxSize shorter than the longest constant name does not make the column too short for a valid value"() { + given: 'an enum whose longest constant, OUT_OF_STOCK, is 12 characters, with a maxSize of 2' + def table = new Table("person") + def property = setupProperty(PersonSizedShort, "status", table) + + when: + def simpleValue = binder.bindEnumType(property as HibernateEnumProperty, "") + + then: 'the column holds the longest name, as maxSize does not validate an enum' + simpleValue.getColumns()[0].getLength() == 12L + } + + @Unroll + def "maxSize is applied to the column of a #mapping: #applied"() { + given: + def table = new Table("person") + def property = setupProperty(clazz, "status", table) + + when: + def simpleValue = binder.bindEnumType(property as HibernateEnumProperty, "") + + then: 'maxSize reaches a string-mapped enum column and leaves an ordinal one at the default' + (simpleValue.getColumns()[0].getLength() == 42L) == applied + + where: + clazz | mapping | applied + PersonSizedDefault | "default" | true + PersonSizedString | "string" | true + PersonSizedOrdinal | "ordinal" | false + PersonSizedCollection | "collection of enum values, where maxSize is the number of values" | false + } + @Unroll def "should set column nullability"() { given: "A root entity and its enum property" @@ -240,6 +272,20 @@ enum Status01 { AVAILABLE, OUT_OF_STOCK } Long id; Status01 status static constraints = { status nullable: false } } +@Entity class PersonSizedDefault { + Long id; Status01 status + static constraints = { status maxSize: 42 } +} +@Entity class PersonSizedString { + Long id; Status01 status + static mapping = { status enumType: "string" } + static constraints = { status maxSize: 42 } +} +@Entity class PersonSizedOrdinal { + Long id; Status01 status + static mapping = { status enumType: "ordinal" } + static constraints = { status maxSize: 42 } +} @Entity class Person02 { Long id; Status01 status static mapping = { status enumType: "string" } @@ -284,3 +330,11 @@ class UserTypeEnumType implements UserType { @Override Serializable disassemble(Object value) { (Serializable)value } @Override Object assemble(Serializable cached, Object owner) { cached } } +@Entity class PersonSizedCollection { + Long id; Set status + static constraints = { status maxSize: 42 } +} +@Entity class PersonSizedShort { + Long id; Status01 status + static constraints = { status maxSize: 2 } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/StringColumnConstraintsBinderSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/StringColumnConstraintsBinderSpec.groovy index 8006ced8ba2..0c28a66b1b5 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/StringColumnConstraintsBinderSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/StringColumnConstraintsBinderSpec.groovy @@ -101,6 +101,31 @@ class StringColumnConstraintsBinderSpec extends Specification { } + def "should leave the column length when the allowed values are not strings"() { + given: 'an enum property lists its constants, and a collection property lists whole collections' + mappedForm.getMaxSize() >> null + mappedForm.getInList() >> [java.util.concurrent.TimeUnit.SECONDS, ['abcdef'], 7] + def originalLength = column.length + + when: + binder.bindStringColumnConstraints(column, mappedForm, null) + + then: + column.length == originalLength + } + + def "should read the strings of a list that has other values too"() { + given: + mappedForm.getMaxSize() >> null + mappedForm.getInList() >> [java.util.concurrent.TimeUnit.SECONDS, '9', ['abcdef']] + + when: + binder.bindStringColumnConstraints(column, mappedForm, null) + + then: + column.length == 9 + } + def "should prioritize maxSize over inList when both are present"() { given: mappedForm.getMaxSize() >> 1 diff --git a/grails-test-examples/hibernate7/grails-hibernate/grails-app/domain/functional/tests/ScenarioEnumSized.groovy b/grails-test-examples/hibernate7/grails-hibernate/grails-app/domain/functional/tests/ScenarioEnumSized.groovy new file mode 100644 index 00000000000..37dd567f6fa --- /dev/null +++ b/grails-test-examples/hibernate7/grails-hibernate/grails-app/domain/functional/tests/ScenarioEnumSized.groovy @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package functional.tests + +import grails.gorm.annotation.Entity + +enum ScenarioEnumKind { ONE, TWO } + +@Entity +class ScenarioEnumSized { + + String label + ScenarioEnumKind kind + + static constraints = { + label nullable: true, maxSize: 100 + kind nullable: true, maxSize: 100 + } +} diff --git a/grails-test-examples/hibernate7/grails-hibernate/src/integration-test/groovy/functional/tests/EnumMaxSizeScenarioSpec.groovy b/grails-test-examples/hibernate7/grails-hibernate/src/integration-test/groovy/functional/tests/EnumMaxSizeScenarioSpec.groovy new file mode 100644 index 00000000000..9b996b42ace --- /dev/null +++ b/grails-test-examples/hibernate7/grails-hibernate/src/integration-test/groovy/functional/tests/EnumMaxSizeScenarioSpec.groovy @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package functional.tests + +import javax.sql.DataSource + +import org.springframework.beans.factory.annotation.Autowired +import spock.lang.Specification + +import grails.testing.mixin.integration.Integration + +/** + * maxSize on an enum property is honoured like it is on a string property (#14505). + */ +@Integration(applicationClass = Application) +class EnumMaxSizeScenarioSpec extends Specification { + + @Autowired + DataSource dataSource + + void cleanup() { + ScenarioEnumSized.withNewTransaction { + ScenarioEnumSized.list()*.delete(flush: true) + } + } + + void "an enum property with maxSize stores and reads its value"() { + given: + ScenarioEnumSized.withNewTransaction { + new ScenarioEnumSized(label: 'x', kind: ScenarioEnumKind.TWO).save(failOnError: true) + } + + expect: + ScenarioEnumSized.withNewSession { ScenarioEnumSized.findByKind(ScenarioEnumKind.TWO).kind == ScenarioEnumKind.TWO } + } + + void "the string column keeps its maxSize"() { + when: + Map lengths = [:] + dataSource.connection.withCloseable { conn -> + def rs = conn.createStatement().executeQuery( + "select column_name, character_maximum_length from information_schema.columns " + + "where lower(table_name) = 'scenario_enum_sized'") + while (rs.next()) { + lengths[rs.getString(1).toLowerCase()] = rs.getInt(2) + } + } + + then: + lengths['label'] == 100 + } +}