soda-sqlserver 4.29.0__tar.gz → 4.30.0__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.
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: soda-sqlserver
3
- Version: 4.29.0
3
+ Version: 4.30.0
4
4
  Summary: Soda SQL Server V4
5
5
  Author-email: "Soda Data N.V." <info@soda.io>
6
6
  License: Proprietary
7
7
  Requires-Python: >=3.10
8
- Requires-Dist: soda-core==4.29.0
8
+ Requires-Dist: soda-core==4.30.0
9
9
  Requires-Dist: pyodbc
10
+ Requires-Dist: azure-identity<2,>=1.17.1
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "soda-sqlserver"
3
- version = "4.29.0"
3
+ version = "4.30.0"
4
4
  description = "Soda SQL Server V4"
5
5
  requires-python = ">=3.10"
6
6
  license = {text = "Proprietary"}
@@ -8,8 +8,9 @@ authors = [
8
8
  {name = "Soda Data N.V.", email = "info@soda.io"}
9
9
  ]
10
10
  dependencies = [
11
- "soda-core==4.29.0",
11
+ "soda-core==4.30.0",
12
12
  "pyodbc",
13
+ "azure-identity>=1.17.1,<2",
13
14
  ]
14
15
 
15
16
  [project.entry-points."soda.plugins.data_source.sqlserver"]
@@ -1,37 +1,60 @@
1
1
  import logging
2
+ import re
2
3
  from copy import deepcopy
3
4
  from datetime import date, datetime
4
5
  from typing import Optional
5
6
 
6
7
  from soda_core.common.data_source_connection import DataSourceConnection
7
8
  from soda_core.common.data_source_impl import DataSourceImpl
9
+ from soda_core.common.exceptions import UnsupportedSqlStatementError
8
10
  from soda_core.common.logging_constants import soda_logger
9
11
  from soda_core.common.metadata_types import SodaDataTypeName, SqlDataType
10
12
  from soda_core.common.sql_ast import (
11
13
  ADD_INTERVAL,
14
+ ANALYZE_TABLE,
12
15
  COLUMN,
13
16
  COUNT,
17
+ CREATE_INDEX_IF_NOT_EXISTS,
18
+ CREATE_SCHEMA_IF_NOT_EXISTS,
14
19
  CREATE_TABLE,
15
20
  CREATE_TABLE_AS_SELECT,
16
21
  CREATE_TABLE_COLUMN,
17
22
  CREATE_TABLE_IF_NOT_EXISTS,
18
23
  CREATE_VIEW,
24
+ CURRENT_TIMESTAMP,
25
+ DATE_ISO_TEXT,
26
+ DATE_TRUNC,
27
+ DELETE,
19
28
  DISTINCT,
20
29
  DROP_TABLE,
21
30
  DROP_TABLE_IF_EXISTS,
22
31
  DROP_VIEW,
23
32
  DROP_VIEW_IF_EXISTS,
33
+ EPOCH_SECONDS,
34
+ FROM,
24
35
  INSERT_INTO,
25
36
  INSERT_INTO_VIA_SELECT,
26
37
  INTO,
38
+ JOIN,
39
+ JSON_MERGE,
40
+ LEFT_INNER_JOIN,
27
41
  LENGTH,
42
+ LIKE,
28
43
  LIMIT,
44
+ LITERAL,
29
45
  OFFSET,
30
46
  PERCENTILE_WITHIN_GROUP,
31
47
  RANDOM,
48
+ REGEXP_REPLACE,
49
+ SOURCE_COLUMN,
32
50
  STRING_HASH,
33
51
  TIME_DELTA,
52
+ TIMESTAMP_ISO_TEXT,
53
+ TO_TIMEZONE,
34
54
  TUPLE,
55
+ UPDATE,
56
+ UPSERT,
57
+ UPSERT_VIA_SELECT,
35
58
  VALUES,
36
59
  WITH,
37
60
  seconds_per_time_bucket,
@@ -47,9 +70,24 @@ logger: logging.Logger = soda_logger
47
70
 
48
71
  # APPROX_PERCENTILE_DISC needs SQL Server 2022+ on-prem, or Azure SQL Database /
49
72
  # Managed Instance (which report a legacy ProductMajorVersion).
73
+ # So does DATETRUNC.
50
74
  SQLSERVER_2022_MAJOR_VERSION = 16
51
75
  AZURE_SQL_DATABASE_ENGINE_EDITION = 5
52
76
  AZURE_SQL_MANAGED_INSTANCE_ENGINE_EDITION = 8
77
+ # REGEXP_REPLACE needs SQL Server 2025+ on-prem, or Azure SQL Database.
78
+ SQLSERVER_2025_MAJOR_VERSION = 17
79
+ SQLSERVER_RELEASE_BY_MAJOR_VERSION = {
80
+ SQLSERVER_2022_MAJOR_VERSION: "SQL Server 2022",
81
+ SQLSERVER_2025_MAJOR_VERSION: "SQL Server 2025",
82
+ }
83
+ AZURE_ENGINE_NAME_BY_EDITION = {
84
+ AZURE_SQL_DATABASE_ENGINE_EDITION: "Azure SQL Database",
85
+ AZURE_SQL_MANAGED_INSTANCE_ENGINE_EDITION: "Azure SQL Managed Instance",
86
+ }
87
+
88
+ # A three-part name, capturing the database. Each part is bracket-quoted, with ]] for a literal ], or plain.
89
+ _NAME_PART_PATTERN = r"(?:\[(?:[^\]]|\]\])*\]|[^.\[\]]*)"
90
+ THREE_PART_NAME_PATTERN = re.compile(rf"({_NAME_PART_PATTERN})\.{_NAME_PART_PATTERN}\.{_NAME_PART_PATTERN}")
53
91
 
54
92
 
55
93
  class SqlServerDataSourceImpl(DataSourceImpl, model_class=SqlServerDataSourceModel):
@@ -102,6 +140,7 @@ class SqlServerSqlDialect(SqlDialect, sqlglot_dialect="tsql"):
102
140
  SODA_DATA_TYPE_SYNONYMS = ((SodaDataTypeName.TEXT, SodaDataTypeName.VARCHAR),)
103
141
  # T-SQL's page window is `OFFSET m ROWS` then `FETCH NEXT n ROWS ONLY`.
104
142
  OFFSET_BEFORE_LIMIT: bool = True
143
+ SUPPORTS_DATA_PLANE_STATEMENTS = True
105
144
 
106
145
  def __init__(self):
107
146
  super().__init__()
@@ -509,6 +548,11 @@ class SqlServerSqlDialect(SqlDialect, sqlglot_dialect="tsql"):
509
548
  def _build_string_hash_sql(self, string_hash: STRING_HASH) -> str:
510
549
  return f"CONVERT(VARCHAR(32), HASHBYTES('MD5', {self.build_expression_sql(string_hash.expression)}), 2)"
511
550
 
551
+ def _hash_operand_text_type(self) -> SodaDataTypeName | str:
552
+ # A bare varchar in a CAST is varchar(30): it cuts longer text and rejects wider numbers and uniqueidentifier.
553
+ # nvarchar, not varchar, so nvarchar text outside the database code page is not folded.
554
+ return "nvarchar(max)"
555
+
512
556
  def _get_add_column_sql_expr(self) -> str:
513
557
  return "ADD"
514
558
 
@@ -539,3 +583,276 @@ class SqlServerSqlDialect(SqlDialect, sqlglot_dialect="tsql"):
539
583
 
540
584
  def _build_random_sql(self, random: RANDOM) -> str:
541
585
  return "ABS(CAST(CHECKSUM(NEWID()) AS FLOAT)) / 2147483648.0"
586
+
587
+ ###
588
+ # Data plane statements
589
+ ###
590
+ # Every override below is inherited by the Fabric and Synapse dialects, which do not set
591
+ # SUPPORTS_DATA_PLANE_STATEMENTS: the base gates each hook on the flag, except
592
+ # _build_current_timestamp_sql, which therefore checks the flag itself.
593
+
594
+ # MERGE names its incoming rows; SOURCE_COLUMN renders as this alias.
595
+ _MERGE_SOURCE_ALIAS = "src"
596
+ _MERGE_DEFAULT_TARGET_ALIAS = "tgt"
597
+
598
+ def _build_update_sql(self, update: UPDATE) -> str:
599
+ if not update.alias:
600
+ if update.from_elements:
601
+ raise self._unaliased_target_error("UPDATE", "from_elements")
602
+ return super()._build_update_sql(update)
603
+ lines: list[str] = [
604
+ f"UPDATE {self.quote_default(update.alias)}",
605
+ f"SET {self._build_assignments_sql(update.assignments)}",
606
+ ]
607
+ lines.extend(
608
+ self._build_target_and_sources_sql_lines(
609
+ update.fully_qualified_table_name, update.alias, update.from_elements
610
+ )
611
+ )
612
+ if update.where is not None:
613
+ lines.extend(self._build_where_sql_lines([update.where]))
614
+ return "\n".join(lines)
615
+
616
+ def _build_delete_sql(self, delete: DELETE) -> str:
617
+ if not delete.alias:
618
+ if delete.using_elements:
619
+ raise self._unaliased_target_error("DELETE", "using_elements")
620
+ return super()._build_delete_sql(delete)
621
+ lines: list[str] = [f"DELETE {self.quote_default(delete.alias)}"]
622
+ lines.extend(
623
+ self._build_target_and_sources_sql_lines(
624
+ delete.fully_qualified_table_name, delete.alias, delete.using_elements
625
+ )
626
+ )
627
+ if delete.where is not None:
628
+ lines.extend(self._build_where_sql_lines([delete.where]))
629
+ return "\n".join(lines)
630
+
631
+ def _unaliased_target_error(self, node_name: str, sources_field: str) -> UnsupportedSqlStatementError:
632
+ return UnsupportedSqlStatementError(
633
+ f"{type(self).__name__} does not support {node_name} with {sources_field} and no alias: T-SQL binds "
634
+ f"an unaliased target to a reference to the same table among the further tables"
635
+ )
636
+
637
+ def _build_target_and_sources_sql_lines(
638
+ self, fully_qualified_table_name: str, alias: str, elements: Optional[list[FROM | JOIN]]
639
+ ) -> list[str]:
640
+ """``FROM <target> AS <alias>`` followed by the further tables, laid out as the base lays out an
641
+ UPDATE's FROM clause: plain FROM elements comma-separated, each JOIN on its own line."""
642
+ lines: list[str] = [f"FROM {self._build_statement_target_sql(fully_qualified_table_name, alias)}"]
643
+ continuation: str = " " * len("FROM ")
644
+ for element in elements or []:
645
+ if isinstance(element, (LEFT_INNER_JOIN, JOIN)):
646
+ lines.append(f"{continuation}{self._build_join_part(element)}")
647
+ else:
648
+ lines[-1] += ","
649
+ lines.append(f"{continuation}{self._build_from_part(element)}")
650
+ return lines
651
+
652
+ def build_upsert_sql(self, upsert: UPSERT, add_semicolon: Optional[bool] = None) -> str:
653
+ # The MERGE carries its own semicolon: T-SQL requires it (error 10713) whatever the caller asks.
654
+ return super().build_upsert_sql(upsert, add_semicolon=False)
655
+
656
+ def build_upsert_via_select_sql(
657
+ self, upsert_via_select: UPSERT_VIA_SELECT, add_semicolon: Optional[bool] = None
658
+ ) -> str:
659
+ return super().build_upsert_via_select_sql(upsert_via_select, add_semicolon=False)
660
+
661
+ def _build_upsert_sql(self, upsert: UPSERT) -> str:
662
+ return self._build_merge_sql(upsert, self._build_insert_into_values_sql(upsert).strip())
663
+
664
+ def _build_upsert_via_select_sql(self, upsert_via_select: UPSERT_VIA_SELECT) -> str:
665
+ # A CTE cannot open a MERGE source (error 156), so it moves in front of the MERGE.
666
+ with_elements, select_elements = self._split_with_elements(upsert_via_select.select_elements)
667
+ merge_sql: str = self._build_merge_sql(
668
+ upsert_via_select, self.build_select_sql(select_elements, add_semicolon=False)
669
+ )
670
+ return "\n".join([*self._build_cte_sql_lines(with_elements), merge_sql])
671
+
672
+ @staticmethod
673
+ def _split_with_elements(select_elements: list) -> tuple[list[WITH], list]:
674
+ """The WITH elements of a statement's SELECT, which T-SQL puts in front of the whole statement, and
675
+ the other elements."""
676
+ with_elements: list[WITH] = [element for element in select_elements if isinstance(element, WITH)]
677
+ other_elements: list = [element for element in select_elements if not isinstance(element, WITH)]
678
+ return with_elements, other_elements
679
+
680
+ def _build_merge_sql(self, upsert: UPSERT | UPSERT_VIA_SELECT, source_sql: str) -> str:
681
+ """HOLDLOCK keeps the key range locked from the match to the insert, so a concurrent upsert of the
682
+ same key waits instead of failing on the primary key."""
683
+ target_alias: str = upsert.alias or self._MERGE_DEFAULT_TARGET_ALIAS
684
+ if target_alias.lower() == self._MERGE_SOURCE_ALIAS:
685
+ raise UnsupportedSqlStatementError(
686
+ f"{type(self).__name__} does not support an upsert target alias {target_alias!r}: "
687
+ f"it names the incoming rows"
688
+ )
689
+ target: str = self.quote_default(target_alias)
690
+ source: str = self.quote_default(self._MERGE_SOURCE_ALIAS)
691
+ column_names: list[str] = [self.quote_default(self._upsert_column_name(column)) for column in upsert.columns]
692
+ columns_sql: str = ", ".join(column_names)
693
+ key_condition_sql: str = " AND ".join(
694
+ f"{target}.{key} = {source}.{key}"
695
+ for key in (self.quote_default(self._upsert_column_name(column)) for column in upsert.key_columns)
696
+ )
697
+ lines: list[str] = [
698
+ f"MERGE INTO {upsert.fully_qualified_table_name} WITH (HOLDLOCK) AS {target}",
699
+ f"USING (\n{source_sql}\n) AS {source} ({columns_sql})",
700
+ f"ON ({key_condition_sql})",
701
+ ]
702
+ if upsert.update_assignments:
703
+ lines.append(f"WHEN MATCHED THEN UPDATE SET {self._build_assignments_sql(upsert.update_assignments)}")
704
+ source_values_sql: str = ", ".join(f"{source}.{column_name}" for column_name in column_names)
705
+ lines.append(f"WHEN NOT MATCHED THEN INSERT ({columns_sql}) VALUES ({source_values_sql});")
706
+ return "\n".join(lines)
707
+
708
+ @staticmethod
709
+ def _upsert_column_name(column: COLUMN | str) -> str:
710
+ column_name = column.name if isinstance(column, COLUMN) else column
711
+ if not isinstance(column_name, str):
712
+ raise ValueError(f"An upsert column must be named, got {column_name!r}")
713
+ return column_name
714
+
715
+ def _build_source_column_sql(self, source_column: SOURCE_COLUMN) -> str:
716
+ return f"{self.quote_default(self._MERGE_SOURCE_ALIAS)}.{self.quote_default(source_column.name)}"
717
+
718
+ def _build_create_index_sql(self, create_index: CREATE_INDEX_IF_NOT_EXISTS) -> Optional[str]:
719
+ # T-SQL has no CREATE INDEX IF NOT EXISTS.
720
+ index_name: str = create_index.index_name
721
+ table_name: str = self._convert_fqn_for_ddl(create_index.fully_qualified_table_name)
722
+ columns_sql: str = self._build_index_columns_sql(create_index.columns)
723
+ return (
724
+ f"IF NOT EXISTS (SELECT 1 FROM {self._sys_indexes_sql(table_name)} "
725
+ f"WHERE name = N{self.literal_string(index_name)} "
726
+ f"AND object_id = OBJECT_ID(N{self.literal_string(table_name)})) "
727
+ f"CREATE INDEX {self.quote_for_ddl(index_name)} ON {table_name} {columns_sql}"
728
+ )
729
+
730
+ @staticmethod
731
+ def _sys_indexes_sql(table_name: str) -> str:
732
+ """The sys.indexes of the database OBJECT_ID resolves the table in: the one its name qualifies it
733
+ with, or else the current one."""
734
+ three_part_name = THREE_PART_NAME_PATTERN.fullmatch(table_name)
735
+ if three_part_name and three_part_name.group(1):
736
+ return f"{three_part_name.group(1)}.sys.indexes"
737
+ return "sys.indexes"
738
+
739
+ def _build_create_schema_sql(self, create_schema: CREATE_SCHEMA_IF_NOT_EXISTS) -> str:
740
+ # CREATE SCHEMA must be alone in its batch, hence EXEC; the schema lands in the named database when
741
+ # one is given, else in the current one.
742
+ database: Optional[str] = self.quote_default(create_schema.prefixes[0])
743
+ schema_name: str = create_schema.prefixes[1]
744
+ create_schema_sql: str = f"CREATE SCHEMA {self.quote_default(schema_name)}"
745
+ if database:
746
+ return (
747
+ f"IF NOT EXISTS (SELECT 1 FROM {database}.sys.schemas "
748
+ f"WHERE name = N{self.literal_string(schema_name)}) "
749
+ f"EXEC {database}.sys.sp_executesql N{self.literal_string(create_schema_sql)}"
750
+ )
751
+ return (
752
+ f"IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = N{self.literal_string(schema_name)}) "
753
+ f"EXEC(N{self.literal_string(create_schema_sql)})"
754
+ )
755
+
756
+ def _build_analyze_table_sql(self, analyze_table: ANALYZE_TABLE) -> Optional[str]:
757
+ return f"UPDATE STATISTICS {self._convert_fqn_for_ddl(analyze_table.fully_qualified_table_name)}"
758
+
759
+ def _build_like_escape_sql(self, like: LIKE) -> str:
760
+ # T-SQL's `[` opens a character-set wildcard, which ANSI LIKE does not have. As the escape character
761
+ # itself, the caller has escaped it already.
762
+ if like.escape == "[" or not (isinstance(like.right, LITERAL) and isinstance(like.right.value, str)):
763
+ return super()._build_like_escape_sql(like)
764
+ pattern: str = like.right.value.replace("[", f"{like.escape}[")
765
+ return (
766
+ f"{self.build_expression_sql(like.left)} like {self.build_expression_sql(LITERAL(pattern))} "
767
+ f"ESCAPE {self.literal_string(like.escape)}"
768
+ )
769
+
770
+ def _build_current_timestamp_sql(self, current_timestamp: CURRENT_TIMESTAMP) -> str:
771
+ if not self.SUPPORTS_DATA_PLANE_STATEMENTS:
772
+ return super()._build_current_timestamp_sql(current_timestamp)
773
+ # T-SQL's CURRENT_TIMESTAMP is the server's local time without an offset.
774
+ return "SYSDATETIMEOFFSET()"
775
+
776
+ def _build_timestamp_iso_text_sql(self, timestamp_iso_text: TIMESTAMP_ISO_TEXT) -> str:
777
+ # Through datetime2(7), so a date or a text renders as a timestamp does.
778
+ timestamp_sql: str = f"CAST({self.build_expression_sql(timestamp_iso_text.expression)} AS datetime2(7))"
779
+ iso_text_sql: str
780
+ if timestamp_iso_text.fractional_seconds:
781
+ # Style 126 drops a zero fraction; style 121 keeps it, with a space where ISO has the T. LEFT
782
+ # truncates the seventh digit as the whole-second form does, where datetime2(6) would round.
783
+ iso_text_sql = f"STUFF(LEFT(CONVERT(varchar(27), {timestamp_sql}, 121), 26), 11, 1, 'T')"
784
+ else:
785
+ iso_text_sql = f"CONVERT(varchar(19), {timestamp_sql}, 126)"
786
+ if timestamp_iso_text.utc_suffix:
787
+ # + propagates NULL; CONCAT would return the bare suffix.
788
+ return f"({iso_text_sql} + '+00:00')"
789
+ return iso_text_sql
790
+
791
+ def _build_date_iso_text_sql(self, date_iso_text: DATE_ISO_TEXT) -> str:
792
+ return f"CONVERT(char(10), {self.build_expression_sql(date_iso_text.expression)}, 23)"
793
+
794
+ def _build_to_timezone_sql(self, to_timezone: TO_TIMEZONE) -> str:
795
+ # AT TIME ZONE takes Windows zone names, so UTC is the one zone rendered.
796
+ if to_timezone.timezone.lower() not in ("utc", "etc/utc"):
797
+ raise UnsupportedSqlStatementError(
798
+ f"{type(self).__name__} does not support TO_TIMEZONE to {to_timezone.timezone!r}: only UTC"
799
+ )
800
+ return f"CAST(SWITCHOFFSET({self.build_expression_sql(to_timezone.expression)}, '+00:00') AS datetime2(7))"
801
+
802
+ def _build_date_trunc_sql(self, date_trunc: DATE_TRUNC) -> str:
803
+ self._require_engine(
804
+ node_name="DATE_TRUNC",
805
+ function_name="DATETRUNC",
806
+ major_version=SQLSERVER_2022_MAJOR_VERSION,
807
+ azure_engine_editions=(AZURE_SQL_DATABASE_ENGINE_EDITION, AZURE_SQL_MANAGED_INSTANCE_ENGINE_EDITION),
808
+ )
809
+ return f"DATETRUNC({date_trunc.unit.upper()}, {self.build_expression_sql(date_trunc.expression)})"
810
+
811
+ def _build_regexp_replace_sql(self, regexp_replace: REGEXP_REPLACE) -> str:
812
+ # A Managed Instance has the regex functions only under some update policies, which its facts
813
+ # do not tell apart.
814
+ self._require_engine(
815
+ node_name="REGEXP_REPLACE",
816
+ function_name="REGEXP_REPLACE",
817
+ major_version=SQLSERVER_2025_MAJOR_VERSION,
818
+ azure_engine_editions=(AZURE_SQL_DATABASE_ENGINE_EDITION,),
819
+ )
820
+ expression_sql: str = self.build_expression_sql(regexp_replace.expression)
821
+ pattern_sql: str = self.literal_string(regexp_replace.pattern)
822
+ replacement_sql: str = self.literal_string(regexp_replace.replacement)
823
+ return f"REGEXP_REPLACE({expression_sql}, {pattern_sql}, {replacement_sql})"
824
+
825
+ def _build_epoch_seconds_sql(self, epoch_seconds: EPOCH_SECONDS) -> str:
826
+ # T-SQL has no interval type: a timestamp difference is DATEDIFF's count of one unit.
827
+ raise self._unsupported_sql_statement_error("EPOCH_SECONDS")
828
+
829
+ def _build_json_merge_sql(self, json_merge: JSON_MERGE) -> str:
830
+ # No T-SQL function merges two JSON objects; a caller sets the keys one by one with JSON_MODIFY.
831
+ raise self._unsupported_sql_statement_error("JSON_MERGE")
832
+
833
+ def _require_engine(
834
+ self,
835
+ node_name: str,
836
+ function_name: str,
837
+ major_version: int,
838
+ azure_engine_editions: tuple[int, ...],
839
+ ) -> None:
840
+ """Raises unless the connected engine has ``function_name``: from ``major_version`` on premises,
841
+ and on the ``azure_engine_editions``, which report a legacy major version. Without server facts
842
+ (rendering only, snapshot replay) the newest engine is assumed, as in
843
+ supports_percentile_within_group."""
844
+ if self.server_major_version is None and self.engine_edition is None:
845
+ return
846
+ if (
847
+ self.server_major_version is not None and self.server_major_version >= major_version
848
+ ) or self.engine_edition in azure_engine_editions:
849
+ return
850
+ engine_names: list[str] = [
851
+ SQLSERVER_RELEASE_BY_MAJOR_VERSION[major_version],
852
+ *(AZURE_ENGINE_NAME_BY_EDITION[edition] for edition in azure_engine_editions),
853
+ ]
854
+ raise UnsupportedSqlStatementError(
855
+ f"{type(self).__name__} does not support {node_name} on this server (major version "
856
+ f"{self.server_major_version}, engine edition {self.engine_edition}): {function_name} needs "
857
+ f"{', '.join(engine_names[:-1])} or {engine_names[-1]}"
858
+ )
@@ -1,15 +1,17 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import logging
4
+ import os
4
5
  import random
5
6
  import struct
6
7
  import time
7
8
  from abc import ABC
9
+ from dataclasses import dataclass
8
10
  from datetime import datetime, timedelta, timezone, tzinfo
9
11
  from typing import Any, Callable, Literal, Optional, TypeVar, Union
10
12
 
11
13
  import pyodbc
12
- from pydantic import Field, SecretStr
14
+ from pydantic import ConfigDict, Field, SecretStr, field_validator
13
15
  from soda_core.__version__ import SODA_CORE_VERSION
14
16
  from soda_core.common.data_source_connection import DataSourceConnection
15
17
  from soda_core.common.data_source_results import QueryResult
@@ -28,6 +30,23 @@ CONTEXT_AUTHENTICATION_DESCRIPTION = "Use context authentication"
28
30
  USER_DESCRIPTION = "Username for authentication"
29
31
  DEFAULT_PORT = 1433
30
32
 
33
+ # Token scope for Azure SQL in the public cloud; sovereign clouds set theirs with the scope property.
34
+ AZURE_SQL_TOKEN_SCOPE = "https://database.windows.net/.default"
35
+ # The only scopes a workload identity token is requested for: the Azure SQL audience of each cloud. No setting can
36
+ # mint a token for Key Vault, ARM, Storage or any other resource the managed identity may also have access to.
37
+ AZURE_SQL_TOKEN_SCOPES = (
38
+ AZURE_SQL_TOKEN_SCOPE,
39
+ "https://database.usgovcloudapi.net/.default", # Azure Government
40
+ "https://database.chinacloudapi.cn/.default", # Azure operated by 21Vianet
41
+ )
42
+ # msodbcsql pre-connect attribute that carries an Entra access token (17 and 18 alike).
43
+ SQL_COPT_SS_ACCESS_TOKEN = 1256
44
+ WORKLOAD_IDENTITY_SETUP_HINT = (
45
+ "Label the runner's pod with 'azure.workload.identity/use: \"true\"' so that the Azure workload identity "
46
+ "webhook injects it, or mount the projected service account token and set AZURE_TENANT_ID, AZURE_CLIENT_ID "
47
+ "and AZURE_FEDERATED_TOKEN_FILE in the runner's Helm values."
48
+ )
49
+
31
50
 
32
51
  class SqlServerConnectionProperties(DataSourceConnectionProperties, ABC):
33
52
  host: str = Field(..., description="Host name of the SQL Server instance")
@@ -79,7 +98,37 @@ class SqlServerActiveDirectoryServicePrincipalAuthentication(SqlServerActiveDire
79
98
  client_secret: SecretStr = Field(..., description="Client secret for authentication")
80
99
 
81
100
 
101
+ class SqlServerWorkloadIdentityAuthentication(SqlServerConnectionProperties):
102
+ """Entra workload identity federation: the pod's projected service-account token is exchanged
103
+ for an access token of a user-assigned managed identity. No credential is stored."""
104
+
105
+ # Rejects leftover credential keys (client_secret, password, ...) instead of keeping them as plain-text extras.
106
+ model_config = ConfigDict(extra="forbid")
107
+
108
+ # Required (no default) so that YAML without an authentication key never resolves to this variant.
109
+ authentication: Literal["workloadidentity"] = Field(..., description="Authentication type")
110
+ client_id: Optional[str] = Field(
111
+ None, description="Client ID of the managed identity; defaults to AZURE_CLIENT_ID from the pod environment"
112
+ )
113
+
114
+ @field_validator("scope")
115
+ @classmethod
116
+ def _scope_is_azure_sql(cls, scope: Optional[str]) -> Optional[str]:
117
+ # Left out means the Azure public cloud.
118
+ if scope and scope not in AZURE_SQL_TOKEN_SCOPES:
119
+ raise ValueError(
120
+ f"Scope '{scope}' is not supported with workload identity authentication: the token is only "
121
+ f"requested for Azure SQL. Leave scope out for the Azure public cloud, or use one of "
122
+ f"{', '.join(AZURE_SQL_TOKEN_SCOPES)}."
123
+ )
124
+ return scope
125
+
126
+
82
127
  class SqlServerDataSource(DataSourceBase, ABC):
128
+ # Keeps resolved secrets out of validation errors: a leftover client_secret or password on the
129
+ # workloadidentity variant fails with extra_forbidden, whose message would otherwise carry the value.
130
+ model_config = ConfigDict(hide_input_in_errors=True)
131
+
83
132
  type: Literal["sqlserver"] = Field("sqlserver")
84
133
 
85
134
  connection_properties: Union[
@@ -87,6 +136,7 @@ class SqlServerDataSource(DataSourceBase, ABC):
87
136
  SqlServerActiveDirectoryInteractiveAuthentication,
88
137
  SqlServerActiveDirectoryPasswordAuthentication,
89
138
  SqlServerActiveDirectoryServicePrincipalAuthentication,
139
+ SqlServerWorkloadIdentityAuthentication,
90
140
  ] = Field(..., alias="connection", description="SQL Server connection configuration")
91
141
 
92
142
 
@@ -109,6 +159,70 @@ def handle_datetimeoffset(dto_value):
109
159
  )
110
160
 
111
161
 
162
+ def pack_access_token(token: str) -> bytes:
163
+ """Encodes an access token the way msodbcsql expects it in SQL_COPT_SS_ACCESS_TOKEN:
164
+ UTF-16-LE, prefixed with its byte length as a 4-byte little-endian integer."""
165
+ encoded = token.encode("utf-16-le")
166
+ return struct.pack(f"<I{len(encoded)}s", len(encoded), encoded)
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class WorkloadIdentity:
171
+ tenant_id: str
172
+ client_id: str
173
+ token_file_path: str
174
+
175
+
176
+ def resolve_workload_identity(config: SqlServerWorkloadIdentityAuthentication) -> WorkloadIdentity:
177
+ """Checks the pod environment before any credential is built, so that a pod that is not set up for
178
+ workload identity fails with the missing variable and the Kubernetes fix, not a bare ValueError.
179
+ The YAML client_id wins over AZURE_CLIENT_ID."""
180
+ tenant_id = os.environ.get("AZURE_TENANT_ID")
181
+ token_file_path = os.environ.get("AZURE_FEDERATED_TOKEN_FILE")
182
+ client_id = config.client_id or os.environ.get("AZURE_CLIENT_ID")
183
+ missing = [
184
+ name
185
+ for name, value in [
186
+ ("AZURE_TENANT_ID", tenant_id),
187
+ ("AZURE_FEDERATED_TOKEN_FILE", token_file_path),
188
+ ("AZURE_CLIENT_ID", client_id),
189
+ ]
190
+ if not value
191
+ ]
192
+ if missing:
193
+ client_id_note = " (or client_id in the connection)" if "AZURE_CLIENT_ID" in missing else ""
194
+ verb = "is" if len(missing) == 1 else "are"
195
+ raise DataSourceConnectionException(
196
+ f"Workload identity federation is not set up for this pod: {', '.join(missing)}{client_id_note} "
197
+ f"{verb} not set in the environment. {WORKLOAD_IDENTITY_SETUP_HINT}"
198
+ )
199
+ return WorkloadIdentity(tenant_id=tenant_id, client_id=client_id, token_file_path=token_file_path)
200
+
201
+
202
+ def acquire_workload_identity_token(config: SqlServerWorkloadIdentityAuthentication) -> str:
203
+ # Imported here so that azure.identity is only loaded by the variant that needs it.
204
+ from azure.core.exceptions import ClientAuthenticationError
205
+ from azure.identity import WorkloadIdentityCredential
206
+
207
+ # Construct WorkloadIdentityCredential explicitly, never DefaultAzureCredential, so a scan pod
208
+ # has no credential chain to fall through. AZURE_AUTHORITY_HOST still comes from the environment.
209
+ identity = resolve_workload_identity(config)
210
+ credential = WorkloadIdentityCredential(
211
+ tenant_id=identity.tenant_id,
212
+ client_id=identity.client_id,
213
+ token_file_path=identity.token_file_path,
214
+ )
215
+ try:
216
+ return credential.get_token(config.scope or AZURE_SQL_TOKEN_SCOPE).token
217
+ except ClientAuthenticationError as e:
218
+ # Entra's message carries the AADSTS code and description (wrong issuer, subject or audience on
219
+ # the federated credential, unknown client ID, ...); it never contains the assertion itself.
220
+ raise DataSourceConnectionException(
221
+ f"Entra ID rejected the workload identity token exchange for client ID '{identity.client_id}' "
222
+ f"in tenant '{identity.tenant_id}': {e.message}"
223
+ ) from e
224
+
225
+
112
226
  class SqlServerDataSourceConnection(DataSourceConnection):
113
227
  # SQL Server resolves lock conflicts by killing one participant with error 1205
114
228
  # (SQLSTATE 40001) and rolling its transaction back; Microsoft's guidance is to
@@ -141,6 +255,11 @@ class SqlServerDataSourceConnection(DataSourceConnection):
141
255
  # failure SQLSTATE that SQL Server raises for deadlock victims (1205).
142
256
  return bool(e.args) and e.args[0] == "40001"
143
257
 
258
+ @staticmethod
259
+ def _is_login_failed_error(e: pyodbc.Error) -> bool:
260
+ # 28000 is the invalid authorization SQLSTATE that SQL Server raises for a rejected login (18456).
261
+ return bool(e.args) and e.args[0] == "28000"
262
+
144
263
  def _execute_with_deadlock_retry(self, operation: Callable[[], T]) -> T:
145
264
  """Assumes ``operation`` is a single-statement unit of work: recovery
146
265
  issues a connection-wide rollback, discarding any earlier uncommitted
@@ -216,6 +335,9 @@ class SqlServerDataSourceConnection(DataSourceConnection):
216
335
  conn_params.append("Authentication=ActiveDirectoryServicePrincipal")
217
336
  conn_params.append(f"UID={{{config.client_id}}}")
218
337
  conn_params.append(f"PWD={{{config.client_secret.get_secret_value()}}}")
338
+ elif config.authentication.lower() == "workloadidentity":
339
+ # The access token goes in as a pre-connect attribute, see _get_pyodbc_attrs.
340
+ pass
219
341
  elif "activedirectory" in config.authentication.lower():
220
342
  conn_params.append(f"Authentication={config.authentication}")
221
343
 
@@ -231,6 +353,10 @@ class SqlServerDataSourceConnection(DataSourceConnection):
231
353
  return conn_str
232
354
 
233
355
  def _get_pyodbc_attrs(self) -> dict[int, bytes] | None:
356
+ # Called once per _create_connection, so every connection opens with a fresh token.
357
+ if isinstance(self.connection_properties, SqlServerWorkloadIdentityAuthentication):
358
+ token = acquire_workload_identity_token(self.connection_properties)
359
+ return {SQL_COPT_SS_ACCESS_TOKEN: pack_access_token(token)}
234
360
  return None
235
361
 
236
362
  def _create_connection(
@@ -238,17 +364,32 @@ class SqlServerDataSourceConnection(DataSourceConnection):
238
364
  config: SqlServerConnectionProperties,
239
365
  ):
240
366
  try:
241
- self.connection = pyodbc.connect(
242
- self.build_connection_string(config),
243
- attrs_before=self._get_pyodbc_attrs(),
244
- timeout=int(config.login_timeout),
245
- autocommit=self._get_autocommit_setting(),
246
- )
367
+ attrs_before = self._get_pyodbc_attrs()
368
+ try:
369
+ self.connection = pyodbc.connect(
370
+ self.build_connection_string(config),
371
+ attrs_before=attrs_before,
372
+ timeout=int(config.login_timeout),
373
+ autocommit=self._get_autocommit_setting(),
374
+ )
375
+ except pyodbc.Error as e:
376
+ # Only a rejected login: an unreachable host, a login timeout or a missing driver also fail
377
+ # here, and the database user hint would send those down the wrong path.
378
+ if isinstance(config, SqlServerWorkloadIdentityAuthentication) and self._is_login_failed_error(e):
379
+ raise DataSourceConnectionException(
380
+ f"An Entra access token was acquired through workload identity federation, but logging in "
381
+ f"to database '{config.database}' on '{config.host}' with it failed: {e}. Check that the "
382
+ f"managed identity has a user in that database (CREATE USER [<managed identity display "
383
+ f"name>] FROM EXTERNAL PROVIDER) and the role grants Soda needs."
384
+ ) from e
385
+ raise
247
386
 
248
387
  self.connection.add_output_converter(-155, handle_datetimeoffset)
249
388
  self.connection.add_output_converter(-150, handle_datetime)
250
389
  self._detect_server_info(self.connection)
251
390
  return self.connection
391
+ except DataSourceConnectionException:
392
+ raise
252
393
  except Exception as e:
253
394
  raise DataSourceConnectionException(e) from e
254
395
 
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: soda-sqlserver
3
- Version: 4.29.0
3
+ Version: 4.30.0
4
4
  Summary: Soda SQL Server V4
5
5
  Author-email: "Soda Data N.V." <info@soda.io>
6
6
  License: Proprietary
7
7
  Requires-Python: >=3.10
8
- Requires-Dist: soda-core==4.29.0
8
+ Requires-Dist: soda-core==4.30.0
9
9
  Requires-Dist: pyodbc
10
+ Requires-Dist: azure-identity<2,>=1.17.1
@@ -0,0 +1,3 @@
1
+ soda-core==4.30.0
2
+ pyodbc
3
+ azure-identity<2,>=1.17.1
@@ -1,2 +0,0 @@
1
- soda-core==4.29.0
2
- pyodbc