Skip to content

The network abstraction

tdslite doesn't open sockets. The protocol code hands finished packets to a backend and asks it for bytes back. This page explains why, and how the two fit together.

Why not just use sockets

There's no common network API across the platforms tdslite targets. An Arduino sketch talks through an EthernetClient or a WiFiClient, which aren't sockets. ESP-IDF has lwIP sockets and esp-tls. Desktops have BSD sockets, Winsock, or Boost.ASIO. Some boards have vendor libraries with an API of their own.

If the protocol code called any one of them, it would run on that platform only. Keeping the network out of it means the same protocol code runs everywhere, and supporting a new platform means writing a small backend, not changing the library.

How the driver and the backend fit

tdsl::driver<NetImpl> is a template, and NetImpl is the backend. The backend derives from tdsl::net::network_io_base<NetImpl>, which holds the network buffer and the protocol's packet handling, and calls back into the backend for the actual I/O.

flowchart LR
    App["Your code"] -->|"connect, execute_query"| Driver["tdsl::driver#lt;NetImpl#gt;"]
    Driver -->|"packets"| Base["network_io_base#lt;NetImpl#gt;"]
    Base -->|"do_send, do_recv"| Impl["NetImpl (backend)"]
    Impl -->|"bytes"| Net[("Network stack")]

The backend implements five functions: do_connect, do_disconnect, do_send and two overloads of do_recv. That's the whole contract; the library checks at compile time that they exist with the right signatures.

The connection is made with the derived class known at compile time (the "curiously recurring template pattern"), not with virtual functions. That costs nothing at runtime: no vtable, and the compiler can inline the backend's functions into the protocol code. On a microcontroller, that's flash and RAM saved.

Synchronous by design

Every backend call blocks: do_recv returns when the bytes it was asked for have arrived, or with an error. That keeps the protocol code a simple loop, with no state machines or event queues, which suits the single-threaded loop() of a sketch. On platforms with threads, run tdslite in a task or thread of its own if the rest of the program must not wait.

One packet, one write

The driver lays each packet out in the network buffer with its 8-byte header directly in front of its data, so a backend can send it with one write. That avoids a tiny extra TCP segment per packet, and with encryption it's essential: SQL Server drops a strict TLS connection when one TDS packet arrives split across several TLS records. That's why the ESP-IDF TLS backend, and the Arduino backend with a TLS client, refuse a packet larger than one record rather than splitting it.