Skip to content

Commit

Permalink
Enable AUTOINCREMENT for serial and bigserial (#98)
Browse files Browse the repository at this point in the history
Co-authored-by: Jeff Newman <[email protected]>
  • Loading branch information
newmanjeff and Jeff Newman authored Jan 10, 2023
1 parent 707fe8e commit 2ee3db4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
17 changes: 6 additions & 11 deletions lib/ecto/adapters/sqlite3/connection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1581,20 +1581,12 @@ defmodule Ecto.Adapters.SQLite3.Connection do
collate = Keyword.get(opts, :collate)
check = Keyword.get(opts, :check)

column_options(default, type, null, pk, collate, check)
end

defp column_options(_default, :serial, _, true, _, _) do
" PRIMARY KEY AUTOINCREMENT"
end

defp column_options(default, type, null, pk, collate, check) do
[
default_expr(default, type),
null_expr(null),
collate_expr(collate),
check_expr(check),
pk_expr(pk)
pk_expr(pk, type)
]
end

Expand Down Expand Up @@ -1660,8 +1652,11 @@ defmodule Ecto.Adapters.SQLite3.Connection do
defp index_expr(literal) when is_binary(literal), do: literal
defp index_expr(literal), do: quote_name(literal)

defp pk_expr(true), do: " PRIMARY KEY"
defp pk_expr(_), do: []
defp pk_expr(true, type) when type in [:serial, :bigserial],
do: " PRIMARY KEY AUTOINCREMENT"

defp pk_expr(true, _), do: " PRIMARY KEY"
defp pk_expr(_, _), do: []

defp options_expr(nil), do: []

Expand Down
18 changes: 18 additions & 0 deletions test/ecto/adapters/sqlite3/connection_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2787,4 +2787,22 @@ defmodule Ecto.Adapters.SQLite3.ConnectionTest do

assert query == ~s{SELECT p0."id", p0."title", p0."content" FROM "posts" AS p0}
end

test "autoincrement support" do
serial = {:create, table(:posts), [{:add, :id, :serial, [primary_key: true]}]}
bigserial = {:create, table(:posts), [{:add, :id, :bigserial, [primary_key: true]}]}
id = {:create, table(:posts), [{:add, :id, :id, [primary_key: true]}]}
integer = {:create, table(:posts), [{:add, :id, :integer, [primary_key: true]}]}

assert execute_ddl(serial) == [
~s/CREATE TABLE "posts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT)/
]

assert execute_ddl(bigserial) == [
~s/CREATE TABLE "posts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT)/
]

assert execute_ddl(id) == [~s/CREATE TABLE "posts" ("id" INTEGER PRIMARY KEY)/]
assert execute_ddl(integer) == [~s/CREATE TABLE "posts" ("id" INTEGER PRIMARY KEY)/]
end
end

0 comments on commit 2ee3db4

Please sign in to comment.