Skip to content

Instantly share code, notes, and snippets.

@stavro
Last active April 1, 2016 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stavro/46c92a9ebc2d5648f07eb81eb15e3558 to your computer and use it in GitHub Desktop.
Save stavro/46c92a9ebc2d5648f07eb81eb15e3558 to your computer and use it in GitHub Desktop.
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