sqllocks-shape-sqlserver 0.9.1__tar.gz → 0.9.3__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 (28) hide show
  1. {sqllocks_shape_sqlserver-0.9.1/src/sqllocks_shape_sqlserver.egg-info → sqllocks_shape_sqlserver-0.9.3}/PKG-INFO +2 -2
  2. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/pyproject.toml +2 -2
  3. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/auth.py +11 -1
  4. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/profiler.py +42 -5
  5. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/sql.py +66 -0
  6. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3/src/sqllocks_shape_sqlserver.egg-info}/PKG-INFO +2 -2
  7. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/sqllocks_shape_sqlserver.egg-info/SOURCES.txt +1 -0
  8. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/sqllocks_shape_sqlserver.egg-info/requires.txt +1 -1
  9. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/tests/test_auth.py +29 -0
  10. sqllocks_shape_sqlserver-0.9.3/tests/test_owner_profile_findings.py +31 -0
  11. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/LICENSE +0 -0
  12. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/README.md +0 -0
  13. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/setup.cfg +0 -0
  14. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/__init__.py +0 -0
  15. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/catalog.py +0 -0
  16. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/command.py +0 -0
  17. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/source.py +0 -0
  18. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/shape_sqlserver/testing.py +0 -0
  19. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/sqllocks_shape_sqlserver.egg-info/dependency_links.txt +0 -0
  20. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/sqllocks_shape_sqlserver.egg-info/entry_points.txt +0 -0
  21. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/src/sqllocks_shape_sqlserver.egg-info/top_level.txt +0 -0
  22. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/tests/test_emulator.py +0 -0
  23. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/tests/test_portability.py +0 -0
  24. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/tests/test_profiler.py +0 -0
  25. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/tests/test_security_review.py +0 -0
  26. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/tests/test_skeleton.py +0 -0
  27. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/tests/test_source.py +0 -0
  28. {sqllocks_shape_sqlserver-0.9.1 → sqllocks_shape_sqlserver-0.9.3}/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.3
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.3
22
22
  Requires-Dist: pyodbc>=5.0
23
23
  Provides-Extra: entra
24
24
  Requires-Dist: azure-identity>=1.16.1; extra == "entra"
@@ -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.3"
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.3", "pyodbc>=5.0"]
25
25
 
26
26
  [project.urls]
27
27
  Homepage = "https://github.com/sqllocks/shape"
@@ -6,11 +6,17 @@ 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 re
9
10
  import struct
10
11
  from dataclasses import dataclass
11
12
  from typing import Any
12
13
 
13
- from .sql import SqlServerError, redact_connection_string, register_converters
14
+ from .sql import (
15
+ SqlServerError,
16
+ normalize_connection_string,
17
+ redact_connection_string,
18
+ register_converters,
19
+ )
14
20
 
15
21
  AUTH_METHODS = ("sql", "cli", "msi", "spn", "fabric")
16
22
  TOKEN_SCOPE = "https://database.windows.net/.default"
@@ -106,6 +112,10 @@ def connect(connection_string: str, creds: Credentials | None = None, *, timeout
106
112
  """
107
113
  creds = creds or Credentials()
108
114
  creds.validate()
115
+ # The Fabric portal gives the ADO.NET form (Data Source=...;Initial Catalog=...): ODBC needs a
116
+ # driver. Any other string (an ODBC one, with or without Driver=, or a DSN) passes through.
117
+ if re.search(r"(^|;)\s*(data source|initial catalog)\s*=", connection_string, re.IGNORECASE):
118
+ connection_string = normalize_connection_string(connection_string)
109
119
  try:
110
120
  import pyodbc # type: ignore[import-not-found,unused-ignore]
111
121
  except ImportError as exc:
@@ -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, "
@@ -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.3
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.3
22
22
  Requires-Dist: pyodbc>=5.0
23
23
  Provides-Extra: entra
24
24
  Requires-Dist: azure-identity>=1.16.1; extra == "entra"
@@ -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_owner_profile_findings.py
20
21
  tests/test_portability.py
21
22
  tests/test_profiler.py
22
23
  tests/test_security_review.py
@@ -1,4 +1,4 @@
1
- sqllocks-shape==0.9.1
1
+ sqllocks-shape==0.9.3
2
2
  pyodbc>=5.0
3
3
 
4
4
  [entra]
@@ -191,3 +191,32 @@ 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
@@ -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"]