dex-connector-microsoft-sql-server 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,127 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from dataclasses import dataclass, field as _dataclass_field
6
+ from typing import Any
7
+
8
+ def _replace_nil_slices(value: Any, depth: int) -> Any:
9
+ if value is None:
10
+ return ()
11
+ if depth == 1:
12
+ return tuple(value)
13
+ return tuple(_replace_nil_slices(item, depth - 1) for item in value)
14
+
15
+
16
+ # QueryRowsInput is one parameterized read statement.
17
+ @dataclass(frozen=True, slots=True)
18
+ class QueryRowsInput:
19
+ # Statement is one SQL statement written as a constant in application code, such as
20
+ # "SELECT id, plan FROM dbo.subscriptions WHERE account_email = @p1". Values belong in
21
+ # Parameters: the connector never formats them into SQL text, and it cannot detect a statement
22
+ # built by concatenating untrusted input. Only statements that start with SELECT or WITH are
23
+ # accepted, and the statement must return one result set.
24
+ statement: str = ''
25
+ # Parameters binds @p1 through @pN in order. Each value is nil for SQL NULL, a string, bool,
26
+ # integer, float, json.Number, json.RawMessage, []byte for binary data, or time.Time, and is sent
27
+ # as a typed sp_executesql parameter. Pass exact decimals as strings or json.Number and CAST them
28
+ # in the statement when the comparison type matters.
29
+ parameters: tuple[Any, ...] = _dataclass_field(default=(), metadata={'dex_json_omit_default': True})
30
+
31
+
32
+ setattr(QueryRowsInput, '__module__', 'dex_connectors.microsoft_sql_server.models')
33
+
34
+
35
+ # Column describes one result column.
36
+ @dataclass(frozen=True, slots=True)
37
+ class Column:
38
+ # Name is the column name the server reports, such as the alias given with AS.
39
+ name: str = ''
40
+ # TypeName is the server's column type, such as DECIMAL, BIGINT, NVARCHAR, VARBINARY,
41
+ # UNIQUEIDENTIFIER, or DATETIMEOFFSET. NUMERIC is reported as DECIMAL, and a CLR type such as
42
+ # GEOGRAPHY or HIERARCHYID by its own name.
43
+ type_name: str = _dataclass_field(default='', metadata={'dex_json_name': 'typeName'})
44
+
45
+
46
+ setattr(Column, '__module__', 'dex_connectors.microsoft_sql_server.models')
47
+
48
+
49
+ # RowSet is the bounded result of one QueryRows statement.
50
+ @dataclass(frozen=True, slots=True)
51
+ class RowSet:
52
+ # Columns lists the result columns in statement order.
53
+ columns: tuple[Column, ...] = ()
54
+ # Rows maps each column name to its JSON value using the connector's documented type mapping.
55
+ # It is empty, never nil, when the statement returned no rows.
56
+ rows: tuple[dict[str, Any] | None, ...] = ()
57
+ # Truncated reports that the statement produced more rows or bytes than maxRows or
58
+ # maxResponseBytes allow, so Rows holds only the rows that fit.
59
+ truncated: bool = _dataclass_field(default=False, metadata={'dex_json_omit_default': True})
60
+
61
+ def __post_init__(self) -> None:
62
+ object.__setattr__(self, 'columns', _replace_nil_slices(self.columns, 1))
63
+ object.__setattr__(self, 'rows', _replace_nil_slices(self.rows, 1))
64
+
65
+
66
+ RowSet.__annotations__['columns'] = tuple[Column, ...] | None
67
+ RowSet.__dataclass_fields__['columns'].type = tuple[Column, ...] | None
68
+ RowSet.__annotations__['rows'] = tuple[dict[str, Any] | None, ...] | None
69
+ RowSet.__dataclass_fields__['rows'].type = tuple[dict[str, Any] | None, ...] | None
70
+ setattr(RowSet, '__module__', 'dex_connectors.microsoft_sql_server.models')
71
+
72
+
73
+ # ExecuteStatementInput is one parameterized write statement.
74
+ @dataclass(frozen=True, slots=True)
75
+ class ExecuteStatementInput:
76
+ # Statement is one SQL statement written as a constant in application code, such as
77
+ # "INSERT INTO dbo.refunds (order_id, amount) VALUES (@p1, CAST(@p2 AS decimal(12, 2)))".
78
+ # Values belong in Parameters: the connector never formats them into SQL text, and it cannot
79
+ # detect a statement built by concatenating untrusted input. Only statements that start with
80
+ # INSERT, UPDATE, DELETE, MERGE, or WITH are accepted. A MERGE must end with a semicolon.
81
+ statement: str = ''
82
+ # Parameters binds @p1 through @pN in order, with the same value rules as QueryRowsInput.
83
+ parameters: tuple[Any, ...] = _dataclass_field(default=(), metadata={'dex_json_omit_default': True})
84
+ # IdempotencyKeyPlaceholder, when non-zero, is the number n of the @pn placeholder that receives
85
+ # this Step execution's idempotency key. It must equal len(Parameters)+1, so the key is always
86
+ # the last placeholder. The key is a 36-character lowercase UUID, bound as nvarchar, that stays
87
+ # the same across every retry and Worker replacement of one Step execution; it is also returned
88
+ # in the Result's Receipt.
89
+ idempotency_key_placeholder: int = _dataclass_field(default=0, metadata={'dex_json_name': 'idempotencyKeyPlaceholder', 'dex_json_omit_default': True})
90
+ # MaxRowsAffected, when set, is the most rows the statement may affect. A statement that affects
91
+ # more is rolled back and selects limitExceeded, which guards against a missing WHERE clause.
92
+ # Nil applies no limit; zero allows only a statement that changes nothing.
93
+ max_rows_affected: int | None = _dataclass_field(default=None, metadata={'dex_json_name': 'maxRowsAffected', 'dex_json_omit_default': True})
94
+ # ReturnsOutputRows declares that the statement has an OUTPUT clause that returns rows to the
95
+ # client. The connector then returns those rows, bounded by maxRows and maxResponseBytes, and
96
+ # counts them as the rows affected. Leave it false for a statement without OUTPUT, or whose
97
+ # OUTPUT clause only writes INTO a table; OUTPUT rows of such a statement are discarded.
98
+ returns_output_rows: bool = _dataclass_field(default=False, metadata={'dex_json_name': 'returnsOutputRows', 'dex_json_omit_default': True})
99
+
100
+
101
+ setattr(ExecuteStatementInput, '__module__', 'dex_connectors.microsoft_sql_server.models')
102
+
103
+
104
+ # StatementExecution is the committed outcome of one ExecuteStatement transaction.
105
+ @dataclass(frozen=True, slots=True)
106
+ class StatementExecution:
107
+ # RowsAffected is the number of rows the statement inserted, updated, deleted, or merged. With
108
+ # ReturnsOutputRows it is the number of OUTPUT rows, one per affected row. Otherwise it is the
109
+ # sum of the row counts the server reported, which also includes rows changed by an AFTER
110
+ # trigger that does not SET NOCOUNT ON.
111
+ rows_affected: int = _dataclass_field(default=0, metadata={'dex_json_name': 'rowsAffected'})
112
+ # Columns lists the OUTPUT columns in statement order; it is empty without ReturnsOutputRows.
113
+ columns: tuple[Column, ...] = ()
114
+ # Rows holds the OUTPUT rows with the same type mapping as RowSet.Rows; it is empty, never nil,
115
+ # without ReturnsOutputRows.
116
+ rows: tuple[dict[str, Any] | None, ...] = ()
117
+
118
+ def __post_init__(self) -> None:
119
+ object.__setattr__(self, 'columns', _replace_nil_slices(self.columns, 1))
120
+ object.__setattr__(self, 'rows', _replace_nil_slices(self.rows, 1))
121
+
122
+
123
+ StatementExecution.__annotations__['columns'] = tuple[Column, ...] | None
124
+ StatementExecution.__dataclass_fields__['columns'].type = tuple[Column, ...] | None
125
+ StatementExecution.__annotations__['rows'] = tuple[dict[str, Any] | None, ...] | None
126
+ StatementExecution.__dataclass_fields__['rows'].type = tuple[dict[str, Any] | None, ...] | None
127
+ setattr(StatementExecution, '__module__', 'dex_connectors.microsoft_sql_server.models')
@@ -0,0 +1,140 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from typing import Any, TypeVar
7
+
8
+ import dex
9
+ from dex_connectors.sdk import (
10
+ MutationResult,
11
+ MutationStep,
12
+ MutationStepConfig,
13
+ QueryResult,
14
+ QueryStep,
15
+ QueryStepConfig,
16
+ StepAnnotations,
17
+ )
18
+
19
+ from ..connection import Connection
20
+ from ..models import ExecuteStatementInput, QueryRowsInput, RowSet, StatementExecution
21
+
22
+ StepInput = TypeVar("StepInput")
23
+
24
+ def new_query_step(
25
+ *,
26
+ step_type: str,
27
+ step_input_type: type[StepInput],
28
+ annotations: StepAnnotations | Mapping[str, str],
29
+ connection: Connection,
30
+ connection_name: str,
31
+ map_to_operation_input: Callable[[StepInput], QueryRowsInput],
32
+ completed: dex.StepTarget[QueryResult[RowSet]],
33
+ truncated: dex.StepTarget[QueryResult[RowSet]] | None = None,
34
+ provider_rejected: dex.StepTarget[QueryResult[RowSet]] | None = None,
35
+ invalid_response: dex.StepTarget[QueryResult[RowSet]] | None = None,
36
+ defect: dex.StepTarget[QueryResult[RowSet]] | None = None,
37
+ result_attribute: dex.Attribute[QueryResult[RowSet]] | None = None,
38
+ step_options_override: dex.StepOptions | None = None,
39
+ ) -> QueryStep[StepInput, QueryRowsInput, RowSet]:
40
+ if connection is None or connection.reference.name != connection_name:
41
+ raise ValueError("Microsoft SQL Server Step connection name must match its connection reference")
42
+ if isinstance(annotations, StepAnnotations):
43
+ step_annotations = annotations
44
+ else:
45
+ if not isinstance(annotations, Mapping) or set(annotations) != {"groupId", "groupLabel", "explanation"}:
46
+ raise ValueError("Microsoft SQL Server Step annotations require groupId, groupLabel, and explanation")
47
+ if any(not isinstance(value, str) for value in annotations.values()):
48
+ raise ValueError("Microsoft SQL Server Step annotations must be strings")
49
+ step_annotations = StepAnnotations(annotations["groupId"], annotations["groupLabel"], annotations["explanation"])
50
+ branches = {
51
+ "completed": completed,
52
+ }
53
+ if truncated is not None:
54
+ branches["truncated"] = truncated
55
+ if provider_rejected is not None:
56
+ branches["providerRejected"] = provider_rejected
57
+ if invalid_response is not None:
58
+ branches["invalidResponse"] = invalid_response
59
+ if defect is not None:
60
+ branches["defect"] = defect
61
+ return QueryStep(
62
+ QueryStepConfig(
63
+ step_type=step_type,
64
+ step_input_type=step_input_type,
65
+ annotations=step_annotations,
66
+ operation=_bound_operation(connection, "query"),
67
+ connection=connection.reference,
68
+ map_to_operation_input=map_to_operation_input,
69
+ branches=branches,
70
+ result_attribute=result_attribute,
71
+ step_options_override=step_options_override,
72
+ )
73
+ )
74
+
75
+ setattr(new_query_step, '__module__', 'dex_connectors.microsoft_sql_server.steps')
76
+
77
+ def new_execute_step(
78
+ *,
79
+ step_type: str,
80
+ step_input_type: type[StepInput],
81
+ annotations: StepAnnotations | Mapping[str, str],
82
+ connection: Connection,
83
+ connection_name: str,
84
+ map_to_operation_input: Callable[[StepInput], ExecuteStatementInput],
85
+ completed: dex.StepTarget[MutationResult[StatementExecution]],
86
+ limit_exceeded: dex.StepTarget[MutationResult[StatementExecution]] | None = None,
87
+ provider_rejected: dex.StepTarget[MutationResult[StatementExecution]] | None = None,
88
+ uncertain: dex.StepTarget[MutationResult[StatementExecution]] | None = None,
89
+ invalid_response: dex.StepTarget[MutationResult[StatementExecution]] | None = None,
90
+ defect: dex.StepTarget[MutationResult[StatementExecution]] | None = None,
91
+ result_attribute: dex.Attribute[MutationResult[StatementExecution]] | None = None,
92
+ step_options_override: dex.StepOptions | None = None,
93
+ ) -> MutationStep[StepInput, ExecuteStatementInput, StatementExecution]:
94
+ if connection is None or connection.reference.name != connection_name:
95
+ raise ValueError("Microsoft SQL Server Step connection name must match its connection reference")
96
+ if isinstance(annotations, StepAnnotations):
97
+ step_annotations = annotations
98
+ else:
99
+ if not isinstance(annotations, Mapping) or set(annotations) != {"groupId", "groupLabel", "explanation"}:
100
+ raise ValueError("Microsoft SQL Server Step annotations require groupId, groupLabel, and explanation")
101
+ if any(not isinstance(value, str) for value in annotations.values()):
102
+ raise ValueError("Microsoft SQL Server Step annotations must be strings")
103
+ step_annotations = StepAnnotations(annotations["groupId"], annotations["groupLabel"], annotations["explanation"])
104
+ branches = {
105
+ "completed": completed,
106
+ }
107
+ if limit_exceeded is not None:
108
+ branches["limitExceeded"] = limit_exceeded
109
+ if provider_rejected is not None:
110
+ branches["providerRejected"] = provider_rejected
111
+ if uncertain is not None:
112
+ branches["uncertain"] = uncertain
113
+ if invalid_response is not None:
114
+ branches["invalidResponse"] = invalid_response
115
+ if defect is not None:
116
+ branches["defect"] = defect
117
+ return MutationStep(
118
+ MutationStepConfig(
119
+ step_type=step_type,
120
+ step_input_type=step_input_type,
121
+ annotations=step_annotations,
122
+ operation=_bound_operation(connection, "execute"),
123
+ connection=connection.reference,
124
+ map_to_operation_input=map_to_operation_input,
125
+ branches=branches,
126
+ result_attribute=result_attribute,
127
+ step_options_override=step_options_override,
128
+ )
129
+ )
130
+
131
+ setattr(new_execute_step, '__module__', 'dex_connectors.microsoft_sql_server.steps')
132
+
133
+
134
+ def _bound_operation(connection: Connection, operation_name: str) -> Any:
135
+ source = getattr(connection, operation_name, None)
136
+ if source is None:
137
+ source = getattr(getattr(connection, "operations", None), operation_name, None)
138
+ if source is None:
139
+ raise ValueError(f"connection operation {operation_name} is missing")
140
+ return source() if callable(source) else source
@@ -0,0 +1,298 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """One native TDS connection per SQL Server operation attempt."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ import os
9
+ import socket
10
+ import ssl
11
+ import threading
12
+ from collections.abc import Callable
13
+ from dataclasses import replace
14
+ from ipaddress import ip_address
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ import certifi
18
+ import pytds # type: ignore[import-untyped]
19
+ from cryptography import x509
20
+ from dex_connectors.sdk import CredentialProvider
21
+ from pytds import tls
22
+
23
+ from ._generated.config import Config, Credentials
24
+ from ._generated.definitions import CONNECTOR_ID, EXECUTE_DEFINITION, QUERY_DEFINITION
25
+
26
+ if TYPE_CHECKING:
27
+ from .operations import ExecuteStatementOperation, QueryRowsOperation, _AttemptDeadline
28
+
29
+ _SESSION_SETTINGS = (
30
+ "SET LANGUAGE us_english",
31
+ "SET DATEFORMAT ymd",
32
+ "SET XACT_ABORT ON",
33
+ "SET NOCOUNT OFF",
34
+ "SET IMPLICIT_TRANSACTIONS OFF",
35
+ "SET ANSI_NULLS ON",
36
+ "SET ANSI_PADDING ON",
37
+ "SET ANSI_WARNINGS ON",
38
+ "SET ARITHABORT ON",
39
+ "SET CONCAT_NULL_YIELDS_NULL ON",
40
+ "SET QUOTED_IDENTIFIER ON",
41
+ "SET NUMERIC_ROUNDABORT OFF",
42
+ "SET TEXTSIZE 2147483647",
43
+ "SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
44
+ )
45
+ _TLS_HOST_VALIDATION = threading.local()
46
+ _ORIGINAL_HOST_VALIDATOR = tls.validate_host
47
+ _ORIGINAL_SOCKET_CONNECTION = socket.create_connection
48
+
49
+
50
+ def _verify_server_hostname(cert: Any, name: bytes) -> bool:
51
+ certificate = cert.to_cryptography()
52
+ try:
53
+ subject_alternative_names = certificate.extensions.get_extension_for_class(
54
+ x509.SubjectAlternativeName
55
+ ).value
56
+ except x509.ExtensionNotFound:
57
+ return False
58
+ try:
59
+ host = name.decode("ascii")
60
+ except UnicodeDecodeError:
61
+ return False
62
+ try:
63
+ address = ip_address(host)
64
+ except ValueError:
65
+ host_labels = host.lower().split(".")
66
+ for dns_name in subject_alternative_names.get_values_for_type(x509.DNSName):
67
+ pattern_labels = dns_name.lower().split(".")
68
+ if len(pattern_labels) == len(host_labels) and (
69
+ pattern_labels == host_labels
70
+ or (pattern_labels[0] == "*" and pattern_labels[1:] == host_labels[1:])
71
+ ):
72
+ return True
73
+ return False
74
+ return address in subject_alternative_names.get_values_for_type(x509.IPAddress)
75
+
76
+
77
+ def _dispatch_host_validation(cert: Any, name: bytes) -> bool:
78
+ if getattr(_TLS_HOST_VALIDATION, "is_sql_server_connection", False):
79
+ return _verify_server_hostname(cert, name)
80
+ return bool(_ORIGINAL_HOST_VALIDATOR(cert, name))
81
+
82
+
83
+ tls.validate_host = _dispatch_host_validation
84
+
85
+
86
+ def _dispatch_socket_connection(*args: Any, **kwargs: Any) -> socket.socket:
87
+ deadline = getattr(_TLS_HOST_VALIDATION, "deadline", None)
88
+ if deadline is not None:
89
+ deadline.check()
90
+ arguments = list(args)
91
+ if len(arguments) > 1:
92
+ arguments[1] = min(arguments[1], deadline.remaining_seconds())
93
+ elif "timeout" in kwargs:
94
+ kwargs["timeout"] = min(kwargs["timeout"], deadline.remaining_seconds())
95
+ args = tuple(arguments)
96
+ connected_socket = _ORIGINAL_SOCKET_CONNECTION(*args, **kwargs)
97
+ if deadline is not None:
98
+ deadline.attach_socket(connected_socket)
99
+ return connected_socket
100
+
101
+
102
+ socket.create_connection = _dispatch_socket_connection
103
+
104
+
105
+ class Client:
106
+ """Validate settings and open one authenticated TDS session for each call.
107
+
108
+ The credential provider resolves the password immediately before each attempt.
109
+ ``connection_factory`` is constructor injection for native-driver tests.
110
+ """
111
+
112
+ def __init__(
113
+ self,
114
+ config: Config,
115
+ credentials: CredentialProvider[Credentials],
116
+ http_client: object | None = None,
117
+ *,
118
+ connection_factory: Callable[..., Any] = pytds.connect,
119
+ ) -> None:
120
+ if config is None or credentials is None or connection_factory is None:
121
+ raise ValueError("SQL Server configuration, credentials, and driver are required")
122
+ if http_client is not None:
123
+ raise ValueError("SQL Server uses a native TDS driver, not an HTTP client")
124
+ defaults = Config(config.host, config.database, config.user)
125
+ config = replace(
126
+ config,
127
+ port=config.port or defaults.port,
128
+ encrypt=config.encrypt or defaults.encrypt,
129
+ connect_timeout_seconds=config.connect_timeout_seconds or defaults.connect_timeout_seconds,
130
+ statement_timeout_seconds=config.statement_timeout_seconds or defaults.statement_timeout_seconds,
131
+ max_rows=config.max_rows or defaults.max_rows,
132
+ max_response_bytes=config.max_response_bytes or defaults.max_response_bytes,
133
+ )
134
+ if (
135
+ not config.host
136
+ or config.host != config.host.strip()
137
+ or any(character in config.host for character in "/\\,;@'\"= ")
138
+ or any(ord(character) < 32 or ord(character) == 127 for character in config.host)
139
+ or "://" in config.host
140
+ or config.host.lower().startswith("tcp:")
141
+ ):
142
+ raise ValueError("SQL Server host must be one DNS name or IP address without a port or instance")
143
+ if ":" in config.host:
144
+ try:
145
+ ip_address(config.host)
146
+ except ValueError as error:
147
+ raise ValueError("SQL Server host must not include a port") from error
148
+ if "%" in config.host:
149
+ raise ValueError("SQL Server host must be an IP address without a scope identifier")
150
+ if not 1 <= config.port <= 65535:
151
+ raise ValueError("SQL Server port must be from 1 through 65535")
152
+ if (
153
+ any(
154
+ not value
155
+ or value != value.strip()
156
+ or len(value) > 128
157
+ or any(ord(char) < 32 for char in value)
158
+ for value in (config.database, config.user)
159
+ )
160
+ or "\\" in config.user
161
+ ):
162
+ raise ValueError("SQL Server database and SQL authentication user are required")
163
+ if (
164
+ config.encrypt == "disable"
165
+ and config.host != "localhost"
166
+ and not (_is_loopback_address(config.host))
167
+ ):
168
+ raise ValueError("SQL Server encrypt disable is allowed only for a loopback host")
169
+ if config.encrypt in ("strict", "trust-server-certificate"):
170
+ raise ValueError(f"SQL Server Python driver does not support encrypt={config.encrypt}")
171
+ if config.encrypt not in ("mandatory", "disable"):
172
+ raise ValueError("SQL Server encrypt mode is invalid")
173
+ if (
174
+ not math.isfinite(config.connect_timeout_seconds)
175
+ or not math.isfinite(config.statement_timeout_seconds)
176
+ or config.connect_timeout_seconds <= 0
177
+ or config.statement_timeout_seconds < 0.001
178
+ ):
179
+ raise ValueError("SQL Server timeouts must be positive; statementTimeout is at least 1ms")
180
+ if int(config.statement_timeout_seconds * 1000 + 0.999) > (1 << 31) - 1:
181
+ raise ValueError("SQL Server statementTimeout exceeds SQL Server LOCK_TIMEOUT range")
182
+ if not 1 <= config.max_rows <= 100_000 or not 1 <= config.max_response_bytes <= 16 << 20:
183
+ raise ValueError("SQL Server row and response bounds are invalid")
184
+ self.config = config
185
+ self.credentials = credentials
186
+ self.connection_factory = connection_factory
187
+
188
+ def query(self) -> QueryRowsOperation:
189
+ """Bind the read operation to this client."""
190
+ from .operations import QueryRowsOperation
191
+
192
+ return QueryRowsOperation(self)
193
+
194
+ def execute(self) -> ExecuteStatementOperation:
195
+ """Bind the transactional write operation to this client."""
196
+ from .operations import ExecuteStatementOperation
197
+
198
+ return ExecuteStatementOperation(self)
199
+
200
+ async def aclose(self) -> None:
201
+ """Release client resources; individual calls already close their sessions."""
202
+
203
+ def open_connection(self, password: str, deadline: _AttemptDeadline | None = None) -> Any:
204
+ """Open and pin a native session with per-connection certificate verification."""
205
+ ca_file: str | None = None
206
+ if self.config.encrypt == "mandatory":
207
+ configured_ca_file = os.environ.get("SQLSERVER_SSL_CA")
208
+ ca_file = configured_ca_file or ssl.get_default_verify_paths().cafile
209
+ if not configured_ca_file and (not ca_file or not os.path.isfile(ca_file)):
210
+ ca_file = certifi.where()
211
+ if not ca_file or not os.path.isfile(ca_file):
212
+ raise ValueError("SQL Server trusted CA bundle is unavailable")
213
+ try:
214
+ trust_context = ssl.create_default_context(cafile=ca_file)
215
+ if trust_context.cert_store_stats()["x509"] == 0:
216
+ raise ValueError("SQL Server trusted CA bundle has no certificates")
217
+ except (OSError, ValueError, ssl.SSLError) as error:
218
+ raise ValueError("SQL Server trusted CA bundle is unreadable") from error
219
+ attempt_timeout_seconds = (
220
+ self.config.connect_timeout_seconds + self.config.statement_timeout_seconds + 5
221
+ )
222
+ connection_settings = dict(
223
+ server=self.config.host,
224
+ port=self.config.port,
225
+ database=self.config.database,
226
+ user=self.config.user,
227
+ password=password,
228
+ login_timeout=self.config.connect_timeout_seconds,
229
+ timeout=attempt_timeout_seconds,
230
+ cafile=ca_file,
231
+ validate_host=True,
232
+ enc_login_only=False,
233
+ disable_connect_retry=True,
234
+ autocommit=False,
235
+ appname="dex-sql-server-connector",
236
+ )
237
+ if self.connection_factory is pytds.connect:
238
+ # pytds performs this check after the handshake and before it sends login credentials.
239
+ _TLS_HOST_VALIDATION.is_sql_server_connection = self.config.encrypt == "mandatory"
240
+ _TLS_HOST_VALIDATION.deadline = deadline
241
+ try:
242
+ connection = self.connection_factory(**connection_settings)
243
+ finally:
244
+ _TLS_HOST_VALIDATION.is_sql_server_connection = False
245
+ _TLS_HOST_VALIDATION.deadline = None
246
+ else:
247
+ connection = self.connection_factory(**connection_settings)
248
+ try:
249
+ if deadline is not None:
250
+ deadline.attach_connection(connection)
251
+ deadline.check()
252
+ cursor = connection.cursor()
253
+ lock_timeout = int(self.config.statement_timeout_seconds * 1000 + 0.999)
254
+ settings = (*_SESSION_SETTINGS, f"SET LOCK_TIMEOUT {lock_timeout}")
255
+ if self.connection_factory is pytds.connect:
256
+ from .operations import _InvalidResponse
257
+
258
+ identity_statement = (
259
+ "SELECT @@SPID, CONVERT(nvarchar(128), SERVERPROPERTY('ProductVersion'))"
260
+ )
261
+ cursor.execute("; ".join((*settings, identity_statement)))
262
+ identity = cursor.fetchone()
263
+ if (
264
+ identity is None
265
+ or len(identity) != 2
266
+ or type(identity[0]) is not int
267
+ or identity[0] < 0
268
+ or not isinstance(identity[1], str)
269
+ ):
270
+ raise _InvalidResponse("SQL Server did not return a valid session identity")
271
+ while cursor.nextset():
272
+ raise _InvalidResponse("SQL Server returned multiple session identity result sets")
273
+ connection._dex_receipt_metadata = {}
274
+ process_id, server_version = str(identity[0]), str(identity[1])
275
+ if process_id.isdecimal() and len(process_id) <= 20:
276
+ connection._dex_receipt_metadata["processId"] = process_id
277
+ if 0 < len(server_version) <= 128 and all(32 <= ord(char) <= 126 for char in server_version):
278
+ connection._dex_receipt_metadata["serverVersion"] = server_version
279
+ else:
280
+ for setting in settings:
281
+ cursor.execute(setting)
282
+ if deadline is not None:
283
+ deadline.check()
284
+ cursor.close()
285
+ except Exception:
286
+ connection.close()
287
+ raise
288
+ return connection
289
+
290
+
291
+ def _is_loopback_address(host: str) -> bool:
292
+ try:
293
+ return ip_address(host).is_loopback
294
+ except ValueError:
295
+ return False
296
+
297
+
298
+ __all__ = ["Client", "Config", "Credentials", "CONNECTOR_ID", "EXECUTE_DEFINITION", "QUERY_DEFINITION"]
@@ -0,0 +1,12 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Generated connection bindings for SQL Server."""
4
+
5
+ from ._generated.connection import (
6
+ Connection,
7
+ new_connection,
8
+ new_connection_with_operations,
9
+ new_project_connection,
10
+ )
11
+
12
+ __all__ = ["Connection", "new_connection", "new_connection_with_operations", "new_project_connection"]
@@ -0,0 +1,92 @@
1
+ {
2
+ "connectorId": "microsoft-sql-server",
3
+ "releaseTag": "connectors/microsoft/sql-server/go/v0.23.0",
4
+ "package": {
5
+ "ecosystem": "pypi",
6
+ "name": "dex-connector-microsoft-sql-server",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "new_query_step",
12
+ "kind": "query",
13
+ "operationId": "query",
14
+ "fields": {
15
+ "stepType": "step_type",
16
+ "annotations": "annotations",
17
+ "connectionName": "connection_name",
18
+ "resultAttribute": "result_attribute"
19
+ },
20
+ "branches": [
21
+ {
22
+ "id": "completed",
23
+ "field": "completed",
24
+ "optional": false
25
+ },
26
+ {
27
+ "id": "truncated",
28
+ "field": "truncated",
29
+ "optional": true
30
+ },
31
+ {
32
+ "id": "providerRejected",
33
+ "field": "provider_rejected",
34
+ "optional": true
35
+ },
36
+ {
37
+ "id": "invalidResponse",
38
+ "field": "invalid_response",
39
+ "optional": true
40
+ },
41
+ {
42
+ "id": "defect",
43
+ "field": "defect",
44
+ "optional": true
45
+ }
46
+ ]
47
+ },
48
+ {
49
+ "name": "new_execute_step",
50
+ "kind": "mutation",
51
+ "operationId": "execute",
52
+ "fields": {
53
+ "stepType": "step_type",
54
+ "annotations": "annotations",
55
+ "connectionName": "connection_name",
56
+ "resultAttribute": "result_attribute"
57
+ },
58
+ "branches": [
59
+ {
60
+ "id": "completed",
61
+ "field": "completed",
62
+ "optional": false
63
+ },
64
+ {
65
+ "id": "limitExceeded",
66
+ "field": "limit_exceeded",
67
+ "optional": true
68
+ },
69
+ {
70
+ "id": "providerRejected",
71
+ "field": "provider_rejected",
72
+ "optional": true
73
+ },
74
+ {
75
+ "id": "uncertain",
76
+ "field": "uncertain",
77
+ "optional": true
78
+ },
79
+ {
80
+ "id": "invalidResponse",
81
+ "field": "invalid_response",
82
+ "optional": true
83
+ },
84
+ {
85
+ "id": "defect",
86
+ "field": "defect",
87
+ "optional": true
88
+ }
89
+ ]
90
+ }
91
+ ]
92
+ }
@@ -0,0 +1,7 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Manifest-generated SQL Server input and result models."""
4
+
5
+ from ._generated.models import Column, ExecuteStatementInput, QueryRowsInput, RowSet, StatementExecution
6
+
7
+ __all__ = ["Column", "ExecuteStatementInput", "QueryRowsInput", "RowSet", "StatementExecution"]