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,91 @@
1
+ Metadata-Version: 2.5
2
+ Name: dex-connector-microsoft-sql-server
3
+ Version: 0.1.0
4
+ Summary: Microsoft SQL Server connector for Dex Flows
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: certifi>=2024.2.2
9
+ Requires-Dist: cryptography<51,>=42
10
+ Requires-Dist: dex-connectors-sdk==0.1.0
11
+ Requires-Dist: dex-python-sdk>=1.28.0
12
+ Requires-Dist: httpx>=0.27
13
+ Requires-Dist: pyopenssl<27,>=24
14
+ Requires-Dist: python-tds<1.18,>=1.17.1
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Microsoft SQL Server Python connector
18
+
19
+ The Python package exposes the manifest's `query` and `execute` operations through native
20
+ `python-tds` sessions. Each attempt resolves the current private password, opens one SQL
21
+ Server connection, pins session settings, and closes it. It never persists the password in
22
+ Flow input, output, a receipt, or an Attribute.
23
+
24
+ ## Install and configure
25
+
26
+ Install `dex-connector-microsoft-sql-server==0.1.0`. Create a Dex Web connection named
27
+ `sqlserver-refunds` for the [runnable example](examples/record_refund/README.md), following
28
+ the authorization guide in the [connector README](../README.md#connection-setup).
29
+ The connection needs a host, database, SQL authentication user and secret password. Port,
30
+ timeouts, row limits, and encryption have manifest defaults.
31
+
32
+ The Python package supports `encrypt=mandatory` with a verified server certificate from the
33
+ system CA file, a bundled `certifi` CA fallback when Python exposes no system CA file, or
34
+ `SQLSERVER_SSL_CA` on the Worker host. An explicitly configured CA path must exist. Hostname
35
+ verification uses Subject Alternative Names, including DNS names and IP addresses; a Common
36
+ Name alone is insufficient. `encrypt=disable` is allowed only for
37
+ `localhost`, `127.0.0.1`, or `::1`. `python-tds` 1.17.1 has no public per-connection mode for
38
+ TDS 8.0 strict encryption or for encryption without certificate validation. The Python
39
+ package therefore rejects `encrypt=strict` and `encrypt=trust-server-certificate` during
40
+ client construction, before any network connection. These modes remain supported by the Go
41
+ connector. Choose the Go connector if either is required; do not change Python's setting
42
+ to another mode without reviewing the server's TLS requirements.
43
+
44
+ `python-tds` converts SQL Server `TIME`, `DATETIME2`, and `DATETIMEOFFSET` values to
45
+ Python's microsecond-resolution types. For a result column with scale 7, this package
46
+ selects `invalidResponse` and names the column before emitting any row, because the
47
+ seventh fractional digit would otherwise be lost. Use a SQL `CAST` to scale 6 or lower
48
+ when microsecond precision is sufficient. Scales 0 through 6 retain their exact values.
49
+ The package restores declared DECIMAL/NUMERIC scale and MONEY/SMALLMONEY's four decimal
50
+ places after driver decoding. It returns serialized GEOGRAPHY, GEOMETRY, and HIERARCHYID
51
+ values as base64 with their SQL type names. Unknown SQL types fail `invalidResponse`.
52
+
53
+ ## Operations
54
+
55
+ `new_query_step` runs a parameterized `SELECT` or `WITH` statement in a transaction. Closing
56
+ its connection without COMMIT makes SQL Server roll it back. It returns `completed` with
57
+ bounded rows, `truncated` when the row or JSON byte bound is reached, `providerRejected`
58
+ for conclusive SQL Server errors,
59
+ `invalidResponse` for undecodable values, and `defect` for invalid local input. Transient
60
+ failures retry.
61
+
62
+ `new_execute_step` runs one parameterized `INSERT`, `UPDATE`, `DELETE`, `MERGE`, or `WITH`
63
+ statement in its own transaction. The optional final `@pN` idempotency-key placeholder
64
+ binds Dex's stable Call ID. A write that exceeds `maxRowsAffected` or an OUTPUT bound
65
+ rolls back and selects `limitExceeded`. A failed COMMIT whose outcome is unknown selects
66
+ `uncertain`; a COMMIT failure retries only when no bytes were sent. Failures before COMMIT
67
+ retry only when safe. Make every write statement idempotent across retries and Worker replacement.
68
+ `rowsAffected` sums all SQL Server DONE counts, including trigger statements. If the server
69
+ supplies no count, `maxRowsAffected` fails `invalidResponse` before COMMIT. Receipts include
70
+ the session process ID and server version; server errors add number, state, and severity.
71
+ The connector enforces an attempt deadline and a response read budget in addition to the
72
+ configured row and JSON response bounds. Exhausting the read budget returns truncated
73
+ query rows or closes an execute session before COMMIT, causing SQL Server to roll it back.
74
+
75
+ Both operations accept `@p1` through `@pN` positional parameters in SQL text. Do not
76
+ interpolate user input into the statement. The connector checks for one allowed statement,
77
+ rejects transaction control and other reserved operations, and binds values through
78
+ `python-tds` named parameters. Python `None` binds as a SQL `NULL` literal, small integers
79
+ bind as SQL `INT`, and timezone-aware `datetime` inputs are unsupported. Use explicit SQL
80
+ casts when a parameter needs a specific SQL type. Read the [runnable Flow](examples/record_refund/flow.py) for
81
+ the exact application call pattern.
82
+
83
+ ## Verification
84
+
85
+ The package unit tests cover routing, driver error numbers, input validation, row bounds,
86
+ and commit uncertainty. The example integration test runs its Worker and Client against a
87
+ real `dexcli dev` server with scripted connector operations. The SQL Server service-container
88
+ workflow runs `tests/integration/test_database.py`; its mandatory TLS pass depends on the
89
+ separate CI workflow change in PR #518. No live
90
+ SQL Server, Azure SQL Database, or Azure SQL Managed Instance has been verified through a
91
+ user-controlled Dex Web connection for this Python package.
@@ -0,0 +1,20 @@
1
+ dex_connectors/microsoft_sql_server/__init__.py,sha256=3KjT8uTEnaQ6v8_7TZzhNK2oMMG0LBqAKfmDgAZJnxc,884
2
+ dex_connectors/microsoft_sql_server/client.py,sha256=EfoXpRnSz97HGwbBf4bisbeswnBkcSBwyS--Iu2ENdo,12740
3
+ dex_connectors/microsoft_sql_server/connection.py,sha256=_pkDf08-OSrJKt1CT8OFq3wFYk6-NVve9Wbzcu8xwXw,362
4
+ dex_connectors/microsoft_sql_server/dex-connector.json,sha256=5Ozp-Dl0IEYecVVIGLpDqmamVwp13nx2cOCFIEviz-A,2134
5
+ dex_connectors/microsoft_sql_server/models.py,sha256=CeLEIeSc9Kcrm2OXP4I5d_7J-dFx-tUwhdTNlxYrxJ8,330
6
+ dex_connectors/microsoft_sql_server/operations.py,sha256=yhTt3X-DfbpA9G0yO0oAdlhgwdUIp-Q8fnjb7nSC_ZA,41427
7
+ dex_connectors/microsoft_sql_server/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ dex_connectors/microsoft_sql_server/steps.py,sha256=M4kpVjtOyiLs6AXz0lJKDX7SQkFpSuwmYqQTYQ7jzEA,242
9
+ dex_connectors/microsoft_sql_server/_generated/__init__.py,sha256=ShfMsAGzSt4xuhCaf20ibgtfXl4pXomZb00ovUw6CeI,66
10
+ dex_connectors/microsoft_sql_server/_generated/config.py,sha256=FUJCezAqbrxt8WlUV4KPcTezr84j3WBJt3Va9aRIJo4,698
11
+ dex_connectors/microsoft_sql_server/_generated/connection.py,sha256=S5kf4ezN-ezBDv8lWHTczAyxzNKY2ngCDVfeVEB5w_4,7954
12
+ dex_connectors/microsoft_sql_server/_generated/definitions.py,sha256=FQD2w9FzaZ5_eOXTJ_ibXsmBUjUcU9-e79I-jWTs0KI,2988
13
+ dex_connectors/microsoft_sql_server/_generated/mock.py,sha256=izWwBRj3Sj4af4TF5qnT1cRSFxgR-BK7B7qcpK5TdmA,9178
14
+ dex_connectors/microsoft_sql_server/_generated/models.py,sha256=DvdqdimVRTazduTpd72zjmtILEqBwGxe_O4GTzTgD08,7315
15
+ dex_connectors/microsoft_sql_server/_generated/steps.py,sha256=cyDauXXdZaWUfU11MBbx9k3Ur3MeZ85PwGyTbqBy29c,6211
16
+ dex_connectors/microsoft_sql_server/sqlservermock/__init__.py,sha256=sEODfqQ6BJ0_cxRmH7FUHlzuhGC26jntpGD0cmUtm_U,167
17
+ dex_connector_microsoft_sql_server-0.1.0.dist-info/METADATA,sha256=zZBi1FJHtOuXU8iu811DF1FV9XVWmD21xetQFp_O138,5613
18
+ dex_connector_microsoft_sql_server-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
19
+ dex_connector_microsoft_sql_server-0.1.0.dist-info/licenses/LICENSE,sha256=WNj87Zd5micrAShl1LujOPM6PDzDqjlNLrryDZ4hE0M,1070
20
+ dex_connector_microsoft_sql_server-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Super Durable
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,28 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ """Microsoft SQL Server connector for Dex Python applications."""
4
+
5
+ from .client import Client, Config, Credentials
6
+ from .connection import Connection, new_connection, new_connection_with_operations, new_project_connection
7
+ from .models import Column, ExecuteStatementInput, QueryRowsInput, RowSet, StatementExecution
8
+ from .operations import ExecuteStatementOperation, QueryRowsOperation
9
+ from .steps import new_execute_step, new_query_step
10
+
11
+ __all__ = [
12
+ "Client",
13
+ "Config",
14
+ "Credentials",
15
+ "Connection",
16
+ "Column",
17
+ "QueryRowsInput",
18
+ "RowSet",
19
+ "ExecuteStatementInput",
20
+ "StatementExecution",
21
+ "QueryRowsOperation",
22
+ "ExecuteStatementOperation",
23
+ "new_connection",
24
+ "new_connection_with_operations",
25
+ "new_project_connection",
26
+ "new_query_step",
27
+ "new_execute_step",
28
+ ]
@@ -0,0 +1,2 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
@@ -0,0 +1,31 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from dex_connectors.sdk import SecretString
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class Config:
12
+
13
+ host: str
14
+ database: str
15
+ user: str
16
+ port: int = 1433
17
+ encrypt: str = "mandatory"
18
+ connect_timeout_seconds: float = 10
19
+ statement_timeout_seconds: float = 5
20
+ max_rows: int = 1000
21
+ max_response_bytes: int = 1048576
22
+
23
+ setattr(Config, '__module__', 'dex_connectors.microsoft_sql_server.client')
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class Credentials:
28
+
29
+ password: SecretString
30
+
31
+ setattr(Credentials, '__module__', 'dex_connectors.microsoft_sql_server.client')
@@ -0,0 +1,173 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+ from dex_connectors.sdk import ConnectionRef, Mutation, Query, Call, SecretString
9
+ from dex_connectors.sdk.projectconfig import ConnectionKey, LoadedProject
10
+
11
+ from ..client import Client, Config, Credentials
12
+ from .definitions import CONNECTOR_ID, EXECUTE_DEFINITION, QUERY_DEFINITION
13
+ from ..models import ExecuteStatementInput, QueryRowsInput, RowSet, StatementExecution
14
+
15
+ class Connection:
16
+
17
+ __slots__ = ('_query', '_execute', '_client', 'reference')
18
+
19
+ def __init__(self,
20
+ reference: ConnectionRef,
21
+ query: Query[QueryRowsInput, RowSet],
22
+ execute: Mutation[ExecuteStatementInput, StatementExecution],
23
+ client: Client | None = None,
24
+ ) -> None:
25
+ reference.validate()
26
+ if reference.provider != CONNECTOR_ID or query is None or execute is None:
27
+ raise ValueError("Microsoft SQL Server connection provider and operations are required")
28
+ if query.definition().operation != QUERY_DEFINITION.operation:
29
+ raise ValueError("Microsoft SQL Server connection operation identity differs")
30
+ if execute.definition().operation != EXECUTE_DEFINITION.operation:
31
+ raise ValueError("Microsoft SQL Server connection operation identity differs")
32
+ self.reference = reference
33
+ self._query = query
34
+ self._execute = execute
35
+ self._client = client
36
+
37
+ def query(self) -> Query[QueryRowsInput, RowSet]:
38
+ return self._query
39
+
40
+ def execute(self) -> Mutation[ExecuteStatementInput, StatementExecution]:
41
+ return self._execute
42
+
43
+ async def aclose(self) -> None:
44
+ if self._client is not None:
45
+ await self._client.aclose()
46
+
47
+ def __repr__(self) -> str:
48
+ return "microsoft_sql_server.Connection([REDACTED])"
49
+
50
+ def __reduce__(self) -> tuple[object, ...]:
51
+ raise TypeError("Microsoft SQL Server connections cannot be serialized")
52
+
53
+ setattr(Connection, '__module__', 'dex_connectors.microsoft_sql_server.connection')
54
+
55
+
56
+ def new_connection(client: Client, reference: ConnectionRef) -> Connection:
57
+ if client is None:
58
+ raise ValueError("Microsoft SQL Server client is required")
59
+ return Connection(reference, client.query(), client.execute(), client)
60
+
61
+ setattr(new_connection, '__module__', 'dex_connectors.microsoft_sql_server.connection')
62
+
63
+
64
+ def new_connection_with_operations(
65
+ query: Query[QueryRowsInput, RowSet],
66
+ execute: Mutation[ExecuteStatementInput, StatementExecution],
67
+ reference: ConnectionRef,
68
+ ) -> Connection:
69
+ return Connection(reference, query, execute)
70
+
71
+ setattr(new_connection_with_operations, '__module__', 'dex_connectors.microsoft_sql_server.connection')
72
+
73
+
74
+ class _ProjectCredentialSource:
75
+
76
+ def __init__(self, project: LoadedProject, key: ConnectionKey) -> None:
77
+ self.project = project
78
+ self.key = key
79
+
80
+ async def resolve(self, call: Call) -> Credentials:
81
+ material = await self.project.resolve_credential(self.key, str(call.id))
82
+ if not isinstance(material, dict):
83
+ raise ValueError("Microsoft SQL Server stored credential does not match the connector credential fields")
84
+ if set(material) - set(('password',)):
85
+ raise ValueError("Microsoft SQL Server stored credential does not match the connector credential fields")
86
+ password = material.get("password")
87
+ if password is not None and not (isinstance(password, str)):
88
+ raise ValueError("Microsoft SQL Server credential password has an invalid type")
89
+ if not password:
90
+ raise ValueError("Microsoft SQL Server credential password is required")
91
+ return Credentials(SecretString(password))
92
+
93
+
94
+ def new_project_connection(
95
+ project: LoadedProject, connection_name: str, http_client: httpx.AsyncClient | None = None
96
+ ) -> Connection:
97
+ if project is None:
98
+ raise ValueError("Microsoft SQL Server connection requires loaded project configuration")
99
+ reference = ConnectionRef(CONNECTOR_ID, connection_name)
100
+ reference.validate()
101
+ key = ConnectionKey(CONNECTOR_ID, connection_name)
102
+ matching = [
103
+ entry
104
+ for entry in project.configuration.connections
105
+ if entry.connector_id == CONNECTOR_ID and entry.connection_name == connection_name
106
+ ]
107
+ if len(matching) != 1:
108
+ raise ValueError("Microsoft SQL Server project connection is missing or duplicated")
109
+ if matching[0].provider != CONNECTOR_ID:
110
+ raise ValueError("Microsoft SQL Server project connection provider differs")
111
+ config = _decode_config(matching[0].configuration)
112
+ client = Client(config, _ProjectCredentialSource(project, key), http_client)
113
+ return new_connection(client, reference)
114
+
115
+ setattr(new_project_connection, '__module__', 'dex_connectors.microsoft_sql_server.connection')
116
+
117
+
118
+ def _decode_config(value: dict[str, Any]) -> Config:
119
+ if set(value) - {"host", "port", "database", "user", "encrypt", "connectTimeout", "statementTimeout", "maxRows", "maxResponseBytes"}:
120
+ raise ValueError("Microsoft SQL Server configuration has unknown fields")
121
+ config_arguments: dict[str, Any] = {}
122
+ if "host" in value:
123
+ host = value["host"]
124
+ if not (isinstance(host, str)):
125
+ raise ValueError("Microsoft SQL Server configuration host has an invalid type")
126
+ config_arguments['host'] = host
127
+ else:
128
+ raise ValueError("Microsoft SQL Server configuration host is required")
129
+ if "port" in value:
130
+ port = value["port"]
131
+ if not (type(port) is int):
132
+ raise ValueError("Microsoft SQL Server configuration port has an invalid type")
133
+ config_arguments['port'] = port
134
+ if "database" in value:
135
+ database = value["database"]
136
+ if not (isinstance(database, str)):
137
+ raise ValueError("Microsoft SQL Server configuration database has an invalid type")
138
+ config_arguments['database'] = database
139
+ else:
140
+ raise ValueError("Microsoft SQL Server configuration database is required")
141
+ if "user" in value:
142
+ user = value["user"]
143
+ if not (isinstance(user, str)):
144
+ raise ValueError("Microsoft SQL Server configuration user has an invalid type")
145
+ config_arguments['user'] = user
146
+ else:
147
+ raise ValueError("Microsoft SQL Server configuration user is required")
148
+ if "encrypt" in value:
149
+ encrypt = value["encrypt"]
150
+ if not (isinstance(encrypt, str) and encrypt in ('mandatory', 'strict', 'trust-server-certificate', 'disable')):
151
+ raise ValueError("Microsoft SQL Server configuration encrypt has an invalid type")
152
+ config_arguments['encrypt'] = encrypt
153
+ if "connectTimeout" in value:
154
+ connect_timeout = value["connectTimeout"]
155
+ if not (type(connect_timeout) is int):
156
+ raise ValueError("Microsoft SQL Server configuration connectTimeout has an invalid type")
157
+ config_arguments['connect_timeout_seconds'] = connect_timeout / 1_000_000_000
158
+ if "statementTimeout" in value:
159
+ statement_timeout = value["statementTimeout"]
160
+ if not (type(statement_timeout) is int):
161
+ raise ValueError("Microsoft SQL Server configuration statementTimeout has an invalid type")
162
+ config_arguments['statement_timeout_seconds'] = statement_timeout / 1_000_000_000
163
+ if "maxRows" in value:
164
+ max_rows = value["maxRows"]
165
+ if not (type(max_rows) is int):
166
+ raise ValueError("Microsoft SQL Server configuration maxRows has an invalid type")
167
+ config_arguments['max_rows'] = max_rows
168
+ if "maxResponseBytes" in value:
169
+ max_response_bytes = value["maxResponseBytes"]
170
+ if not (type(max_response_bytes) is int):
171
+ raise ValueError("Microsoft SQL Server configuration maxResponseBytes has an invalid type")
172
+ config_arguments['max_response_bytes'] = max_response_bytes
173
+ return Config(**config_arguments)
@@ -0,0 +1,60 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from datetime import timedelta
6
+
7
+ from dex_connectors.sdk import (
8
+ BranchDefinition,
9
+ MutationDefinition,
10
+ OperationRef,
11
+ QueryDefinition,
12
+ RetryPolicy,
13
+ StepDefaults,
14
+ default_connector_step_execute_retry_policy,
15
+ )
16
+
17
+ CONNECTOR_ID = "microsoft-sql-server"
18
+ PROVIDER = "microsoft-sql-server"
19
+ QUERY_OPERATION_ID = "query"
20
+ EXECUTE_OPERATION_ID = "execute"
21
+ COMPLETED = "completed"
22
+ DEFECT = "defect"
23
+ INVALID_RESPONSE = "invalidResponse"
24
+ LIMIT_EXCEEDED = "limitExceeded"
25
+ PROVIDER_REJECTED = "providerRejected"
26
+ TRUNCATED = "truncated"
27
+ UNCERTAIN = "uncertain"
28
+
29
+ QUERY_DEFINITION = QueryDefinition(
30
+ OperationRef(CONNECTOR_ID, QUERY_OPERATION_ID),
31
+ (
32
+ BranchDefinition(COMPLETED, "The server ran the statement and returned every row, possibly none, within maxRows and maxResponseBytes.", False),
33
+ BranchDefinition(TRUNCATED, "The statement produced more rows or bytes than maxRows or maxResponseBytes allow; the Result holds only the rows that fit.", True),
34
+ BranchDefinition(PROVIDER_REJECTED, "The server conclusively refused the connection or statement, such as bad credentials, a firewall rule, a syntax error, a missing table, a permission error, or statementTimeout.", True),
35
+ BranchDefinition(INVALID_RESPONSE, "The server returned a value the connector cannot decode under its documented type mapping.", True),
36
+ BranchDefinition(DEFECT, "Local input, connection configuration, or connector definition is invalid.", True),
37
+ ),
38
+ StepDefaults(
39
+ timedelta(seconds=30),
40
+ 2,
41
+ execute_retry=default_connector_step_execute_retry_policy(),
42
+ ),
43
+ )
44
+
45
+ EXECUTE_DEFINITION = MutationDefinition(
46
+ OperationRef(CONNECTOR_ID, EXECUTE_OPERATION_ID),
47
+ (
48
+ BranchDefinition(COMPLETED, "The server committed the statement's transaction; the Result holds the rows affected and any OUTPUT rows.", False),
49
+ BranchDefinition(LIMIT_EXCEEDED, "The statement affected more rows than maxRowsAffected, or its OUTPUT rows exceeded maxRows or maxResponseBytes, so the connector rolled back and nothing was written.", True),
50
+ BranchDefinition(PROVIDER_REJECTED, "The server conclusively refused the connection, statement, or commit, such as a duplicate key, a syntax error, or a permission error; nothing was written.", True),
51
+ BranchDefinition(UNCERTAIN, "The connection failed after COMMIT was sent, so whether the server committed the write is unknown.", True),
52
+ BranchDefinition(INVALID_RESPONSE, "The server returned a value the connector cannot decode under its documented type mapping; the connector rolled back and nothing was written.", True),
53
+ BranchDefinition(DEFECT, "Local input, connection configuration, or connector definition is invalid.", True),
54
+ ),
55
+ StepDefaults(
56
+ timedelta(seconds=30),
57
+ 2,
58
+ execute_retry=default_connector_step_execute_retry_policy(),
59
+ ),
60
+ )
@@ -0,0 +1,155 @@
1
+ # Copyright (c) 2026 Super Durable
2
+ # SPDX-License-Identifier: MIT
3
+ # ruff: noqa
4
+
5
+ from datetime import datetime
6
+
7
+ from dex_connectors.sdk import ConnectionRef, Failure, FailureKind
8
+ from dex_connectors.sdk.connectormock import Case, Mutation, Query
9
+
10
+ from ..connection import Connection, new_connection_with_operations
11
+ from ..models import Column, ExecuteStatementInput, QueryRowsInput, RowSet, StatementExecution
12
+ from .definitions import CONNECTOR_ID, COMPLETED, DEFECT, EXECUTE_DEFINITION, INVALID_RESPONSE, LIMIT_EXCEEDED, PROVIDER_REJECTED, QUERY_DEFINITION, TRUNCATED, UNCERTAIN
13
+
14
+ def query_completed(value: RowSet, failure: Failure | None = None) -> Case[RowSet]:
15
+ return Case.branch_result(COMPLETED, value, failure)
16
+
17
+ setattr(query_completed, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
18
+
19
+ def query_truncated(value: RowSet, failure: Failure | None = None) -> Case[RowSet]:
20
+ return Case.branch_result(TRUNCATED, value, failure)
21
+
22
+ setattr(query_truncated, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
23
+
24
+ def query_provider_rejected(value: RowSet, failure: Failure | None = None) -> Case[RowSet]:
25
+ return Case.branch_result(PROVIDER_REJECTED, value, failure)
26
+
27
+ setattr(query_provider_rejected, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
28
+
29
+ def query_invalid_response(value: RowSet, failure: Failure | None = None) -> Case[RowSet]:
30
+ return Case.branch_result(INVALID_RESPONSE, value, failure)
31
+
32
+ setattr(query_invalid_response, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
33
+
34
+ def query_defect(value: RowSet, failure: Failure | None = None) -> Case[RowSet]:
35
+ return Case.branch_result(DEFECT, value, failure)
36
+
37
+ setattr(query_defect, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
38
+
39
+ def query_retry(failure: Failure, after_seconds: float = 0) -> Case[RowSet]:
40
+ return Case.retry(failure, after_seconds)
41
+
42
+ setattr(query_retry, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
43
+
44
+ def query_completed_default_answer() -> Case[RowSet]:
45
+ return Case.branch_result(COMPLETED, RowSet(columns=(Column(name='refund_id', type_name='BIGINT'), Column(name='order_id', type_name='NVARCHAR'), Column(name='amount_usd', type_name='DECIMAL'), Column(name='external_reference', type_name='NVARCHAR'), Column(name='idempotency_key', type_name='UNIQUEIDENTIFIER'), Column(name='recorded_at', type_name='DATETIME2')), rows=({'refund_id': '1', 'order_id': '88213', 'amount_usd': '250.00', 'external_reference': 'tkt_5488', 'idempotency_key': '6f1c2a9e-0000-4000-8000-000000000001', 'recorded_at': '2026-10-01T12:00:00.25'},)))
46
+
47
+ setattr(query_completed_default_answer, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
48
+
49
+ def query_row_limit() -> Case[RowSet]:
50
+ return Case.branch_result(TRUNCATED, RowSet(columns=(Column(name='refund_id', type_name='BIGINT'), Column(name='order_id', type_name='NVARCHAR'), Column(name='amount_usd', type_name='DECIMAL'), Column(name='external_reference', type_name='NVARCHAR'), Column(name='idempotency_key', type_name='UNIQUEIDENTIFIER'), Column(name='recorded_at', type_name='DATETIME2')), rows=({'refund_id': '1', 'order_id': '88213', 'amount_usd': '250.00', 'external_reference': 'tkt_5488', 'idempotency_key': '6f1c2a9e-0000-4000-8000-000000000001', 'recorded_at': '2026-10-01T12:00:00.25'},), truncated=True), Failure(FailureKind.RESPONSE_TOO_LARGE, CONNECTOR_ID, "query", "Querying refund_ledger for order 88213 with maxRows 1 below the result size returns a truncated row set."))
51
+
52
+ setattr(query_row_limit, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
53
+
54
+ def query_missing_table() -> Case[RowSet]:
55
+ return Case.branch_result(PROVIDER_REJECTED, RowSet(), Failure(FailureKind.NOT_FOUND, CONNECTOR_ID, "query", "Querying a missing refund_ledger table is rejected."))
56
+
57
+ setattr(query_missing_table, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
58
+
59
+ def execute_completed(value: StatementExecution, failure: Failure | None = None) -> Case[StatementExecution]:
60
+ return Case.branch_result(COMPLETED, value, failure)
61
+
62
+ setattr(execute_completed, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
63
+
64
+ def execute_limit_exceeded(value: StatementExecution, failure: Failure | None = None) -> Case[StatementExecution]:
65
+ return Case.branch_result(LIMIT_EXCEEDED, value, failure)
66
+
67
+ setattr(execute_limit_exceeded, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
68
+
69
+ def execute_provider_rejected(value: StatementExecution, failure: Failure | None = None) -> Case[StatementExecution]:
70
+ return Case.branch_result(PROVIDER_REJECTED, value, failure)
71
+
72
+ setattr(execute_provider_rejected, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
73
+
74
+ def execute_uncertain(value: StatementExecution, failure: Failure) -> Case[StatementExecution]:
75
+ return Case.uncertain(value, failure)
76
+
77
+ setattr(execute_uncertain, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
78
+
79
+ def execute_invalid_response(value: StatementExecution, failure: Failure | None = None) -> Case[StatementExecution]:
80
+ return Case.branch_result(INVALID_RESPONSE, value, failure)
81
+
82
+ setattr(execute_invalid_response, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
83
+
84
+ def execute_defect(value: StatementExecution, failure: Failure | None = None) -> Case[StatementExecution]:
85
+ return Case.branch_result(DEFECT, value, failure)
86
+
87
+ setattr(execute_defect, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
88
+
89
+ def execute_retry(failure: Failure, after_seconds: float = 0) -> Case[StatementExecution]:
90
+ return Case.retry(failure, after_seconds)
91
+
92
+ setattr(execute_retry, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
93
+
94
+ def execute_completed_default_answer() -> Case[StatementExecution]:
95
+ return Case.branch_result(COMPLETED, StatementExecution(rows_affected=1, columns=(Column(name='refund_id', type_name='BIGINT'), Column(name='order_id', type_name='NVARCHAR'), Column(name='amount_usd', type_name='DECIMAL'), Column(name='external_reference', type_name='NVARCHAR'), Column(name='idempotency_key', type_name='UNIQUEIDENTIFIER'), Column(name='recorded_at', type_name='DATETIME2')), rows=({'refund_id': '1', 'order_id': '88213', 'amount_usd': '250.00', 'external_reference': 'tkt_5488', 'idempotency_key': '6f1c2a9e-0000-4000-8000-000000000001', 'recorded_at': '2026-10-01T12:00:00.25'},)))
96
+
97
+ setattr(execute_completed_default_answer, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
98
+
99
+ def execute_race_lost() -> Case[StatementExecution]:
100
+ return Case.branch_result(COMPLETED, StatementExecution(rows_affected=0, columns=(Column(name='refund_id', type_name='BIGINT'), Column(name='order_id', type_name='NVARCHAR'), Column(name='amount_usd', type_name='DECIMAL'), Column(name='external_reference', type_name='NVARCHAR'), Column(name='idempotency_key', type_name='UNIQUEIDENTIFIER'), Column(name='recorded_at', type_name='DATETIME2')), rows=()))
101
+
102
+ setattr(execute_race_lost, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
103
+
104
+ def execute_row_limit() -> Case[StatementExecution]:
105
+ return Case.branch_result(LIMIT_EXCEEDED, StatementExecution(), Failure(FailureKind.CONFLICT, CONNECTOR_ID, "execute", "Updating more rows than maxRowsAffected rolls back the statement."))
106
+
107
+ setattr(execute_row_limit, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
108
+
109
+ def execute_duplicate_key() -> Case[StatementExecution]:
110
+ return Case.branch_result(PROVIDER_REJECTED, StatementExecution(), Failure(FailureKind.CONFLICT, CONNECTOR_ID, "execute", "Inserting a duplicate unique key is rejected before commit."))
111
+
112
+ setattr(execute_duplicate_key, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
113
+
114
+
115
+ class Mock:
116
+
117
+ def __init__(self, connection_name: str = "microsoft-sql-server") -> None:
118
+ self.query_script: Query[QueryRowsInput, RowSet] = Query(QUERY_DEFINITION)
119
+ self.query_script.default(query_completed_default_answer())
120
+ self.execute_script: Mutation[ExecuteStatementInput, StatementExecution] = Mutation(EXECUTE_DEFINITION)
121
+ self.execute_script.default(execute_completed_default_answer())
122
+ self._connection = new_connection_with_operations(
123
+ query=self.query_script,
124
+ execute=self.execute_script,
125
+ reference=ConnectionRef(CONNECTOR_ID, connection_name),
126
+ )
127
+
128
+ def connection(self) -> Connection:
129
+ return self._connection
130
+
131
+ setattr(Mock, '__module__', "dex_connectors.microsoft_sql_server.sqlservermock")
132
+
133
+ __all__ = [
134
+ "Mock",
135
+ "query_completed",
136
+ "query_truncated",
137
+ "query_provider_rejected",
138
+ "query_invalid_response",
139
+ "query_defect",
140
+ "query_retry",
141
+ "query_completed_default_answer",
142
+ "query_row_limit",
143
+ "query_missing_table",
144
+ "execute_completed",
145
+ "execute_limit_exceeded",
146
+ "execute_provider_rejected",
147
+ "execute_uncertain",
148
+ "execute_invalid_response",
149
+ "execute_defect",
150
+ "execute_retry",
151
+ "execute_completed_default_answer",
152
+ "execute_race_lost",
153
+ "execute_row_limit",
154
+ "execute_duplicate_key",
155
+ ]