SQL Server (TDS) wire protocol implementation

This page describes how SynergyDB implements Microsoft's Tabular Data Stream (TDS) protocol and the T-SQL language on top of it. It is the implementation reference. Scores, connection strings, known gaps and how to re-run the proofs are on the operator page, SQL Server. Authentication policy across all wires is in Security, and config keys are in the Configuration reference.

Code lives in src/protocol/mssql/:

File Role
mod.rs MsSqlHandler: listener, TLS sniffing, packet loop, PRELOGIN and LOGIN7, RPC framing, sp_reset_connection, session cleanup
tds.rs Packet header, packet types, PRELOGIN encoding, token types, ENVCHANGE codes, LOGINACK and DONE encoding
tls.rs Encryption negotiation table and the TLS-inside-PRELOGIN transport (PreloginIo)
lex.rs T-SQL tokenizer (brackets, N'..', @vars, #temp)
batch.rs Batch parser: control flow, DECLARE, SET, TRY/CATCH, EXEC, CREATE PROCEDURE
tsql.rs tsql::Exec: the interpreter, statement dispatch, function and catalog translation, transactions, RPC, error mapping
rowenc.rs Result column type inference, row encoding, PLP chunking, RPC parameter decoding
types.rs SqlServerType, TdsValue, ColumnMetadata used by the legacy in-memory path

Shared pieces: src/protocol/tls.rs (rustls config, plaintext_allowed), src/auth/wire_auth.rs (credential check and failed-login delay), src/query/mssql_funcs.rs (__tds_* engine builtins). TLS uses the tokio-rustls / rustls crates.

1. Listener and connection lifecycle

The server starts the handler when mssql_port is set (default 1433), built as MsSqlHandler::with_storage(storage).with_tls(tls_config). (source: src/server/mod.rs, the SQL Server block of server start-up; src/config.rs, port defaults)

MsSqlHandler::with_storage builds a tsql::Shared value (storage, an identity lock and the routine registry) shared by all connections. Each connection gets an SPID; SPIDs start at 51. (source: src/protocol/mssql/mod.rs, MsSqlHandler::with_storage, next_spid)

handle_connection works as follows (source: src/protocol/mssql/mod.rs, handle_connection):

  1. With TLS configured, it peeks the first byte with a 30 s timeout. A first byte of 0x16 (a TLS ClientHello) means TDS 8.0 strict mode: the TLS handshake runs at once with the tds/8.0 ALPN configuration, and TDS runs inside TLS from the first packet. Any other first byte continues in plaintext.
  2. It creates one QueryEngine per connection with set_mssql_dialect(true), and a tsql::ConnState.
  3. It runs serve_connection (section 3).
  4. On close, for any reason, it calls abort_open_transaction, then drops the session's local temporary tables ("<name>__s<spid>") and their __catalog__:tds_ident: identity keys.

Global temporary tables (##t) keep their plain name and are not dropped when the session ends. Not verified: no test covers ##t lifetime. (source: src/protocol/mssql/tsql.rs, temp-table name mapping; src/protocol/mssql/mod.rs, connection cleanup)

2. Pre-login, TLS and LOGIN7

2.1 PRELOGIN

The server answers PRELOGIN (packet type 0x12) with VERSION 16.0.4135, an ENCRYPTION byte from the negotiation table below, and MARS 0. It writes only the VERSION, ENCRYPTION and MARS options. (source: src/protocol/mssql/mod.rs, serve_connection; src/protocol/mssql/tds.rs, PreLoginPacket)

Encryption values are ENCRYPT_OFF = 0, ENCRYPT_ON = 1, ENCRYPT_NOT_SUP = 2, ENCRYPT_REQ = 3. tls::negotiate(client, tls, plaintext_ok) masks off the high bit of the client's byte and decides (source: src/protocol/mssql/tls.rs, negotiate; test negotiation_table, reads_encryption_option):

TLS configured Client sends Plaintext allowed for peer Server answers Effect
No anything n/a NOT_SUP Plaintext session
Yes NOT_SUP or no option yes NOT_SUP Plaintext session
Yes NOT_SUP or no option no REQ Connection refused and closed
Yes OFF yes OFF TLS handshake; login packet encrypted, then back to plaintext (login-only)
Yes OFF no REQ Full TLS for the session
Yes ON, REQ, other either ON Full TLS for the session

"Plaintext allowed" is crate::protocol::tls::plaintext_allowed(require_tls, peer): true unless [tls] require_tls is set, and always true for loopback peers. (source: src/protocol/tls.rs, plaintext_allowed)

2.2 TLS inside TDS

For TDS 7.x the TLS handshake records travel inside PRELOGIN packets (type 0x12) of up to 4096 bytes, through tls::PreloginIo. That configuration allows TLS 1.2 only and sets no ALPN. The strict (TDS 8.0) configuration allows TLS 1.3 and 1.2 and advertises ALPN tds/8.0. With login-only encryption the connection returns to plaintext after the LOGIN7 packet (login_only flag). (source: src/protocol/mssql/tls.rs, TdsTls, PreloginIo; src/protocol/mssql/mod.rs, serve_connection, start_tls)

Not verified: the TLS transport has no unit test in the snapshot. The status entry 2026-11-30-tls-remaining-wires.md, cited by the security guide, is the only evidence that drivers complete these handshakes.

2.3 LOGIN7

handle_login decodes LOGIN7 (packet type 0x10) (source: src/protocol/mssql/mod.rs, handle_login):

  • Strings are UCS-2 at offsets relative to the login body (offset minus 94 from the fixed header).
  • The password is de-obfuscated by swapping nibbles and XOR with 0xA5.
  • Requested packet size 0 becomes 4096; any other value is clamped to 512..32767.
  • Credentials go to wire_auth::verify_credential(storage, None, user, password), which checks the catalog's Argon2id hash in a timing-safe way and applies the shared failed-login delay. On failure the server sends error 18456 Login failed for user '<name>'. and closes.
  • A requested database that does not exist gives error 4060 (class 11) followed by 18456 (class 14).

On success the server sends, in order (source: src/protocol/mssql/mod.rs, handle_login):

Token Content
ENVCHANGE type 1 Database
ENVCHANGE type 4 Packet size, new value and old value 4096
INFO 5701 Changed database context
ENVCHANGE type 7 SQL collation bytes 09 04 D0 00 34 (SQL_Latin1_General_CP1_CI_AS)
LOGINACK TDS version 0x74000004, server version 16.0
DONE  

No FEATUREEXTACK is sent, so no feature extension (column encryption, session recovery, UTF-8, federated authentication) is acknowledged. (source: src/protocol/mssql/mod.rs, handle_login)

The engine session is then set with AuthenticatedSession::resolve_from_catalog(..., username, "synergydb"), so table privileges and row-level security apply to the login. (source: src/protocol/mssql/mod.rs, serve_connection)

2.4 Built-in users

MsSqlAuthConfig::new() creates no users. Well-known development users are provisioned only when SYNERGYDB_DEV_INSECURE_AUTH is 1 or true. validate uses Argon2id with a dummy hash for unknown names. (source: src/protocol/mssql/mod.rs, MsSqlAuthConfig::new, validate; tests test_default_users_gated_behind_dev_flag in mod.rs and the auth-config tests in tests/protocol_mssql.rs)

3. Packet dispatch

serve_connection reassembles packets until the EOM status bit or an Attention packet. The negotiated packet size is clamped to 512..32767. (source: src/protocol/mssql/mod.rs, serve_connection)

Type Name Handling
0x01 SQL Batch tsql::Exec::run_batch, run off the async worker through PostgresHandler::run_engine
0x02 Pre-TDS7 Login Error 8002 "Unsupported packet type"
0x03 RPC run_rpc_request (section 6)
0x04 Tabular Result Server-to-client only
0x06 Attention DONE with the attention flag (handle_attention)
0x07 Bulk Load Error 8002
0x08 Federated Auth Token Error 8002
0x0E Transaction Manager run_tm_request (section 8)
0x10 TDS7 Login handle_login
0x11 SSPI Error 8002
0x12 PRELOGIN Negotiation and TLS (section 2)

SQL Batch, RPC or Transaction Manager before login gets error 18456 "Login failed: log in before sending requests." and the connection closes. (source: src/protocol/mssql/mod.rs, serve_connection; src/protocol/mssql/tds.rs, PacketType; tests test_header_encode_decode, header_length_below_header_size_is_rejected)

The ALL_HEADERS block of a batch or RPC is read for the RESETCONNECTION status bits: 0x08 runs reset_session, and 0x10 (RESETCONNECTIONSKIPTRAN) keeps an open transaction. reset_session resets NOCOUNT, XACT_ABORT, IDENTITY_INSERT, @@IDENTITY, @@ROWCOUNT, @@ERROR, prepared handles, cursors, @@FETCH_STATUS (to -1), the isolation level (to 2) and the database, drops session temp tables, and rolls back unless the skip bit is set. No ENVCHANGE acknowledges the reset. (source: src/protocol/mssql/mod.rs, reset_session; docs/status/2026-11-24-mssql-efcore-15-of-15.md)

Not verified: Attention handling only answers with DONE; whether a running statement is interrupted is not shown in the code read, and no test covers it.

Legacy handlers (handle_sql_batch, handle_rpc, handle_transaction, the in-memory MsSqlTable) run only when the handler has no storage, which happens only in unit tests. Not wired: these paths are not reachable from a running server. (source: src/protocol/mssql/mod.rs, serve_connection)

4. Response encoding

Token types written: COLMETADATA, ROW, DONE, DONEPROC, DONEINPROC, ENVCHANGE, ERROR, INFO, LOGINACK, RETURNVALUE (0xAC), RETURNSTATUS (0x79). ENVCHANGE codes defined are 1 (database), 2 (language), 3 (charset), 4 (packet size), 7 (SQL collation), 8 (begin transaction), 9 (commit), 10 (rollback), 11, 12 and 20. (source: src/protocol/mssql/tds.rs, TokenType, EnvChangeType; tests test_login_ack, test_done_token, test_prelogin_encode)

Every response ends with a DONE; all but the last DONE carry DONE_MORE. Statement results end with DONE or DONEINPROC with status 0x02 (count valid) unless NOCOUNT is on. ERROR tokens name the server SynergyDB. finish_packets(psize) splits the stream into packets and re-aligns PLP chunks to packet boundaries, which SqlClient needs for long text. (source: src/protocol/mssql/tsql.rs, report, finish_packets; src/protocol/mssql/rowenc.rs, test plp_chunks_end_at_packet_boundaries; docs/status/2026-11-24-mssql-sqlclient-long-text.md)

5. Result type mapping

5.1 Engine type to TDS type

rowenc::sql_type_for_oid maps the engine's result column type to a TDS type (source: src/protocol/mssql/rowenc.rs, sql_type_for_oid):

Engine type (OID) TDS type
bool (16) BIT
int2 (21) SMALLINT
int4 (23) INT
int8 (20) BIGINT
float4 (700) REAL
float8 (701) FLOAT
numeric (1700) DECIMAL(38,0) before scale inference
money (790) MONEY
date (1082) DATE
time, timetz (1083, 1266) TIME(7)
timestamp (1114) DATETIME2(7)
timestamptz (1184) DATETIMEOFFSET(7)
uuid (2950) UNIQUEIDENTIFIER
bytea (17) VARBINARY
anything else NVARCHAR

When the statement declares a type (a table column, CAST, a variable), tsql::sql_type_for_decl gives the wire type instead. Fractional-second scales are capped at 7. text, varchar and char declarations map to VARCHAR; other character types map to NVARCHAR; ntext and xml map to NVARCHAR(MAX). (source: src/protocol/mssql/tsql.rs, sql_type_for_decl)

rowenc::finalize_types then adjusts each column from the actual values (source: src/protocol/mssql/rowenc.rs, finalize_types; test decimal_scaling):

  • DECIMAL takes the widest scale seen in the column; a declared (p,s) keeps its scale.
  • An integer value that does not fit the column type widens it to the next integer type.
  • A VARCHAR column holding characters outside code page 1252 becomes NVARCHAR.
  • Text over 4000 UTF-16 units becomes MAX; VARBINARY over 16002 bytes becomes MAX.

5.2 TDS type info bytes

TDS type Wire byte and info
INTN 0x26, length 1/2/4/8
BITN 0x68
FLTN 0x6D
DECIMALN 0x6A, length 17, precision, scale
MONEYN 0x6E
DATE 0x28
TIME 0x29, scale
DATETIME2 0x2A, scale
DATETIMEOFFSET 0x2B, scale
DATETIMN 0x6F
GUID 0x24
BIGVARBINARY 0xA5, 8000 or 0xFFFF (MAX, PLP)
NVARCHAR 0xE7, length, collation
BIGVARCHAR 0xA7, length, collation

(source: src/protocol/mssql/rowenc.rs, encode_type_info; test datetime_offset_text)

5.3 T-SQL DDL type to engine type

tsql::pg_type rewrites column types in DDL and CAST (source: src/protocol/mssql/tsql.rs, pg_type; test tsql_types_map_to_engine_types):

T-SQL type Engine type
int INTEGER
bigint BIGINT
smallint, tinyint SMALLINT
bit BOOLEAN
decimal, numeric with no arguments NUMERIC(18,0)
money NUMERIC(19,4)
smallmoney NUMERIC(10,4)
float(n) with n up to 24, real REAL
float (other) DOUBLE PRECISION
date DATE
time TIME
datetime, datetime2, smalldatetime TIMESTAMP
datetimeoffset TIMESTAMPTZ
char, nchar CHAR(n)
varchar, nvarchar VARCHAR(n)
varchar(max), nvarchar(max) TEXT
text, ntext, xml, sql_variant, hierarchyid TEXT
sysname VARCHAR(128)
binary, varbinary, image, rowversion, timestamp BYTEA
uniqueidentifier UUID

A DATETIMEOFFSET column is stored as TIMESTAMPTZ, normalized to UTC, which is why it comes back in UTC (the README known gap). DATETIMEOFFSET expressions keep their offset as canonical text and sort by instant through __tds_* builtins. (source: src/protocol/mssql/tsql.rs, pg_type; src/query/mssql_funcs.rs, dto_sort_key)

tinyint is stored as SMALLINT; a value outside 0..255 is rejected with error 220. xml, sql_variant and hierarchyid are plain TEXT with no type-specific behaviour. SERVERPROPERTY is reported as NVARCHAR, not sql_variant. (source: src/protocol/mssql/tsql.rs, pg_type, map_engine_error; docs/status/2026-11-30-mssql-result-column-types-2.md)

6. RPC requests and stored procedures

6.1 RPC framing

run_rpc_request parses one or more RPC calls in a packet, separated by the batch flags 0x80, 0xFF or 0xFE. A procedure is named either by text or by a numeric id. A parse failure gives error 8016. (source: src/protocol/mssql/mod.rs, run_rpc_request)

Parameter types accepted by rowenc::read_rpc_params / read_typed_value (source: src/protocol/mssql/rowenc.rs, read_typed_value; test rpc_int_and_nvarchar_roundtrip):

Accepted Not accepted (error 8016)
fixed and nullable integers, BIT, FLOAT/REAL, MONEY, DATETIME family, DECIMAL/NUMERIC, DATE, TIME, DATETIME2, DATETIMEOFFSET, CHAR/VARCHAR/NCHAR/NVARCHAR/BINARY/VARBINARY including MAX (PLP), TEXT/NTEXT/IMAGE, XML (0xF1, read as NVARCHAR(MAX)) table-valued parameters (0xF3), sql_variant, CLR UDT

6.2 RPC procedures

rpc_proc_name maps ids 1 to 15 (sp_cursor .. sp_unprepare) to names. tsql::Exec::run_rpc then handles (source: src/protocol/mssql/tsql.rs, run_rpc, rpc_proc_name):

Procedure Behaviour
sp_executesql Runs @statement with the declared parameters; missing @statement is error 201
sp_prepare Stores the statement and returns a handle
sp_prepexec Prepare and execute in one call
sp_execute Runs a prepared handle; unknown handle is error 8179
sp_unprepare Drops a handle
sp_prepexecrpc ODBC {CALL ...} form (RPC_CALL_MARK)
any other name run_named_proc: system procedure or user procedure

OUTPUT parameters come back as RETURNVALUE tokens, then RETURNSTATUS, then DONEPROC. (source: src/protocol/mssql/tsql.rs, run_rpc; docs/status/2026-11-24-mssql-odbc-call.md)

Not implemented: the API server cursor procedures sp_cursor, sp_cursoropen, sp_cursorprepare, sp_cursorexecute, sp_cursorprepexec, sp_cursorunprepare, sp_cursorfetch, sp_cursoroption, sp_cursorclose (ids 1 to 9). They fall through to the user-procedure lookup and fail with 2812 "Could not find stored procedure". (source: src/protocol/mssql/tsql.rs, run_rpc, exec_proc)

6.3 EXEC and system procedures

exec_proc resolves sp_executesql, the system procedures below, then user procedures from shared.proc_def by bare name or dbo./bracketed name. Errors: not found 2812 (aborts the batch), unknown named parameter 8145, too many arguments 8144, nesting deeper than 32 gives 217. (source: src/protocol/mssql/tsql.rs, exec_proc)

System procedure Notes
sp_tables, sp_columns, sp_pkeys, sp_fkeys, sp_helpindex Catalog result sets
sp_rename Table and column rename
sp_getapplock, sp_releaseapplock pg_try_advisory[_xact]_lock on a hash of the resource, polled every 20 ms until @LockTimeout (default -1 waits forever). @LockOwner = 'Transaction' outside a transaction is error 1223 and returns -999
sp_reset_connection Same as the RESETCONNECTION bit (section 3)

(source: src/protocol/mssql/tsql.rs, system_proc)

CREATE PROCEDURE stores the body under __catalog__:tds_proc: and __catalog__:tds_procs. Procedures run in the interpreter with their own variable scope. (source: src/protocol/mssql/tsql.rs, exec_proc; src/protocol/mssql/batch.rs, Stmt::CreateProc)

7. T-SQL interpreter

7.1 Batch execution

run_batch / run_text tokenize the batch (lex::tokenize), pad catalog type literals, and parse it with batch::parse_batch into statements, then run_list executes them. GO is a client-side separator and is not handled by the server. (source: src/protocol/mssql/tsql.rs, run_batch, run_text; src/protocol/mssql/batch.rs, parse_batch; test splits_batches_without_semicolons)

Error handling in a batch (source: src/protocol/mssql/tsql.rs, run_list):

  • With XACT_ABORT ON and an open transaction, an error rolls back everything and aborts the batch.
  • An error that aborts the batch, or any error inside TRY, propagates.
  • Otherwise the error is reported and the next statement runs.

Statement kinds parsed by batch.rs (source: src/protocol/mssql/batch.rs, Stmt; test param_declarations_parse):

Kind Notes
SQL statement Sent to exec_sql_inner
DECLARE Scalar variables, table variables, cursors
SET @v =, SELECT @v = Variable assignment
SET <option> Section 7.3
IF / ELSE, BEGIN ... END  
WHILE, BREAK, CONTINUE A loop stops after 10,000,000 iterations with error 50000
BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH ERROR_NUMBER() etc. available in CATCH
BEGIN TRAN, COMMIT, ROLLBACK [name], SAVE TRAN Section 8
EXEC proc, EXEC (@sql)  
RAISERROR, THROW, PRINT, RETURN THROW with no arguments rethrows (10704 outside CATCH)
CREATE PROCEDURE  
USE db Unknown database is error 911

7.2 Statement dispatch

exec_sql_inner routes each SQL statement (source: src/protocol/mssql/tsql.rs, exec_sql_inner):

Statement Handling
SELECT, WITH ... Rewritten to engine SQL; CTE followed by SELECT or DML
INSERT, UPDATE, DELETE, MERGE Wrapped in with_trigger_txn so triggers and the statement are atomic; OUTPUT supported; MERGE matching a target row twice is error 8672
CREATE/ALTER FUNCTION, CREATE/ALTER TRIGGER, DROP FUNCTION/TRIGGER Interpreter objects (7.5)
DECLARE/OPEN/FETCH/CLOSE/DEALLOCATE cursor Interpreter-side T-SQL cursors
DBCC CHECKIDENT Reseeds an identity
CREATE/ALTER/DROP DATABASE Database registry (7.6)
CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE TABLE TRUNCATE also resets the identity
CREATE/ALTER VIEW, CREATE OR ALTER ...  
DROP PROCEDURE/PROC/VIEW/INDEX  
Other CREATE/ALTER/DROP CLUSTERED, NONCLUSTERED, INCLUDE(...), WITH(...) and ON [PRIMARY] are stripped; errors from SCHEMA, DATABASE, LOGIN and USER statements are ignored; DROP SCHEMA in use is 3729
GRANT, REVOKE, DENY, other DBCC, CHECKPOINT, WAITFOR No-ops that return DONE
anything else Error 102 (syntax)

Because GRANT, REVOKE and DENY are no-ops on this wire, permissions must be managed over a wire that executes them. WAITFOR does not wait. (source: src/protocol/mssql/tsql.rs, exec_sql_inner)

Query features translated in tsql.rs: TOP, FOR XML (rewrite_for_xml), FOR JSON, PIVOT / UNPIVOT, OPENJSON, STRING_SPLIT, GENERATE_SERIES, CROSS APPLY / OUTER APPLY, sequences and NEXT VALUE FOR, bracketed identifiers, and LIKE bracket classes (rewritten to an anchored regex). (source: src/protocol/mssql/tsql.rs, exec_sql_inner, rewrite_for_xml; tests bracket_identifiers_are_rewritten, like_brackets_become_anchored_regex in mod.rs and tsql.rs)

7.3 SET options

set_option handles (source: src/protocol/mssql/tsql.rs, set_option):

Option Effect
NOCOUNT Suppresses row counts in DONE
XACT_ABORT Batch-abort on error inside a transaction
LOCK_TIMEOUT n engine.set_lock_timeout_ms
IDENTITY_INSERT t ON/OFF Error 8106 if the table has no identity; 544/545 on misuse
TRANSACTION ISOLATION LEVEL Stores level 1 to 5 in the connection; see section 8
anything else Accepted and ignored

7.4 Functions and system variables

render_func translates these built-in functions to engine SQL or __tds_* builtins (source: src/protocol/mssql/tsql.rs, render_func; src/query/mssql_funcs.rs):

APP_NAME, ASCII, ATN2, CAST, CEILING, CHAR, CHARINDEX, CHOOSE, COLUMNPROPERTY, COL_LENGTH, COL_NAME, CONVERT, COUNT_BIG, CURRENT_USER, DATABASEPROPERTYEX, DATALENGTH, DATEADD, DATEDIFF, DATEDIFF_BIG, DATEFROMPARTS, DATENAME, DATEPART, DATETIME2FROMPARTS, DATETIMEFROMPARTS, DATETRUNC, DATE_BUCKET, DAY, DB_ID, DB_NAME, EOMONTH, ERROR_LINE, ERROR_MESSAGE, ERROR_NUMBER, ERROR_PROCEDURE, ERROR_SEVERITY, ERROR_STATE, FORMAT, GETDATE, GETUTCDATE, HOST_NAME, IDENT_CURRENT, IDENT_INCR, IDENT_SEED, IIF, ISJSON, ISNULL, ISNUMERIC, IS_MEMBER, IS_ROLEMEMBER, IS_SRVROLEMEMBER, JSON_MODIFY, JSON_QUERY, JSON_VALUE, LEN, LOG, LOG10, MONTH, NCHAR, NEWID, NEWSEQUENTIALID, OBJECTPROPERTY, OBJECTPROPERTYEX, OBJECT_ID, OBJECT_NAME, ORIGINAL_LOGIN, PATINDEX, POWER, QUOTENAME, RAND, REPLICATE, ROUND, SCHEMA_ID, SCHEMA_NAME, SCOPE_IDENTITY, SERVERPROPERTY, SPACE, SQUARE, STDEV, STDEVP, STR, STUFF, SUSER_NAME, SUSER_SNAME, SWITCHOFFSET, SYSDATETIME, SYSDATETIMEOFFSET, SYSTEM_USER, SYSUTCDATETIME, TODATETIMEOFFSET, TRY_CAST, TRY_CONVERT, TYPE_NAME, UNICODE, USER_NAME, VAR, VARP, XACT_STATE, YEAR.

Time-zone names for AT TIME ZONE come from a built-in table of Windows zone names (zone() in mssql_funcs.rs) covering UTC/GMT and US, European, Australian and New Zealand zones with their DST rules. A zone not in that table is not available. (source: src/query/mssql_funcs.rs, zone)

sysvar answers these @@ variables (source: src/protocol/mssql/tsql.rs, sysvar):

Variable Value
@@ROWCOUNT, @@IDENTITY, @@TRANCOUNT, @@ERROR, @@SPID, @@FETCH_STATUS, @@LOCK_TIMEOUT Session state
@@VERSION Microsoft SQL Server 2022 (RTM) - 16.0.1000.6 (X64) ... SynergyDB 0.1.0 TDS 7.4 interface
@@SERVERNAME, @@SERVICENAME SynergyDB
@@LANGUAGE, @@LANGID us_english, 0
@@MAX_PRECISION 38
@@DATEFIRST 7
@@TEXTSIZE -1
@@OPTIONS 5496
@@PROCID, @@NESTLEVEL 0
@@MICROSOFTVERSION 268436456
any other Error 137

@@NESTLEVEL is always 0, even inside a procedure. (source: src/protocol/mssql/tsql.rs, sysvar)

7.5 Triggers and user-defined functions

Triggers: AFTER / FOR and INSTEAD OF on INSERT, UPDATE and DELETE, with inserted / deleted pseudo-tables, fired by fire_triggers. Ending the transaction inside a trigger is error 3609. User-defined functions: scalar, inline table-valued and multi-statement table-valued. Definitions are kept under __catalog__:tds_routines / tds_routine:. (source: src/protocol/mssql/tsql.rs, parse_trigger, fire_triggers)

Not verified: no unit test in the snapshot covers triggers or UDFs; the differential log (section 12) is the evidence.

7.6 Databases, schemas and names

Databases are a registry under __catalog__:tds_databases with the system databases master, tempdb, model and msdb. All databases share one table namespace; DROP DATABASE drops the objects recorded as created in it (tds_dbobjs:). Three- and two-part names lose the database and dbo/sys parts (ms_physical); other schemas map to schema-qualified physical names. (source: src/protocol/mssql/tsql.rs, ms_physical, the database registry functions; docs/status/2026-11-24-mssql-wire-sqlclient-ef-core.md)

Name mapping for temporary objects (source: src/protocol/mssql/tsql.rs, temp-table mapping):

Written Physical name Lifetime
#t #t__s<spid> Session; dropped at close or reset
##t ##t Until dropped
@t table variable internal name Dropped when its scope ends

Interpreter metadata keys: __catalog__:tds_table:, tds_ident:, tds_proc:, tds_procs, tds_routines, tds_routine:, tds_databases, tds_dbobjs:. (source: src/protocol/mssql/tsql.rs; test table_meta_roundtrips)

7.7 Catalog views

catalog_view / catalog_view_more answer these views from the engine catalog (source: src/protocol/mssql/tsql.rs, catalog_view):

Schema Views
INFORMATION_SCHEMA TABLES, COLUMNS, ROUTINES, SCHEMATA, TABLE_CONSTRAINTS, KEY_COLUMN_USAGE, REFERENTIAL_CONSTRAINTS, CHECK_CONSTRAINTS, CONSTRAINT_COLUMN_USAGE
sys tables, columns, all_columns, schemas, databases, objects, all_objects, procedures, views, dm_exec_sessions, dm_exec_requests, indexes, index_columns, foreign_keys, foreign_key_columns, key_constraints, check_constraints, default_constraints, types, identity_columns

Catalog view column types differ from SQL Server in some cases (for example VARCHAR reported as NVARCHAR); these account for most of the 18 metadata misses in the differential. (source: docs/status/2026-11-30-mssql-result-column-types-2.md; docs/proof/2026-11-30/proof-pack-a3232c9/logs/mssql-sql-server-diff.txt)

8. Transactions and isolation

@@TRANCOUNT nesting is kept in the interpreter (source: src/protocol/mssql/tsql.rs, begin_tran, transaction functions):

Statement Behaviour
BEGIN TRAN Issues engine BEGIN only when the count is 0, sends ENVCHANGE 8 with a transaction id, then increments the count
COMMIT Count 0 is error 3902; commits and sends ENVCHANGE 9 when the count reaches 0
ROLLBACK Count 0 is error 3903; with a savepoint name runs ROLLBACK TO SAVEPOINT; otherwise rolls back everything and sends ENVCHANGE 10
SAVE TRAN name Outside a transaction is error 628
Deadlock (1205) Rolls back the whole transaction

Transaction Manager requests (packet 0x0E, run_tm) (source: src/protocol/mssql/tsql.rs, run_tm):

Request Action
5 Begin
7 Commit (optional fBeginXact starts a new transaction)
8 Rollback, optional savepoint name and fBeginXact
9 Save
other DONE only

Isolation: SET TRANSACTION ISOLATION LEVEL stores 1 to 5 in the connection and sys.dm_exec_sessions.transaction_isolation_level reports it, but it does not change engine behaviour. The isolation byte in a TM begin request is ignored. Readers see the last committed value instead of blocking on an uncommitted write, which matches READ_COMMITTED_SNAPSHOT ON. (source: src/protocol/mssql/tsql.rs, set_option, run_tm; docs/status/2026-11-24-mssql-wire-sqlclient-ef-core.md; README Known gaps)

Not verified: distributed transactions (TM requests other than 5, 7, 8, 9, such as DTC enlist) are answered with DONE and do nothing; no test covers them.

9. Error number mapping

map_engine_error maps engine errors to SQL Server numbers (source: src/protocol/mssql/tsql.rs, map_engine_error):

Engine condition SQL Server error
__tds_err:N:msg from a builtin N, passed through
Division by zero 8134
Table not found 208
Column not found 207
Unique / primary key violation 2627 (2601 for a unique index; UNIQUE KEY text for UQ constraints)
NOT NULL violation 515
Foreign key or CHECK violation 547
Arithmetic overflow 8115
String truncation 2628
Subquery returned more than one row 512
Permission denied 229
Deadlock, transaction conflict 1205
Lock timeout 1222
Conversion failure 245; 241 (date); 8114 (numeric); 8169 (uniqueidentifier); 220 (tinyint range)
Parse error 102
Ambiguous column 209
Not in GROUP BY 8120
Object already exists 2714
anything else 50000

Other numbers raised directly by the interpreter: 105 (unclosed quote), 109/110 (INSERT column count), 137, 155, 174, 201, 217, 544/545, 628, 911, 1087, 1223, 1801, 2501, 2760, 2812, 3609, 3701, 3702, 3708, 3728, 3729, 3902, 3903, 4108 (windowed function in WHERE), 5011, 7997, 8106, 8144, 8145, 8179, 8197, 8672, 10704, 13609 (JSON), 15009, 15225, 15252, 16905, 16915, 16916, 16917, 16924, 50000. (source: src/protocol/mssql/tsql.rs)

10. Limits and configuration

Item Value Source
Port mssql_port, default 1433 src/config.rs
TLS [tls] section; require_tls refuses plaintext from non-loopback peers src/protocol/tls.rs, plaintext_allowed
Packet size 512..32767; 0 means 4096 src/protocol/mssql/mod.rs, handle_login
TLS handshake packet size 4096 src/protocol/mssql/tls.rs
First-byte sniff timeout 30 s src/protocol/mssql/mod.rs, handle_connection
Procedure nesting 32 (error 217) src/protocol/mssql/tsql.rs, exec_proc
WHILE iterations 10,000,000 (error 50000) src/protocol/mssql/tsql.rs
First SPID 51 src/protocol/mssql/mod.rs, next_spid
Dev users only with SYNERGYDB_DEV_INSECURE_AUTH src/protocol/mssql/mod.rs, MsSqlAuthConfig::new

11. Not implemented

From the README known gaps and status entries:

  • DATETIMEOFFSET columns come back in UTC, not their original offset. (source: README Known gaps; src/protocol/mssql/tsql.rs, pg_type)
  • Readers do not block on uncommitted writes; the isolation level setting has no effect (section 8).
  • Result metadata differences: DECIMAL precision of expressions and parameters, VARCHAR reported as NVARCHAR through CTEs, views and derived tables, NEXT VALUE FOR typed as INT/BIGINT differently, SERVERPROPERTY not sql_variant, FOR XML PATH typing, NTEXT columns. (source: docs/status/2026-11-30-mssql-result-column-types-2.md)
  • CREATE SEQUENCE ... START WITH is ignored; no ENVCHANGE acknowledges a connection reset. (source: docs/status/2026-11-24-mssql-efcore-15-of-15.md)
  • FOR JSON in a scalar subquery is a syntax error; REPLICATE does not truncate at 4000/8000. (source: docs/status/2026-11-24-mssql-sqlclient-long-text.md)
  • A recursive CTE loses sibling CTE columns; a derived-table alias loses window columns. (source: docs/status/2026-11-24-mssql-wire-sqlclient-ef-core.md)

Rejected or absent in the code:

  • Packet types Bulk Load (0x07), SSPI (0x11), Federated Auth Token (0x08) and pre-TDS7 login (0x02): error 8002. So there is no BULK INSERT / SqlBulkCopy over the wire, no Windows (SSPI/Kerberos) login and no Azure AD login. (source: src/protocol/mssql/mod.rs, serve_connection)
  • MARS: PRELOGIN answers MARS off. (source: src/protocol/mssql/mod.rs, serve_connection)
  • FEATUREEXT: none acknowledged (Always Encrypted, session recovery, UTF-8 support). (source: src/protocol/mssql/mod.rs, handle_login)
  • API server cursors (sp_cursor* RPCs). (source: src/protocol/mssql/tsql.rs, run_rpc)
  • Table-valued parameters, sql_variant and CLR UDT parameters. (source: src/protocol/mssql/rowenc.rs, read_typed_value)
  • GRANT, REVOKE, DENY and WAITFOR do nothing. (source: src/protocol/mssql/tsql.rs, exec_sql_inner)
  • xml, sql_variant and hierarchyid are stored as text with no type methods. (source: src/protocol/mssql/tsql.rs, pg_type)

12. Test coverage

Test What it covers
tests/protocol_mssql.rs Auth config (no default users; validate and add_user), SQL through QueryEngine (create, insert, select, where, order by, update, delete, join, count), handler construction, invalid SQL. It does not open a TDS connection.
src/protocol/mssql/tds.rs unit tests test_header_encode_decode, test_prelogin_encode, test_login_ack, test_done_token, header_length_below_header_size_is_rejected
src/protocol/mssql/tls.rs unit tests negotiation_table, reads_encryption_option
src/protocol/mssql/rowenc.rs unit tests plp_chunks_end_at_packet_boundaries, decimal_scaling, datetime_offset_text, rpc_int_and_nvarchar_roundtrip
src/protocol/mssql/mod.rs unit tests bracket_identifiers_are_rewritten, tsql_session_statements_are_recognized, test_default_users_gated_behind_dev_flag, test_handler_creation, test_session_creation
src/protocol/mssql/tsql.rs, batch.rs unit tests like_brackets_become_anchored_regex, param_declarations_parse, tsql_types_map_to_engine_types, table_meta_roundtrips, interval_uses_text_cast, splits_batches_without_semicolons
src/query/mssql_funcs.rs 4 unit tests of the __tds_* builtins
Proof pack differential docs/proof/2026-11-30/proof-pack-a3232c9/logs/mssql-sql-server-diff.txt: 304/322 match against SQL Server 2022 (single connection 292/309, cross-connection 5/5, durable 7/8). All 18 misses are result metadata.

Driver suites named in the status entries (test-scripts/diff-mssql/diff_mssql.py, odbc_call.py, test-scripts/efcore/, test-scripts/sqlclient-text/) are not in the code snapshot reviewed. Not verified: their results are taken from docs/status/2026-11-24-mssql-*.md only.