Skip to content

Fit tdslite into a small RAM budget

On a board with 2 kB of RAM, such as the Arduino Uno, every byte counts. This guide shows how to choose the network buffer size, and where else to save.

Choose the network buffer size

The network buffer is the biggest piece of RAM tdslite uses, and you decide its size. It has to hold two things:

Your longest query. Queries are sent as UTF-16, two bytes per character, plus an 8-byte header:

buffer size >= 8 + 2 × (characters in the query)

A 768-byte buffer sends queries of up to 380 characters. On a TLS connection, subtract another 11 characters (a 22-byte header). A query that doesn't fit is not sent: the result reports request_too_large.

Your largest row. Each row of a result set must fit into the buffer as a whole. Add up the column sizes of your widest row, with some room to spare: a row with a single varchar of 760 characters fits into 768 bytes, one of 800 doesn't. A row that doesn't fit ends the query with response_too_large (and network_error): tdslite closes the connection, and the driver has to reconnect. The same goes for the column list of a result set, and for a message from the server (e.g. from PRINT or RAISERROR).

The number of rows doesn't matter: rows go to your callback one at a time, so a 500-row result set reads through a 256-byte buffer.

Start with the smallest buffer that holds both, then round up. The tutorials use 768 bytes on an Uno.

Set the packet size

params.packet_size is the size of the TDS packets that tdslite and the server exchange. It must be between 512 and 32767. On small boards, keep it at 512 and use a buffer somewhat larger than that:

params.packet_size = 512;

Keep strings in flash

On AVR boards, string literals are copied into RAM at startup. Wrap connection parameters and queries in TDSL_PMEMSTR(...) to keep them in flash, and use progmem_connection_parameters:

decltype(driver)::progmem_connection_parameters params;
params.server_name = TDSL_PMEMSTR("192.168.1.10");
params.user_name   = TDSL_PMEMSTR("sa");
params.password    = TDSL_PMEMSTR("<password>");

driver.execute_query(TDSL_PMEMSTR("SELECT id, name FROM fruits"), on_row);

Use F("...") for your own Serial.print strings for the same reason.

Select fewer columns

tdslite allocates a small descriptor per column of a result set from the heap, and frees it when the query ends. SELECT id, name costs less than SELECT * on a wide table, and transfers less too.

Column names aren't stored unless you turn them on with driver.option_set_read_column_names(true). Leave them off if you don't need them.

Measure

The Arduino IDE prints RAM use when it compiles ("Global variables use ... bytes"). That includes the network buffer, but not the heap allocations made while a query runs. For those, print the free memory at runtime, e.g. with the MemoryFree library, while a query is running (inside the row callback).

For reference, the tested numbers on an Uno.