Skip to content

Memory model

On a microcontroller with 2 kB of RAM, a database client can't buffer a result set, can't hold a copy of every string, and can't grow its buffers when a large row arrives. tdslite's memory use is built around that.

One buffer, sized by you

All network traffic goes through one buffer, which you hand to the driver:

tdsl::uint8_t net_buf [768] = {};
tdsl::arduino_driver<EthernetClient> driver{net_buf};

tdslite uses it both ways: it builds outgoing packets in it, and receives responses into it. It never reallocates it. This makes the biggest piece of tdslite's memory use visible and fixed at compile time: the IDE's "global variables use ... bytes" includes it, and nothing grows behind your back.

The cost of a fixed buffer is that two things have to fit into it: the longest query you send, and the largest row you receive. The how-to guide shows how to size it.

Rows stream through

A response is parsed while it arrives. When a complete row is in the buffer, tdslite calls your row callback with it, and once the callback returns, the row's bytes are discarded to make room for the next one. A result set never exists in memory as a whole, so its length doesn't matter: a 500-row result set reads through a 256-byte buffer.

This is why rows come through a callback instead of being returned: returning them would mean storing them all.

It also explains the rules for the views you read from a row:

  • A char_view or u16le_view points into the network buffer. It's valid until the callback returns. Copy what you need to keep.
  • A row has to fit into the buffer as a whole, because it's handed to you as a whole.

A little heap, briefly

While a query runs, tdslite allocates a few small descriptors from the heap:

  • one per column of the result set (type, size, and the name if you turned column names on), when the result set starts. They're freed when the query ends.
  • one per field of a row, while the row is handed to your callback. They're freed when the callback returns.

Between queries, tdslite holds no heap memory of its own.

By default this uses malloc and free. You can supply your own functions, e.g. to serve them from a static pool on a system without a heap, or to trace them. If an allocation fails, the query fails with response_error, and the connection remains usable.

Strings in flash

On AVR boards (Uno, Mega, Nano), string literals are copied into RAM at startup, unless they're marked to stay in flash. TDSL_PMEMSTR("...") does that, and tdslite reads such strings straight from flash when it sends them. That's why the connection parameters come in a progmem_connection_parameters flavour, and why execute_query and execute_rpc accept TDSL_PMEMSTR queries. On boards whose flash is memory-mapped (ESP32, ARM), this makes no difference.