Skip to content

Instantly share code, notes, and snippets.

@lubien
Created April 5, 2024 12:18
Show Gist options
  • Save lubien/cf83f5f7286892d9687aaae480cb1359 to your computer and use it in GitHub Desktop.
Save lubien/cf83f5f7286892d9687aaae480cb1359 to your computer and use it in GitHub Desktop.
ecto_sqlite livebook

Untitled notebook

Mix.install([
  {:liveview_playground, "~> 0.1.8"},
  {:phoenix_ecto, "~> 4.5"},
  {:ecto, "~> 3.11"},
  {:ecto_sqlite3, "~> 0.13"}
])

Section

defmodule LiveviewPlayground.Repo do
  use Ecto.Repo, otp_app: :liveview_playground, adapter: Ecto.Adapters.SQLite3
end

defmodule LiveviewPlayground.Repo.Migrations.Initial do
  use Ecto.Migration

  def change do
    create table(:products) do
      add(:name, :string, null: false)
      add(:description, :string, null: false)
    end
  end
end

db_config = [database: ":memory:", pool_size: 1]
LiveviewPlayground.Repo.start_link(db_config)
# LiveviewPlayground.Repo.__adapter__().storage_up(db_config)
Ecto.Migrator.up(LiveviewPlayground.Repo, 1, LiveviewPlayground.Repo.Migrations.Initial)
defmodule Product do
  use Ecto.Schema
  import Ecto.Changeset

  schema "products" do
    field(:name, :string, default: "")
    field(:description, :string, default: "")
  end

  def changeset(product, params \\ %{}) do
    product
    |> cast(params, [:name, :description])
    |> validate_required([:name, :description])
  end
end

defmodule Store do
  alias LiveviewPlayground.Repo

  def create_product(attrs) do
    Product.changeset(%Product{}, attrs)
    |> Repo.insert()
  end
end

Store.create_product(%{name: "a", description: "asd"}) |> dbg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment