One problem I commonly solve is that of keeping immutable versions of a document rather than editing the document. When asked for the document, retrieve the most recent version.
One way to do this is with timestamps:
doc 0:
{
id: "e69e0bea-77ea-4d97-bedf-d3cca27ae4b6",
correlationId: "d00be916-10e3-415c-aaf6-9acb7c70cf4f",
created: "11/17/2018 2:20:25 AM",
value: "foo"
}
doc 1:
{
id: "37ef6f99-bc87-45bb-87ae-a1b81070cc91",
correlationId: "d00be916-10e3-415c-aaf6-9acb7c70cf4f",
created: "11/17/2018 2:20:44 AM",
value: "bar"
}
doc 2:
{
id: "93fc913e-5ecc-4c59-a130-0e577ed4f2fb",
correlationId: "d00be916-10e3-415c-aaf6-9acb7c70cf4f",
created: "11/17/2018 2:21:51 AM",
value: "baz"
}
The downside of using timestamps is you have to order by the timestamp (O(n*log(n))
) to get the Nth most recent version.
I desire to make this O(n)
by storing pointers to the previous version, like
{
id: "e69e0bea-77ea-4d97-bedf-d3cca27ae4b6",
previousId: null,
correlationId: "d00be916-10e3-415c-aaf6-9acb7c70cf4f",
created: "11/17/2018 2:20:25 AM",
value: "foo"
}
doc 1:
{
id: "37ef6f99-bc87-45bb-87ae-a1b81070cc91",
previousId: "e69e0bea-77ea-4d97-bedf-d3cca27ae4b6",
correlationId: "d00be916-10e3-415c-aaf6-9acb7c70cf4f",
created: "11/17/2018 2:20:44 AM",
value: "bar"
}
doc 2:
{
id: "93fc913e-5ecc-4c59-a130-0e577ed4f2fb",
previousId: "37ef6f99-bc87-45bb-87ae-a1b81070cc91",
correlationId: "d00be916-10e3-415c-aaf6-9acb7c70cf4f",
created: "11/17/2018 2:21:51 AM",
value: "baz"
}
so it is a linked list like
NULL <- doc0 <- doc1 <- doc2
The only thing stopping me from doing this is that for creating a new version I would need some locking mechanism, like (in pseudo-code)
lock correlationId
get latest
new.previousId = latest.id
insert new
but I'm not sure if it's possible at the database level.