Skip to content

Implement values #174

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

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
3 changes: 0 additions & 3 deletions integration_test/test_helper.exs
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,6 @@ excludes = [

# SQLite does not support anything except a single column in DISTINCT
:multicolumn_distinct,

# Values list
:values_list
]

ExUnit.configure(exclude: excludes)
Expand Down
59 changes: 59 additions & 0 deletions integration_test/values_test.exs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can shove this into the test/ directory under the connection/ directory as values_test

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inside test/ecto/adapters/sqlite3/connection?
If I do that I get ** (Exqlite.Error) no such table: posts. So there is some setup missing there.

Also, I didn't see any other similar tests in that directory, tests that actually operate on a Repo. Only in integration_test/

Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
defmodule Ecto.Integration.ValuesTest do
use Ecto.Integration.Case, async: true

import Ecto.Query, only: [from: 2, with_cte: 3]

alias Ecto.Integration.Comment
alias Ecto.Integration.Post
alias Ecto.Integration.TestRepo

test "join to values works" do
TestRepo.insert!(%Post{id: 1})
TestRepo.insert!(%Comment{post_id: 1, text: "short"})
TestRepo.insert!(%Comment{post_id: 1, text: "much longer text"})

params = [%{id: 1, post_id: 1, n: 0}, %{id: 2, post_id: 1, n: 10}]
types = %{id: :integer, post_id: :integer, n: :integer}

results =
from(p in Post,
right_join: params in values(params, types),
on: params.post_id == p.id,
left_join: c in Comment,
on: c.post_id == p.id and fragment("LENGTH(?)", c.text) > params.n,
group_by: params.id,
select: {params.id, count(c.id)}
)
|> TestRepo.all()

assert [{1, 2}, {2, 1}] = results
end

test "values can be used together with CTE" do
TestRepo.insert!(%Post{id: 1, visits: 42})
TestRepo.insert!(%Comment{post_id: 1, text: "short"})
TestRepo.insert!(%Comment{post_id: 1, text: "much longer text"})

params = [%{id: 1, post_id: 1, n: 0}, %{id: 2, post_id: 1, n: 10}]
types = %{id: :integer, post_id: :integer, n: :integer}

cte_query = from(p in Post, select: %{id: p.id, visits: coalesce(p.visits, 0)})

q = Post |> with_cte("xxx", as: ^cte_query)

results =
from(p in q,
right_join: params in values(params, types),
on: params.post_id == p.id,
left_join: c in Comment,
on: c.post_id == p.id and fragment("LENGTH(?)", c.text) > params.n,
left_join: cte in "xxx",
on: cte.id == p.id,
group_by: params.id,
select: {params.id, count(c.id), cte.visits}
)
|> TestRepo.all()

assert [{1, 2, 42}, {2, 1, 42}] = results
end
end
43 changes: 35 additions & 8 deletions lib/ecto/adapters/sqlite3/connection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1037,12 +1037,6 @@ defmodule Ecto.Adapters.SQLite3.Connection do
message: "join hints are not supported by SQLite3"
end

defp assert_valid_join(%JoinExpr{source: {:values, _, _}}, query) do
raise Ecto.QueryError,
query: query,
message: "SQLite3 adapter does not support values lists"
end

defp assert_valid_join(_join_expr, _query), do: :ok

defp join_on(:cross, true, _sources, _query), do: []
Expand Down Expand Up @@ -1368,8 +1362,8 @@ defmodule Ecto.Adapters.SQLite3.Connection do
|> parens_for_select
end

defp expr({:values, _, _}, _, _query) do
raise ArgumentError, "SQLite3 adapter does not support values lists"
defp expr({:values, _, [types, idx, num_rows]}, _, _query) do
[?(, values_list(types, idx + 1, num_rows), ?)]
end

defp expr({:identifier, _, [literal]}, _sources, _query) do
Expand Down Expand Up @@ -1560,6 +1554,36 @@ defmodule Ecto.Adapters.SQLite3.Connection do
message: "unsupported expression #{inspect(expr)}"
end

defp values_list(types, idx, num_rows) do
rows = :lists.seq(1, num_rows, 1)
col_names = Enum.map_join(types, ", ", &elem(&1, 0))

[
"WITH xxx(",
col_names,
") AS (VALUES ",
intersperse_reduce(rows, ?,, idx, fn _, idx ->
{value, idx} = values_expr(types, idx)
{[?(, value, ?)], idx}
end)
|> elem(0),
") SELECT * FROM xxx"
]
end

defp values_expr(types, idx) do
intersperse_reduce(types, ?,, idx, fn {_field, _type}, idx ->
# TODO: cast?
# {[?$, Integer.to_string(idx), ?:, ?: | tagged_to_db(type)], idx + 1}
{[?$, Integer.to_string(idx)], idx + 1}
end)
end

# defp tagged_to_db(:id), do: "bigint"
# defp tagged_to_db(:integer), do: "bigint"
# defp tagged_to_db({:array, type}), do: [tagged_to_db(type), ?[, ?]]
# defp tagged_to_db(type), do: ecto_to_db(type)

def interval(_, "microsecond", _sources) do
raise ArgumentError,
"SQLite does not support microsecond precision in datetime intervals"
Expand Down Expand Up @@ -1618,6 +1642,9 @@ defmodule Ecto.Adapters.SQLite3.Connection do
{:fragment, _, _} ->
{nil, as_prefix ++ [?f | Integer.to_string(pos)], nil}

{:values, _, _} ->
{nil, as_prefix ++ [?v | Integer.to_string(pos)], nil}

{table, schema, prefix} ->
name = as_prefix ++ [create_alias(table) | Integer.to_string(pos)]
{quote_table(prefix, table), name, schema}
Expand Down
15 changes: 9 additions & 6 deletions test/ecto/adapters/sqlite3/connection/join_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,11 @@
end
end

test "join with values is not supported" do
assert_raise Ecto.QueryError, fn ->
rows = [%{x: 1, y: 1}, %{x: 2, y: 2}]
types = %{x: :integer, y: :integer}
test "join with values" do

Check failure on line 138 in test/ecto/adapters/sqlite3/connection/join_test.exs

View workflow job for this annotation

GitHub Actions / Test Elixir 1.17, OTP 25, OS ubuntu-latest

test join with values (Ecto.Adapters.SQLite3.Connection.JoinTest)

Check failure on line 138 in test/ecto/adapters/sqlite3/connection/join_test.exs

View workflow job for this annotation

GitHub Actions / Test Elixir 1.18, OTP 25, OS ubuntu-latest

test join with values (Ecto.Adapters.SQLite3.Connection.JoinTest)

Check failure on line 138 in test/ecto/adapters/sqlite3/connection/join_test.exs

View workflow job for this annotation

GitHub Actions / Test Elixir 1.15, OTP 25, OS ubuntu-latest

test join with values (Ecto.Adapters.SQLite3.Connection.JoinTest)

Check failure on line 138 in test/ecto/adapters/sqlite3/connection/join_test.exs

View workflow job for this annotation

GitHub Actions / Test Elixir 1.16, OTP 25, OS ubuntu-latest

test join with values (Ecto.Adapters.SQLite3.Connection.JoinTest)
rows = [%{x: 1, y: 1}, %{x: 2, y: 2}]
types = %{x: :integer, y: :integer}

query =
Schema
|> join(
:inner,
Expand All @@ -149,8 +149,11 @@
)
|> select([p, q], {p.id, q.x})
|> plan()
|> all()
end

assert ~s{SELECT s0."id", v1."x" FROM "schema" AS s0 } <>
~s{INNER JOIN (WITH xxx(y, x) AS (VALUES ($1,$2),($3,$4)) SELECT * FROM xxx) AS v1 } <>
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This tests fails with OTP 25, as the order of x, y is swapped in xxx(y, x).
This is because types is a map and therefore unordered.
It's not a bug, since if the order is different here, it will also be different later when passed as parameters. Both orders are correct and lead to the same query.

I'm not sure how to solve this, any idea?

~s{ON (v1."x" = s0."x") AND (v1."y" = s0."y")} ==
all(query)
end

test "join with fragment" do
Expand Down
Loading