sqllocks-shape-sqlserver 0.9.1__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.1/src/sqllocks_shape_sqlserver.egg-info → sqllocks_shape_sqlserver-0.9.5}/PKG-INFO +8 -2
  2. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/README.md +6 -0
  3. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/pyproject.toml +5 -2
  4. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/auth.py +78 -4
  5. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/command.py +1 -1
  6. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/profiler.py +42 -5
  7. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/source.py +17 -2
  8. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/sql.py +66 -0
  9. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5/src/sqllocks_shape_sqlserver.egg-info}/PKG-INFO +8 -2
  10. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/SOURCES.txt +2 -0
  11. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/requires.txt +1 -1
  12. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/tests/test_auth.py +72 -0
  13. sqllocks_shape_sqlserver-0.9.5/tests/test_live_fabric_endpoint.py +15 -0
  14. sqllocks_shape_sqlserver-0.9.5/tests/test_owner_profile_findings.py +31 -0
  15. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/tests/test_source.py +48 -0
  16. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/LICENSE +0 -0
  17. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/setup.cfg +0 -0
  18. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/__init__.py +0 -0
  19. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/catalog.py +0 -0
  20. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/shape_sqlserver/testing.py +0 -0
  21. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/dependency_links.txt +0 -0
  22. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/entry_points.txt +0 -0
  23. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/src/sqllocks_shape_sqlserver.egg-info/top_level.txt +0 -0
  24. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/tests/test_emulator.py +0 -0
  25. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/tests/test_portability.py +0 -0
  26. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/tests/test_profiler.py +0 -0
  27. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/tests/test_security_review.py +0 -0
  28. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.5}/tests/test_skeleton.py +0 -0
  29. {sqllocks_shape_sqlserver-0.9.1 → 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.1
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.1
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.1"
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.1", "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,17 +6,29 @@ 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
10
+ import re
9
11
  import struct
10
12
  from dataclasses import dataclass
11
13
  from typing import Any
12
14
 
13
- from .sql import SqlServerError, redact_connection_string, register_converters
15
+ from .sql import (
16
+ SqlServerError,
17
+ normalize_connection_string,
18
+ redact_connection_string,
19
+ register_converters,
20
+ )
14
21
 
15
- AUTH_METHODS = ("sql", "cli", "msi", "spn", "fabric")
22
+ AUTH_METHODS = ("sql", "cli", "msi", "spn", "fabric", "token")
16
23
  TOKEN_SCOPE = "https://database.windows.net/.default"
17
24
  FABRIC_TOKEN_AUDIENCE = "https://database.windows.net/"
18
25
  # ODBC connection attribute that carries an access token (SQL_COPT_SS_ACCESS_TOKEN).
19
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
+ )
20
32
 
21
33
 
22
34
  @dataclass(frozen=True, slots=True, repr=False)
@@ -26,18 +38,21 @@ class Credentials:
26
38
  ``sql``: the login is in the connection string. ``cli``: the Azure CLI's signed-in account.
27
39
  ``msi``: managed identity (or the default Azure credential chain). ``spn``: a service
28
40
  principal (``tenant_id``, ``client_id``, ``client_secret``). ``fabric``: the token of the
29
- running Fabric notebook.
41
+ running Fabric notebook. ``token``: a caller-supplied bearer or an ``env://NAME`` reference.
30
42
  """
31
43
 
32
44
  method: str = "cli"
33
45
  tenant_id: str | None = None
34
46
  client_id: str | None = None
35
47
  client_secret: str | None = None
48
+ token: str | None = None
36
49
 
37
50
  def __repr__(self) -> str: # never show the secret
51
+ masked_token = ", token=***" if self.token is not None else ""
38
52
  return (
39
53
  f"Credentials(method={self.method!r}, tenant_id={self.tenant_id!r}, "
40
- 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})"
41
56
  )
42
57
 
43
58
  def validate(self) -> None:
@@ -47,6 +62,8 @@ class Credentials:
47
62
  )
48
63
  if self.method == "spn" and not (self.tenant_id and self.client_id and self.client_secret):
49
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")
50
67
 
51
68
 
52
69
  def _credential(creds: Credentials) -> Any:
@@ -85,6 +102,21 @@ def access_token(creds: Credentials) -> bytes:
85
102
  raise SqlServerError("auth 'sql' uses the login in the connection string, not a token")
86
103
  if creds.method == "fabric":
87
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")
88
120
  token: str = _credential(creds).get_token(TOKEN_SCOPE).token
89
121
  return token.encode("utf-16-le")
90
122
 
@@ -94,6 +126,38 @@ def token_struct(token: bytes) -> bytes:
94
126
  return struct.pack(f"<I{len(token)}s", len(token), token)
95
127
 
96
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
+
97
161
  def connect(connection_string: str, creds: Credentials | None = None, *, timeout: int = 30) -> Any:
98
162
  """An open pyodbc connection.
99
163
 
@@ -106,6 +170,12 @@ def connect(connection_string: str, creds: Credentials | None = None, *, timeout
106
170
  """
107
171
  creds = creds or Credentials()
108
172
  creds.validate()
173
+ if creds.method == "token":
174
+ validate_token_connection_string(connection_string)
175
+ # The Fabric portal gives the ADO.NET form (Data Source=...;Initial Catalog=...): ODBC needs a
176
+ # driver. Any other string (an ODBC one, with or without Driver=, or a DSN) passes through.
177
+ if re.search(r"(^|;)\s*(data source|initial catalog)\s*=", connection_string, re.IGNORECASE):
178
+ connection_string = normalize_connection_string(connection_string)
109
179
  try:
110
180
  import pyodbc # type: ignore[import-not-found,unused-ignore]
111
181
  except ImportError as exc:
@@ -116,6 +186,10 @@ def connect(connection_string: str, creds: Credentials | None = None, *, timeout
116
186
  try:
117
187
  if creds.method == "sql":
118
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
+ )
119
193
  else:
120
194
  token = token_struct(access_token(creds))
121
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)",
@@ -224,14 +224,40 @@ def _arrow_table(sample: dict[str, list[Any]]) -> Any:
224
224
 
225
225
  def _links_from_data(
226
226
  samples: dict[str, dict[str, list[Any]] | None],
227
+ notes: dict[tuple[str, str], str],
227
228
  ) -> dict[str, dict[str, Any]]:
228
229
  """Foreign keys that profiling the sampled tables together finds between them."""
229
230
  from shape.api import profile as shape_profile
231
+ from shape.profile.reference.dtparse import ZonedTextError
230
232
 
231
233
  tables = {name: _arrow_table(s) for name, s in samples.items() if s is not None}
232
234
  if not tables:
233
235
  return {}
234
- found = shape_profile(tables).to_dict()
236
+ while tables:
237
+ try:
238
+ found = shape_profile(tables).to_dict()
239
+ break
240
+ except ZonedTextError as exc:
241
+ # SQL's declared type remains authoritative for the column statistics. Only
242
+ # this column's optional data-based relationship inference is unavailable.
243
+ removed = False
244
+ for name, table in list(tables.items()):
245
+ if exc.column in table.column_names and exc.text in table[exc.column].to_pylist():
246
+ notes[(name, exc.column)] = (
247
+ "Sampled date text has a time zone or UTC offset; data-based relationship "
248
+ "inference is unavailable for this column. SQL type and sampled statistics "
249
+ "are retained. Convert it to a timestamp before inferring relationships."
250
+ )
251
+ rest = table.drop([exc.column])
252
+ if rest.num_columns:
253
+ tables[name] = rest
254
+ else:
255
+ del tables[name]
256
+ removed = True
257
+ if not removed:
258
+ raise
259
+ else:
260
+ return {}
235
261
  return {
236
262
  rel["name"]: {
237
263
  "child_table": rel["child"],
@@ -281,7 +307,9 @@ def _infer_keys_from_names(
281
307
 
282
308
  def _profile_tables(
283
309
  cursor: Any, catalog: Catalog, sample_rows: int
284
- ) -> tuple[Any, dict[str, int], dict[str, str], dict[tuple[str, str], str]]:
310
+ ) -> tuple[
311
+ Any, dict[str, int], dict[str, str], dict[tuple[str, str], str], dict[tuple[str, str], str]
312
+ ]:
285
313
  from shape.profile.reference.model import DatasetProfile, TableProfile
286
314
 
287
315
  samples, methods = _sample_all(cursor, catalog, sample_rows)
@@ -300,7 +328,8 @@ def _profile_tables(
300
328
  for name, fk in catalog.foreign_keys.items()
301
329
  }
302
330
  covered = {(lk["child_table"], c) for lk in links.values() for c in lk["child_columns"]}
303
- for name, lk in _links_from_data(samples).items():
331
+ notes: dict[tuple[str, str], str] = {}
332
+ for name, lk in _links_from_data(samples, notes).items():
304
333
  if any((lk["child_table"], c) in covered for c in lk["child_columns"]):
305
334
  continue
306
335
  links[name] = {**lk, "evidence": DATA}
@@ -360,7 +389,13 @@ def _profile_tables(
360
389
  "evidence": lk["evidence"],
361
390
  }
362
391
  )
363
- return DatasetProfile(tables=profiles, relationships=relationships), sampled, methods, evidence
392
+ return (
393
+ DatasetProfile(tables=profiles, relationships=relationships),
394
+ sampled,
395
+ methods,
396
+ evidence,
397
+ notes,
398
+ )
364
399
 
365
400
 
366
401
  def _check_found(cursor: Any, catalog: Catalog, tables: list[str] | None) -> None:
@@ -417,7 +452,7 @@ def profile_database(
417
452
  try:
418
453
  catalog = read_catalog(cursor, schema, tables)
419
454
  _check_found(cursor, catalog, tables)
420
- dataset, sampled, methods, evidence = _profile_tables(cursor, catalog, sample_rows)
455
+ dataset, sampled, methods, evidence, notes = _profile_tables(cursor, catalog, sample_rows)
421
456
  finally:
422
457
  cursor.close()
423
458
  if connection is None:
@@ -432,6 +467,8 @@ def profile_database(
432
467
  table["sample_method"] = methods[table_name]
433
468
  for col_name, column in table["columns"].items():
434
469
  column["fk_evidence"] = evidence.get((table_name, col_name))
470
+ if note := notes.get((table_name, col_name)):
471
+ column["profiling_note"] = note
435
472
  data["sampling"] = {
436
473
  "method": (
437
474
  "spread over the table: SELECT TOP n ... ORDER BY a scrambled CHECKSUM(primary key, "
@@ -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)
@@ -318,3 +318,69 @@ def sql_type_to_arrow(type_name: str, precision: int = 0, scale: int = 0) -> Any
318
318
  if t in ("decimal", "numeric"):
319
319
  return pa.decimal128(max(int(precision), 1), int(scale))
320
320
  return pa.string()
321
+
322
+
323
+ _ADO_PAIR = re.compile(r"""\s*([^=;]+?)\s*=\s*("(?:[^"]|"")*"|'(?:[^']|'')*'|[^;]*)""")
324
+ _TRUE = ("true", "yes", "1")
325
+ _FALSE = ("false", "no", "0")
326
+
327
+
328
+ def _unquote(value: str) -> str:
329
+ value = value.strip()
330
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
331
+ return value[1:-1].replace(value[0] * 2, value[0])
332
+ return value
333
+
334
+
335
+ def normalize_connection_string(cs: str, driver: str | None = None) -> str:
336
+ """``cs`` as an ODBC connection string. The Fabric portal gives the ADO.NET form
337
+ (``Data Source=...;Initial Catalog=...``); an ODBC string (it has ``Driver=``) is returned
338
+ unchanged. ``Encrypt=Strict`` is kept, ``Application Name`` and ``MultipleActiveResultSets``
339
+ become ODBC's ``APP`` and ``MARS_Connection``; other ADO.NET-only settings (``Persist Security
340
+ Info``, pooling) have no ODBC meaning and are left out. ``driver`` defaults to the SQL Server
341
+ plugin's (ODBC Driver 18)."""
342
+ if re.search(r"(^|;)\s*driver\s*=", cs, re.IGNORECASE):
343
+ return cs
344
+ driver = driver or DEFAULT_DRIVER
345
+ parts = {m.group(1).strip().lower(): _unquote(m.group(2)) for m in _ADO_PAIR.finditer(cs)}
346
+ server = parts.get("data source") or parts.get("server")
347
+ if not server:
348
+ raise SqlServerError("the connection string has no server (Data Source= or Server=)")
349
+ if server.lower().startswith("tcp:"):
350
+ server = server[4:]
351
+
352
+ def flag(*keys: str) -> bool | None:
353
+ for key in keys:
354
+ if key in parts:
355
+ low = parts[key].lower()
356
+ return True if low in _TRUE else False if low in _FALSE else None
357
+ return None
358
+
359
+ encrypt = flag("encrypt")
360
+ trust = flag("trust server certificate", "trustservercertificate")
361
+ timeout = parts.get("connect timeout") or parts.get("connection timeout")
362
+ if timeout and not timeout.strip().isdigit():
363
+ raise SqlServerError(f"the connection timeout must be whole seconds, not {timeout!r}")
364
+ extra: dict[str, str] = {}
365
+ if "authentication" in parts:
366
+ extra["Authentication"] = parts["authentication"].replace(" ", "")
367
+ if parts.get("encrypt", "").strip().lower() == "strict":
368
+ extra["Encrypt"] = "strict" # TDS 8 with strict certificate checks: never weakened
369
+ if parts.get("application name"):
370
+ extra["APP"] = parts["application name"]
371
+ mars = flag("multipleactiveresultsets", "multiple active result sets")
372
+ if mars is not None:
373
+ extra["MARS_Connection"] = "yes" if mars else "no"
374
+ return str(
375
+ build_connection_string(
376
+ server,
377
+ parts.get("initial catalog") or parts.get("database"),
378
+ user=parts.get("user id") or parts.get("uid") or parts.get("user"),
379
+ password=parts.get("password") or parts.get("pwd"),
380
+ driver=driver,
381
+ encrypt=True if encrypt is None else encrypt,
382
+ trust_server_certificate=bool(trust),
383
+ timeout=int(timeout) if timeout else 30,
384
+ extra=extra,
385
+ )
386
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqllocks-shape-sqlserver
3
- Version: 0.9.1
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.1
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,8 @@ 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
21
+ tests/test_owner_profile_findings.py
20
22
  tests/test_portability.py
21
23
  tests/test_profiler.py
22
24
  tests/test_security_review.py
@@ -1,4 +1,4 @@
1
- sqllocks-shape==0.9.1
1
+ sqllocks-shape==0.9.5
2
2
  pyodbc>=5.0
3
3
 
4
4
  [entra]
@@ -191,3 +191,75 @@ def test_fabric_auth_takes_the_notebook_token(monkeypatch, module):
191
191
  def test_sql_auth_has_no_token():
192
192
  with pytest.raises(SqlServerError, match="login in the connection string"):
193
193
  auth.access_token(Credentials("sql"))
194
+
195
+
196
+ def test_connect_turns_a_portal_connection_string_into_an_odbc_one(monkeypatch):
197
+ """profile-db given the Fabric portal's ADO.NET string failed with IM002 (no driver)."""
198
+ import sys
199
+ import types
200
+
201
+ seen = []
202
+
203
+ class Error(Exception):
204
+ pass
205
+
206
+ def connect(cs, **kw):
207
+ seen.append(cs)
208
+ return types.SimpleNamespace(add_output_converter=lambda *a: None)
209
+
210
+ monkeypatch.setitem(sys.modules, "pyodbc", types.SimpleNamespace(connect=connect, Error=Error))
211
+ monkeypatch.setattr("shape_sqlserver.auth.register_converters", lambda conn: None)
212
+ from shape_sqlserver import auth
213
+
214
+ auth.connect(
215
+ "Data Source=x.datawarehouse.fabric.microsoft.com;Initial Catalog=wh",
216
+ auth.Credentials(method="sql"),
217
+ )
218
+ assert seen[0].lower().startswith("driver={odbc driver 18 for sql server}")
219
+ assert "x.datawarehouse.fabric.microsoft.com" in seen[0]
220
+ odbc = "Driver={ODBC Driver 18 for SQL Server};Server=s;UID=u;PWD=p"
221
+ auth.connect(odbc, auth.Credentials(method="sql"))
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
@@ -0,0 +1,31 @@
1
+ """A problematic sampled text column must not discard the database profile."""
2
+
3
+ from shape_sqlserver import profile_database
4
+ from shape_sqlserver.testing import FakeColumn, FakeConnection, FakeTable
5
+
6
+
7
+ def test_database_profile_records_a_zoned_text_column_problem():
8
+ table = FakeTable(
9
+ "events",
10
+ [FakeColumn("id", "int"), FakeColumn("when", "varchar")],
11
+ [(1, "2026-10-11T18:00:00+02:00"), (2, "2026-10-11T19:00:00+02:00")],
12
+ )
13
+ data = profile_database(connection=FakeConnection([table])).to_dict()
14
+ columns = data["tables"]["events"]["columns"]
15
+ assert columns["id"]["cardinality"] == 2
16
+ assert columns["when"]["dtype"] == "string"
17
+ assert "time zone" in columns["when"]["profiling_note"]
18
+
19
+
20
+ def test_database_profile_keeps_hour_buckets_and_other_columns():
21
+ table = FakeTable(
22
+ "hours",
23
+ [FakeColumn("id", "int"), FakeColumn("HourlyBucket", "varchar")],
24
+ [(1, "18:00-18:59"), (2, "19:00-19:59")],
25
+ )
26
+ columns = profile_database(connection=FakeConnection([table])).to_dict()["tables"]["hours"][
27
+ "columns"
28
+ ]
29
+ assert columns["HourlyBucket"]["dtype"] == "string"
30
+ assert columns["id"]["cardinality"] == 2
31
+ assert "profiling_note" not in columns["HourlyBucket"]
@@ -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)