Skip to content

fix(datamapping): a unique constraint checks the connection of the block it runs in - #16935

Open
borinquenkid wants to merge 8 commits into
8.0.xfrom
fix/unique-constraint-connection-scope-8.0.x
Open

borinquenkid wants to merge 8 commits into
8.0.xfrom
fix/unique-constraint-connection-scope-8.0.x

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

A unique constraint on a domain class mapped to several data sources checked the default connection, whatever connection the block named. Inside Book.second.withTransaction { }, validate() and save() looked for the duplicate on the default data source: a value that existed only on the default was reported as a duplicate, one that existed only on the second was missed, and with a session bound for the second only the check failed with No Session found for current thread.

UniqueConstraint built its DetachedCriteria with no connection, and the criteria resolves its API with its default connection name, so the connection block (GormRegistry.withConnectionScope) never applied to it. GormRegistry.currentConnection(entity) now names the connection the unqualified calls are routed to, and the constraint's criteria uses it. Outside a block it is the default connection, as before.

Tests:

  • UniqueConstraintConnectionScopeHibernate7Spec: two H2 data sources, an entity mapped to both; a duplicate that exists only on the second is rejected inside its block and accepted on the default, and the other way round. It failed before, with No Session found for current thread.
  • GormRegistryCoverageSpec: currentConnection outside a block, in nested blocks, and for an entity a block does not route.
  • The Hibernate 5 UniqueWithMultipleDataSourcesSpec was @Ignored for this since 2017; it now runs and passes. The Hibernate 7 copy asserted the old routing and, through the test manager, its two connections are one database, so it is replaced by the spec above.

Docs: the unique constraint reference, an upgrade note and an entry in the upgrade skill next to the one for rlike.

7.0.x has no connection scope, so the blocks are not affected there; a save that names its connection has the same bug on 7.0.x, and that gets its own pull request against 7.0.x. 9.0.x gets this through the merge-up; I ran the new specs on 9.0.x with this commit applied and they pass.

Results that change

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

  • a value that exists only on the default data source is no longer reported as a duplicate while saving to another connection, and one that exists only on the other connection is now found;
  • a save that names its connection (book.third.save(), Book.second.save(book)) checks that connection, also inside a block for another one;
  • a subclass is checked where it is saved, and so is an instance a save cascades to;
  • with a session bound for the second data source and none for the default, the check no longer fails with No Session found for current thread.

Code that relied on one value being unique across every data source has to enforce that itself.

Fixes #16934

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

…ock it runs in (#16934)

UniqueConstraint built its criteria on the default connection, so validate() or save() inside a connection block checked
the default data source, or failed with No Session found for current thread when only the second had a session.
GormRegistry.currentConnection names the connection the unqualified calls are routed to; the constraint's criteria uses it.

The Hibernate 7 UniqueWithMultipleDataSourcesSpec is replaced by UniqueConstraintConnectionScopeHibernate7Spec: through the
test manager its two connections are one database, so it could not tell the routing. The Hibernate 5 copy is no longer ignored.
Copilot AI balanced review requested due to automatic review settings November 11, 2026 23:51

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.

Not approving. A unique check inside one connection block rejects a save that names another connection.

… that connection, not the block around it (#16934)

The API of a connection runs its validation in the scope of that connection, so book.third.save() inside a block for the
second checks the third. The connection comes from the API's qualifier, or from the connection source of the datastore it
was made for, which is how the Hibernate APIs of a connection are made; an API of the default connection follows the block.

@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.

A save that names a non-default connection is checked on that connection. Not approving. A save that names the default connection is still checked on the block around it.

*/
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.

Book.second.withNewSession { Book.DEFAULT.save(new Book(name: 'taken')) }, where taken exists only on second and the default connection is empty. The save returns null. The book is saved to the default connection. Check that connection, not the block around it.

…ecks the default connection (#16934)

The instance-taking save, insert and merge of a connection's static API, Book.DEFAULT.save(book) and
Book.second.save(book), now run in the connection scope of that API, as its withSession and withTransaction do.
Book.DEFAULT.save(book) inside a block of another connection checked the block's connection, so the unique
constraint rejected or accepted the save on the wrong connection.

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

Copy link
Copy Markdown
Member Author

Reproduced and fixed in 481b593. Book.DEFAULT.save(book) is the static API of the default connection, and its save, insert and merge took the block around it, because only its withSession, withTransaction and the other block methods ran in the scope of their connection.

The instance-taking save, insert and merge of GormStaticApi now run in the connection scope of that API, as those do: Book.DEFAULT.save(book) inside a block of the second connection checks and saves on the default connection, and Book.second.save(book) on the second one. A qualifier that names no connection, such as a DISCRIMINATOR tenant id, is left alone, as before. The unqualified book.save() still follows the block, which is what the earlier commits establish.

Cases: your Book.second.withNewSession { Book.DEFAULT.save(...) } in UniqueConstraintConnectionScopeHibernate7Spec and in UniqueWithMultipleDataSourcesSpec (Hibernate 5), a row that exists on the second connection only and an empty default. Both fail without the commit. A second feature in the Hibernate 7 spec checks Book.second.save(...) outside the block of the default and is a guard.

The tests of grails-datamapping-core (1821), grails-data-simple (15), Hibernate 5 core (1206) and Hibernate 7 core (4649) pass, and codeStyle is clean. I did not run MongoDB or Neo4j, which share GormStaticApi.

If another call names a connection and is checked on the block's, the call would let me trace which API it goes through.

https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL

@matrei matrei 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.

Reviewed at 481b593 (base 8.0.x, at 47d8021). I ran:

  • the new specs with and without the change;
  • a probe of my own with three H2 data sources, 36 cases with Hibernate 7 and with Hibernate 5 at this head and on 8.0.x (47d8021), and 33 of them with Hibernate 5 on 7.0.x (aee4c04). Each case runs in a transaction on every connection, as a request with a session for each would;
  • a MongoDB probe with two connections, at the same three commits;
  • the tests of grails-datamapping-core, grails-datamapping-core-test, grails-data-simple, Hibernate 5, Hibernate 7, MongoDB and Neo4j at this head.

The tests pass at this head, with the counts that you give for grails-datamapping-core (1821), grails-data-simple (15), Hibernate 5 (1206) and Hibernate 7 (4649), and for MongoDB (1033), Neo4j (623) and grails-datamapping-core-test (692) as well.

The fix works for a block and for the static API of a connection. Without the change, 4 of the 5 features of UniqueConstraintConnectionScopeHibernate7Spec fail, and the first feature of UniqueWithMultipleDataSourcesSpec. In my probe, with name unique on a Book mapped to every connection, onSecond stored on the second connection only and onDefault on the default only:

Hibernate 5 and Hibernate 7 8.0.x This head
Book.second.withTransaction { new Book(name: 'onSecond').save() }, also Book.second.save(book), Book.second.insert(book), a method annotated @Transactional(connection = 'second'), and Book.third.withTransaction { } inside the block for a value on the third the check passes, and the insert fails at the unique index (DuplicateKeyException) rejected (unique)
the block, Book.second.save(book) and the method with onDefault rejected saved on the second
validate() inside Book.second.withTransaction { }, Book.second.withNewSession { } or such a method, for onSecond valid invalid
With Hibernate 7, new Book(name: 'onSecond').second.save() / with onDefault DuplicateKeyException / rejected rejected / saved
MongoDB: Book.withConnection('second') { new Book(name: 'onSecond').save() }, also Book.second.withNewSession { } and Book.second.save(book) a second onSecond is stored rejected

Book.DEFAULT.save(book), insert and a nested Book.DEFAULT.withTransaction { } inside a block for the second connection are checked and saved on the default connection, here as on 8.0.x.

Needs a fix

1. With Hibernate 5, a save that names its connection on the instance is still checked on another connection. The second commit runs the validation of the Hibernate 7 HibernateGormInstanceApi and HibernateGormValidationApi in inConnection. Their Hibernate 5 counterparts, AbstractHibernateGormInstanceApi.save and AbstractHibernateGormValidationApi.validate, aren't changed:

Hibernate 5 8.0.x This head Hibernate 7 at this head
new Book(name: 'onSecond').second.save() DuplicateKeyException DuplicateKeyException rejected
new Book(name: 'onDefault').second.save() rejected rejected saved on the second
Book.second.withTransaction { new Book(name: 'onSecond').third.save() } saved on the third rejected saved on the third
Book.second.withTransaction { new Book(name: 'onThird').third.save() } DuplicateKeyException DuplicateKeyException rejected

The third row is James's first case, which worked on 8.0.x with Hibernate 5, because the default connection doesn't have the value either, and fails here, because the check now runs on the block's connection. The note and the reference say that book.third.save() checks the third connection, for both modules, and the Hibernate 5 spec covers only a block. With the validation in those two classes wrapped in inConnection, as for Hibernate 7, the four rows come out as they do with Hibernate 7.

2. With inheritance, the check runs on the connection of the class that declares the property, and for a cascade on the default connection. Animal declares tag unique and Dog extends Animal; Author has many Books, and title is unique. onSecondTag and onSecondTitle exist on the second connection only, onDefaultTag on the default only:

Hibernate 5 and Hibernate 7 8.0.x This head
Animal.second.withTransaction { new Dog(tag: 'onDefaultTag').save() } rejected DuplicateKeyException
Animal.second.withTransaction { new Dog(tag: 'onSecondTag').save() } saved on the default rejected
Dog.second.withTransaction { new Dog(tag: 'onSecondTag').save() }, also new Dog(tag: 'onSecondTag').second.save() DuplicateKeyException DuplicateKeyException
Dog.second.withTransaction { new Dog(tag: 'onDefaultTag').save() } rejected rejected
Author.second.withTransaction { author.addToBooks(title: 'onSecondTitle').save() }, also author.second.save() DuplicateKeyException DuplicateKeyException

The block of Animal routes Animal only, so the Dog is saved on the default connection, here as on 8.0.x. The constraint looks the connection up for Animal, the class that declares tag, so it now checks the second connection: the first two rows are new wrong results. The block of Dog and dog.second.save() route Dog, so the check of Animal stays on the default connection, and the cascade validates the books while only Author is routed. A method annotated @Transactional(connection = 'second') routes every class that is mapped to its connection, and rejects onSecondTag for a Dog and onSecondTitle in a cascade.

Two changes fix them in my probe:

  • look the connection up for the class of the instance that is validated, mappingContext.proxyHandler.getProxiedClass(target), instead of constraintClass, and query constraintClass on it;
  • in AbstractGormApi.inConnection, route every class that is mapped to the connection, with GormRegistry.withConnectionScope(connection, callable), so that a cascaded instance is checked where it's saved.

With those and point 1, every save and validation of my probe is checked on the connection that it saves on, with both modules. The suites that I ran at this head pass with them as well, except the feature of AbstractGormApiSpec that expects the form for one class: its stubbed class isn't mapped to third, so the scope for every class doesn't cover it. A spec for a subclass in its own block, one in the block of its parent, and one for a cascade would cover it.

3. Where it goes. The description leaves 7.0.x out, since it has no connection scope. That holds for the blocks: on 7.0.x, the unqualified calls inside Book.second.withTransaction { } go to the default connection, and the check runs there as well. But a save that names its connection has the same bug on 7.0.x:

7.0.x
Hibernate 5: new Book(name: 'onSecond').second.save(), Book.second.save(book), Book.second.insert(book), also inside Book.second.withNewTransaction { } DuplicateKeyException
Hibernate 5: new Book(name: 'onDefault').second.save(), Book.second.save(book) rejected
MongoDB: Book.second.save(new Book(name: 'onSecond')) a second onSecond is stored

By #17061, a call that fails and a value that is rejected on a connection that doesn't have it are fixed on the oldest branch. So that part needs a pull request against 7.0.x, where the API of the connection hands its connection to the constraint without a scope, and this pull request then builds on it at the merge-up.

4. The note and the reference.

  • upgrading80x.adoc conflicts with 8.0.x. The notes of the "Grails 8.0.1" section have no number now, so the note goes there as a heading without "94.".
  • Both say that a save() or validate() that names a connection checks it. new Book(...).third.validate() fails with MissingMethodException: No signature of method: validate for class: DelegatingGormEntityApi, so only save names a connection on an instance. Book.second.save(book) does too.
  • This changes which values are accepted on a connection. By #17061, that needs a "Results that change" section in the description, an entry in the upgrade skill next to the other 8.0.1 entries, such as the one for rlike, and a second reviewer.

5. CI. The pull request has the no ci label and conflicts with 8.0.x, so no check has run on it. Its base is the default branch, so once the label is removed and the conflict resolved, the tests run.

Notes

  1. On James's comments: with Hibernate 7, both hold at this head. Book.second.withNewSession { new Book(name: 'taken').third.save() } saves on the third connection, and Book.DEFAULT.save(new Book(name: 'taken')) inside a block for the second saves on the default. With Hibernate 5 the first doesn't (point 1).

  2. Book.DEFAULT.save(book) inside a block for the second connection is checked on the default connection on 8.0.x as well. The third commit undoes what the second one changed there, so the features for it, in both specs, pass on 8.0.x, and they guard the second commit rather than #16934.

@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 that names the default connection is still checked on another 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 session for another connection is open, and the default session is open too. Saving through the default connection should check the default connection. It checks the other one, so a value that is free on the default connection is refused. Check the connection the save named.

@borinquenkid

Copy link
Copy Markdown
Member Author

Matrei, thanks for the probes, which I ran as written.

  1. Hibernate 5 save and validate run the check in inConnection now, as Hibernate 7 does. The four rows of your table come out as the Hibernate 7 column.
  2. The connection is looked up for the class of the validated instance, and inConnection routes every class mapped to the connection, so a subclass and a cascaded instance are checked where they are saved. Specs for a subclass in its own block, in the block of its parent, and for a cascade, in both modules.
  3. The note and the reference say that only save() names a connection, the heading has no number, the description has a "Results that change" section, and the upgrade skill has an entry. The no ci label is off.
  4. The 7.0.x pull request for a save that names its connection follows; this one does not wait for it.
    I asked James Daugherty for the second review.

@borinquenkid

Copy link
Copy Markdown
Member Author

The 7.0.x half, a save that names a connection, is #17136.

@jdaugherty jdaugherty 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.

Reviewed at ab28079c93665c92013ca0d8fc4ff4a600141d99. The Hibernate 5 named-save wrappers, validated-instance class lookup, and non-default cascade scope address the earlier cases. One combination remains: an explicit DEFAULT save inside a scope for its child class.

Map Author and Book to DEFAULT and second, with cascading books and a unique Book.title. Store taken only on second, then construct a new author containing a book with that title:

Author.withNewTransaction {
    Book.second.withNewSession {
        Author.DEFAULT.save(author)
    }
}

GormStaticApi.inConnectionScope overrides the connection only for Author. AbstractGormApi.inConnection returns immediately for DEFAULT. Cascaded validation calls the child's constraints directly, without entering a child validation API that could reset its scope. Consequently, UniqueConstraint still selects second for Book and rejects a title that is free on the destination connection.

Please make cascaded validation follow the explicitly selected default connection too. Add public-API regressions in both Hibernate suites for this child-scoped case, checking titles present only on second and only on DEFAULT. Keep the existing single-entity DEFAULT and non-default cascade cases.

This finding is source-traced; I have not executed this end-to-end GORM reproducer.

The upgrade guide and upgrade skill conflicts are resolved by keeping both notes.

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

Copy link
Copy Markdown
Member Author

8.0.x is merged into this branch (83ad3f5) to clear conflicts in the 8.0.x upgrade guide and the upgrade skill, resolved by keeping both notes. No source conflicted. grails-datamapping-core (1839), the Hibernate 5 module (3844) and the Hibernate 7 module (5414) pass on the merged tree and codeStyle passes. This does not answer the open review; the replies follow separately.

…ecks a cascaded instance there, whatever block for another connection is open for its class

Inside a block for another connection that is open for the class of a cascaded instance, a save through the API of the default connection
validated that instance on the connection of the block: UnqBook.second.withNewSession { UnqAuthor.DEFAULT.save(author) } checked the
title of a book of the author on second, though the book is saved by the session of the author, on the default connection. A save on the
default connection refused a title that was free there, and accepted one that the default connection holds.

The API of a connection other than the default already ran its save and validation with every class mapped to that connection routed to
it. The default connection does the same now; outside every block that costs nothing, as before.
@borinquenkid

Copy link
Copy Markdown
Member Author

Pushed the next commit, which answers the review of 12-03 at ab28079: an explicit DEFAULT save inside a block for its child class. You are right, and it is the cascaded validation that did not follow.

What happened. In UnqBook.second.withNewSession { UnqAuthor.DEFAULT.save(author) } the block makes second the connection of UnqBook, and UnqAuthor.DEFAULT routed only UnqAuthor to the default connection. The cascaded book is validated by PersistentEntityValidator directly, and UniqueConstraint asks GormRegistry.currentConnection(UnqBook), which is second in that block, although the book is saved by the session of the author, on the default connection. So a title that was free on the default connection was refused, and one that only the default connection holds was accepted (and refused by the database at commit).

The change. AbstractGormApi.inConnection, which validate and the Hibernate saves run in, now runs the API of the default connection with every class routed to the default connection, as the API of a connection other than the default already did for every class mapped to it. A block for another connection that is open for the class of a cascaded instance does not decide where it is checked: the save names the connection. Outside every block it costs nothing, as before (withConnectionScope returns the call when no scope is open).

One thing that changes with it, and that an independent read of the change pointed out: for as long as a save or a validation on the default connection runs, every class is routed that way, so a listener or a validator that it calls, and that reaches another class without naming a connection, reaches the default connection too, also when an enclosing block routed that class elsewhere. A call that names its connection (Book.second.save()) is unaffected. It is in the Javadoc of inConnection. The same mechanism is what the cascade needs, so I did not find a way to tell the two apart.

The class, not the one sample. Both Hibernate suites have a table of 24 rows (48 in all), through the public API: three entries (Author.DEFAULT.save(author), an unqualified author.save(), author.validate()), a session and a transaction of the second connection for the book (the author's own session or transaction around it), and the title taken only on the second connection, only on the default connection, on both, or on neither. The expected value is accepted unless the default connection holds the title. Without the change 12 rows fail in each suite: all those where the title is only on one of them. The single-entity DEFAULT row and the cascade through the second connection stay as they were. AbstractGormApiSpec had a test that asserted the old contract (an API of the default connection follows the block around it); it is replaced by two that say what inConnection does now, for the class of the API and for a class that a block covers.

grails-datamapping-core (1845), grails-datamapping-core-test (715), grails-data-hibernate5-core (4179) and grails-data-hibernate7-core (5500) pass, and codeStyle is clean. I merged 8.0.x first, with no conflict.

@testlens-app

testlens-app Bot commented Dec 5, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 4474bda
▶️ Tests: 111954 executed
⚪️ Checks: 97/97 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

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

A unique constraint is checked against the default connection inside a named connection block

5 participants