-
-
Save stavro/46c92a9ebc2d5648f07eb81eb15e3558 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
alias SchedWeb.Repo | |
Ecto.Adapters.SQL.query(Repo, "CREATE TABLE foos (id serial primary key)", []) | |
Ecto.Adapters.SQL.query(Repo, "CREATE TABLE bars (id serial primary key, foo_id integer not null references foos)", []) | |
Ecto.Adapters.SQL.query(Repo, "create unique index index_bars_on_foo_id ON bars(foo_id)", []) | |
defmodule Foo do | |
use Ecto.Schema | |
schema "foos" do | |
has_many :bars, Bar | |
end | |
end | |
defmodule Bar do | |
use Ecto.Schema | |
import Ecto | |
import Ecto.Changeset | |
schema "bars" do | |
belongs_to :foo, Foo | |
end | |
def create(foo_id) do | |
%__MODULE__{} | |
|> change(foo_id: foo_id) | |
|> unique_constraint(:foo_id, name: :index_bars_on_foo_id) | |
end | |
end | |
# Test Run: | |
import Ecto.Query | |
Repo.transaction(fn -> | |
foo = %Foo{} |> Repo.insert!() | |
Bar.create(foo.id) |> Repo.insert!() | |
try do | |
Bar.create(foo.id) |> Repo.insert!() | |
rescue | |
err in [Ecto.InvalidChangesetError] -> | |
IO.inspect err | |
end | |
# Repo connection is completely busted here | |
(from b in Bar, select: count(b.id)) |> Repo.one! #=> ** (exit) exited in: Ecto.Adapters.SQL.query(SchedWeb.Repo, "SELECT count(b0.\"id\") FROM \"bars\" AS b0", [], []) ** (EXIT) :noconnect | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment