Repository navigation
Record row state on audited models - #178
Merged
Merged
Conversation
AuditOptions(record_state="always" | "on_delete") stores the row in data.state next to the diff, under the column policies, with tracked collections as sorted member ids. Unloaded columns and collections are loaded before the flush. Masking, compaction and scrub cover the state. query.state_at() and astate_at() read a record's state at a point in time. With integrity, record_state is refused for now.
Unloaded columns load in one SELECT per mapper and unloaded tracked collections in one per relationship, set as committed values, and only for objects that will get an entry; lazy="raise" collections work. write_only and dynamic tracked collections are refused with record_state, and check_models reports them as state-collection. The integrity guard runs at flush only, so a separate trail without integrity can use record_state. modes_of is cached per mapper count.
# Conflicts: # CHANGELOG.md # audit_trail/query.py # docs/guides/querying.md # tests/db/test_plans_history.py
The flush finds delete-orphan orphans after before_flush, so the first before_delete of an Audited instance in the flush batch-loads every deleted instance before_flush did not see, before any row is deleted.
Loading a tracked collection into a deleted or updated object made the flush act on its members: a passive_deletes collection had its foreign keys set to NULL instead of being left to ON DELETE CASCADE. The member ids are now read into InstanceState.info and the collection stays unloaded, so the flush emits the same statements with and without record_state. A row that is gone when its state is loaded now fails the flush with ObjectDeletedError instead of storing an incomplete state. The modes_of cache is keyed on the set of registries and the mapper count. Tests cover passive_deletes, composite keys, the 500-row batches and the gone row.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #51.
AuditOptions(record_state="always" | "on_delete")stores the row indata.statenext to the diff: audited columns under their policy, tracked collections as sorted member ids."always"on everyentity.*entry (after the change; before it for a delete),"on_delete"on deletes only.before_flush, batched per model and relationship, so the state has no"<unknown>"for them.data.changesstays as without the option.hidden_fieldsmasks state values, compaction keeps the newest state,scrub()erases it.audit.query.state_at()/astate_at(): the state of the newestentity.*entry at or beforeat, one lookup on the object index (plan test added).Nonebefore the first entry, after a delete, or when visibility hides that entry.ValueErrorwhen an imported model with thatobject_typedoes not use"always", or when the entry has no state.AuditTrail(integrity=...), a flush of a model withrecord_stateraisesAuditOptionErroruntil integrity coversdata.state.audit_trail/_state.py; docs in the models, querying and privacy guides, limitations and the continuum page.Review follow-up
lazy="raise"tracked collections are loaded by the batch query below instead of attribute access. Test: an"always"model with a raise collection, reloaded, updated, committed.write_onlyanddynamictracked collections withrecord_stateraiseValueErrornaming the model and relationship: at mapper configure (once a trail is installed), and on every flush of the model, since SQLAlchemy raises a configure error only once.check_models()reports them asstate-collection(error). Docs bullet fixed.Loading is batched: one
SELECT pk, cols ... WHERE pk IN (...)per mapper for unloaded columns, oneSELECT parent_pk, member ... JOINper mapper and tracked relationship for unloaded collections, chunks of 500, values set withset_committed_value(pending backref appends are applied on top, as a lazy load does). New objects load nothing. Deleting a parent that cascades to 20 children with a deferred column: 20 extra SELECTs before, 1 after (the reviewer's probe); the new test with a tracked collection on the children asserts 3 (parent columns, children columns, children's tags). Test that pending column values and a pending backref append survive the batch. Cost statement updated.The orphan-delete sentence is gone from the docs (AT-73 handles the bug).
The install-time integrity scan is dropped (a trail is given no models); the flush check stays, now on every entry of a model with
record_state, so an"on_delete"model fails on its first write. Test: an integrity trail and a non-integrity trail on separate session classes.modes_ofreuseslistener._subclasses; it still sees every imported model, as no narrower set exists.Updates are checked for a possible entry (an audited column change or a tracked collection change) before loading; an update of an excluded column alone runs no SELECT (tested).
modes_ofis cached per object type and read again when the process's mapper count changes, asby_actor_typedoes (unit test).Orphan deletes (with Audit objects deleted as orphans #180): SQLAlchemy decides them during the flush, after
before_flush, so the firstbefore_deleteof anAuditedinstance in a flush batch-loads every instance the unit of work deletes thatbefore_flushdid not see (flush_context.stateswithisdelete), before any row is deleted. Test:clear()on adelete-orphancollection of"on_delete"children with a deferred column and alazy="raise"tracked collection gives real values indata.state, with one extra SELECT for the orphans' columns (the flush itself still loads each orphan's association rows).Collections are no longer loaded into the objects (second review, blocker): loading a
passive_deletes=Truecollection made the flush act on its members (UPDATE ... SET fk=NULL, failing with a non-null FK, leaving children with a NULL FK with a nullable one).load_for_statenow reads only the member ids of unloaded tracked collections, in one outer-joinedSELECTper mapper and relationship, intoInstanceState.info; the listener takes them for the entry andentity_stateapplies the collection's pending backref changes on top. The collection stays unloaded, so the flush does what it does without the option. Tests: an"on_delete"parent with a trackedpassive_deletescollection and anON DELETE CASCADEFK (nullable, non-null, and withdelete-orphan), and an"always"update of the same: the app's DML is identical with and withoutrecord_state, the database deletes the children, and the state holds the member ids. The cascade query-count test now compares against the same delete without the option (+3 SELECTs).A row that is gone when its state is loaded (deleted by SQL earlier in the transaction) fails the flush with SQLAlchemy's
ObjectDeletedErrornaming the model and id, and nothing is written: leaving the state out with a warning would still store less than promised. Detected for both the column load and the member query (the outer join gives every live parent a row). Documented under "Row state". Tests for both paths, plus the composite-keytuple_().in_()branch and the 500-row batches (501 objects: two SELECTs each for columns and member ids).modes_ofis keyed on the set of registries (weak references) plus the mapper count; unit test with one registry disposed and another added with as many mappers.Cleanup notes
entity_stateandentity_changesrepeat the "column never set on a new instance" rule and the hash key-ring check._state._may_write_updatemirrors the history comparison inentity_changesfor updates; one helper could serve both._mask_activityhandlespayloadandstatewith the same comprehension._state._load_orphansreads SQLAlchemy'sUOWTransaction.states, as Audit objects deleted as orphans #180's_flushed_deletesdoes; they could share one helper._state._mappers_keyuses SQLAlchemy's privatemapperlib._all_registries()(present in 2.0 and 2.1).