BoxTurtle.Schema.Change (BoxTurtle v0.1.0)

Copy Markdown View Source

Generates the write functions of BoxTurtle.Schema.Change.API for an Ecto schema.

Attribute maps go through the schema's changeset functions, so the schema must define them: changeset/2 by default, for both inserts and updates.

defmodule MyApp.Blog.Post do
  use Ecto.Schema
  import Ecto.Changeset

  schema "posts" do
    field :title, :string
    timestamps()
  end

  def changeset(post, attrs), do: post |> cast(attrs, [:title]) |> validate_required([:title])
end

# delete/1 by primary key looks rows up through the sibling Query module.
defmodule MyApp.Blog.Post.Query do
  use BoxTurtle.Schema.Query, repo: MyApp.Repo
end

defmodule MyApp.Blog.Post.Change do
  use BoxTurtle.Schema.Change, repo: MyApp.Repo
end

alias MyApp.Blog.Post

{:ok, post} = Post.Change.create(%{title: "Hello"})
{:error, %Ecto.Changeset{}} = Post.Change.create(%{title: nil})
{:ok, post} = Post.Change.update(post, %{title: "Hello again"})
{:ok, _deleted} = Post.Change.delete(post.id)
{:error, :not_found} = Post.Change.delete(post.id)

Options

  • :repo - the Ecto.Repo to write to. Required.
  • :schema - the schema module. Defaults to the parent of the using module (MyApp.Blog.Post above).
  • :query - the BoxTurtle.Schema.Query module used to look rows up by key in delete/1. Defaults to <schema>.Query.
  • :create_changeset - name of the schema's fun(struct, attrs) used by create. Defaults to :changeset.
  • :update_changeset - name of the schema's fun(struct, attrs) used by update. Defaults to :changeset.
  • :create_opts - options passed to Ecto.Repo.insert/2, e.g. [on_conflict: :nothing].