Skip to content

fix(datamapping): a save that names a connection checks the unique constraint on that connection - #17136

Draft
borinquenkid wants to merge 13 commits into
7.0.xfrom
fix/unique-constraint-named-connection-7.0.x
Draft

borinquenkid wants to merge 13 commits into
7.0.xfrom
fix/unique-constraint-named-connection-7.0.x

Conversation

@borinquenkid

Copy link
Copy Markdown
Member

A save() that names a connection, such as book.second.save(), Book.second.save(book) or Book.second.insert(book), checked the unique constraint against the default data source, whichever connection it named. With a value that exists on one connection only, the check of a save to the second connection looked at the default one: a value that is free on the second connection was reported as a duplicate, and one that exists only on the second was missed, so the save failed at the unique index with a DuplicateKeyException, or, with MongoDB, stored a second copy.

UniqueConstraint built its DetachedCriteria with no connection. The API of a connection now runs its save and its validation with that connection as the one the check uses (AbstractGormApi.inConnection), and the constraint applies it with withConnection. An API of the default connection changes nothing. This is the 7.0.x half of #16935: 7.0.x has no connection scope, so the unqualified calls inside Book.second.withTransaction { } still go to the default connection here, and so does their check.

Tests:

  • UniqueNamedConnectionSpec (Hibernate 5, three H2 data sources): a save that names the second connection is refused for a value of the second and saved for one of the default; the same through Book.second.save(book) and insert; a save that names the third inside a block of the second checks the third; a save through the default connection still checks the default. Three of its four features fail without the change.
  • UniqueNamedConnectionMongoSpec (MongoDB, two connections): the same for Book.archive.save(...). Docker was not running where this was written, so this spec has not run yet; CI runs it first.

Results that change

For a domain class mapped to several data sources, with a unique constraint:

  • a save that names a connection checks that connection, so a value that exists only on the default data source is no longer reported as a duplicate while saving to another one, and a value that exists only on the other connection is now found;
  • validate() through the API of a connection is checked there too.

Code that relied on one value being unique across every data source has to enforce that itself. The guide, the unique reference and the upgrade skill say so.

Part of #16934. The 8.0.x half, with the connection block, is #16935.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

Copilot AI left a comment

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A save through the default connection, made while another connection is being saved, is still checked on the other connection.

*/
protected <T1> T1 inConnection(Closure<T1> callable) {
String connection = connectionName()
if (connection == null || ConnectionSource.DEFAULT == connection) {

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.

A save on another connection runs a check that saves a new instance through the default connection. That value is free on the default connection. The save is refused, because the other connection is still the one being checked. Check the connection the inner save named.

…fault connection also inside a save that names another one

inConnection left the connection of an outer save on the thread when the API was the one of the default connection, so
a save through the default connection, made while a save on another connection ran, had its unique constraint checked
on the other connection. An API of the default connection now clears the named connection for its call and restores it.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed. inConnection left the connection of an outer save on the thread when the API was the one of the default connection, so a save through the default connection made while a save on another connection ran was still checked on the other one. An API of the default connection now clears the named connection for its call and restores it afterwards. UniqueNamedConnectionSpec has the case: the validator of a book saved on the third connection saves an audit through the default connection, where the value is free and taken on the third; it fails without the change. A second row keeps the outer save checked on the third connection afterwards. grails-datamapping-core and the Hibernate 5 module pass, and so does codeStyle.

@sanjana2505006 sanjana2505006 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for this fix, the approach reads cleanly. While going through it I noticed three things that might need a look. I may be missing context, so please correct me if any of these are wrong.

  1. Stateless validation APIs (RxGORM) may now throw on validate().
  2. The Mongo spec maps 'default' in lowercase, which I think stops the datastore from starting.
  3. Cascaded validation of an associated entity could pick up the parent's connection.

Details are inline. Happy to help with tests if that's useful.

}

private String connectionName() {
Datastore current = getDatastore()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

getDatastore() throws IllegalStateException ("No datastore configured in stateless mode") when the API was built without a datastore. RxGormValidationApi uses the MappingContext constructor, and doValidate now calls inConnection before the existing hasDatastore check, so I think every RxGORM validate() would fail here. Would a null-safe read (e.g. this.@datastore) work instead?

}

static mapping = {
connections 'default', 'archive'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this needs to be ConnectionSource.DEFAULT ('DEFAULT'). The name is matched case-sensitively, so 'default' gets registered as its own qualifier, and getDatastoreForQualifier then throws ConfigurationException("Invalid connection [default] ...") while setupSpec builds the datastore.

// a save or a validation that names a connection, such as book.third.save(), checks that connection
String namedConnection = AbstractGormApi.validationConnection()
if (namedConnection != null) {
detachedCriteria = detachedCriteria.withConnection(namedConnection)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Question: cascading validation calls the associated entity's validator directly, so the thread-local from the parent's save still applies here. If the associated class isn't mapped to that connection, for example a non-MultiTenant child of a MultiTenant parent in DATABASE mode, findStaticApi(cls, name) would throw. Would it make sense to apply the connection only when ConnectionSourcesSupport.usesConnectionSource(entity, namedConnection) is true?

…he connection of a save runs on its own connection, and the Mongo spec names the default connection

The validation of an association cascades to the validator of the associated entity, which runs inside the save that names a
connection, so its unique constraint asked for that connection on an entity that may not be mapped to it, and the lookup of
its static API threw. The named connection applies where the entity checked is mapped to it (ConnectionSourcesSupport).
UniqueNamedConnectionMongoSpec mapped the default connection as 'default', which the datastore rejects because connection names
are case-sensitive, so the spec never ran; it uses ConnectionSource.DEFAULT now.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@sanjana2505006 thank you for the careful read. Your three points, in order:

  1. Stateless APIs (RxGORM). I traced it with an API built from a mapping context only, as RxGormValidationApi is. inConnection did ask getDatastore(), but with that out of the way the same validate() throws a few lines later, at GormValidationApi.getErrors, which reads datastore.currentSession; that code is on 7.0.x as it is and this pull request only wraps the call in inConnection. So a stateless validate() fails before and after this change, and grails-datamapping-rx is commented out of settings.gradle, so nothing builds or runs it. I did not change connectionName(): reading the field would only move where the exception comes from, and no test through the public API could tell. If the Rx module comes back, getErrors and createValidationEvent are where a stateless validate needs work.
  2. The Mongo spec. You are right, and it was worse than the casing: the spec had never run, because the datastore refuses 'default' (Invalid connection [default] configured for class ...UniqueNamedItem). It uses ConnectionSource.DEFAULT now, and both of its features pass.
  3. Cascaded validation. Also right. The validator of an associated entity is called inside the save that names the connection, so for an entity that is not mapped to it the lookup of its static API threw. The named connection now applies only where the entity checked is mapped to it (ConnectionSourcesSupport.usesConnectionSource). UniqueNamedConnectionSpec has a validator that calls the validator of an entity of the default connection only, as cascading does; it fails without the change with ... is not a domain class or GORM has not been initialized correctly, and passes with it.

The Hibernate 5, datamapping-core and MongoDB core modules pass, and so does codeStyle.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A check that has no datastore now throws before it runs.

}
}

private String connectionName() {

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.

A check is built with a mapping and no datastore. Validating an instance should run that check. It throws, because this asks for a datastore that was not given. Run the check without one.

…s the constraints

A validation API built from a mapping context has no datastore. Naming the connection of the validation asked for it through the getter,
which throws, and so did firing the validation event, whose source is a datastore. The connection of an API without one is the default,
read from the field, and the event is not fired when there is no datastore to name as its source. ValidationWithoutDatastoreSpec runs
validate, validate with fields, validate with arguments and hasErrors, for a valid and an invalid instance, on Hibernate 5 and MongoDB.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Reproduced and fixed. A validation API built from a mapping context has no datastore, and naming the connection of the validation read it through the getter, which throws; the connection of an API without a datastore is the default one, so it is read from the field now. That was only the first of two places that asked for it: firing the validation event did as well, because the event's source is a datastore, and that was already the case before this pull request, so an API built that way could not validate at all. It does not fire the event when there is no datastore to name; beforeValidate still runs.

ValidationWithoutDatastoreSpec (TCK) builds the API from the mapping context only and runs each entry point for a valid and an invalid instance: validate, validate with a list of fields (the invalid field asked for and not asked for), validate with arguments, and hasErrors after validate. All ten pass on Hibernate 5 and MongoDB, and all ten fail before the change.

Checked and not changed: GormValidationApi is the only API with a constructor that takes a mapping context, so it is the only one that can lack a datastore; the instance API and both Hibernate APIs are always built with one. Not covered: the in-memory datastore does not register its validators in the mapping context, so an API built from that context finds none and validates nothing, which is a different gap; and getErrors of an instance that is not a GormValidateable still needs a datastore, since its errors are kept in the session.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A check that has no datastore is now sent through a connection.

}

private boolean doValidate(D instance, Map arguments, List fields) {
return inConnection { doValidateInConnection(instance, arguments, fields) }

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.

A check is built with a mapping and no datastore. Validating a plain bean should record the failure. It throws, because this sends every check through a connection. Run the check without one.

@sanjana2505006

Copy link
Copy Markdown
Member

Thanks @borinquenkid, all three points are addressed: reading the field fixes the no-datastore path, the Mongo spec now runs with ConnectionSource.DEFAULT, and the usesConnectionSource check handles cascaded validation. I've resolved my threads. I'll approve once James's comment on validating a plain object without a datastore is settled.

…s errors on the API

Validating a bean that does not hold its own errors, through an API built from a mapping context, read and wrote its errors on the session of a datastore the API does not have, and threw. The errors of such a bean now live on the API, as they live on the session when there is a datastore.

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed 5e23444. The throw was in the errors of a bean that is not a GormValidateable: getErrors, setErrors and hasErrors kept them on datastore.currentSession, and an API built from a mapping context has no datastore.

Such a bean's errors now live on the API when there is no datastore (a weak map keyed by the bean), and on the session as before when there is one. PlainBeanValidationWithoutDatastoreSpec covers a valid and a blank-named bean, two beans that do not share errors, and clearErrors; its four rows fail with the change reverted and pass with it. grails-datamapping-core runs 256 tests green, ValidationWithoutDatastoreSpec passes on Hibernate 5, and codeStyle is clean.

@jamesfredley jamesfredley left a comment

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.

Requested changes. A listener checks uniqueness before the save has chosen its connection.

@@ -126,12 +126,15 @@ abstract class AbstractHibernateGormInstanceApi<D> extends GormInstanceApi<D> {
if (validator) {
datastore.applicationEventPublisher?.publishEvent(new ValidationEvent(datastore, target))

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.

A value exists only on the default connection. Saving it on another connection should succeed. A listener runs the check first and sees the default connection, so the save is refused. Choose the connection before that listener runs.

@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed 80ba875. The event the save publishes (ValidationEvent) was published before the save entered its connection, so a listener that checked the target ran with no connection chosen and checked the default one. It now runs inside it, in both places Hibernate 5 publishes it: AbstractHibernateGormInstanceApi line 129 for a save, and AbstractHibernateGormValidationApi line 80 for a validation. The validation of the core API (GormValidationApi.fireEvent) already ran inside its connection block.

The test: UniqueNamedConnectionSpec line 162, a listener that runs the entity's validator on the target of each event, for a save of the instance and a save of the API, with a value that exists only on the default connection, saved on the second; and line 186, the same listener for an audit saved or validated through the default connection while a save on the third connection runs, which must see the default one. Four rows fail without the change. grails-data-hibernate5-core (712 tests), grails-datamapping-core (256) and codeStyle are green.

Documentation: the constraint's reference page says only that the check is a persistent call (unique.adoc line 45, with the sentence this PR adds below it); the upgrade note is upgrading60x.adoc line 1338. Nothing documents which connection a listener of the event sees.

@sanjana2505006 sanjana2505006 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @borinquenkid, the plain object case no longer throws, and the listener fix works for me too. I said I would approve after that, but I found two more things while testing 80ba875:

  1. Hibernate 5: an update through a named connection can be silently lost. If the new value exists only on the default connection, b.second.save() without flush: true returns the object, but the row is not updated. Before this PR it returned null with a unique error. At flush, ClosureEventListener.doValidate validates through the default API and cancels the update.

  2. unattachedErrors never frees its entries, because each ValidationErrors holds its bean. It also compares beans by equals, so two equal beans share errors.

The first one is the main blocker for me. I'm happy to approve once these are fixed. Sorry for not catching them earlier.

validator.validate(target, errors)
// on the connection this API names, which a connection block around the save does not decide, and the
// listeners of the event run on it too: one that checks the target checks that connection
inConnection {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this also needs a fix at flush time. With a value that exists only on the default connection:

b.name = 'onDefault'
b.second.save()   // flushed at commit

save() returns the object, but the row is not updated. Before this PR it returned null with a unique error. With flush: true it works.

At flush, ClosureEventListener.doValidate calls validate() through the default API, finds the value there and cancels the update. Could it use the validation API of its own connection, as ValidationEventListener does? A test that updates a row and reads it back would cover this.

protected final MappingContext mappingContext
protected final ApplicationEventPublisher eventPublisher
protected final boolean hasDatastore
private final Map<Object, Errors> unattachedErrors = Collections.synchronizedMap(new WeakHashMap<Object, Errors>())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Each ValidationErrors holds its bean, so the weak keys are never freed. After 1000 validations and several GCs, all 1000 entries were still there.

The map also uses equals/hashCode, while the session uses identity. Two equal beans share errors, and changing a bean after validation can lose its errors.

Could this use weak identity keys, with values that don't hold the bean strongly?

@jamesfredley jamesfredley left a comment

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.

Requested changes. A listener built without a datastore still checks the default connection.

return callable.call()
}
if (named == null) {
VALIDATION_CONNECTION.remove()

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.

A value exists only on the default connection. Saving it on another connection should succeed. A listener built without a datastore clears the chosen connection and checks the default one, so the save is refused. Check the connection the save named.

…tion, an API without a datastore keeps the connection it is called in, and a bean's errors are kept by identity without holding it

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed 2c35aef, one change for each of the three comments.

  1. A listener built without a datastore (AbstractGormApi.groovy line 92). An API with no datastore has no connection to name, and my inConnection treated that as "the default one" and cleared the connection the save had chosen. It now runs the call as it is, on the connection it is called in: AbstractGormApi.inConnection, line 85. Test: UniqueNamedConnectionSpec line 228, a validator that validates a book that only the default connection has through an API built from a mapping context, during book.second.save(); the value is free on the second connection and no error is recorded.

  2. The flush (AbstractHibernateGormInstanceApi.groovy line 129). You are right that save() returned the object and the update was dropped at the commit: ClosureEventListener.doValidate validated through the instance, which uses the default API. It now validates through the validation API of the connection of the datastore that flushes, as ValidationEventListener does: ClosureEventListener.validate, line 316, with the connection passed in by HibernateEventListener, line 214. Test: UniqueNamedConnectionSpec line 212, the update you describe, committed without a flush and read back from the second connection. One thing to look at: the listener takes the connection name through a second public constructor of ClosureEventListener, an internal class; the three-argument constructor stays and passes null, which validates as before. That is a new public constructor on a patch line, so say if you want it another way.

  3. The weak map (GormValidationApi.groovy line 59). It used equals and the errors held the bean, so nothing was ever freed. The errors of a bean without a session are now kept by identity under a weak key, and what is kept is the list of its errors, not the errors object that holds the bean; each read builds an errors object over the list and an error added to it is kept too: UnattachedErrors, line 322 and KeptErrors, line 351. Tests: PlainBeanValidationWithoutDatastoreSpec line 93 (two equal beans do not share errors), line 108 (a changed bean keeps them) and line 135 (a bean nothing refers to is freed after a gc).

Five rows fail without these changes. grails-data-hibernate5-core (714 tests), grails-datamapping-core (260), grails-data-mongodb-core (581) and codeStyle are green. Nothing documents which connection a listener or a flush validates on; the unique constraint page, unique.adoc, only describes the check.

@jamesfredley jamesfredley left a comment

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.

Requested changes. The first recorded error on a bean that has no datastore is lost.

else {

Errors errors = (Errors) datastore.currentSession.getAttribute(instance, GormProperties.ERRORS)
Errors errors = readErrors(instance)

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.

A check is built with a mapping and no datastore. Recording an error on a new bean, then asking whether it has errors, should say yes. It says no, because the recorded error is not the one that is stored. Store the error that was recorded.

…atastore is kept

The errors handed back for a bean that was never validated, or whose errors were cleared, were a plain object while what the API keeps is a list copied from it, so an error recorded on it was lost and hasErrors answered no.
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed 0f9de48. You are right: for a bean with no datastore the API keeps a list of its errors, and resetErrors handed back a plain ValidationErrors that the list was copied from, so an error recorded on it afterwards was never kept. It now hands back the object that adds to the kept list.

Test: PlainBeanValidationWithoutDatastoreSpec line 135 records an error on a bean that was never validated, clears the errors, and records another; each time hasErrors answers yes and the error read back has the recorded code. With the change reverted the row fails. Fix: GormValidationApi.resetErrors, line 253. grails-datamapping-core 261 tests, codeStyle clean.

@jamesfredley jamesfredley left a comment

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.

Requested changes. Errors added together on a bean that has no datastore are lost.

}

@Override
void addError(ObjectError error) {

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.

A check is built with a mapping and no datastore. Adding a set of errors to a new bean should keep them. Asking whether the bean has errors says no, because the added errors never reach the stored list. Store those errors.

@borinquenkid
borinquenkid marked this pull request as draft November 26, 2026 00:59
@borinquenkid borinquenkid added no ci and removed run ci labels Nov 26, 2026
…that has no datastore

A bean that cannot carry its own errors and has no session keeps them on the
API as a list, and the view of them that is handed out added to that list only
through addError. Spring adds a whole set of errors with addAllErrors, which
does not go through addError, so the errors added together were not there the
next time they were read (review on #17136).

Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed in 588fffa. The view of the errors that a bean without a datastore gets added to the kept list only through addError, and Spring's addAllErrors adds a whole set to its own list without calling it. The view now overrides addAllErrors too (GormValidationApi.groovy, the KeptErrors class).

PlainBeanValidationWithoutDatastoreSpec has the case for a bean that was validated and one that never was: a field error and a global error are added together, and both are still there the next time they are read. It fails without the change. grails-datamapping-core, grails-datamapping-core-test, the Hibernate 5 module, the MongoDB module and codeStyle pass.

…t-named-connection-7.0.x

# Conflicts:
#	grails-doc/src/en/guide/upgrading/upgrading60x.adoc
#	grails-skills/upgrade/skills/grails-upgrade/SKILL.md
@testlens-app

testlens-app Bot commented Dec 2, 2026

Copy link
Copy Markdown

🔎 No tests executed 🔎

🏷️ Commit: 89f5fb5
▶️ Tests: 0 executed
⚪️ Checks: 27/27 completed


Learn more about TestLens at testlens.app/docs.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants