Repository navigation
fix(datamapping): a unique constraint checks the connection of the block it runs in - #16935
borinquenkid wants to merge 8 commits into
Conversation
…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.
jamesfredley
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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
|
Reproduced and fixed in 481b593. The instance-taking Cases: your The tests of If another call names a connection and is checked on the block's, the call would let me trace which API it goes through. |
matrei
left a comment
There was a problem hiding this comment.
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 ofconstraintClass, and queryconstraintClasson it; - in
AbstractGormApi.inConnection, route every class that is mapped to the connection, withGormRegistry.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.adocconflicts 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()orvalidate()that names a connection checks it.new Book(...).third.validate()fails withMissingMethodException: No signature of method: validate for class: DelegatingGormEntityApi, so onlysavenames 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
-
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, andBook.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). -
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
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
…nstance and every class mapped to the connection, and Hibernate 5 saves check the connection they name Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
Matrei, thanks for the probes, which I ran as written.
|
|
The 7.0.x half, a save that names a connection, is #17136. |
jdaugherty
left a comment
There was a problem hiding this comment.
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
|
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. |
…t-connection-scope-8.0.x
…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.
|
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 The change. 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 ( The class, not the one sample. Both Hibernate suites have a table of 24 rows (48 in all), through the public API: three entries (
|
✅ All tests passed ✅🏷️ Commit: 4474bda Learn more about TestLens at testlens.app/docs. |
A
uniqueconstraint on a domain class mapped to several data sources checked the default connection, whatever connection the block named. InsideBook.second.withTransaction { },validate()andsave()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 withNo Session found for current thread.UniqueConstraintbuilt itsDetachedCriteriawith 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, withNo Session found for current thread.GormRegistryCoverageSpec:currentConnectionoutside a block, in nested blocks, and for an entity a block does not route.UniqueWithMultipleDataSourcesSpecwas@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
uniqueconstraint reference, an upgrade note and an entry in the upgrade skill next to the one forrlike.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
uniqueconstraint:book.third.save(),Book.second.save(book)) checks that connection, also inside a block for another one;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