diff --git a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java index 12603e33bee..f21bb9c9d7b 100644 --- a/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java +++ b/grails-data-hibernate5/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java @@ -81,6 +81,7 @@ import org.grails.datastore.mapping.core.connections.ConnectionSource; import org.grails.datastore.mapping.core.connections.ConnectionSources; import org.grails.datastore.mapping.core.connections.ConnectionSourcesInitializer; +import org.grails.datastore.mapping.core.connections.ConnectionSourcesSupport; import org.grails.datastore.mapping.core.connections.DefaultConnectionSource; import org.grails.datastore.mapping.core.connections.SingletonConnectionSources; import org.grails.datastore.mapping.core.exceptions.ConfigurationException; @@ -183,19 +184,22 @@ public void persistentEntityAdded(PersistentEntity entity) { }); if (multiTenantMode == MultiTenancySettings.MultiTenancyMode.SCHEMA) { + Collection tenantSchemaNames = new ArrayList<>(); if (this.tenantResolver instanceof AllTenantsResolver) { - AllTenantsResolver allTenantsResolver = (AllTenantsResolver) tenantResolver; - Iterable tenantIds = allTenantsResolver.resolveTenantIds(); - - for (Serializable tenantId : tenantIds) { - addTenantForSchemaInternal(tenantId.toString()); + for (Serializable tenantId : ((AllTenantsResolver) tenantResolver).resolveTenantIds()) { + tenantSchemaNames.add(tenantId.toString()); } } else { - Collection allSchemas = schemaHandler.resolveSchemaNames(defaultConnectionSource.getDataSource()); - for (String schema : allSchemas) { - addTenantForSchemaInternal(schema); - } + tenantSchemaNames.addAll(schemaHandler.resolveSchemaNames(defaultConnectionSource.getDataSource())); + } + List unmapped = ConnectionSourcesSupport.findAssociationsToEntitiesMissingFromTenantSchemas(mappingContext.getPersistentEntities(), tenantSchemaNames); + if (!unmapped.isEmpty()) { + throw new ConfigurationException("Multi-tenancy mode SCHEMA cannot map an association from a MultiTenant entity to an entity that is not MultiTenant and that a tenant schema does not map: " + + String.join(", ", unmapped) + ". Make the target MultiTenant, map it on every tenant schema (datasource 'ALL', or name each schema), or use the DISCRIMINATOR multi-tenancy mode."); + } + for (String tenantSchemaName : tenantSchemaNames) { + addTenantForSchemaInternal(tenantSchemaName); } } } diff --git a/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationLayoutSpec.groovy b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationLayoutSpec.groovy new file mode 100644 index 00000000000..b6409184632 --- /dev/null +++ b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationLayoutSpec.groovy @@ -0,0 +1,326 @@ +/* + * 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.MultiTenant +import grails.gorm.annotation.Entity +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.datastore.mapping.core.exceptions.ConfigurationException +import org.grails.datastore.mapping.multitenancy.AllTenantsResolver +import org.grails.orm.hibernate.HibernateDatastore +import org.grails.orm.hibernate.cfg.Settings +import spock.lang.Issue +import spock.lang.Specification +import spock.lang.Unroll + +/** + * With SCHEMA multi-tenancy a tenant schema maps the multi tenant entities and the others only when they use every + * connection. The startup check must refuse exactly the associations that have nothing to refer to, so each layout + * a mapping can declare for the target is tried: the ones that reach the tenant schemas must start. + */ +@Issue('https://github.com/apache/grails-core/issues/14345') +class SchemaTenantAssociationLayoutSpec extends Specification { + + private static HibernateDatastore start(Class... classes) { + startWith([:], classes) + } + + private static HibernateDatastore startWith(Map extra, Class... classes) { + Map config = [ + (Settings.SETTING_DB_CREATE) : 'create-drop', + 'dataSource.url' : "jdbc:h2:mem:schemaTenantLayout${System.nanoTime()};LOCK_TIMEOUT=10000", + 'grails.gorm.multiTenancy.mode' : 'SCHEMA', + 'grails.gorm.multiTenancy.tenantResolverClass': 'org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantResolver' + ] + config.putAll(extra) + new HibernateDatastore(DatastoreUtils.createPropertyResolver(config), classes) + } + + @Unroll + void "an owner of a multi tenant entity pointing at a target #layout is refused at startup"() { + when: + start(*classes) + + then: + ConfigurationException e = thrown() + e.message.contains(classes[0].simpleName) + + where: + layout | classes + 'with no datasource declared' | [LayoutOwnerNone, LayoutTargetNone] + } + + @Unroll + void "an owner of a multi tenant entity pointing at a target #layout starts"() { + when: + HibernateDatastore datastore = start(*classes) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + + where: + layout | classes + 'that declares datasource ALL' | [LayoutOwnerAll, LayoutTargetAll] + 'that declares datasources with only ALL' | [LayoutOwnerAllList, LayoutTargetAllList] + 'that is a subclass of a root using every connection' | [LayoutOwnerChild, LayoutAllRoot, LayoutAllChild] + 'that is the root of a hierarchy using every connection' | [LayoutOwnerRoot, LayoutAllRoot, LayoutAllChild] + 'that is mapped by a JPA annotation and lists no datasource' | [LayoutOwnerJpa, LayoutJpaTarget] + } + + private static HibernateDatastore startWithTenants(Class... classes) { + startWith(['grails.gorm.multiTenancy.tenantResolverClass': KnownTenantsResolver.name], classes) + } + + @Unroll + void "with the tenant schemas known, an owner pointing at a target that #layout starts"() { + when: + HibernateDatastore datastore = startWithTenants(*classes) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + + where: + layout | classes + 'lists the default connection and the tenant' | [KnownOwnerDefaultAndTenant, KnownTargetDefaultAndTenant] + 'declares datasource ALL' | [KnownOwnerAll, KnownTargetAll] + 'is mapped by a JPA annotation and lists no datasource' | [KnownOwnerJpa, KnownJpaTarget] + } + + @Unroll + void "with the tenant schemas known, an owner pointing at a target that #layout is refused at startup"() { + when: + startWithTenants(*classes) + + then: + ConfigurationException e = thrown() + e.message.contains(classes[0].simpleName) + + where: + layout | classes + 'lists only the default connection' | [KnownOwnerDefaultOnly, KnownTargetDefaultOnly] + 'lists the default connection and another tenant' | [KnownOwnerOtherTenant, KnownTargetOtherTenant] + } + + void "with the tenant schemas known, an owner pointing at a target that lists only the tenant schema does not start"() { + when: 'the default connection also maps the owner, and not the target; Hibernate refuses it before the schema check runs' + startWithTenants(KnownOwnerTenantOnly, KnownTargetTenantOnly) + + then: + thrown(Exception) + } + + void "an owner of a multi tenant entity pointing at a target that uses every connection through the default mapping starts"() { + when: + HibernateDatastore datastore = startWith(['grails.gorm.default.mapping': { datasource 'ALL' }], + LayoutOwnerDefault, LayoutTargetDefault) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + } +} + +@Entity +class LayoutTargetNone { + String name +} + +@Entity +class LayoutOwnerNone implements MultiTenant { + String name + LayoutTargetNone target +} + +@Entity +class LayoutTargetAll { + String name + static mapping = { + datasource 'ALL' + } +} + +@Entity +class LayoutOwnerAll implements MultiTenant { + String name + LayoutTargetAll target +} + +@Entity +class LayoutTargetAllList { + String name + static mapping = { + datasources(['ALL']) + } +} + +@Entity +class LayoutOwnerAllList implements MultiTenant { + String name + LayoutTargetAllList target +} + +@Entity +class LayoutAllRoot { + String name + static mapping = { + datasource 'ALL' + } +} + +@Entity +class LayoutAllChild extends LayoutAllRoot { + String extra +} + +@Entity +class LayoutOwnerChild implements MultiTenant { + String name + LayoutAllChild target +} + +@Entity +class LayoutOwnerRoot implements MultiTenant { + String name + LayoutAllRoot target +} + +@Entity +class LayoutTargetDefault { + String name +} + +@Entity +class LayoutOwnerDefault implements MultiTenant { + String name + LayoutTargetDefault target +} + +@jakarta.persistence.Entity +class LayoutJpaTarget { + @jakarta.persistence.Id + Long id + String name +} + +@Entity +class LayoutOwnerJpa implements MultiTenant { + String name + LayoutJpaTarget target +} + +@jakarta.persistence.Entity +class KnownJpaTarget { + @jakarta.persistence.Id + Long id + String name +} + +@Entity +class KnownOwnerJpa implements MultiTenant { + String name + KnownJpaTarget target +} + +class KnownTenantsResolver implements AllTenantsResolver { + @Override + Serializable resolveTenantIdentifier() { + 'tenant1' + } + + @Override + Iterable resolveTenantIds() { + ['tenant1'] + } +} + +@Entity +class KnownTargetDefaultAndTenant { + String name + static mapping = { + datasources(['default', 'tenant1']) + } +} + +@Entity +class KnownOwnerDefaultAndTenant implements MultiTenant { + String name + KnownTargetDefaultAndTenant target +} + +@Entity +class KnownTargetTenantOnly { + String name + static mapping = { + datasources(['tenant1']) + } +} + +@Entity +class KnownOwnerTenantOnly implements MultiTenant { + String name + KnownTargetTenantOnly target +} + +@Entity +class KnownTargetAll { + String name + static mapping = { + datasource 'ALL' + } +} + +@Entity +class KnownOwnerAll implements MultiTenant { + String name + KnownTargetAll target +} + +@Entity +class KnownTargetDefaultOnly { + String name +} + +@Entity +class KnownOwnerDefaultOnly implements MultiTenant { + String name + KnownTargetDefaultOnly target +} + +@Entity +class KnownTargetOtherTenant { + String name + static mapping = { + datasources(['default', 'tenant2']) + } +} + +@Entity +class KnownOwnerOtherTenant implements MultiTenant { + String name + KnownTargetOtherTenant target +} diff --git a/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationSpec.groovy b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationSpec.groovy new file mode 100644 index 00000000000..915fc6c9393 --- /dev/null +++ b/grails-data-hibernate5/core/src/test/groovy/grails/gorm/tests/SchemaTenantAssociationSpec.groovy @@ -0,0 +1,101 @@ +/* + * 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.MultiTenant +import grails.gorm.annotation.Entity +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.datastore.mapping.core.exceptions.ConfigurationException +import org.grails.orm.hibernate.cfg.Settings +import org.grails.orm.hibernate.HibernateDatastore +import spock.lang.Issue +import spock.lang.Specification + +@Issue('https://github.com/apache/grails-core/issues/14345') +class SchemaTenantAssociationSpec extends Specification { + + private static HibernateDatastore start(Class... classes) { + Map config = [ + (Settings.SETTING_DB_CREATE) : 'create-drop', + 'dataSource.url' : "jdbc:h2:mem:schemaTenantAssociation${System.nanoTime()};LOCK_TIMEOUT=10000", + 'grails.gorm.multiTenancy.mode' : 'SCHEMA', + 'grails.gorm.multiTenancy.tenantResolverClass': 'org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantResolver' + ] + new HibernateDatastore(DatastoreUtils.createPropertyResolver(config), classes) + } + + void "a hasMany from a multi tenant entity to an entity that is not multi tenant is refused with a clear message"() { + when: + start(StaOwner, StaShared) + + then: + ConfigurationException e = thrown() + e.message.contains('StaOwner.shared -> StaShared') + e.message.contains('DISCRIMINATOR') + } + + void "a to-one association from a multi tenant entity to an entity that is not multi tenant is refused"() { + when: + start(StaRef, StaShared) + + then: + ConfigurationException e = thrown() + e.message.contains('StaRef.shared -> StaShared') + } + + void "associations between multi tenant entities still start"() { + when: + HibernateDatastore datastore = start(StaTenantChild, StaTenantParent) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + } +} + +@Entity +class StaShared { + String name +} + +@Entity +class StaOwner implements MultiTenant { + String name + static hasMany = [shared: StaShared] +} + +@Entity +class StaRef implements MultiTenant { + String name + StaShared shared +} + +@Entity +class StaTenantChild implements MultiTenant { + String name +} + +@Entity +class StaTenantParent implements MultiTenant { + String name + StaTenantChild child + static hasMany = [children: StaTenantChild] +} diff --git a/grails-data-hibernate5/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc b/grails-data-hibernate5/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc index ff365424c25..f94296d68bd 100644 --- a/grails-data-hibernate5/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc +++ b/grails-data-hibernate5/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc @@ -39,6 +39,10 @@ The `TenantResolver` can optionally implement the `AllTenantsResolver` interface If the `AllTenantsResolver` resolver is not implemented then GORM will use the configured link:../api/org/grails/org/hibernate/jdbc/schema/SchemaHandler.html[SchemaHandler] to resolve all the schema names from the database which it will use for the tenants. +==== Associations to Entities That Are Not Multi-Tenant + +Each tenant schema gets its own `SessionFactory`, which maps the entities that implement `MultiTenant` and every other entity whose mapping uses that schema's connection: one that declares `datasource 'ALL'`, or one that lists the schema by name. The default connection maps the `MultiTenant` entities too, so a target that is not `MultiTenant` has to be mapped there as well: list `default` together with the tenant schemas, or use `ALL`. An entity that implements `MultiTenant` can have a `hasMany` or a to-one association to such an entity only when every connection that maps the owner maps the target. When one does not, the association has nothing to refer to: GORM refuses to start and names the associations, for example `Vehicle` in `TenantUser.vehicles -> Vehicle`. Make the target entity implement `MultiTenant` as well, map it on every tenant schema, or use the `DISCRIMINATOR` mode, which keeps every entity in the same tables. The check runs against the tenant schemas known at startup, so a schema added later has to map the target too: use `datasource 'ALL'` when tenants can be added at runtime. Embedded associations are not affected. + ==== Runtime Schema Creation On startup, if `dataSource.dbCreate` is set to create the database at runtime, then GORM will attempt to create the schemas if they are missing. diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java index 1aeba5accca..54ecd126981 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/HibernateDatastore.java @@ -102,6 +102,7 @@ import org.grails.datastore.mapping.core.connections.ConnectionSourceFactory; import org.grails.datastore.mapping.core.connections.ConnectionSources; import org.grails.datastore.mapping.core.connections.ConnectionSourcesInitializer; +import org.grails.datastore.mapping.core.connections.ConnectionSourcesSupport; import org.grails.datastore.mapping.core.connections.DefaultConnectionSource; import org.grails.datastore.mapping.core.connections.MultipleConnectionSourceCapableDatastore; import org.grails.datastore.mapping.core.connections.SingletonConnectionSources; @@ -343,17 +344,23 @@ public void persistentEntityAdded(PersistentEntity entity) { }); if (multiTenantMode == MultiTenancySettings.MultiTenancyMode.SCHEMA) { - if (this.tenantResolver instanceof AllTenantsResolver allTenantsResolver) { - Iterable tenantIds = allTenantsResolver.resolveTenantIds(); - for (Serializable tenantId : tenantIds) { - addTenantForSchemaInternal(tenantId.toString()); - } - } else { - Collection allSchemas = schemaHandler.resolveSchemaNames(defaultConnectionSource.getDataSource()); - for (String schema : allSchemas) { - addTenantForSchemaInternal(schema); + Collection tenantSchemaNames = new ArrayList<>(); + if (this.tenantResolver instanceof AllTenantsResolver) { + for (Serializable tenantId : ((AllTenantsResolver) tenantResolver).resolveTenantIds()) { + tenantSchemaNames.add(tenantId.toString()); } } + else { + tenantSchemaNames.addAll(schemaHandler.resolveSchemaNames(defaultConnectionSource.getDataSource())); + } + List unmapped = ConnectionSourcesSupport.findAssociationsToEntitiesMissingFromTenantSchemas(mappingContext.getPersistentEntities(), tenantSchemaNames); + if (!unmapped.isEmpty()) { + throw new ConfigurationException("Multi-tenancy mode SCHEMA cannot map an association from a MultiTenant entity to an entity that is not MultiTenant and that a tenant schema does not map: " + + String.join(", ", unmapped) + ". Make the target MultiTenant, map it on every tenant schema (datasource 'ALL', or name each schema), or use the DISCRIMINATOR multi-tenancy mode."); + } + for (String tenantSchemaName : tenantSchemaNames) { + addTenantForSchemaInternal(tenantSchemaName); + } } } diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/SchemaTenantAssociationLayoutSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/SchemaTenantAssociationLayoutSpec.groovy new file mode 100644 index 00000000000..373296400a1 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/SchemaTenantAssociationLayoutSpec.groovy @@ -0,0 +1,325 @@ +/* + * 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.MultiTenant +import grails.gorm.annotation.Entity +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.datastore.mapping.core.exceptions.ConfigurationException +import org.grails.datastore.mapping.multitenancy.AllTenantsResolver +import org.grails.orm.hibernate.cfg.Settings +import spock.lang.Issue +import spock.lang.Specification +import spock.lang.Unroll + +/** + * With SCHEMA multi-tenancy a tenant schema maps the multi tenant entities and the others only when they use every + * connection. The startup check must refuse exactly the associations that have nothing to refer to, so each layout + * a mapping can declare for the target is tried: the ones that reach the tenant schemas must start. + */ +@Issue('https://github.com/apache/grails-core/issues/14345') +class SchemaTenantAssociationLayoutSpec extends Specification { + + private static HibernateDatastore start(Class... classes) { + startWith([:], classes) + } + + private static HibernateDatastore startWith(Map extra, Class... classes) { + Map config = [ + (Settings.SETTING_DB_CREATE) : 'create-drop', + 'dataSource.url' : "jdbc:h2:mem:schemaTenantLayout${System.nanoTime()};LOCK_TIMEOUT=10000", + 'grails.gorm.multiTenancy.mode' : 'SCHEMA', + 'grails.gorm.multiTenancy.tenantResolverClass': 'org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantResolver' + ] + config.putAll(extra) + new HibernateDatastore(DatastoreUtils.createPropertyResolver(config), classes) + } + + @Unroll + void "an owner of a multi tenant entity pointing at a target #layout is refused at startup"() { + when: + start(*classes) + + then: + ConfigurationException e = thrown() + e.message.contains(classes[0].simpleName) + + where: + layout | classes + 'with no datasource declared' | [LayoutOwnerNone, LayoutTargetNone] + } + + @Unroll + void "an owner of a multi tenant entity pointing at a target #layout starts"() { + when: + HibernateDatastore datastore = start(*classes) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + + where: + layout | classes + 'that declares datasource ALL' | [LayoutOwnerAll, LayoutTargetAll] + 'that declares datasources with only ALL' | [LayoutOwnerAllList, LayoutTargetAllList] + 'that is a subclass of a root using every connection' | [LayoutOwnerChild, LayoutAllRoot, LayoutAllChild] + 'that is the root of a hierarchy using every connection' | [LayoutOwnerRoot, LayoutAllRoot, LayoutAllChild] + 'that is mapped by a JPA annotation and lists no datasource' | [LayoutOwnerJpa, LayoutJpaTarget] + } + + private static HibernateDatastore startWithTenants(Class... classes) { + startWith(['grails.gorm.multiTenancy.tenantResolverClass': KnownTenantsResolver.name], classes) + } + + @Unroll + void "with the tenant schemas known, an owner pointing at a target that #layout starts"() { + when: + HibernateDatastore datastore = startWithTenants(*classes) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + + where: + layout | classes + 'lists the default connection and the tenant' | [KnownOwnerDefaultAndTenant, KnownTargetDefaultAndTenant] + 'declares datasource ALL' | [KnownOwnerAll, KnownTargetAll] + 'is mapped by a JPA annotation and lists no datasource' | [KnownOwnerJpa, KnownJpaTarget] + } + + @Unroll + void "with the tenant schemas known, an owner pointing at a target that #layout is refused at startup"() { + when: + startWithTenants(*classes) + + then: + ConfigurationException e = thrown() + e.message.contains(classes[0].simpleName) + + where: + layout | classes + 'lists only the default connection' | [KnownOwnerDefaultOnly, KnownTargetDefaultOnly] + 'lists the default connection and another tenant' | [KnownOwnerOtherTenant, KnownTargetOtherTenant] + } + + void "with the tenant schemas known, an owner pointing at a target that lists only the tenant schema does not start"() { + when: 'the default connection also maps the owner, and not the target; Hibernate refuses it before the schema check runs' + startWithTenants(KnownOwnerTenantOnly, KnownTargetTenantOnly) + + then: + thrown(Exception) + } + + void "an owner of a multi tenant entity pointing at a target that uses every connection through the default mapping starts"() { + when: + HibernateDatastore datastore = startWith(['grails.gorm.default.mapping': { datasource 'ALL' }], + LayoutOwnerDefault, LayoutTargetDefault) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + } +} + +@Entity +class LayoutTargetNone { + String name +} + +@Entity +class LayoutOwnerNone implements MultiTenant { + String name + LayoutTargetNone target +} + +@Entity +class LayoutTargetAll { + String name + static mapping = { + datasource 'ALL' + } +} + +@Entity +class LayoutOwnerAll implements MultiTenant { + String name + LayoutTargetAll target +} + +@Entity +class LayoutTargetAllList { + String name + static mapping = { + datasources(['ALL']) + } +} + +@Entity +class LayoutOwnerAllList implements MultiTenant { + String name + LayoutTargetAllList target +} + +@Entity +class LayoutAllRoot { + String name + static mapping = { + datasource 'ALL' + } +} + +@Entity +class LayoutAllChild extends LayoutAllRoot { + String extra +} + +@Entity +class LayoutOwnerChild implements MultiTenant { + String name + LayoutAllChild target +} + +@Entity +class LayoutOwnerRoot implements MultiTenant { + String name + LayoutAllRoot target +} + +@Entity +class LayoutTargetDefault { + String name +} + +@Entity +class LayoutOwnerDefault implements MultiTenant { + String name + LayoutTargetDefault target +} + +@jakarta.persistence.Entity +class LayoutJpaTarget { + @jakarta.persistence.Id + Long id + String name +} + +@Entity +class LayoutOwnerJpa implements MultiTenant { + String name + LayoutJpaTarget target +} + +@jakarta.persistence.Entity +class KnownJpaTarget { + @jakarta.persistence.Id + Long id + String name +} + +@Entity +class KnownOwnerJpa implements MultiTenant { + String name + KnownJpaTarget target +} + +class KnownTenantsResolver implements AllTenantsResolver { + @Override + Serializable resolveTenantIdentifier() { + 'tenant1' + } + + @Override + Iterable resolveTenantIds() { + ['tenant1'] + } +} + +@Entity +class KnownTargetDefaultAndTenant { + String name + static mapping = { + datasources(['default', 'tenant1']) + } +} + +@Entity +class KnownOwnerDefaultAndTenant implements MultiTenant { + String name + KnownTargetDefaultAndTenant target +} + +@Entity +class KnownTargetTenantOnly { + String name + static mapping = { + datasources(['tenant1']) + } +} + +@Entity +class KnownOwnerTenantOnly implements MultiTenant { + String name + KnownTargetTenantOnly target +} + +@Entity +class KnownTargetAll { + String name + static mapping = { + datasource 'ALL' + } +} + +@Entity +class KnownOwnerAll implements MultiTenant { + String name + KnownTargetAll target +} + +@Entity +class KnownTargetDefaultOnly { + String name +} + +@Entity +class KnownOwnerDefaultOnly implements MultiTenant { + String name + KnownTargetDefaultOnly target +} + +@Entity +class KnownTargetOtherTenant { + String name + static mapping = { + datasources(['default', 'tenant2']) + } +} + +@Entity +class KnownOwnerOtherTenant implements MultiTenant { + String name + KnownTargetOtherTenant target +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/SchemaTenantAssociationSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/SchemaTenantAssociationSpec.groovy new file mode 100644 index 00000000000..0b7c1cbb81a --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/SchemaTenantAssociationSpec.groovy @@ -0,0 +1,101 @@ +/* + * 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.MultiTenant +import grails.gorm.annotation.Entity +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.datastore.mapping.core.exceptions.ConfigurationException +import org.grails.orm.hibernate.cfg.Settings + +import spock.lang.Issue +import spock.lang.Specification + +@Issue('https://github.com/apache/grails-core/issues/14345') +class SchemaTenantAssociationSpec extends Specification { + + private static HibernateDatastore start(Class... classes) { + Map config = [ + (Settings.SETTING_DB_CREATE) : 'create-drop', + 'dataSource.url' : "jdbc:h2:mem:schemaTenantAssociation${System.nanoTime()};LOCK_TIMEOUT=10000", + 'grails.gorm.multiTenancy.mode' : 'SCHEMA', + 'grails.gorm.multiTenancy.tenantResolverClass': 'org.grails.datastore.mapping.multitenancy.resolvers.SystemPropertyTenantResolver' + ] + new HibernateDatastore(DatastoreUtils.createPropertyResolver(config), classes) + } + + void "a hasMany from a multi tenant entity to an entity that is not multi tenant is refused with a clear message"() { + when: + start(StaOwner, StaShared) + + then: + ConfigurationException e = thrown() + e.message.contains('StaOwner.shared -> StaShared') + e.message.contains('DISCRIMINATOR') + } + + void "a to-one association from a multi tenant entity to an entity that is not multi tenant is refused"() { + when: + start(StaRef, StaShared) + + then: + ConfigurationException e = thrown() + e.message.contains('StaRef.shared -> StaShared') + } + + void "associations between multi tenant entities still start"() { + when: + HibernateDatastore datastore = start(StaTenantChild, StaTenantParent) + + then: + noExceptionThrown() + + cleanup: + datastore?.close() + } +} + +@Entity +class StaShared { + String name +} + +@Entity +class StaOwner implements MultiTenant { + String name + static hasMany = [shared: StaShared] +} + +@Entity +class StaRef implements MultiTenant { + String name + StaShared shared +} + +@Entity +class StaTenantChild implements MultiTenant { + String name +} + +@Entity +class StaTenantParent implements MultiTenant { + String name + StaTenantChild child + static hasMany = [children: StaTenantChild] +} diff --git a/grails-data-hibernate7/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc b/grails-data-hibernate7/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc index 09a09fba759..829eb903866 100644 --- a/grails-data-hibernate7/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc +++ b/grails-data-hibernate7/docs/src/docs/asciidoc/multiTenancy/schemaPerTenant.adoc @@ -39,6 +39,10 @@ The `TenantResolver` can optionally implement the `AllTenantsResolver` interface If the `AllTenantsResolver` resolver is not implemented then GORM will use the configured link:../api/org/grails/org/hibernate/jdbc/schema/SchemaHandler.html[SchemaHandler] to resolve all the schema names from the database which it will use for the tenants. +==== Associations to Entities That Are Not Multi-Tenant + +Each tenant schema gets its own `SessionFactory`, which maps the entities that implement `MultiTenant` and every other entity whose mapping uses that schema's connection: one that declares `datasource 'ALL'`, or one that lists the schema by name. The default connection maps the `MultiTenant` entities too, so a target that is not `MultiTenant` has to be mapped there as well: list `default` together with the tenant schemas, or use `ALL`. An entity that implements `MultiTenant` can have a `hasMany` or a to-one association to such an entity only when every connection that maps the owner maps the target. When one does not, the association has nothing to refer to: GORM refuses to start and names the associations, for example `Vehicle` in `TenantUser.vehicles -> Vehicle`. Make the target entity implement `MultiTenant` as well, map it on every tenant schema, or use the `DISCRIMINATOR` mode, which keeps every entity in the same tables. The check runs against the tenant schemas known at startup, so a schema added later has to map the target too: use `datasource 'ALL'` when tenants can be added at runtime. Embedded associations are not affected. + ==== Runtime Schema Creation On startup, if `dataSource.dbCreate` is set to create the database at runtime, then GORM will attempt to create the schemas if they are missing. diff --git a/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/connections/ConnectionSourcesSupportSpec.groovy b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/connections/ConnectionSourcesSupportSpec.groovy new file mode 100644 index 00000000000..f9cb17fa5fd --- /dev/null +++ b/grails-datamapping-core/src/test/groovy/org/grails/datastore/gorm/connections/ConnectionSourcesSupportSpec.groovy @@ -0,0 +1,94 @@ +/* + * 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.datastore.gorm.connections + +import grails.gorm.MultiTenant +import org.grails.datastore.mapping.core.connections.ConnectionSourcesSupport +import grails.gorm.annotation.Entity +import org.grails.datastore.mapping.simple.SimpleMapDatastore +import spock.lang.Issue +import spock.lang.Specification + +@Issue('https://github.com/apache/grails-core/issues/14345') +class ConnectionSourcesSupportSpec extends Specification { + + private static List findIn(Class... classes) { + SimpleMapDatastore datastore = new SimpleMapDatastore(classes) + try { + ConnectionSourcesSupport.findAssociationsToEntitiesMissingFromTenantSchemas(datastore.mappingContext.persistentEntities) + } finally { + datastore.close() + } + } + + void "a hasMany from a multi tenant entity to an entity that is not multi tenant is reported"() { + expect: + findIn(SharedThing, TenantOwner) == ['TenantOwner.things -> SharedThing'] + } + + void "a to-one association from a multi tenant entity to an entity that is not multi tenant is reported"() { + expect: + findIn(SharedThing, TenantRef) == ['TenantRef.shared -> SharedThing'] + } + + void "associations between multi tenant entities are not reported"() { + expect: + findIn(TenantChild, TenantOwnerOfTenants).isEmpty() + } + + void "an association from an entity that is not multi tenant is not reported"() { + expect: + findIn(SharedThing, PlainOwner).isEmpty() + } +} + +@Entity +class SharedThing { + String name +} + +@Entity +class TenantOwner implements MultiTenant { + String name + static hasMany = [things: SharedThing] +} + +@Entity +class TenantRef implements MultiTenant { + String name + SharedThing shared +} + +@Entity +class TenantChild implements MultiTenant { + String name +} + +@Entity +class TenantOwnerOfTenants implements MultiTenant { + String name + TenantChild child + static hasMany = [children: TenantChild] +} + +@Entity +class PlainOwner { + String name + static hasMany = [things: SharedThing] +} diff --git a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/connections/ConnectionSourcesSupport.java b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/connections/ConnectionSourcesSupport.java index bcf560494b1..5307455962b 100644 --- a/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/connections/ConnectionSourcesSupport.java +++ b/grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/connections/ConnectionSourcesSupport.java @@ -19,14 +19,22 @@ package org.grails.datastore.mapping.core.connections; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; import org.springframework.util.ClassUtils; import org.grails.datastore.mapping.config.Entity; import org.grails.datastore.mapping.model.PersistentEntity; +import org.grails.datastore.mapping.model.PersistentProperty; +import org.grails.datastore.mapping.model.types.Association; +import org.grails.datastore.mapping.model.types.Embedded; +import org.grails.datastore.mapping.model.types.EmbeddedCollection; import org.grails.datastore.mapping.multitenancy.TenantDataSourceConfig; /** @@ -39,6 +47,8 @@ public class ConnectionSourcesSupport { public static final List DEFAULT_CONNECTION_SOURCE_NAMES = Collections.singletonList(ConnectionSource.DEFAULT); + private static final String JPA_ENTITY_ANNOTATION = "jakarta.persistence.Entity"; + /** * If a domain class uses more than one datasource, we need to know which one to use * when calling a method without a namespace qualifier. @@ -87,6 +97,87 @@ public static boolean usesConnectionSource(PersistentEntity entity, String conne } } + /** + * With schema based multi-tenancy every tenant schema gets its own connection source, which maps the + * multi tenant entities but only those other entities that use that connection source. An association + * from a multi tenant entity to any other entity therefore has nothing to refer to in a tenant schema + * that does not map the target. + * + *

Without the names of the tenant schemas the target has to use every connection source ({@code ALL}), + * because any schema can be added later. + * + * @param entities The persistent entities of the application + * @return A description of each association of a multi tenant entity to an entity the tenant schemas do + * not map, in the form {@code Owner.property -> Target}; empty when there is none + */ + public static List findAssociationsToEntitiesMissingFromTenantSchemas(Iterable entities) { + return findAssociationsToEntitiesMissingFromTenantSchemas(entities, Collections.emptyList()); + } + + /** + * The same check against the tenant schemas that are known: a target is mapped when it uses every connection + * source or lists each of the named tenant schemas, so a shared entity that names the default connection and + * the tenant schemas explicitly is accepted. + * + * @param entities The persistent entities of the application + * @param tenantSchemaNames The names of the tenant schemas (connection sources) that exist now + * @return A description of each association of a multi tenant entity to an entity that at least one tenant + * schema does not map, in the form {@code Owner.property -> Target}; empty when there is none + */ + public static List findAssociationsToEntitiesMissingFromTenantSchemas(Iterable entities, Collection tenantSchemaNames) { + List found = new ArrayList<>(); + for (PersistentEntity entity : entities) { + if (!entity.isMultiTenant()) { + continue; + } + for (PersistentProperty property : entity.getPersistentProperties()) { + if (!(property instanceof Association) || property instanceof Embedded || property instanceof EmbeddedCollection) { + continue; + } + PersistentEntity target = ((Association) property).getAssociatedEntity(); + if (target != null && !target.isMultiTenant() && !isMappedWhereOwnerIs(entity, target, tenantSchemaNames)) { + found.add(entity.getJavaClass().getSimpleName() + '.' + property.getName() + " -> " + target.getJavaClass().getSimpleName()); + } + } + } + return found; + } + + /** + * Whether the target is mapped on every connection source the owner is mapped on: each tenant schema, and the default + * connection, which also maps a multi tenant entity. A target that lists the tenant schema but not the default connection + * leaves the default session factory with an association to an entity it does not map. + */ + private static boolean isMappedWhereOwnerIs(PersistentEntity owner, PersistentEntity target, Collection tenantSchemaNames) { + if (getConnectionSourceNames(target).contains(ConnectionSource.ALL) || isMappedByJpaAnnotation(target)) { + return true; + } + if (tenantSchemaNames == null || tenantSchemaNames.isEmpty()) { + return false; + } + Set names = new LinkedHashSet<>(tenantSchemaNames); + names.add(ConnectionSource.DEFAULT); + for (String name : names) { + if (usesConnectionSource(owner, name) && !usesConnectionSource(target, name)) { + return false; + } + } + return true; + } + + /** + * Whether the entity is a JPA entity by its annotation. The Hibernate binders add such a class to every session factory, + * whatever datasources its mapping lists, so it is mapped on each tenant schema. + */ + private static boolean isMappedByJpaAnnotation(PersistentEntity entity) { + for (java.lang.annotation.Annotation annotation : entity.getJavaClass().getAnnotations()) { + if (JPA_ENTITY_ANNOTATION.equals(annotation.annotationType().getName())) { + return true; + } + } + return false; + } + protected static boolean isMultiTenant(Class[] interfaces) { for (Class anInterface : interfaces) { String name = anInterface.getName();