4

Manual document revisions with RavenDB

 3 years ago
source link: https://ayende.com/blog/192801-A/manual-document-revisions-with-ravendb?Key=119c4102-91b6-4831-b91d-19bfd926d3bd&utm_campaign=Feed%3A+AyendeRahien+%28Ayende+%40+Rahien%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Dec 28 2020

Manual document revisions with RavenDB

time to read 2 min | 287 words

We got an interesting question a few times in recent weeks. How can I manually create a document revision with RavenDB? The answer for that is that you can use the ForceRevisionCreationFor() method to do so. Here is how you’ll typically use this API:

using (var session = store.OpenSession()) { var company = new Company { Name = "HR" }; session.Store(company); session.Advanced.Revisions.ForceRevisionCreationFor(company); session.SaveChanges(); }

This is the typical expected usage for the API. We intended this to make it so users can manually triggers revisions, for example, when moving a document from draft mode to public and the like.

It turns out that there is another reason to want to use this API, when you migrate data to RavenDB and want to create historical revisions. The API we envisioned isn’t suitable for this, but the layered API in RavenDB means that we can still get the desired behavior.

Here is how we can achieve this:

using (var session = store.OpenSession()) { session.Advanced.Defer(new PutCommandData("users/1", null, new DynamicJsonValue { ["Name"] = "Oren" })); session.Advanced.Defer(new ForceRevisionCommandData("users/1"));

session.Advanced.Defer(new PutCommandData("users/1", null, new DynamicJsonValue { ["Name"] = "Ayende" })); session.Advanced.Defer(new ForceRevisionCommandData("users/1"));

session.SaveChanges(); }

Basically, we manually create the transaction steps that will run on the server, and we can apply the command to the same document multiple times.

Note that RavenDB requires a document to create a revision from it, so we set the document, create a revision and overwrite the document again, as many times as we need to.

Another issue that was brought up is that the @last-modified property on the document is set to the date of the revision creation. In some cases, they want to do this to get the revision to be created at the right time it was originally created during the migration period.

That is not supported by RavenDB, because the @last-modified is tracking the time that RavenDB modified the document or revision. If you need to track the time a document was modified in the domain, you need to keep that as part of your actual domain model.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK