Skip to content

Commit

Permalink
Infer from primary_key opts if identity should be used.
Browse files Browse the repository at this point in the history
Adding support for `:cache` & `:clause` settings.
  • Loading branch information
seivan committed Sep 13, 2023
1 parent e9515f2 commit 63cb112
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
30 changes: 14 additions & 16 deletions lib/ecto/adapters/postgres/connection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1619,26 +1619,24 @@ if Code.ensure_loaded?(Postgrex) do
end

defp column_type(:identity, opts) do
start_value = [Keyword.get(opts, :start_value)]
increment = [Keyword.get(opts, :increment)]
start_value = Keyword.get(opts, :start_value)
increment = Keyword.get(opts, :increment)
cache = Keyword.get(opts, :cache)
clause = Keyword.get(opts, :clause, :by_default) |> to_string |> String.upcase |> String.split("_") |> Enum.join(" ")
type_name = ecto_to_db(:identity)

cleanup = fn v -> is_integer(v) and v > 0 end

sequence =
start_value
|> Enum.filter(cleanup)
|> Enum.map(&"START WITH #{&1}")
|> Kernel.++(
increment
|> Enum.filter(cleanup)
|> Enum.map(&"INCREMENT BY #{&1}")
)
[start_value]
|> Enum.filter(&(is_integer/1)) |> Enum.map(&"START WITH #{&1}")
|> Kernel.++( [increment] |> Enum.filter(&(is_integer/1)) |> Enum.map(&"INCREMENT BY #{&1}") )
|> Kernel.++( [cache] |> Enum.filter(&(is_integer(&1) && Kernel.>(&1, 0))) |> Enum.map(&"CACHE #{&1}"))
|> case do
[] -> []
[h | t] -> [["(", h], [t, ") "]]
end
|> (&([type_name, " GENERATED #{clause} AS IDENTITY", &1 |> Enum.join(" ")])).()


case sequence do
[] -> [type_name, " GENERATED BY DEFAULT AS IDENTITY"]
_ -> [type_name, " GENERATED BY DEFAULT AS IDENTITY(", Enum.join(sequence, " "), ") "]
end
end

defp column_type(type, opts) do
Expand Down
5 changes: 3 additions & 2 deletions lib/ecto/migration.ex
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ defmodule Ecto.Migration do
name: String.t(),
prefix: atom | nil,
comment: String.t() | nil,
primary_key: boolean | keyword(),
primary_key: boolean | keyword() | [start_value: integer(), increment: integer(), cache: pos_integer(), clause: :by_default | :always],
engine: atom,
options: String.t()
}
Expand Down Expand Up @@ -1595,8 +1595,9 @@ defmodule Ecto.Migration do

defp pk_opts_to_tuple(opts) do
opts = Keyword.put(opts, :primary_key, true)
inferred_type = [:start_value, :increment, :cache, :clause] |> Enum.any?(&Keyword.has_key?(opts, &1)) && :bigint || :bigserial
{name, opts} = Keyword.pop(opts, :name, :id)
{type, opts} = Keyword.pop(opts, :type, :bigserial)
{type, opts} = Keyword.pop(opts, :type, inferred_type)
{name, type, opts}
end
end

0 comments on commit 63cb112

Please sign in to comment.