View Source LibEctoV2 (lib_ecto v0.3.8)

V2 is a complete rewrite of LibEcto, it's much more powerful and flexible. It simply breaks down the original complex macros into more reasonable ones. Here's how to use it:

Setup your Schema

   defmodule Test.Schema do
    @moduledoc false
    use Ecto.Schema

    import Ecto.Changeset

    @primary_key {:id, KsuidType, autogenerate: true}
    schema "test" do
      field(:name, :string)
      field(:value, :string)
      field(:removed_at, :integer)
    end

    def changeset(m, params) do
      cast(m, params, [:name, :value])
    end
  end

use LibEctoV2 to setup DB layer

  defmodule Test.DB do
    @moduledoc false
    use LibEctoV2

    @repo Repo
    @schema Test.Schema
    @filters [:id, :name]

    def filter(:id, dynamic, %{"id" => value}) when is_binary(value),
      do: {:ok, dynamic([m], ^dynamic and fragment("binary(?)", m.id) == ^value)}

    def filter(:id, dynamic, %{"id" => value}) when is_list(value), do: {:ok, dynamic([m], ^dynamic and m.id in ^value)}

    def filter(:name, dynamic, %{"name" => value}) when is_binary(value),
      do: {:ok, dynamic([m], ^dynamic and m.name == ^value)}

    def filter(:name, dynamic, %{"name" => {"like", value}}) when is_binary(value),
      do: {:ok, dynamic([m], ^dynamic and like(m.name, ^value))}

    def filter(:name, dynamic, %{"name" => value}) when is_list(value),
      do: {:ok, dynamic([m], ^dynamic and m.name in ^value)}

    def filter(_, dynamic, _), do: {:ok, dynamic}

    def init_filter, do: dynamic([m], m.removed_at == 0)
  end

Enjoy it

iex> Sample.DB.create_one(%{name: "test", value: "testv"})
{:ok, %Simple.Schema{id: "2JIebKci1ZgKenvhllJa3PMbydB", name: "test", value: "testv"}}

iex> Sample.DB.get_one(%{"name" => "test"})
{:ok, %Simple.Schema{id: "2JIebKci1ZgKenvhllJa3PMbydB", name: "test", value: "testv"}}

iex> Sample.DB.get_one(%{"name" => "not-exists"})
{:ok, nil}

iex> Sample.DB.get_one!(%{"name" => "not-exists"})
** LibEcto.Exception (** (Exception) not found: [{"name", "not-exists"}]

iex> {:ok, m} = Sample.DB.get_one(%{"name" => "test"})
iex> Sample.DB.update_one(m, name: "test2")
{:ok, %Simple.Schema{id: "2JIebKci1ZgKenvhllJa3PMbydB", name: "test2", value: "testv"}}

Summary

Functions

Link to this function

build_condition(init, params, filters, filter_fn, check_empty? \\ true)

View Source
Link to this function

generate_get_many_funcs(schema, repo, columns, filters)

View Source
Link to this function

generate_get_one_funcs(schema, repo, columns, filters)

View Source
Link to this function

generate_other_funcs(schema, repo, filters)

View Source
Link to this function

generate_write_funcs(schema, repo, filters)

View Source