LoginSignup
61
67

More than 5 years have passed since last update.

Elixir Phoenixのデータベース操作モジュールEcto入門2

Posted at

前回の続き。
今回はEcto.Repoの解説。

データベース操作の抽象レイヤー

EctoのRepoはデータベースとのやりとりを抽象化している。
データベースがMySQLでも、PostgreSQLだろうとどんな形式で保存されていようと、Repoモジュールを通して操作することができる。

データベース設定

データベースの設定はconfig/prod.exsconfig/dev.exsconfig/test.exsに記述する。それぞれ、本番、開発、テスト環境の設定。
デフォルトではPostgreSQLだが、他のデータベースを利用したい場合は、mix.exsの以下の部分のアダプターを変更して設定ファイルを変更すればいい。

 config :my_app, Repo,
   adapter: Ecto.Adapters.Postgres,
   database: "ecto_simple",
   username: "postgres",
   password: "postgres",
   hostname: "localhost

もっと短くこのように書くこともできる。

config :my_app, Repo,
  url: "ecto://postgres:postgres@localhost/ecto_simple

対応データベース

データベース Dependency
PostgreSQL postgrex
MySQL mariaex
MSSQL tds_ecto
SQLite sqlite_ecto

データベース操作

データベース操作はinsertinsert!のように!が付くものと付かないものがあって何が違うのか疑問だった。
!が付くものは、失敗時に例外を投げる。

insert

データベースにレコードを挿入する。
elixir:
Repo.insert! user

update, update_all

レコードを更新する。

updateクエリには4つのオペレーターがある

  • set - フィールドの値を更新する。
  • inc - フィールドの値をインクリメントする。
  • push - フィールドに値を追加する。
  • pull - フィールドから値を削除する。
Repo.update! %{post | title: "new title"}
Repo.update_all Post, set: [title: "title"]

delete, delete_all

レコードを削除する。

Repo.delete! user
Repo.delete_all User
Repo.delete_all assoc(post, :messages)

read

レコードの取得方法は複数ある。

get

primary_keyを指定して取得する。

Repo.get! User, 1

get_by

フィールドを指定して取得する。

Repo.get_by(ProgrammingLanguage, name: "Elixir")

all

複数のレコードを取得する。

query = from w in Weather,
    where: w.prcp <= 0.0 or is_nil(w.prcp),
    select: w
query |> Repo.all

one

一つだけレコードを取得する。

Repo.one(User)

preload

関連も一緒に取得してくる。preloadしなかった場合、NotLoadedになる。

post = Post |> Repo.get(1) |> Repo.preload(:messages)
post.messages // ちゃんと取得される
61
67
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
61
67