dex-connector-microsoft-sql-server 0.1.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.
- dex_connector_microsoft_sql_server-0.1.0/.gitignore +16 -0
- dex_connector_microsoft_sql_server-0.1.0/LICENSE +21 -0
- dex_connector_microsoft_sql_server-0.1.0/PKG-INFO +91 -0
- dex_connector_microsoft_sql_server-0.1.0/README.md +75 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/__init__.py +3 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/README.md +22 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/__init__.py +3 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/flow.py +135 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/integration_test.py +71 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/sample-input.json +1 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/schema.sql +5 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/start.py +59 -0
- dex_connector_microsoft_sql_server-0.1.0/examples/record_refund/worker.py +51 -0
- dex_connector_microsoft_sql_server-0.1.0/pyproject.toml +39 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/__init__.py +28 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/_generated/__init__.py +2 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/_generated/config.py +31 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/_generated/connection.py +173 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/_generated/definitions.py +60 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/_generated/mock.py +155 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/_generated/models.py +127 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/_generated/steps.py +140 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/client.py +298 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/connection.py +12 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/dex-connector.json +92 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/models.py +7 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/operations.py +1039 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/py.typed +0 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/sqlservermock/__init__.py +6 -0
- dex_connector_microsoft_sql_server-0.1.0/src/dex_connectors/microsoft_sql_server/steps.py +7 -0
- dex_connector_microsoft_sql_server-0.1.0/tests/integration/test_database.py +288 -0
- dex_connector_microsoft_sql_server-0.1.0/tests/test_operations.py +1028 -0
- dex_connector_microsoft_sql_server-0.1.0/tests/test_tds_identity.py +174 -0
- dex_connector_microsoft_sql_server-0.1.0/uv.lock +894 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
.DS_Store
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
node_modules/
|
|
5
|
+
dist/
|
|
6
|
+
sdkpython/dist/dex_connectors_sdk-0.1.0-py3-none-any.whl
|
|
7
|
+
/.bin/dexcli
|
|
8
|
+
/.bin/dex-server-zd
|
|
9
|
+
/sdkpython/.dexcli-data/
|
|
10
|
+
site/.catalog.yaml
|
|
11
|
+
coverage/
|
|
12
|
+
*.out
|
|
13
|
+
*.test
|
|
14
|
+
go.work
|
|
15
|
+
go.work.sum
|
|
16
|
+
.idea/
|
|
@@ -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,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,75 @@
|
|
|
1
|
+
# Microsoft SQL Server Python connector
|
|
2
|
+
|
|
3
|
+
The Python package exposes the manifest's `query` and `execute` operations through native
|
|
4
|
+
`python-tds` sessions. Each attempt resolves the current private password, opens one SQL
|
|
5
|
+
Server connection, pins session settings, and closes it. It never persists the password in
|
|
6
|
+
Flow input, output, a receipt, or an Attribute.
|
|
7
|
+
|
|
8
|
+
## Install and configure
|
|
9
|
+
|
|
10
|
+
Install `dex-connector-microsoft-sql-server==0.1.0`. Create a Dex Web connection named
|
|
11
|
+
`sqlserver-refunds` for the [runnable example](examples/record_refund/README.md), following
|
|
12
|
+
the authorization guide in the [connector README](../README.md#connection-setup).
|
|
13
|
+
The connection needs a host, database, SQL authentication user and secret password. Port,
|
|
14
|
+
timeouts, row limits, and encryption have manifest defaults.
|
|
15
|
+
|
|
16
|
+
The Python package supports `encrypt=mandatory` with a verified server certificate from the
|
|
17
|
+
system CA file, a bundled `certifi` CA fallback when Python exposes no system CA file, or
|
|
18
|
+
`SQLSERVER_SSL_CA` on the Worker host. An explicitly configured CA path must exist. Hostname
|
|
19
|
+
verification uses Subject Alternative Names, including DNS names and IP addresses; a Common
|
|
20
|
+
Name alone is insufficient. `encrypt=disable` is allowed only for
|
|
21
|
+
`localhost`, `127.0.0.1`, or `::1`. `python-tds` 1.17.1 has no public per-connection mode for
|
|
22
|
+
TDS 8.0 strict encryption or for encryption without certificate validation. The Python
|
|
23
|
+
package therefore rejects `encrypt=strict` and `encrypt=trust-server-certificate` during
|
|
24
|
+
client construction, before any network connection. These modes remain supported by the Go
|
|
25
|
+
connector. Choose the Go connector if either is required; do not change Python's setting
|
|
26
|
+
to another mode without reviewing the server's TLS requirements.
|
|
27
|
+
|
|
28
|
+
`python-tds` converts SQL Server `TIME`, `DATETIME2`, and `DATETIMEOFFSET` values to
|
|
29
|
+
Python's microsecond-resolution types. For a result column with scale 7, this package
|
|
30
|
+
selects `invalidResponse` and names the column before emitting any row, because the
|
|
31
|
+
seventh fractional digit would otherwise be lost. Use a SQL `CAST` to scale 6 or lower
|
|
32
|
+
when microsecond precision is sufficient. Scales 0 through 6 retain their exact values.
|
|
33
|
+
The package restores declared DECIMAL/NUMERIC scale and MONEY/SMALLMONEY's four decimal
|
|
34
|
+
places after driver decoding. It returns serialized GEOGRAPHY, GEOMETRY, and HIERARCHYID
|
|
35
|
+
values as base64 with their SQL type names. Unknown SQL types fail `invalidResponse`.
|
|
36
|
+
|
|
37
|
+
## Operations
|
|
38
|
+
|
|
39
|
+
`new_query_step` runs a parameterized `SELECT` or `WITH` statement in a transaction. Closing
|
|
40
|
+
its connection without COMMIT makes SQL Server roll it back. It returns `completed` with
|
|
41
|
+
bounded rows, `truncated` when the row or JSON byte bound is reached, `providerRejected`
|
|
42
|
+
for conclusive SQL Server errors,
|
|
43
|
+
`invalidResponse` for undecodable values, and `defect` for invalid local input. Transient
|
|
44
|
+
failures retry.
|
|
45
|
+
|
|
46
|
+
`new_execute_step` runs one parameterized `INSERT`, `UPDATE`, `DELETE`, `MERGE`, or `WITH`
|
|
47
|
+
statement in its own transaction. The optional final `@pN` idempotency-key placeholder
|
|
48
|
+
binds Dex's stable Call ID. A write that exceeds `maxRowsAffected` or an OUTPUT bound
|
|
49
|
+
rolls back and selects `limitExceeded`. A failed COMMIT whose outcome is unknown selects
|
|
50
|
+
`uncertain`; a COMMIT failure retries only when no bytes were sent. Failures before COMMIT
|
|
51
|
+
retry only when safe. Make every write statement idempotent across retries and Worker replacement.
|
|
52
|
+
`rowsAffected` sums all SQL Server DONE counts, including trigger statements. If the server
|
|
53
|
+
supplies no count, `maxRowsAffected` fails `invalidResponse` before COMMIT. Receipts include
|
|
54
|
+
the session process ID and server version; server errors add number, state, and severity.
|
|
55
|
+
The connector enforces an attempt deadline and a response read budget in addition to the
|
|
56
|
+
configured row and JSON response bounds. Exhausting the read budget returns truncated
|
|
57
|
+
query rows or closes an execute session before COMMIT, causing SQL Server to roll it back.
|
|
58
|
+
|
|
59
|
+
Both operations accept `@p1` through `@pN` positional parameters in SQL text. Do not
|
|
60
|
+
interpolate user input into the statement. The connector checks for one allowed statement,
|
|
61
|
+
rejects transaction control and other reserved operations, and binds values through
|
|
62
|
+
`python-tds` named parameters. Python `None` binds as a SQL `NULL` literal, small integers
|
|
63
|
+
bind as SQL `INT`, and timezone-aware `datetime` inputs are unsupported. Use explicit SQL
|
|
64
|
+
casts when a parameter needs a specific SQL type. Read the [runnable Flow](examples/record_refund/flow.py) for
|
|
65
|
+
the exact application call pattern.
|
|
66
|
+
|
|
67
|
+
## Verification
|
|
68
|
+
|
|
69
|
+
The package unit tests cover routing, driver error numbers, input validation, row bounds,
|
|
70
|
+
and commit uncertainty. The example integration test runs its Worker and Client against a
|
|
71
|
+
real `dexcli dev` server with scripted connector operations. The SQL Server service-container
|
|
72
|
+
workflow runs `tests/integration/test_database.py`; its mandatory TLS pass depends on the
|
|
73
|
+
separate CI workflow change in PR #518. No live
|
|
74
|
+
SQL Server, Azure SQL Database, or Azure SQL Managed Instance has been verified through a
|
|
75
|
+
user-controlled Dex Web connection for this Python package.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Record a refund with SQL Server
|
|
2
|
+
|
|
3
|
+
Create `dbo.refund_ledger` with `schema.sql` using an administrator connection. Create the
|
|
4
|
+
`sqlserver-refunds` connection in Dex Web with SQL authentication and the required SELECT and INSERT
|
|
5
|
+
permissions. Run `uv run --project connectors/microsoft/sql-server/python python -m examples.record_refund.worker`
|
|
6
|
+
with `DEX_FLOW_SERVICE_ADDRESS` pointing to the Dex server, then start a Flow with
|
|
7
|
+
`uv run --project connectors/microsoft/sql-server/python python -m examples.record_refund.start
|
|
8
|
+
<unique-flow-id> connectors/microsoft/sql-server/python/examples/record_refund/sample-input.json`.
|
|
9
|
+
|
|
10
|
+
The write binds the stable Dex Call ID as its final unique key, and the subsequent read returns the
|
|
11
|
+
committed row. Optional branches remain unwired so the Flow fails on a rejected or uncertain write.
|
|
12
|
+
From the repository root, generate and lint strict Flow Definition Graph 2.0:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
PYTHONPATH=connectors/microsoft/sql-server/python dexcli visualize \
|
|
16
|
+
connectors/microsoft/sql-server/python/examples/record_refund/flow.py \
|
|
17
|
+
--language python --schema-version 2.0 --lint app --json \
|
|
18
|
+
--python connectors/microsoft/sql-server/python/.venv/bin/python \
|
|
19
|
+
--out /tmp/sqlserver-python-fdg/record-refund
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The graph shows PrepareRefund, WriteRefund, PrepareReadBack, ReadRefund, and CompleteRefund.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Durable SQL Server refund write followed by read-back."""
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import dex
|
|
8
|
+
from dex_connectors.sdk import MutationResult, QueryResult
|
|
9
|
+
|
|
10
|
+
from dex_connectors.microsoft_sql_server import (
|
|
11
|
+
Connection,
|
|
12
|
+
ExecuteStatementInput,
|
|
13
|
+
QueryRowsInput,
|
|
14
|
+
RowSet,
|
|
15
|
+
StatementExecution,
|
|
16
|
+
new_execute_step,
|
|
17
|
+
new_query_step,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
CONNECTION_NAME = "sqlserver-refunds"
|
|
21
|
+
FLOW_TYPE = "SQLServerRecordRefundPython"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class RefundRequest:
|
|
26
|
+
"""An order and exact decimal amount to record once."""
|
|
27
|
+
|
|
28
|
+
order_id: str
|
|
29
|
+
amount_usd: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_REQUEST = dex.Attribute("sqlserver-python-refund-request", RefundRequest)
|
|
33
|
+
_RESULT = dex.Attribute("sqlserver-python-refund-result", RowSet)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def execute_input(request: RefundRequest) -> ExecuteStatementInput:
|
|
37
|
+
"""Use the stable Dex Call ID as the final unique write key."""
|
|
38
|
+
return ExecuteStatementInput(
|
|
39
|
+
"INSERT INTO dbo.refund_ledger (order_id, amount_usd, call_key) "
|
|
40
|
+
"SELECT @p1, CAST(@p2 AS decimal(12,2)), @p3 "
|
|
41
|
+
"WHERE NOT EXISTS (SELECT 1 FROM dbo.refund_ledger WHERE call_key = @p3)",
|
|
42
|
+
(request.order_id, request.amount_usd),
|
|
43
|
+
idempotency_key_placeholder=3,
|
|
44
|
+
max_rows_affected=1,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def query_input(request: RefundRequest) -> QueryRowsInput:
|
|
49
|
+
"""Read back the committed refund by its application order ID."""
|
|
50
|
+
return QueryRowsInput(
|
|
51
|
+
"SELECT order_id, amount_usd, call_key FROM dbo.refund_ledger WHERE order_id = @p1",
|
|
52
|
+
(request.order_id,),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# dex:group group-id:refund group-label:"Record refund"
|
|
57
|
+
# dex:explanation text:"Validate and retain the refund request before the SQL Server write."
|
|
58
|
+
class PrepareRefund(dex.Step[RefundRequest]):
|
|
59
|
+
def get_step_type(self) -> str:
|
|
60
|
+
return "PrepareRefund"
|
|
61
|
+
|
|
62
|
+
def execute(self, context: dex.Context, input: RefundRequest) -> dex.StepDecision:
|
|
63
|
+
if not input.order_id.strip() or not input.amount_usd.strip():
|
|
64
|
+
return dex.force_fail("order_id and amount_usd are required")
|
|
65
|
+
_REQUEST.set(context, input)
|
|
66
|
+
return dex.go_to(dex.StepRef("WriteRefund"), input)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# dex:group group-id:refund group-label:"Record refund"
|
|
70
|
+
# dex:explanation text:"Pass the retained order to the read-back Query after the write commits."
|
|
71
|
+
class PrepareReadBack(dex.Step[MutationResult[StatementExecution]]):
|
|
72
|
+
def get_step_type(self) -> str:
|
|
73
|
+
return "PrepareReadBack"
|
|
74
|
+
|
|
75
|
+
def execute(self, context: dex.Context, input: MutationResult[StatementExecution]) -> dex.StepDecision:
|
|
76
|
+
return dex.go_to(dex.StepRef("ReadRefund"), _REQUEST.get(context))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# dex:group group-id:refund group-label:"Record refund"
|
|
80
|
+
# dex:explanation text:"Persist the read-back rows and complete the refund Flow."
|
|
81
|
+
class CompleteRefund(dex.Step[QueryResult[RowSet]]):
|
|
82
|
+
def get_step_type(self) -> str:
|
|
83
|
+
return "CompleteRefund"
|
|
84
|
+
|
|
85
|
+
def execute(self, context: dex.Context, input: QueryResult[RowSet]) -> dex.StepDecision:
|
|
86
|
+
_RESULT.set(context, input.value)
|
|
87
|
+
return dex.graceful_complete(input.value)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class RecordRefundFlow(dex.Flow[RefundRequest]):
|
|
91
|
+
"""Write a refund once and read its committed row through SQL Server."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, connection: Connection) -> None:
|
|
94
|
+
if connection.reference.name != CONNECTION_NAME:
|
|
95
|
+
raise ValueError("refund Flow requires its static SQL Server connection")
|
|
96
|
+
self.prepare = PrepareRefund()
|
|
97
|
+
self.prepare_read = PrepareReadBack()
|
|
98
|
+
self.complete = CompleteRefund()
|
|
99
|
+
self.execute = new_execute_step(
|
|
100
|
+
step_type="WriteRefund",
|
|
101
|
+
step_input_type=RefundRequest,
|
|
102
|
+
annotations={
|
|
103
|
+
"groupId": "refund",
|
|
104
|
+
"groupLabel": "Record refund",
|
|
105
|
+
"explanation": "Insert the keyed refund transaction once.",
|
|
106
|
+
},
|
|
107
|
+
connection=connection,
|
|
108
|
+
connection_name=CONNECTION_NAME,
|
|
109
|
+
map_to_operation_input=execute_input,
|
|
110
|
+
completed=self.prepare_read,
|
|
111
|
+
)
|
|
112
|
+
self.query = new_query_step(
|
|
113
|
+
step_type="ReadRefund",
|
|
114
|
+
step_input_type=RefundRequest,
|
|
115
|
+
annotations={
|
|
116
|
+
"groupId": "refund",
|
|
117
|
+
"groupLabel": "Record refund",
|
|
118
|
+
"explanation": "Read the committed refund row by order ID.",
|
|
119
|
+
},
|
|
120
|
+
connection=connection,
|
|
121
|
+
connection_name=CONNECTION_NAME,
|
|
122
|
+
map_to_operation_input=query_input,
|
|
123
|
+
completed=self.complete,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def get_flow_type(self) -> str:
|
|
127
|
+
return "SQLServerRecordRefundPython"
|
|
128
|
+
|
|
129
|
+
def get_steps(self) -> dex.StepList[RefundRequest]:
|
|
130
|
+
return dex.StepList.start_step(self.prepare).other_steps(
|
|
131
|
+
self.execute, self.prepare_read, self.query, self.complete
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def get_persistence_schema(self) -> dex.PersistenceSchema:
|
|
135
|
+
return dex.PersistenceSchema.of(_REQUEST, _RESULT)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Run the checked-in refund Flow through a real Dex Worker and Client."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
from datetime import timedelta
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
import dex
|
|
12
|
+
import pytest
|
|
13
|
+
from dex_connectors.sdk import Failure, FailureKind
|
|
14
|
+
|
|
15
|
+
from dex_connectors.microsoft_sql_server.sqlservermock import (
|
|
16
|
+
Mock,
|
|
17
|
+
execute_completed_default_answer,
|
|
18
|
+
execute_provider_rejected,
|
|
19
|
+
execute_retry,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from .flow import CONNECTION_NAME, RecordRefundFlow, RefundRequest
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.mark.asyncio
|
|
26
|
+
async def test_refund_flow_routes_success_retry_and_unwired_rejection(tmp_path: Path) -> None:
|
|
27
|
+
"""Check durable operation routing and stable retry identity in Dex."""
|
|
28
|
+
address = os.environ["DEX_FLOW_SERVICE_ADDRESS"]
|
|
29
|
+
mock = Mock(CONNECTION_NAME)
|
|
30
|
+
flow = RecordRefundFlow(mock.connection())
|
|
31
|
+
registry = dex.Registry([flow], allow_async_handlers=True)
|
|
32
|
+
cache = dex.open_blob_cache(dex.BlobCacheConfig(str(tmp_path / "blobs"), 64 * 1024 * 1024))
|
|
33
|
+
worker = dex.AsyncWorker(registry, cache, dex.WorkerOptions(server_address=address))
|
|
34
|
+
worker_task = asyncio.create_task(worker.start())
|
|
35
|
+
try:
|
|
36
|
+
await worker.wait_pull_registered(timeout=30)
|
|
37
|
+
async with dex.AsyncClient(registry, cache, dex.ClientOptions(server_address=address)) as client:
|
|
38
|
+
success_id = f"sqlserver-python-success-{uuid4().hex}"
|
|
39
|
+
await client.start_flow(flow, success_id, RefundRequest("order-88213", "250.00"))
|
|
40
|
+
success = await client.wait_for_flow(success_id, timedelta(seconds=30))
|
|
41
|
+
assert success.status == dex.FlowStatus.COMPLETED, success.error_message
|
|
42
|
+
|
|
43
|
+
retry_id = f"sqlserver-python-retry-{uuid4().hex}"
|
|
44
|
+
mock.execute_script.for_flow(retry_id).respond(
|
|
45
|
+
execute_retry(
|
|
46
|
+
Failure(FailureKind.AVAILABILITY, "microsoft-sql-server", "execute", "temporary outage")
|
|
47
|
+
),
|
|
48
|
+
execute_completed_default_answer(),
|
|
49
|
+
)
|
|
50
|
+
await client.start_flow(flow, retry_id, RefundRequest("order-88214", "100.00"))
|
|
51
|
+
retried = await client.wait_for_flow(retry_id, timedelta(seconds=30))
|
|
52
|
+
assert retried.status == dex.FlowStatus.COMPLETED, retried.error_message
|
|
53
|
+
calls = [item for item in mock.execute_script.calls() if item.flow_id == retry_id]
|
|
54
|
+
assert len(calls) == 2
|
|
55
|
+
assert calls[0].call_id == calls[1].call_id
|
|
56
|
+
|
|
57
|
+
rejected_id = f"sqlserver-python-rejected-{uuid4().hex}"
|
|
58
|
+
mock.execute_script.for_flow(rejected_id).respond(
|
|
59
|
+
execute_provider_rejected(
|
|
60
|
+
value=execute_completed_default_answer().value,
|
|
61
|
+
failure=Failure(FailureKind.CONFLICT, "microsoft-sql-server", "execute", "duplicate key"),
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
await client.start_flow(flow, rejected_id, RefundRequest("order-88215", "100.00"))
|
|
65
|
+
rejected = await client.wait_for_flow(rejected_id, timedelta(seconds=30))
|
|
66
|
+
assert rejected.status == dex.FlowStatus.FAILED
|
|
67
|
+
assert rejected.error_message is not None and "providerRejected" in rejected.error_message
|
|
68
|
+
finally:
|
|
69
|
+
await worker.stop()
|
|
70
|
+
await worker_task
|
|
71
|
+
cache.close()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"order_id":"order-88213","amount_usd":"250.00"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Start the checked-in SQL Server refund Flow from JSON input."""
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import os
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import dex
|
|
12
|
+
from dex_connectors.sdk.projectconfig import load_from_environment
|
|
13
|
+
|
|
14
|
+
from dex_connectors.microsoft_sql_server import new_project_connection
|
|
15
|
+
|
|
16
|
+
from .flow import CONNECTION_NAME, RecordRefundFlow, RefundRequest
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def start_refund(flow_id: str, input_file: Path) -> str:
|
|
20
|
+
"""Submit one validated JSON request to Dex."""
|
|
21
|
+
encoded = input_file.read_bytes()
|
|
22
|
+
if len(encoded) > 65_536:
|
|
23
|
+
raise ValueError("refund input exceeds 65536 bytes")
|
|
24
|
+
request = (
|
|
25
|
+
dex.CodecRegistry()
|
|
26
|
+
.resolve(RefundRequest)
|
|
27
|
+
.decode(dex.Value(dex.WireKind.JSON, encoded.decode("utf-8")))
|
|
28
|
+
)
|
|
29
|
+
project = await load_from_environment()
|
|
30
|
+
connection = new_project_connection(project, CONNECTION_NAME)
|
|
31
|
+
try:
|
|
32
|
+
flow = RecordRefundFlow(connection)
|
|
33
|
+
registry = dex.Registry([flow], allow_async_handlers=True)
|
|
34
|
+
with tempfile.TemporaryDirectory(prefix="sqlserver-python-start-blobs-") as cache_directory:
|
|
35
|
+
cache = dex.open_blob_cache(dex.BlobCacheConfig(cache_directory, 1 << 24))
|
|
36
|
+
try:
|
|
37
|
+
address = os.environ.get("DEX_FLOW_SERVICE_ADDRESS", "localhost:8801")
|
|
38
|
+
async with dex.AsyncClient(
|
|
39
|
+
registry, cache, dex.ClientOptions(server_address=address)
|
|
40
|
+
) as client:
|
|
41
|
+
return await client.start_flow(flow, flow_id, request)
|
|
42
|
+
finally:
|
|
43
|
+
cache.close()
|
|
44
|
+
finally:
|
|
45
|
+
await connection.aclose()
|
|
46
|
+
await project.close()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def main() -> None:
|
|
50
|
+
"""Accept a unique Flow ID and request JSON path."""
|
|
51
|
+
parser = argparse.ArgumentParser(description="Start a SQL Server refund Flow")
|
|
52
|
+
parser.add_argument("flow_id")
|
|
53
|
+
parser.add_argument("input_file", type=Path)
|
|
54
|
+
args = parser.parse_args()
|
|
55
|
+
print(asyncio.run(start_refund(args.flow_id, args.input_file)))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
if __name__ == "__main__":
|
|
59
|
+
main()
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Worker entrypoint for the SQL Server refund Flow."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import dex
|
|
11
|
+
from dex_connectors.sdk.projectconfig import load_from_environment
|
|
12
|
+
|
|
13
|
+
from dex_connectors.microsoft_sql_server import new_project_connection
|
|
14
|
+
|
|
15
|
+
from .flow import CONNECTION_NAME, RecordRefundFlow
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def run_worker() -> None:
|
|
19
|
+
"""Load the named Dex Web connection and serve refund Flows."""
|
|
20
|
+
project = await load_from_environment()
|
|
21
|
+
connection = None
|
|
22
|
+
cache = None
|
|
23
|
+
try:
|
|
24
|
+
connection = new_project_connection(project, CONNECTION_NAME)
|
|
25
|
+
registry = dex.Registry([RecordRefundFlow(connection)], allow_async_handlers=True)
|
|
26
|
+
cache_directory = os.environ.get(
|
|
27
|
+
"DEX_BLOB_CACHE_DIR", str(Path(tempfile.gettempdir()) / "dex-sqlserver-refund-blobs")
|
|
28
|
+
)
|
|
29
|
+
cache = dex.open_blob_cache(dex.BlobCacheConfig(cache_directory, 1 << 30))
|
|
30
|
+
worker = dex.AsyncWorker(
|
|
31
|
+
registry,
|
|
32
|
+
cache,
|
|
33
|
+
dex.WorkerOptions(server_address=os.environ.get("DEX_FLOW_SERVICE_ADDRESS", "localhost:8801")),
|
|
34
|
+
)
|
|
35
|
+
async with worker:
|
|
36
|
+
await worker.start()
|
|
37
|
+
finally:
|
|
38
|
+
if connection is not None:
|
|
39
|
+
await connection.aclose()
|
|
40
|
+
if cache is not None:
|
|
41
|
+
cache.close()
|
|
42
|
+
await project.close()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main() -> None:
|
|
46
|
+
"""Serve refund Flows until interrupted."""
|
|
47
|
+
asyncio.run(run_worker())
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__":
|
|
51
|
+
main()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dex-connector-microsoft-sql-server"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Microsoft SQL Server connector for Dex Flows"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = ["dex-connectors-sdk==0.1.0", "dex-python-sdk>=1.28.0", "python-tds>=1.17.1,<1.18", "pyOpenSSL>=24,<27", "cryptography>=42,<51", "certifi>=2024.2.2", "httpx>=0.27"]
|
|
14
|
+
|
|
15
|
+
[dependency-groups]
|
|
16
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.24", "mypy>=1.13", "ruff>=0.7"]
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["src/dex_connectors"]
|
|
20
|
+
|
|
21
|
+
[tool.pytest.ini_options]
|
|
22
|
+
testpaths = ["tests"]
|
|
23
|
+
pythonpath = [".", "src"]
|
|
24
|
+
norecursedirs = ["integration"]
|
|
25
|
+
asyncio_mode = "auto"
|
|
26
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
27
|
+
|
|
28
|
+
[tool.mypy]
|
|
29
|
+
python_version = "3.11"
|
|
30
|
+
strict = true
|
|
31
|
+
mypy_path = "src"
|
|
32
|
+
explicit_package_bases = true
|
|
33
|
+
|
|
34
|
+
[tool.ruff]
|
|
35
|
+
target-version = "py311"
|
|
36
|
+
line-length = 110
|
|
37
|
+
|
|
38
|
+
[tool.ruff.lint]
|
|
39
|
+
select = ["E", "F", "I", "UP", "B"]
|
|
@@ -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
|
+
]
|