Ecto는 Elixir 및 Phoenix 애플리케이션을 위한 강력한 데이터베이스 래퍼이자 통합 쿼리 언어입니다.
스키마 정의 (Schemas)
코드 자동 생성
$ mix phx.gen.html Accounts Profile profiles email:string age:integer
스키마 모듈 선언
defmodule MyApp.Accounts.User do
use Ecto.Schema
schema "users" do
field :name, :string
field :age, :integer
field :password, :string, virtual: true
timestamps()
end
end
지원 필드 타입 목록
| Field Type | Description |
|---|---|
:id |
Integer primary key |
:binary_id |
UUID primary key |
:string |
UTF-8 string |
:integer |
Standard integer |
:float |
Floating-point number |
:decimal |
Arbitrary precision decimal |
:boolean |
True / false value |
:map |
JSON or native map |
{:array, inner_type} |
Array of specified inner type |
Changeset 및 데이터 검증 (Changesets & Validations)
Changeset 함수 정의
def changeset(user, params \\ :empty) do
user
|> cast(params, ~w(name email), ~w(age))
|> validate_format(:email, ~r/@/)
|> validate_inclusion(:age, 18..100)
|> validate_exclusion(:role, ~w(admin superadmin))
|> validate_subset(:pets, ~w(cat dog parrot whale))
|> validate_length(:body, min: 1, max: 160)
|> validate_number(:score, greater_than: 0)
|> validate_confirmation(:password, message: "does not match")
|> unique_constraint(:email)
|> foreign_key_constraint(:post_id)
|> assoc_constraint(:post)
end
Changeset 내부 상태 검사
changeset.valid? # Boolean validation state
changeset.errors # List of validation errors
changeset.changes # Map of modified attributes
changeset.params[:title] # Raw input parameters
Changeset 값 프로그래밍 변경
changeset
|> put_change(:title, "New Title")
|> force_change(:title, "Forced Title")
|> update_change(:title, &(&1 <> "..."))
|> delete_change(:title)
|> add_error(:title, "cannot be blank")
레포지토리 조작 (Repo Operations)
단일/다중 레코드 조회
# Fetch by primary key
user = Repo.get(User, id)
user = Repo.get!(User, id)
# Fetch by attributes
user = Repo.get_by(User, email: "[email protected]")
생성, 수정 및 삭제
# Persist changeset
case Repo.insert(changeset) do
{:ok, user} -> IO.puts("Created user: #{user.name}")
{:error, changeset} -> IO.inspect(changeset.errors)
end
Repo.update(changeset)
Repo.insert_or_update(changeset)
Repo.delete(user)
Ecto 쿼리 (Ecto Queries)
import Ecto.Query
query = from p in Post,
where: p.published == true,
where: [state: "published"],
order_by: [desc: p.inserted_at],
limit: 10,
preload: [:author, :comments],
select: p
posts = Repo.all(query)