mssql-python Adapter¶
from sqlspec.adapters.mssql_python import (
MssqlPythonBulkCopyResult,
MssqlPythonConfig,
MssqlPythonConnectionParams,
MssqlPythonConnectionPool,
MssqlPythonDriver,
MssqlPythonDriverFeatures,
MssqlPythonExceptionHandler,
MssqlPythonPoolParams,
MssqlPythonSessionContextStrategy,
)
Microsoft SQL Server and Azure SQL adapter built on Microsoft's official mssql-python driver with native Bulk Copy (BCP) support. Inherited execution methods are documented on SyncDriverAdapterBase. See the SQL Server Setup Guide for setup and bulk copy examples, and the SQL Server Data Dictionary & SQL Catalog.
Configuration & Parameters¶
MssqlPythonConfig
¶
Bases: SyncDatabaseConfig[MssqlPythonConnection, MssqlPythonConnectionPool, MssqlPythonDriver]
Configuration for mssql-python synchronous database connections.
MssqlPythonConnectionParams
¶
Bases: TypedDict
mssql-python connection parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
connection_string |
NotRequired[str]
|
Full ODBC/TDS semicolon-delimited connection string passed to |
host |
NotRequired[str]
|
Alias for the SQL Server endpoint. |
server |
NotRequired[str]
|
SQL Server hostname, |
address |
NotRequired[str]
|
ODBC |
addr |
NotRequired[str]
|
ODBC |
port |
NotRequired[int]
|
SQL Server TCP port (defaults to |
database |
NotRequired[str]
|
Initial SQL Server or Azure SQL database name. |
db |
NotRequired[str]
|
Alias normalized to |
uid |
NotRequired[str]
|
SQL authentication login ID. |
user |
NotRequired[str]
|
Alias normalized to |
username |
NotRequired[str]
|
Alias normalized to |
pwd |
NotRequired[str]
|
SQL authentication password. |
password |
NotRequired[str]
|
Alias normalized to |
authentication |
NotRequired[str]
|
ODBC |
trusted_connection |
NotRequired[bool | str]
|
Use integrated Windows / Kerberos authentication ( |
trust_server_certificate |
NotRequired[bool | str]
|
Bypass TLS server certificate chain validation ( |
trust |
NotRequired[bool | str]
|
Short alias for |
encrypt |
NotRequired[bool | str]
|
TLS encryption policy ( |
hostname_in_certificate |
NotRequired[str]
|
Expected DNS subject name validated in the server TLS certificate. |
hostnameincertificate |
NotRequired[str]
|
ODBC keyword alias for |
server_certificate |
NotRequired[str]
|
Filesystem path to an expected server certificate file for pinning. |
servercertificate |
NotRequired[str]
|
ODBC keyword alias for |
server_spn |
NotRequired[str]
|
Kerberos Service Principal Name for the SQL Server target. |
serverspn |
NotRequired[str]
|
ODBC keyword alias for |
multi_subnet_failover |
NotRequired[bool | str]
|
Enable parallel IP connection attempts for Always On availability groups. |
multisubnetfailover |
NotRequired[bool | str]
|
ODBC keyword alias for |
application_intent |
NotRequired[str]
|
Availability group workload routing intent ( |
applicationintent |
NotRequired[str]
|
ODBC keyword alias for |
connect_retry_count |
NotRequired[int]
|
Number of automatic connection retry attempts on broken idle connections. |
connectretrycount |
NotRequired[int]
|
ODBC keyword alias for |
connect_retry_interval |
NotRequired[int]
|
Delay in seconds between automatic connection recovery attempts. |
connectretryinterval |
NotRequired[int]
|
ODBC keyword alias for |
keep_alive |
NotRequired[int]
|
TCP keepalive idle interval in milliseconds. |
keepalive |
NotRequired[int]
|
ODBC keyword alias for |
keep_alive_interval |
NotRequired[int]
|
Interval in milliseconds between TCP keepalive probes. |
keepaliveinterval |
NotRequired[int]
|
ODBC keyword alias for |
ip_address_preference |
NotRequired[str]
|
Address family preference during DNS resolution ( |
ipaddresspreference |
NotRequired[str]
|
ODBC keyword alias for |
packet_size |
NotRequired[int]
|
TDS network packet size in bytes. |
packetsize |
NotRequired[int]
|
ODBC keyword alias for |
connection_timeout |
NotRequired[int]
|
Connection establishment timeout in seconds. |
login_timeout |
NotRequired[int]
|
Login handshake timeout in seconds. |
command_timeout |
NotRequired[int]
|
Default SQL statement execution timeout in seconds. |
autocommit |
NotRequired[bool]
|
Enable autocommit mode on new |
attrs_before |
NotRequired[dict[int, int | str | bytes]]
|
Pre-connect SQL_ATTR_* ODBC connection attributes dictionary (such as access tokens). |
timeout |
NotRequired[int]
|
Query execution timeout in seconds assigned on the connection. |
native_uuid |
NotRequired[bool]
|
Return |
token_provider |
NotRequired[TokenProvider]
|
Callable or Entra ID credential provider supplying OAuth access tokens. |
extra |
NotRequired[dict[str, Any]]
|
Additional connection attributes forwarded to |
MssqlPythonPoolParams
¶
Bases: MssqlPythonConnectionParams
mssql-python driver-level pooling parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
pool_size |
NotRequired[int]
|
Maximum number of connections retained in |
pool_idle_timeout |
NotRequired[int]
|
Idle duration in seconds before pooled SQL Server connections are closed. |
pool_enabled |
NotRequired[bool]
|
Enable |
MssqlPythonDriverFeatures
¶
Bases: TypedDict
mssql-python driver feature flags.
Attributes:
| Name | Type | Description |
|---|---|---|
tenant_strategy |
NotRequired[SyncTenantStrategy | TenantStrategyShorthand | None]
|
Opt-in tenant strategy, or the |
enable_pooling |
NotRequired[bool]
|
Enable SQLSpec connection pooling around |
json_serializer |
NotRequired[Callable[[Any], str]]
|
Custom JSON serializer applied to bound JSON parameters (defaults to |
json_deserializer |
NotRequired[Callable[[str], Any]]
|
Custom JSON deserializer applied to JSON result columns (defaults to |
on_connection_create |
NotRequired[Callable[[MssqlPythonConnection], None]]
|
Synchronous hook invoked with each raw |
enable_events |
NotRequired[bool]
|
Enable durable table-backed SQLSpec event queue support. |
events_backend |
NotRequired[Literal['poll_queue']]
|
Event channel backend ( |
Tenant Strategies¶
Set driver_features={"tenant_strategy": "rls"} ("session_context", "default", and True select the same strategy). Enabling a tenant strategy automatically defaults pool_enabled to False when omitted from connection_config and rejects explicit pool_enabled=True. Because mssql-python sets driver pooling process-wide, any non-tenant administrative MssqlPythonConfig in the same process must still pass connection_config={"pool_enabled": False, ...} before opening its first connection; conflicting process-wide pooling modes fail construction.
Checkout captures and applies mutable owned keys, then verifies their values in one SQL batch. Checkin restores and verifies them in one batch. Keys use @read_only=0; values are bound. Strategies do not commit, roll back, or toggle autocommit. Both providers run the lease; cleanup failure physically closes the unpooled connection.
Missing tenant identity raises TenantContextError before acquisition. Failed cleanup raises TenantCleanupError when no body exception is pending; otherwise the body error keeps its identity and receives a cleanup note. See Multi-Tenancy and Tenant Operations.
MssqlPythonSessionContextStrategy
¶
Bases: MssqlTenantSettings
Apply and restore owned mutable keys with one verified SQL batch per boundary.
Driver, Pool & Data Dictionary¶
MssqlPythonDriver
¶
Bases: SyncDriverAdapterBase
mssql-python sync driver.
bulk_copy
¶
bulk_copy(
target_table,
rows,
*,
batch_size=0,
timeout=30,
column_mappings=None,
keep_identity=False,
check_constraints=False,
table_lock=False,
keep_nulls=False,
fire_triggers=False,
use_internal_transaction=False,
)
Bulk insert rows via mssql-python cursor.bulkcopy().
MssqlPythonBulkCopyResult
¶
Bases: TypedDict
BulkCopy statistics returned by mssql-python.
Attributes:
| Name | Type | Description |
|---|---|---|
rows_copied |
int
|
Total number of rows inserted via TDS |
batch_count |
NotRequired[int]
|
Number of bulk-copy batches committed during the transfer. |
elapsed_time |
NotRequired[float]
|
Wall-clock bulk-copy execution time in seconds. |
MssqlPythonExceptionHandler
¶
MssqlPythonConnectionPool
¶
Small SQLSpec pool facade over mssql-python's driver-level pooling.
MssqlPythonSyncDataDictionary
¶
Extension Stores & Configs¶
MssqlPythonStore
¶
Bases: BaseSQLSpecStore['MssqlPythonConfig']
SQL Server-backed session store using mssql-python sync sessions.
MssqlPythonADKConfig
¶
Bases: ADKConfig
mssql-python ADK extension settings.
Attributes:
| Name | Type | Description |
|---|---|---|
native_json |
NotRequired[bool]
|
Force native SQL Server JSON columns when True, or NVARCHAR(MAX) when False. |