sqllocks-shape-sqlserver 0.9.3__tar.gz → 0.9.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. {sqllocks_shape_sqlserver-0.9.3/src/sqllocks_shape_sqlserver.egg-info → sqllocks_shape_sqlserver-0.9.5}/PKG-INFO +8 -2
  2. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/README.md +6 -0
  3. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/pyproject.toml +5 -2
  4. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/auth.py +67 -3
  5. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/command.py +1 -1
  6. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/source.py +17 -2
  7. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5/src/sqllocks_shape_sqlserver.egg-info}/PKG-INFO +8 -2
  8. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/SOURCES.txt +1 -0
  9. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/requires.txt +1 -1
  10. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_auth.py +43 -0
  11. sqllocks_shape_sqlserver-0.9.5/tests/test_live_fabric_endpoint.py +15 -0
  12. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_source.py +48 -0
  13. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/LICENSE +0 -0
  14. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/setup.cfg +0 -0
  15. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/__init__.py +0 -0
  16. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/catalog.py +0 -0
  17. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/profiler.py +0 -0
  18. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/sql.py +0 -0
  19. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/testing.py +0 -0
  20. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/dependency_links.txt +0 -0
  21. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/entry_points.txt +0 -0
  22. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/top_level.txt +0 -0
  23. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_emulator.py +0 -0
  24. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_owner_profile_findings.py +0 -0
  25. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_portability.py +0 -0
  26. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_profiler.py +0 -0
  27. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_security_review.py +0 -0
  28. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_skeleton.py +0 -0
  29. {sqllocks_shape_sqlserver-0.9.3 → sqllocks_shape_sqlserver-0.9.5}/tests/test_sql.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqllocks-shape-sqlserver
3
- Version: 0.9.3
3
+ Version: 0.9.5
4
4
  Summary: Shape plugin: SQL Server, Azure SQL and Fabric SQL database profiling and source
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/sqllocks/shape
@@ -18,7 +18,7 @@ Classifier: Topic :: Database
18
18
  Requires-Python: >=3.11
19
19
  Description-Content-Type: text/markdown
20
20
  License-File: LICENSE
21
- Requires-Dist: sqllocks-shape==0.9.3
21
+ Requires-Dist: sqllocks-shape==0.9.5
22
22
  Requires-Dist: pyodbc>=5.0
23
23
  Provides-Extra: entra
24
24
  Requires-Dist: azure-identity>=1.16.1; extra == "entra"
@@ -47,5 +47,11 @@ shape profile-db --server myserver.database.windows.net --database shop --auth c
47
47
  You also need the Microsoft ODBC Driver 18 for SQL Server (and unixODBC on Linux).
48
48
  The full guide is `docs/plugins/sqlserver.md` in the repository.
49
49
 
50
+ For a read-only Fabric Lakehouse SQL analytics endpoint, use
51
+ `mssql://<endpoint>.datawarehouse.fabric.microsoft.com/<lakehouse>?schema=dbo&table=T`.
52
+ Pass `auth="token", token=access_token` to `SqlServerSource.schema()` or `.read()`,
53
+ where `access_token` is a bearer held in memory or an `env://NAME` reference.
54
+ The endpoint also accepts `auth="cli"` or `auth="spn"` with service principal options.
55
+
50
56
  Its version always equals core's (`sqllocks-shape`), and it is released together with core.
51
57
  How plugins are written: `docs/plugins/authoring.md`.
@@ -21,5 +21,11 @@ shape profile-db --server myserver.database.windows.net --database shop --auth c
21
21
  You also need the Microsoft ODBC Driver 18 for SQL Server (and unixODBC on Linux).
22
22
  The full guide is `docs/plugins/sqlserver.md` in the repository.
23
23
 
24
+ For a read-only Fabric Lakehouse SQL analytics endpoint, use
25
+ `mssql://<endpoint>.datawarehouse.fabric.microsoft.com/<lakehouse>?schema=dbo&table=T`.
26
+ Pass `auth="token", token=access_token` to `SqlServerSource.schema()` or `.read()`,
27
+ where `access_token` is a bearer held in memory or an `env://NAME` reference.
28
+ The endpoint also accepts `auth="cli"` or `auth="spn"` with service principal options.
29
+
24
30
  Its version always equals core's (`sqllocks-shape`), and it is released together with core.
25
31
  How plugins are written: `docs/plugins/authoring.md`.
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
  [project]
6
6
  name = "sqllocks-shape-sqlserver"
7
7
  # Lockstep with core (T-09): scripts/check_plugin_skeletons.py fails when this drifts.
8
- version = "0.9.3"
8
+ version = "0.9.5"
9
9
  description = "Shape plugin: SQL Server, Azure SQL and Fabric SQL database profiling and source"
10
10
  readme = "README.md"
11
11
  requires-python = ">=3.11"
@@ -21,7 +21,7 @@ classifiers = [
21
21
  "Operating System :: OS Independent",
22
22
  "Topic :: Database",
23
23
  ]
24
- dependencies = ["sqllocks-shape==0.9.3", "pyodbc>=5.0"]
24
+ dependencies = ["sqllocks-shape==0.9.5", "pyodbc>=5.0"]
25
25
 
26
26
  [project.urls]
27
27
  Homepage = "https://github.com/sqllocks/shape"
@@ -41,3 +41,6 @@ profile-db = "shape_sqlserver:ProfileDbCommand"
41
41
 
42
42
  [tool.setuptools.packages.find]
43
43
  where = ["src"]
44
+
45
+ [tool.uv.sources]
46
+ sqllocks-shape = { workspace = true }
@@ -6,6 +6,7 @@ loads (and ``shape plugins doctor`` is clean) on a machine that has neither.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import os
9
10
  import re
10
11
  import struct
11
12
  from dataclasses import dataclass
@@ -18,11 +19,16 @@ from .sql import (
18
19
  register_converters,
19
20
  )
20
21
 
21
- AUTH_METHODS = ("sql", "cli", "msi", "spn", "fabric")
22
+ AUTH_METHODS = ("sql", "cli", "msi", "spn", "fabric", "token")
22
23
  TOKEN_SCOPE = "https://database.windows.net/.default"
23
24
  FABRIC_TOKEN_AUDIENCE = "https://database.windows.net/"
24
25
  # ODBC connection attribute that carries an access token (SQL_COPT_SS_ACCESS_TOKEN).
25
26
  ACCESS_TOKEN_ATTR = 1256
27
+ _LOGIN_KEYS = re.compile(
28
+ r"(?:^|;)\s*(?:uid|pwd|user id|password|authentication|trusted_connection|"
29
+ r"integrated security|access\s*token)\s*=",
30
+ re.IGNORECASE,
31
+ )
26
32
 
27
33
 
28
34
  @dataclass(frozen=True, slots=True, repr=False)
@@ -32,18 +38,21 @@ class Credentials:
32
38
  ``sql``: the login is in the connection string. ``cli``: the Azure CLI's signed-in account.
33
39
  ``msi``: managed identity (or the default Azure credential chain). ``spn``: a service
34
40
  principal (``tenant_id``, ``client_id``, ``client_secret``). ``fabric``: the token of the
35
- running Fabric notebook.
41
+ running Fabric notebook. ``token``: a caller-supplied bearer or an ``env://NAME`` reference.
36
42
  """
37
43
 
38
44
  method: str = "cli"
39
45
  tenant_id: str | None = None
40
46
  client_id: str | None = None
41
47
  client_secret: str | None = None
48
+ token: str | None = None
42
49
 
43
50
  def __repr__(self) -> str: # never show the secret
51
+ masked_token = ", token=***" if self.token is not None else ""
44
52
  return (
45
53
  f"Credentials(method={self.method!r}, tenant_id={self.tenant_id!r}, "
46
- f"client_id={self.client_id!r}, client_secret={'***' if self.client_secret else None})"
54
+ f"client_id={self.client_id!r}, client_secret={'***' if self.client_secret else None}"
55
+ f"{masked_token})"
47
56
  )
48
57
 
49
58
  def validate(self) -> None:
@@ -53,6 +62,8 @@ class Credentials:
53
62
  )
54
63
  if self.method == "spn" and not (self.tenant_id and self.client_id and self.client_secret):
55
64
  raise SqlServerError("auth 'spn' needs a tenant id, a client id and a client secret")
65
+ if self.method == "token" and (not isinstance(self.token, str) or not self.token.strip()):
66
+ raise SqlServerError("auth 'token' needs a non-empty token or env://NAME reference")
56
67
 
57
68
 
58
69
  def _credential(creds: Credentials) -> Any:
@@ -91,6 +102,21 @@ def access_token(creds: Credentials) -> bytes:
91
102
  raise SqlServerError("auth 'sql' uses the login in the connection string, not a token")
92
103
  if creds.method == "fabric":
93
104
  return _fabric_token().encode("utf-16-le")
105
+ if creds.method == "token":
106
+ assert creds.token is not None
107
+ value = creds.token
108
+ if value.startswith("env://"):
109
+ name = value.removeprefix("env://")
110
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
111
+ raise SqlServerError("auth 'token' needs an environment reference like env://NAME")
112
+ value = os.environ.get(name, "")
113
+ if not value.strip():
114
+ raise SqlServerError("auth 'token' needs a non-empty token in the environment variable")
115
+ try:
116
+ return value.encode("utf-16-le")
117
+ except UnicodeEncodeError:
118
+ pass
119
+ raise SqlServerError("auth 'token' needs a valid Unicode access token")
94
120
  token: str = _credential(creds).get_token(TOKEN_SCOPE).token
95
121
  return token.encode("utf-16-le")
96
122
 
@@ -100,6 +126,38 @@ def token_struct(token: bytes) -> bytes:
100
126
  return struct.pack(f"<I{len(token)}s", len(token), token)
101
127
 
102
128
 
129
+ def validate_token_connection_string(connection_string: str) -> None:
130
+ """Check the original connection string for settings that conflict with token auth."""
131
+ if _LOGIN_KEYS.search(connection_string):
132
+ raise SqlServerError("a connection string used with auth 'token' must omit login settings")
133
+
134
+
135
+ def connect_with_access_token(
136
+ driver: Any,
137
+ connection_string: str,
138
+ creds: Credentials,
139
+ *,
140
+ timeout: int,
141
+ autocommit: bool,
142
+ ) -> Any:
143
+ """Connect with a supplied token and keep driver diagnostics out of the exception chain."""
144
+ packed = token_struct(access_token(creds))
145
+ try:
146
+ return driver.connect(
147
+ connection_string,
148
+ attrs_before={ACCESS_TOKEN_ATTR: packed},
149
+ timeout=timeout,
150
+ autocommit=autocommit,
151
+ )
152
+ except driver.Error:
153
+ pass
154
+ # A driver diagnostic can contain the bearer in plain text or in encoded form.
155
+ raise SqlServerError(
156
+ "could not connect with the supplied Entra access token; if it is invalid or expired, "
157
+ "supply a fresh token for Azure SQL"
158
+ )
159
+
160
+
103
161
  def connect(connection_string: str, creds: Credentials | None = None, *, timeout: int = 30) -> Any:
104
162
  """An open pyodbc connection.
105
163
 
@@ -112,6 +170,8 @@ def connect(connection_string: str, creds: Credentials | None = None, *, timeout
112
170
  """
113
171
  creds = creds or Credentials()
114
172
  creds.validate()
173
+ if creds.method == "token":
174
+ validate_token_connection_string(connection_string)
115
175
  # The Fabric portal gives the ADO.NET form (Data Source=...;Initial Catalog=...): ODBC needs a
116
176
  # driver. Any other string (an ODBC one, with or without Driver=, or a DSN) passes through.
117
177
  if re.search(r"(^|;)\s*(data source|initial catalog)\s*=", connection_string, re.IGNORECASE):
@@ -126,6 +186,10 @@ def connect(connection_string: str, creds: Credentials | None = None, *, timeout
126
186
  try:
127
187
  if creds.method == "sql":
128
188
  conn = pyodbc.connect(connection_string, timeout=timeout, autocommit=True)
189
+ elif creds.method == "token":
190
+ conn = connect_with_access_token(
191
+ pyodbc, connection_string, creds, timeout=timeout, autocommit=True
192
+ )
129
193
  else:
130
194
  token = token_struct(access_token(creds))
131
195
  conn = pyodbc.connect(
@@ -37,7 +37,7 @@ class ProfileDbCommand:
37
37
  parser.add_argument("--database", help="database name, with --server")
38
38
  parser.add_argument(
39
39
  "--auth",
40
- choices=AUTH_METHODS,
40
+ choices=tuple(method for method in AUTH_METHODS if method != "token"),
41
41
  default="cli",
42
42
  help="sql: login in the connection string; cli, msi, spn or fabric: Microsoft Entra "
43
43
  "(default: cli)",
@@ -10,6 +10,8 @@ secret. Options (all optional):
10
10
  a full ODBC connection string, instead of building one from the URI.
11
11
  ``credentials`` / ``auth``
12
12
  a :class:`~shape_sqlserver.auth.Credentials`, or one of its method names (default ``cli``).
13
+ ``token``
14
+ with ``auth="token"``, a bearer supplied in memory or an ``env://NAME`` reference.
13
15
  ``user`` and ``password``
14
16
  a SQL login, used with ``auth="sql"`` (or when given, by default).
15
17
  ``batch_size``
@@ -21,7 +23,7 @@ from __future__ import annotations
21
23
  import datetime as dt
22
24
  from collections.abc import Callable, Iterator
23
25
  from typing import Any
24
- from urllib.parse import parse_qs, unquote, urlparse
26
+ from urllib.parse import parse_qs, parse_qsl, unquote, urlparse
25
27
 
26
28
  import pyarrow as pa # type: ignore[import-untyped]
27
29
 
@@ -45,6 +47,8 @@ DEFAULT_BATCH_SIZE = 65536
45
47
  def parse_uri(uri: str) -> tuple[str, int | None, str | None, str, str]:
46
48
  """``(server, port, database, schema, table)`` of an ``mssql://`` URI."""
47
49
  parsed = urlparse(uri)
50
+ if any(key.lower() == "token" for key, _ in parse_qsl(parsed.query, keep_blank_values=True)):
51
+ raise SqlServerError("pass the token in source options")
48
52
  if parsed.scheme != SCHEME:
49
53
  raise SqlServerError(f"{uri!r} is not an {SCHEME}:// URI")
50
54
  query = parse_qs(parsed.query)
@@ -88,6 +92,12 @@ class SqlServerSource:
88
92
 
89
93
  def _credentials(self, options: dict[str, Any]) -> Credentials:
90
94
  given = options.get("credentials")
95
+ if "token" in options:
96
+ if isinstance(given, Credentials) or options.get("auth") not in (None, "token"):
97
+ raise SqlServerError(
98
+ "use the token option without credentials or another auth method"
99
+ )
100
+ return Credentials(method="token", token=options["token"])
91
101
  if isinstance(given, Credentials):
92
102
  return given
93
103
  auth = options.get("auth") or ("sql" if options.get("user") else "cli")
@@ -100,11 +110,16 @@ class SqlServerSource:
100
110
 
101
111
  def _open(self, uri: str, options: dict[str, Any]) -> tuple[Any, bool]:
102
112
  """``(connection, owned)``."""
113
+ creds = self._credentials(options)
103
114
  if options.get("connection") is not None:
115
+ if creds.method == "token":
116
+ raise SqlServerError("use either a token or an open connection")
104
117
  register_converters(options["connection"])
105
118
  return options["connection"], False
106
119
  text = options.get("connection_string")
107
120
  if not text and self._factory is not None:
121
+ if creds.method == "token":
122
+ raise SqlServerError("use either a token or a connection factory")
108
123
  return self._factory(), True
109
124
  if not text:
110
125
  server, port, database, _, _ = parse_uri(uri)
@@ -120,7 +135,7 @@ class SqlServerSource:
120
135
  password=options.get("password"),
121
136
  trust_server_certificate=bool(options.get("trust_server_certificate", False)),
122
137
  )
123
- return connect(text, self._credentials(options)), True
138
+ return connect(text, creds), True
124
139
 
125
140
  def schema(self, uri: str, **options: Any) -> pa.Schema:
126
141
  _, _, _, schema_name, table = parse_uri(uri)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqllocks-shape-sqlserver
3
- Version: 0.9.3
3
+ Version: 0.9.5
4
4
  Summary: Shape plugin: SQL Server, Azure SQL and Fabric SQL database profiling and source
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/sqllocks/shape
@@ -18,7 +18,7 @@ Classifier: Topic :: Database
18
18
  Requires-Python: >=3.11
19
19
  Description-Content-Type: text/markdown
20
20
  License-File: LICENSE
21
- Requires-Dist: sqllocks-shape==0.9.3
21
+ Requires-Dist: sqllocks-shape==0.9.5
22
22
  Requires-Dist: pyodbc>=5.0
23
23
  Provides-Extra: entra
24
24
  Requires-Dist: azure-identity>=1.16.1; extra == "entra"
@@ -47,5 +47,11 @@ shape profile-db --server myserver.database.windows.net --database shop --auth c
47
47
  You also need the Microsoft ODBC Driver 18 for SQL Server (and unixODBC on Linux).
48
48
  The full guide is `docs/plugins/sqlserver.md` in the repository.
49
49
 
50
+ For a read-only Fabric Lakehouse SQL analytics endpoint, use
51
+ `mssql://<endpoint>.datawarehouse.fabric.microsoft.com/<lakehouse>?schema=dbo&table=T`.
52
+ Pass `auth="token", token=access_token` to `SqlServerSource.schema()` or `.read()`,
53
+ where `access_token` is a bearer held in memory or an `env://NAME` reference.
54
+ The endpoint also accepts `auth="cli"` or `auth="spn"` with service principal options.
55
+
50
56
  Its version always equals core's (`sqllocks-shape`), and it is released together with core.
51
57
  How plugins are written: `docs/plugins/authoring.md`.
@@ -17,6 +17,7 @@ src/sqllocks_shape_sqlserver.egg-info/requires.txt
17
17
  src/sqllocks_shape_sqlserver.egg-info/top_level.txt
18
18
  tests/test_auth.py
19
19
  tests/test_emulator.py
20
+ tests/test_live_fabric_endpoint.py
20
21
  tests/test_owner_profile_findings.py
21
22
  tests/test_portability.py
22
23
  tests/test_profiler.py
@@ -1,4 +1,4 @@
1
- sqllocks-shape==0.9.3
1
+ sqllocks-shape==0.9.5
2
2
  pyodbc>=5.0
3
3
 
4
4
  [entra]
@@ -220,3 +220,46 @@ def test_connect_turns_a_portal_connection_string_into_an_odbc_one(monkeypatch):
220
220
  odbc = "Driver={ODBC Driver 18 for SQL Server};Server=s;UID=u;PWD=p"
221
221
  auth.connect(odbc, auth.Credentials(method="sql"))
222
222
  assert seen[1] == odbc
223
+
224
+
225
+ @pytest.mark.parametrize("reference", [False, True], ids=["literal", "environment"])
226
+ def test_supplied_access_token_is_encoded_and_masked(monkeypatch, reference):
227
+ fake = "fake-sql-bearer-for-tests"
228
+ monkeypatch.setenv("SHAPE_TEST_SQL_TOKEN", fake)
229
+ monkeypatch.setitem(sys.modules, "azure", None)
230
+ value = "env://SHAPE_TEST_SQL_TOKEN" if reference else fake
231
+ creds = Credentials("token", token=value)
232
+ assert "***" in repr(creds)
233
+ assert value not in repr(creds) and value not in str(creds)
234
+ assert auth.access_token(creds) == fake.encode("utf-16-le")
235
+
236
+
237
+ @pytest.mark.parametrize("value", [None, "", " ", 123, "env://", "env://UNSET_SHAPE_TOKEN"])
238
+ def test_supplied_access_token_validation(value, monkeypatch):
239
+ monkeypatch.delenv("UNSET_SHAPE_TOKEN", raising=False)
240
+ with pytest.raises(SqlServerError, match="auth 'token'"):
241
+ auth.access_token(Credentials("token", token=value))
242
+
243
+
244
+ @pytest.mark.parametrize(
245
+ "connection_string",
246
+ [
247
+ "Server=s;Trusted_Connection=yes",
248
+ "Data Source=s;Initial Catalog=db;Integrated Security=SSPI",
249
+ ],
250
+ )
251
+ def test_supplied_access_token_cannot_be_combined_with_a_login(monkeypatch, connection_string):
252
+ calls: list[object] = []
253
+ monkeypatch.setitem(sys.modules, "pyodbc", _fake_pyodbc(calls))
254
+ with pytest.raises(SqlServerError, match="connection string.*login"):
255
+ auth.connect(connection_string, Credentials("token", token="fake"))
256
+ assert not calls
257
+
258
+
259
+ def test_rejected_access_token_discards_the_driver_error(monkeypatch, caplog):
260
+ fake = "fake-sql-bearer-rejected-by-driver"
261
+ monkeypatch.setitem(sys.modules, "pyodbc", _fake_pyodbc([], fail=f"28000 invalid JWT {fake}"))
262
+ with pytest.raises(SqlServerError, match=r"Entra access token.*invalid or expired") as err:
263
+ auth.connect("Server=s", Credentials("token", token=fake))
264
+ assert fake not in str(err.value) and fake not in caplog.text
265
+ assert err.value.__cause__ is None and err.value.__context__ is None
@@ -0,0 +1,15 @@
1
+ """Needs a Fabric account. Not run in CI."""
2
+
3
+ import os
4
+
5
+ import pytest
6
+ from shape_sqlserver import SqlServerSource
7
+
8
+
9
+ @pytest.mark.live
10
+ def test_fabric_sql_analytics_endpoint_reads_catalog():
11
+ uri = os.environ.get("SHAPE_LIVE_FABRIC_SQL_ENDPOINT_URI")
12
+ if not uri:
13
+ pytest.fail("Set SHAPE_LIVE_FABRIC_SQL_ENDPOINT_URI to a Fabric table URI")
14
+ schema = SqlServerSource().schema(uri, auth="token", token="env://SHAPE_LIVE_FABRIC_SQL_TOKEN")
15
+ assert len(schema) > 0
@@ -325,3 +325,51 @@ def test_alias_type_columns_are_read_and_profiled_as_their_base_type():
325
325
  assert columns["amt"]["dtype"] == "float"
326
326
  assert columns["amt"]["min"] == 5.25
327
327
  assert columns["flag"]["dtype"] == "boolean"
328
+
329
+
330
+ @pytest.mark.parametrize("reference", [False, True], ids=["literal", "environment"])
331
+ @pytest.mark.parametrize("explicit_auth", [False, True], ids=["implicit-auth", "explicit-auth"])
332
+ def test_fabric_sql_analytics_endpoint_connection(monkeypatch, reference, explicit_auth, caplog):
333
+ import sys
334
+ from types import SimpleNamespace
335
+
336
+ calls = []
337
+ conn = scenario("retail")
338
+ fake = "fake-analytics-bearer-for-tests"
339
+ monkeypatch.setenv("SHAPE_TEST_SQL_TOKEN", fake)
340
+
341
+ def connect(text, **kwargs):
342
+ calls.append((text, kwargs))
343
+ return conn
344
+
345
+ monkeypatch.setitem(sys.modules, "pyodbc", SimpleNamespace(connect=connect, Error=RuntimeError))
346
+ uri = "mssql://endpoint.datawarehouse.fabric.microsoft.com/lakehouse?schema=dbo&table=orders"
347
+ value = "env://SHAPE_TEST_SQL_TOKEN" if reference else fake
348
+ options = {"auth": "token"} if explicit_auth else {}
349
+ assert SqlServerSource().schema(uri, token=value, **options).names
350
+ ((text, kwargs),) = calls
351
+ assert "Driver={ODBC Driver 18 for SQL Server}" in text
352
+ assert "Server=endpoint.datawarehouse.fabric.microsoft.com" in text
353
+ assert "Database=lakehouse" in text and "Encrypt=yes" in text
354
+ assert "UID=" not in text and "PWD=" not in text and fake not in text
355
+ encoded = fake.encode("utf-16-le")
356
+ assert kwargs["attrs_before"] == {1256: struct.pack("<I", len(encoded)) + encoded}
357
+ assert kwargs["autocommit"] is True
358
+ assert fake not in caplog.text
359
+
360
+
361
+ def test_source_refuses_a_token_in_uri_without_echoing_it():
362
+ fake = "fake-token-in-uri"
363
+ with pytest.raises(SqlServerError, match="token.*options") as err:
364
+ SqlServerSource().schema(f"mssql://host/db?token={fake}")
365
+ assert fake not in str(err.value)
366
+
367
+
368
+ @pytest.mark.parametrize(
369
+ "conflict",
370
+ [{"auth": "cli"}, {"connection": object()}],
371
+ ids=["other-auth", "open-connection"],
372
+ )
373
+ def test_source_refuses_conflicting_token_options(conflict):
374
+ with pytest.raises(SqlServerError, match="token"):
375
+ SqlServerSource().schema(URI, token="fake", **conflict)