View Source Versioned.Schema (Versioned v0.4.0)
Enhances Ecto.Schema
modules to track a full history of changes.
The versioned_schema
macro works just like schema
in Ecto.Schema
but it
also builds an OriginalModule.Version
schema module as well to represent a
version at a particular point in time.
In addition to options allowed by Ecto.Schema
, new ones are also allowed.
additional-belongs_to-options
Additional belongs_to
Options
:versioned
- Iftrue
, the version schema will include an extra field of the same name but with_version
appended. The parent record which existed when this version was created can be loaded into this field viaVersioned.preload/2
.
Example:
versioned_schema "people" do
belongs_to :car, Car, type: :binary_id, versioned: true
end
additional-has_many-options
Additional has_many
Options
:versioned
- Iftrue
, the version schema will include an extra field of the same name but with_version
appended. If defined as another truthy atom, then that field name will be used instead. The child records which existed when this version was created can be loaded into this field viaVersioned.preload/2
.
Example:
versioned_schema "cars" do
has_many :people, Person, on_replace: :delete, versioned: :person_versions
end
i-already-have-an-integer-primary-key
I already have an integer primary key.
While Versioned generally operates with binary_ids, it is possible to adopt it
for an existing table which uses integers. First, you'll need to create a
migration to create the versions table. Then, define your own @primary_key
attribute. Versioned will preserve it. (Note that the versions table must
still use UUIDs.)
@primary_key {:id, :id, autogenerate: true}
versioned_schema "cars" do
...
end
add-code-to-the-version-module
Add Code to the Version Module
To add additional functions to the version module, auto-generated by
versioned_schema/2
, add a version
block somewhere before
versioned_schema
.
version do
def hello_world, do: :ok
end
versioned_schema "cars" do
...
end
example
Example
defmodule MyApp.Car do
use Versioned.Schema
versioned_schema "cars" do
field :name, :string
has_many :people, MyApp.Person, versioned: true
end
end
Link to this section Summary
Functions
Register some code to be injected into the Version module.
Convert a list of ast lines from the main schema into ast lines to be used for the version schema.
Create a versioned schema.
Link to this section Functions
Register some code to be injected into the Version module.
Convert a list of ast lines from the main schema into ast lines to be used for the version schema.
Create a versioned schema.