From 9412b5f0377de9648ea4e89741718c12bb360069 Mon Sep 17 00:00:00 2001 From: Adam Oswalt Date: Sat, 24 Oct 2020 03:01:46 -0500 Subject: [PATCH] Add support for tsql 3 and 4 part naming (#279) 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"}` --- lib/ecto/adapters/tds/connection.ex | 8 +++++++- test/ecto/adapters/tds_test.exs | 10 ++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/ecto/adapters/tds/connection.ex b/lib/ecto/adapters/tds/connection.ex index b641d5d5..a2d61722 100644 --- a/lib/ecto/adapters/tds/connection.ex +++ b/lib/ecto/adapters/tds/connection.ex @@ -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)) diff --git a/test/ecto/adapters/tds_test.exs b/test/ecto/adapters/tds_test.exs index 872a25be..c84674d3 100644 --- a/test/ecto/adapters/tds_test.exs +++ b/test/ecto/adapters/tds_test.exs @@ -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}