Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

ecto2

stage2/ecto2.livemd

ecto2

Mix.install([
  {:ecto_sql, "~> 3.9"},
  {:ecto, "~> 3.9"},
  {:kino, "~> 0.10.0"},
  {:ecto_sqlite3, "~> 0.12"}
])

Section

defmodule Person do
  use Ecto.Schema
  import Ecto.Changeset

  schema "people" do
    field(:name, :string)
    field(:age, :integer)
    timestamps()
  end

  def changeset(person, attrs) do
    person
    |> cast(attrs, [:name, :age])
    |> validate_required([:name, :age])
  end
end
defmodule CreatePeople do
  use Ecto.Migration

  def change do
    create table(:people) do
      add(:name, :string)
      add(:age, :integer)
      timestamps()
    end
  end
end
defmodule Repo do
  use Ecto.Repo, adapter: Ecto.Adapters.SQLite3, otp_app: :nothing
end
Repo.start_link(database: "test.db")
Ecto.Migrator.up(Repo, 1, CreatePeople)
now =
  NaiveDateTime.utc_now()
  |> NaiveDateTime.truncate(:second)

entries =
  [
    %{name: "Bob", age: 20},
    %{name: "John", age: 30},
    %{name: "Ryo", age: 39}
  ]
  |> Enum.map(fn attr ->
    Map.merge(attr, %{
      inserted_at: now,
      updated_at: now
    })
  end)

Repo.insert_all(Person, entries)
Repo.all(Person)
|> Kino.DataTable.new()
Person
|> Repo.get_by!(name: "Ryo")
|> Repo.delete()
%Person{name: "Ai", age: 55}
|> Repo.insert!()
Person
|> Repo.get!(4)
|> Person.changeset(%{
  name: "Ai",
  age: 21
})
|> Repo.update()