Skip to content

pymssql Adapter

from sqlspec.adapters.pymssql import (
    PymssqlConfig,
    PymssqlConnectionParams,
    PymssqlConnectionPool,
    PymssqlDriver,
    PymssqlDriverFeatures,
    PymssqlExceptionHandler,
    PymssqlPoolParams,
    PymssqlSessionContextStrategy,
)

Synchronous Microsoft SQL Server adapter built on pymssql (FreeTDS). Inherited execution methods are documented on SyncDriverAdapterBase. See the SQL Server Setup Guide for usage examples and the SQL Server Data Dictionary & SQL Catalog.

Configuration & Parameters

PymssqlConfig

Bases: SyncDatabaseConfig[PymssqlConnection, PymssqlConnectionPool, PymssqlDriver]

Configuration for pymssql synchronous connections.

PymssqlConnectionParams

Bases: TypedDict

pymssql connection parameters.

Attributes:

Name Type Description
server NotRequired[str]

SQL Server hostname, host:port, or host\instance target.

host NotRequired[str]

Alias for server accepted by pymssql.connect.

user NotRequired[str]

SQL Server or Windows domain login (DOMAIN\user).

password NotRequired[str]

Password for user.

db NotRequired[str]

Alias for the target database.

username NotRequired[str]

Alias for the authentication user.

database NotRequired[str]

Initial SQL Server database selected on connect.

port NotRequired[int | str]

SQL Server TCP port (defaults to 1433).

timeout NotRequired[PymssqlTimeout]

Query response timeout in seconds (0 means wait indefinitely).

login_timeout NotRequired[PymssqlTimeout]

Connection and authentication timeout in seconds (defaults to 60).

charset NotRequired[str]

Character encoding communicated over FreeTDS (defaults to 'UTF-8').

as_dict NotRequired[bool]

Return rows from raw pymssql cursors as dictionaries instead of tuples.

appname NotRequired[str]

Application name visible in sys.dm_exec_sessions.

conn_properties NotRequired[str]

Semicolon-separated SET session statements run immediately upon connect.

autocommit NotRequired[bool]

Enable autocommit mode on new pymssql connections.

tds_version NotRequired[str]

Explicit FreeTDS protocol version (such as '7.4').

encryption NotRequired[Literal['off', 'request', 'require']]

FreeTDS TLS transport encryption requirement (off, request, or require).

use_datetime2 NotRequired[bool]

Bind Python datetime values using DATETIME2 precision instead of legacy DATETIME.

arraysize NotRequired[int]

Default row batch count returned by cursor.fetchmany().

conv NotRequired[Mapping[int | type[Any], Callable[..., Any]]]

Custom FreeTDS type serialization/deserialization mapping.

read_only NotRequired[bool]

Set Always On ApplicationIntent=ReadOnly during login.

pool_recycle_seconds NotRequired[int]

Maximum connection age in seconds before PymssqlConnectionPool recycles connections.

health_check_interval NotRequired[float]

Minimum interval in seconds between connection health checks in PymssqlConnectionPool.

extra NotRequired[dict[str, Any]]

Additional keyword arguments forwarded to pymssql.connect.

PymssqlPoolParams

Bases: PymssqlConnectionParams

pymssql pool parameters.

PymssqlDriverFeatures

Bases: TypedDict

Optional pymssql driver feature flags for JSON serialization, connection hooks, and events.

Attributes:

Name Type Description
tenant_strategy NotRequired[SyncTenantStrategy | TenantStrategyShorthand | None]

Opt-in tenant strategy, or the "session_context" shorthand, applied to every session and connection lease.

json_serializer NotRequired[Callable[[Any], str]]

Custom JSON serializer applied to bound JSON parameters (defaults to to_json).

json_deserializer NotRequired[Callable[[str], Any]]

Custom JSON deserializer applied to JSON result columns (defaults to from_json).

on_connection_create NotRequired[Callable[[PymssqlConnection], None]]

Synchronous hook invoked with each raw pymssql.Connection upon creation.

enable_events NotRequired[bool]

Enable durable table-backed SQLSpec event queue support.

events_backend NotRequired[Literal['poll_queue']]

Event channel backend (poll_queue is the sole SQL Server backend).

enable_pooling NotRequired[bool]

Enable driver-level connection pooling (defaults to True).

enable_uuid_conversion NotRequired[bool]

Enable automatic UUID string-to-object conversions.

Tenant Strategies

Set driver_features={"tenant_strategy": "rls"}; "session_context", "default", and True select the same strategy. Both providers use one standalone connection per lease rather than the normal thread-local connection. Cleanup or setup failure physically closes that connection. Standalone create_connection() is rejected in tenant mode.

Each boundary uses one bound SQL batch: capture/apply/verify at checkout, restore/verify at checkin. Owned keys remain mutable (@read_only=0). The strategy neither commits nor rolls back nor changes autocommit. The lease rolls back unfinished work before cleanup and closes its standalone connection after release.

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.

PymssqlSessionContextStrategy

Bases: MssqlTenantSettings

Apply and restore owned mutable keys with one verified SQL batch per boundary.

__init__

__init__(*, tenant_key=DEFAULT_MSSQL_TENANT_KEY, variable_keys=None)

checkout

checkout(connection, payload)

Capture previous settings, bind identity and verify the resulting values.

checkin

checkin(connection, state)

Restore and verify only this lease's captured settings.

Driver, Pool & Data Dictionary

PymssqlDriver

Bases: SyncDriverAdapterBase

SQL Server database driver using pymssql.

PymssqlExceptionHandler

Bases: BaseSyncExceptionHandler

Context manager for handling pymssql exceptions.

PymssqlConnectionPool

Thread-local connection manager for pymssql.

PymssqlSyncDataDictionary

Bases: _MssqlDataDictionaryMixin, SyncDataDictionaryBase

MSSQL sync data dictionary.

Extension Stores & Configs

PymssqlStore

Bases: BaseSQLSpecStore['PymssqlConfig']

SQL Server-backed session store using pymssql sync sessions.

PymssqlADKConfig

Bases: ADKConfig

pymssql ADK extension settings.

Attributes:

Name Type Description
native_json NotRequired[bool]

Force native SQL Server JSON columns when True, or NVARCHAR(MAX) when False.

PymssqlADKStore

Bases: BaseSyncADKStore['PymssqlConfig']

Synchronous pymssql ADK session/event store.

PymssqlADKMemoryStore

Bases: BaseSyncADKMemoryStore['PymssqlConfig']

SQL Server ADK memory store using pymssql.

PymssqlEventQueueStore

Bases: BaseEventQueueStore[PymssqlConfig]

T-SQL DDL hooks for the event queue store.