Erlang/Elixir 简单体验 Ecto(用自带 ETS 数据库,免安装)

chenge · 2021年04月28日 · 328 次阅读

今天看了一个视频,“Ecto without db”。介绍了几种 adapter,可见 Ecto 是十分灵活的。这里就用 ETS 来演示。

1 创建项目

mix new ecto_demo
cd ecto_demo

2 修改一个主文件 mix.exs

def application do
  [
    extra_applications: [:logger, :ets_ecto]
  ]
end

defp deps do
  [
    {:ets_ecto, "~> 0.0.1", github: "wojtekmach/ets_ecto"}
  ]
end

3 编译

mix deps.get
mix compile

4 启动 iex

iex -S mix

5 试验 Ecto 操作

# 1. Define `Repo`
defmodule Repo do
  use Ecto.Repo,
    otp_app: :my_app,
    adapter: ETS.Ecto
end

# 2. Configure the application
Application.put_env(:my_app, Repo, [])

# 3. Start the Repo process. In a real project you'd put the Repo module in your project's supervision tree:
{:ok, _pid} = Repo.start_link()

# 4. Import Ecto.Query
import Ecto.Query

# 5. Define schema
defmodule Article do
  use Ecto.Schema

  schema "articles" do
    field :title, :string
  end
end

# 6. Interact with the Repo
Repo.insert!(%Article{title: "Article 1"})

q = from(a in Article, select: a.title)
Repo.all(q)
# => ["Article 1"]

# 7 changeset
import Ecto.Changeset

 %Article{title: "Article 1", id: 52}  |> cast(%{title: "article 1"}, [:title]) |> validate_required(:title) |> Repo.insert

 %Article{title: "Article 1", id: 52} |> cast(%{title: "new 2"}, [:title]) |> validate_required(:title) |> Repo.update

结束

就这样,好理解吗?不难吧。

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号