SQL Server front-end (T-SQL)

The TDS protocol server

How the TDS protocol is implemented: packets, login, batches, RPC, types, and what is not done.

The TDS (Tabular Data Stream) protocol of the SQL Server front-end of Raft DB (decision D90). The crate speaks the wire protocol that SQL Server clients (sqlcmd, ODBC, mssql-jdbc, .NET SqlClient) use and gives every statement to an engine through the contract in src/api.rs (Handler, Session, Outcome). There is no engine inside; the engine is raftdb-mssql, written against api.rs. Std only: no third-party dependencies, no async runtime, one thread per connection.

Rust
let listener = std::net::TcpListener::bind("127.0.0.1:1433")?;
raftdb_tds::serve(listener, std::sync::Arc::new(my_handler))?;   // my_handler: impl raftdb_tds::api::Handler

What is implemented (TDS 7.4; 7.3 clients are accepted too)#

PartState
Packets8-byte header, default 4096, size negotiated through LOGIN7 and ENVCHANGE (512 to 32767), multi-packet messages (EOM bit), reply cut into packets as it is written, 64 MiB message limit
PRELOGINVERSION, ENCRYPTION answered ENCRYPT_NOT_SUP, INSTOPT empty, MARS on when the client asks (stage 6)
LOGIN7every offset and length bounds checked; password de-obfuscated (swap nibbles, xor 0xA5); SQL authentication; answer: ENVCHANGE database, INFO 5701, ENVCHANGE language, INFO 5703, ENVCHANGE packet size and collation, LOGINACK (version and name from ServerInfo), DONE
Failed loginthe handler's error (18456, class 14, state 1 or 8 by the handler) then DONE with the error bit, then the connection closes; SSPI logins and TDS versions below 7.3 get 18456 with a message that says why
SQL batchALL_HEADERS skipped correctly; Session::batch
RPCby name or by well-known id, option flags, parameters with name, status (output, default), TYPE_INFO and value; several RPCs in one message (batch flag). sp_executesql (10), sp_prepare (11), sp_execute (12), sp_prepexec (13), sp_unprepare (15) are handled here; everything else goes to Session::call_procedure
Prepared statementskept per connection: handle to statement text and parameter declaration; run through Session::execute_sql; the handle is returned as RETURNVALUE ordinal 0 (@handle) as drivers expect; a failed first sp_prepexec leaves nothing prepared (the driver prepares again); unknown handle: error 8179
Cursorssp_cursor* (ids 1 to 9, or the names) go to the session as procedure calls; the fetch buffer of a cursor is sent with TABNAME and COLINFO after COLMETADATA, its last column ROWSTAT hidden; an RPC with fNoMetaData gets COLMETADATA with 0xFFFF columns (stage 7, D127: see Stage 7)
Transaction manager (type 0x0E)begin, commit, rollback (also named), save point; mapped to Session::batch("BEGIN TRANSACTION") and so on; ENVCHANGE 8, 9, 10 with an 8-byte descriptor
Reply tokensLOGINACK, ENVCHANGE, INFO, ERROR, COLMETADATA, ROW, DONE / DONEPROC / DONEINPROC with MORE, ERROR, COUNT and ATTN bits, RETURNSTATUS, RETURNVALUE
Attentionan attention received while idle or while a big reply is being written stops the reply and is answered with DONE (attention bit). While a request runs, a sentinel thread sets the session's cancel flag when the client sends something; the session stops at its next statement or wait (WAITFOR), the reply is dropped and the connection answers an empty DONE and then the DONE with the attention bit (two messages: the Microsoft JDBC driver needs both). A statement that is already inside the engine runs to its end
Bulk load (packet 0x07)INSERT BULK and the bulk message of bcp, SqlBulkCopy (.NET and JDBC): COLMETADATA, ROW, NBCROW, ORDER, DONE become rows for Session::bulk_load; up to 256 MiB a message; one transaction; tested with bcp, mssql-jdbc 13.6.2 and System.Data.SqlClient
Typestinyint, smallint, int, bigint, bit, decimal/numeric (precision and scale, 5/9/13/17 bytes), float, real, money, smallmoney, date, time(0..7), datetime, smalldatetime, datetime2(0..7), datetimeoffset(0..7), uniqueidentifier (mixed-endian), varchar/char (code page 1252, collation Latin1_General_CI_AS), nvarchar/nchar (UTF-16LE), varchar(max)/nvarchar(max)/varbinary(max)/xml as PLP chunks, varbinary/binary. Not-null columns without NULL values use the fixed forms (INT4, BIT, ...), others the nullable forms (INTN, BITN, ...), as SQL Server does

How a statement's reply is shaped: items of an Outcome are sent in order; a result set is COLMETADATA, ROWs and a DONE with the row count; every DONE except the last carries MORE; after an error the items before it are sent, then ERROR, then DONE with the error bit. Inside an RPC the statements end in DONEINPROC, then RETURNSTATUS, RETURNVALUEs (ordinal = wire position of the parameter), DONEPROC.

What is not implemented#

  • TLS without settings. Started without --ssl auto or --ssl-cert / --ssl-key, the server answers ENCRYPT_NOT_SUP, and clients that require encryption (ODBC Driver 18 and mssql-jdbc 12+ with their defaults, Encrypt=True) refuse to connect; the login password is then only obfuscated, not protected. With them (D146) the login, or the whole connection when the client asks for it, runs under TLS 1.2 (--ssl-mode login|preferred|required).
  • Under MARS a request cannot be cancelled while it runs and the rows of two replies are not interleaved row by row.
  • SSPI / Windows and Azure AD authentication, column encryption, session recovery, text / ntext / image in results, CLR user types other than geometry and geography (read as bytes), the FEATUREEXTACK token (clients that ask for features get none).
  • Done in D111: table-valued parameters (type 0xF3: the type's name, the columns and the rows are read into Value::Table) and sql_variant (type 0x62: read and written; NULL is a zero length).
  • The reset-connection flag of a request is read and ignored.
  • INXACT in DONE is not tracked.

Modules#

packet (framing, PacketWriter), login (PRELOGIN, LOGIN7), codec (TYPE_INFO and values, PLP, code page 1252, bounds-checked Reader), bulk (bulk load messages), watch (the sentinel for attention), calendar (days since 0001-01-01, 1900 epoch with 1/300 s ticks, smalldatetime minutes, text forms), tokens (reply tokens), rpc (requests, parameter declarations), the connection state machine (private), api (the contract).

Robustness: every length read from the wire is checked against the message; a malformed message closes that connection and never panics; idle login has a 30 s read timeout; messages over 64 MiB close the connection. Set the environment variable RAFTDB_TDS_TRACE to print every RPC kind to stderr.

How it is checked#

The crate has unit tests (codec round trips, packets, login) and the protocol tests below. A small server that answers canned statements (SELECT <literal>, CAST(.. AS type), parameters, errors) was used with real clients.

The protocol tests use a fake Handler and a minimal TDS client on TcpStream: login, failed login, a batch with every type, error after items, several items, RPC sp_executesql with parameters and OUTPUT, sp_prepare / sp_prepexec / sp_execute / sp_unprepare, named procedures, cursors refused, batch of RPCs, 512-byte packets with a 3000-row reply and a 200 000 character request, attention, transaction manager, malformed input.

Real clients against the canned-answer server: sqlcmd (SELECT 1 AS a, N'x' AS b, CAST(1.5 AS decimal(10,2)) AS c) and a Java program with the mssql-jdbc driver.

That Java program runs a Statement (every type group, several result sets, an error and the connection after it), PreparedStatements with int, string, decimal, date, UUID and NULL parameters (the driver uses sp_executesql on the first execution of a statement, sp_prepexec on the second and sp_execute after; RAFTDB_TDS_TRACE shows it), more parameter types, ResultSetMetaData (name, type name, JDBC type, precision, scale, nullability, class), typed getters and a transaction (setAutoCommit(false) / commit). The program prints one line per fact.