Skip to content

Commit

Permalink
Add support for tsql 3 and 4 part naming (#279)
Browse files Browse the repository at this point in the history
Tables may be referenced in SQL Server by up to 4-part naming of
`[server].[database].[schema].[table]`.

These may be passed to the Tds adapter via the schema_prefix as tuples:
`@schema_prefix {"database", "schema"}` and
`@schema_prefix {"server", "database", "schema"}`
  • Loading branch information
aoswalt authored and josevalim committed Oct 24, 2020
1 parent 121c5be commit 9412b5f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/ecto/adapters/tds/connection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1477,8 +1477,14 @@ if Code.ensure_loaded?(Tds) do

defp quote_table(nil, name), do: quote_table(name)

defp quote_table({server, db, schema}, name),
do: [quote_table(server), ".", quote_table(db), ".", quote_table(schema), ".", quote_table(name)]

defp quote_table({db, schema}, name),
do: [quote_table(db), ".", quote_table(schema), ".", quote_table(name)]

defp quote_table(prefix, name),
do: Enum.map_join([quote_table(prefix), ".", quote_table(name)], "", &"#{&1}")
do: [quote_table(prefix), ".", quote_table(name)]

defp quote_table(name) when is_atom(name), do: quote_table(Atom.to_string(name))

Expand Down
10 changes: 10 additions & 0 deletions test/ecto/adapters/tds_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,16 @@ defmodule Ecto.Adapters.TdsTest do
assert all(query) == ~s{SELECT s0.[binary] FROM [foo].[schema3] AS s0}
end

test "from with 2-part prefix" do
query = Schema |> select([r], r.x) |> Map.put(:prefix, {"database", "db_schema"}) |> plan()
assert all(query) == ~s{SELECT s0.[x] FROM [database].[db_schema].[schema] AS s0}
end

test "from with 3-part prefix" do
query = Schema |> select([r], r.x) |> Map.put(:prefix, {"server", "database", "db_schema"}) |> plan()
assert all(query) == ~s{SELECT s0.[x] FROM [server].[database].[db_schema].[schema] AS s0}
end

test "from without schema" do
query = "schema" |> select([r], r.x) |> plan()
assert all(query) == ~s{SELECT s0.[x] FROM [schema] AS s0}
Expand Down

0 comments on commit 9412b5f

Please sign in to comment.