Repository navigation
fix(datamapping): a save that names a connection checks the unique constraint on that connection - #17136
fix(datamapping): a save that names a connection checks the unique constraint on that connection#17136borinquenkid wants to merge 13 commits into
Conversation
…nstraint on that connection Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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
|
@jamesfredley Fixed. |
sanjana2505006
left a comment
There was a problem hiding this comment.
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.
- Stateless validation APIs (RxGORM) may now throw on
validate(). - The Mongo spec maps
'default'in lowercase, which I think stops the datastore from starting. - 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() |
There was a problem hiding this comment.
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' |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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
|
@sanjana2505006 thank you for the careful read. Your three points, in order:
The Hibernate 5, datamapping-core and MongoDB core modules pass, and so does |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A check that has no datastore now throws before it runs.
| } | ||
| } | ||
|
|
||
| private String connectionName() { |
There was a problem hiding this comment.
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
|
@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;
Checked and not changed: |
jamesfredley
left a comment
There was a problem hiding this comment.
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) } |
There was a problem hiding this comment.
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.
|
Thanks @borinquenkid, all three points are addressed: reading the field fixes the no-datastore path, the Mongo spec now runs with |
…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
|
Pushed 5e23444. The throw was in the errors of a bean that is not a 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. |
jamesfredley
left a comment
There was a problem hiding this comment.
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)) | |||
There was a problem hiding this comment.
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.
…nection the save or validation names Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
Pushed 80ba875. The event the save publishes ( The test: Documentation: the constraint's reference page says only that the check is a persistent call ( |
sanjana2505006
left a comment
There was a problem hiding this comment.
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:
-
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()withoutflush: truereturns the object, but the row is not updated. Before this PR it returned null with a unique error. At flush,ClosureEventListener.doValidatevalidates through the default API and cancels the update. -
unattachedErrorsnever frees its entries, because eachValidationErrorsholds its bean. It also compares beans byequals, 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 { |
There was a problem hiding this comment.
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 commitsave() 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>()) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Requested changes. A listener built without a datastore still checks the default connection.
| return callable.call() | ||
| } | ||
| if (named == null) { | ||
| VALIDATION_CONNECTION.remove() |
There was a problem hiding this comment.
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
|
Pushed 2c35aef, one change for each of the three comments.
Five rows fail without these changes. |
jamesfredley
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
|
Pushed 0f9de48. You are right: for a bean with no datastore the API keeps a list of its errors, and Test: |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. Errors added together on a bean that has no datastore are lost.
| } | ||
|
|
||
| @Override | ||
| void addError(ObjectError error) { |
There was a problem hiding this comment.
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.
…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
|
@jamesfredley Fixed in 588fffa. The view of the errors that a bean without a datastore gets added to the kept list only through
|
…t-named-connection-7.0.x # Conflicts: # grails-doc/src/en/guide/upgrading/upgrading60x.adoc # grails-skills/upgrade/skills/grails-upgrade/SKILL.md
🔎 No tests executed 🔎🏷️ Commit: 89f5fb5 Learn more about TestLens at testlens.app/docs. |
A
save()that names a connection, such asbook.second.save(),Book.second.save(book)orBook.second.insert(book), checked theuniqueconstraint 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 aDuplicateKeyException, or, with MongoDB, stored a second copy.UniqueConstraintbuilt itsDetachedCriteriawith 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 withwithConnection. 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 insideBook.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 throughBook.second.save(book)andinsert; 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 forBook.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
uniqueconstraint: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
uniquereference 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