Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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());
Expand All @@ -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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

status inList: [Status.AVAILABLE], with no maxSize. Startup throws. The allowed value is the enum, not a string. Do not read it as a string.

// 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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ private static boolean isUnboundedTextType(String typeName) {
}

private Optional<Integer> 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));
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, Integer> 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<EnumLongKind> kinds

static hasMany = [kinds: EnumLongKind]

static constraints = {
kinds maxSize: 2
}
}
Original file line number Diff line number Diff line change
@@ -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<String, Object> 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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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" }
Expand Down Expand Up @@ -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<Status01> status
static constraints = { status maxSize: 42 }
}
@Entity class PersonSizedShort {
Long id; Status01 status
static constraints = { status maxSize: 2 }
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading