Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable AUTOINCREMENT for serial and bigserial #98

Merged
merged 2 commits into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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