# tdslite > Lightweight, header-only Microsoft SQL Server (MSSQL) client in pure C++11 for Arduino, ESP32, ESP8266, ESP-IDF and desktop, working with just 2 kB of RAM. tdslite connects microcontrollers (Arduino, ESP32, ESP8266) and desktop programs directly to Microsoft SQL Server and Azure SQL over the TDS protocol. It is header-only C++11 with no dependencies, streams result rows through a callback so it runs in 2 kB of RAM, supports parameterized queries and TLS (TDS 8.0 strict mode), and plugs into any network stack through small backends (Arduino EthernetClient/WiFiClient, BSD sockets, ESP-IDF esp-tls, Boost.ASIO). The C++ API reference is generated by Doxygen and linked from the Reference section. # Overview # Connect Arduino, ESP32 and C++ to Microsoft SQL Server A lightweight, header-only SQL Server client in pure C++11.\ Query a database from an Arduino Uno with 2 kB of RAM, or from anything bigger. [Get started](https://tdslite.github.io/tdslite/latest/tutorials/index.md) [Install](https://tdslite.github.io/tdslite/latest/how-to/install/index.md) [View on GitHub](https://github.com/tdslite/tdslite) - Header-only - Zero dependencies - No C++ standard library needed - MIT licensed - Tested on SQL Server 2017 – 2025 - **Fits on the smallest boards** ______________________________________________________________________ One fixed network buffer that you size, rows streamed to a callback one at a time. A 500-row result set reads through a 256-byte buffer. - **Runs on any network stack** ______________________________________________________________________ Arduino `EthernetClient` and `WiFiClient`, BSD sockets, ESP-IDF, Boost.ASIO, or a backend you write yourself in five functions. - **TLS when you need it** ______________________________________________________________________ TDS 8.0 strict encryption on ESP32 and ESP8266, ESP-IDF and desktop, with certificate checks on by default. - **Small, plain API** ______________________________________________________________________ Connect, `execute_query`, `execute_rpc` with bound parameters. No exceptions, no RTTI: every call returns a result you can check. ## A taste ```c++ // Called once for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto id = row [0].as(); const auto name = row [1].as(); Serial.printf("%d: %.*s\n", static_cast(id), static_cast(name.size()), name.data()); } void setup() { // ... connect to Wi-Fi, then: decltype(driver)::connection_parameters params; params.server_name = "192.168.1.10"; params.user_name = "sa"; params.password = ""; if (driver.connect(params) == decltype(driver)::e_driver_error_code::success) { driver.execute_query("SELECT id, name FROM fruits", print_row); } } ``` ## Where to go next - **[Tutorials](https://tdslite.github.io/tdslite/latest/tutorials/index.md)** New to tdslite? Run your first query on Arduino, PlatformIO, ESP-IDF or a desktop computer, step by step. - **[How-to guides](https://tdslite.github.io/tdslite/latest/how-to/index.md)** Recipes for a specific job: parameterized queries, TLS, error handling, squeezing into a small RAM budget. - **[Reference](https://tdslite.github.io/tdslite/latest/reference/index.md)** Connection parameters, type mappings, error codes, limits and the C++ API. - **[Explanation](https://tdslite.github.io/tdslite/latest/explanation/index.md)** Why tdslite is built the way it is: the design goals, the network abstraction, the memory model and TDS encryption. ## Frequently asked questions **Can an Arduino connect to SQL Server directly?** : Yes. tdslite speaks SQL Server's own protocol (TDS), so an Arduino with an Ethernet shield or Wi-Fi logs in and runs queries without a web service or gateway in between. It runs on an Arduino Uno, with 2 kB of RAM. See the [Arduino tutorial](https://tdslite.github.io/tdslite/latest/tutorials/arduino/index.md). **Does it work with ESP32 and ESP8266?** : Yes, with the Arduino core (`WiFiClient`, or `WiFiClientSecure` for TLS), PlatformIO, or ESP-IDF. See the [PlatformIO](https://tdslite.github.io/tdslite/latest/tutorials/platformio/index.md) and [ESP-IDF](https://tdslite.github.io/tdslite/latest/tutorials/esp-idf/index.md) tutorials, and [Connect an ESP8266](https://tdslite.github.io/tdslite/latest/how-to/esp8266/index.md). **Which SQL Server versions are supported?** : CI tests SQL Server 2017, 2019, 2022 and 2025 on every pull request. Encrypted connections need SQL Server 2025, SQL Server 2022 on Windows, or Azure SQL. See [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/#platform), and [Connect to Azure SQL Database](https://tdslite.github.io/tdslite/latest/how-to/azure-sql/index.md) (not tested in CI). **Is the connection encrypted?** : It can be: tdslite supports TLS in TDS 8.0 strict mode on ESP32, ESP8266, ESP-IDF and desktop. The plaintext backends send everything unencrypted. See [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md). **Does it support parameterized queries?** : Yes, with `execute_rpc`, which sends the values separately from the SQL text. See [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md). **Does it support Windows authentication?** : No, only SQL Server authentication (user name and password). **What does it need from the compiler and platform?** : A C++11 compiler, nothing more: no C++ standard library, no exceptions, no RTTI, no external dependencies. It's header-only, so there's nothing to build or link. # Tutorials # Tutorials Each tutorial takes you from nothing to a program that prints rows from SQL Server. Pick the one that matches what you have on your desk: - **[Arduino IDE](https://tdslite.github.io/tdslite/latest/tutorials/arduino/index.md)** An Arduino Uno (or Mega, Nano...) with an Ethernet shield, programmed from the Arduino IDE. - **[PlatformIO (ESP32)](https://tdslite.github.io/tdslite/latest/tutorials/platformio/index.md)** An ESP32 board on Wi-Fi, built with PlatformIO in VS Code or on the command line. - **[ESP-IDF](https://tdslite.github.io/tdslite/latest/tutorials/esp-idf/index.md)** An ESP32, ESP32-C3 or ESP32-S3 programmed with Espressif's own framework. - **[Desktop](https://tdslite.github.io/tdslite/latest/tutorials/desktop/index.md)** A Linux or macOS computer and a C++ compiler. The quickest way to try tdslite without any hardware. All four build the same small program: create a table, put three fruits in it, and read them back. ## Before you start: a SQL Server to talk to Every tutorial needs a SQL Server that your device can reach. If you don't have one, run one in [Docker](https://docs.docker.com/get-docker/) on your computer: ```bash docker run -d --name tdslite-tutorial -p 1433:1433 \ -e ACCEPT_EULA=Y -e MSSQL_SA_PASSWORD=Tutorial-Passw0rd \ mcr.microsoft.com/mssql/server:2022-latest ``` This starts SQL Server 2022 with the user `sa` and the password `Tutorial-Passw0rd`, which the tutorials use. It listens on port 1433 of your computer. > **Note: Find your computer's IP address** > > A board on your network connects to your computer's IP address, not to `localhost`. Look it up with `ipconfig` (Windows), `ip addr` (Linux) or in the network settings (macOS). The tutorials use `192.168.1.10`; replace it with yours. When you're done with the tutorials, remove the server: ```bash docker rm -f tdslite-tutorial ``` # Your first query on Arduino In this tutorial you'll program an Arduino Uno to log in to SQL Server, create a table, and print its rows to the Serial Monitor. **You need:** - An Arduino Uno, Mega or Nano, with a W5100 or W5500 Ethernet shield, plugged into the same network as your computer - The [Arduino IDE](https://www.arduino.cc/en/software) 2.x - A SQL Server: see [Before you start](https://tdslite.github.io/tdslite/latest/tutorials/#before-you-start-a-sql-server-to-talk-to) ## 1. Install tdslite 1. In the Arduino IDE, open **Tools → Manage Libraries...** 1. Search for `tdslite` and click **Install**. The Ethernet library comes with the IDE, so there's nothing else to install. ## 2. Create the sketch Open **File → New Sketch** and save it as `first-query`. Replace its contents step by step with the code below. Start with the two libraries the sketch uses: ```c++ #include #include ``` tdslite needs a buffer to send and receive data through. You give it one when you create the driver, so you decide how much RAM it uses: ```c++ // The buffer that tdslite uses to send and receive data tdsl::uint8_t net_buf [768] = {}; // The driver, talking over the Ethernet shield tdsl::arduino_driver driver{net_buf}; ``` When a query returns rows, tdslite calls a function of yours once for each row. This one prints the two columns of the table you'll create: ```c++ // Called once for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto name = row [1].as(); Serial.print(row [0].as()); Serial.print(F(": ")); Serial.write(name.data(), name.size()); Serial.println(); } ``` Add a small helper that stops the sketch when something goes wrong: ```c++ static void halt(const __FlashStringHelper * why) { Serial.println(why); while (true) { delay(1000); } } ``` ## 3. Connect to SQL Server Now write `setup()`. First bring up the Ethernet shield. Pick an IP address that is free in your network: ```c++ void setup() { Serial.begin(115200); while (!Serial) { } // Change the IP address to a free one in your network byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; Ethernet.begin(mac, IPAddress(192, 168, 1, 50)); if (Ethernet.hardwareStatus() == EthernetNoHardware) { halt(F("No Ethernet shield found")); } ``` Then tell tdslite where the server is and log in. Put your computer's IP address in `server_name`: ```c++ // TDSL_PMEMSTR keeps the strings in flash, which saves RAM decltype(driver)::progmem_connection_parameters params; params.server_name = TDSL_PMEMSTR("192.168.1.10"); // your computer's IP address params.port = 1433; params.user_name = TDSL_PMEMSTR("sa"); params.password = TDSL_PMEMSTR("Tutorial-Passw0rd"); params.packet_size = 512; Serial.println(F("Connecting...")); if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) { halt(F("Could not connect to SQL Server")); } Serial.println(F("Connected")); ``` ## 4. Create a table Still in `setup()`, create a table and put three rows in it, then close the function: ```c++ // A table whose name starts with # is temporary: SQL Server drops it // when the connection closes driver.execute_query(TDSL_PMEMSTR("CREATE TABLE #fruits(id INT, name VARCHAR(16))")); driver.execute_query( TDSL_PMEMSTR("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')")); } ``` ## 5. Read the rows Finally, select the rows every ten seconds in `loop()`: ```c++ void loop() { const auto result = driver.execute_query(TDSL_PMEMSTR("SELECT id, name FROM #fruits"), print_row); Serial.print(result.affected_rows); Serial.println(F(" row(s)")); delay(10000); } ``` ## 6. Run it 1. Select your board and port in the IDE, and click **Upload**. 1. Open **Tools → Serial Monitor** and set it to 115200 baud. After a few seconds you'll see: ```text Connecting... Connected 1: apple 2: banana 3: cherry 3 row(s) ``` and the last four lines again every ten seconds. If you see `Could not connect to SQL Server` instead, check the server's IP address and that your computer's firewall lets port 1433 in. [Troubleshoot](https://tdslite.github.io/tdslite/latest/how-to/troubleshooting/index.md) has more. ## What you've done You've connected an Arduino to SQL Server, created a table, and read rows from it through a callback, all within the 2 kB of RAM of an Uno. When you compile the sketch, the IDE prints how much RAM it uses: the 768-byte network buffer is most of it. **The complete sketch** ```c++ #include #include // The buffer that tdslite uses to send and receive data tdsl::uint8_t net_buf [768] = {}; // The driver, talking over the Ethernet shield tdsl::arduino_driver driver{net_buf}; // Called once for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto name = row [1].as(); Serial.print(row [0].as()); Serial.print(F(": ")); Serial.write(name.data(), name.size()); Serial.println(); } static void halt(const __FlashStringHelper * why) { Serial.println(why); while (true) { delay(1000); } } void setup() { Serial.begin(115200); while (!Serial) { } // Change the IP address to a free one in your network byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; Ethernet.begin(mac, IPAddress(192, 168, 1, 50)); if (Ethernet.hardwareStatus() == EthernetNoHardware) { halt(F("No Ethernet shield found")); } // TDSL_PMEMSTR keeps the strings in flash, which saves RAM decltype(driver)::progmem_connection_parameters params; params.server_name = TDSL_PMEMSTR("192.168.1.10"); // your computer's IP address params.port = 1433; params.user_name = TDSL_PMEMSTR("sa"); params.password = TDSL_PMEMSTR("Tutorial-Passw0rd"); params.packet_size = 512; Serial.println(F("Connecting...")); if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) { halt(F("Could not connect to SQL Server")); } Serial.println(F("Connected")); // A table whose name starts with # is temporary: SQL Server drops it // when the connection closes driver.execute_query(TDSL_PMEMSTR("CREATE TABLE #fruits(id INT, name VARCHAR(16))")); driver.execute_query( TDSL_PMEMSTR("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')")); } void loop() { const auto result = driver.execute_query(TDSL_PMEMSTR("SELECT id, name FROM #fruits"), print_row); Serial.print(result.affected_rows); Serial.println(F(" row(s)")); delay(10000); } ``` ## Next steps - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md) to put values in a query safely. - [Handle errors and server messages](https://tdslite.github.io/tdslite/latest/how-to/handle-errors/index.md) to find out why a query failed. - [Fit tdslite into a small RAM budget](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md) to choose the buffer size for your own queries. # Your first query with PlatformIO In this tutorial you'll build a PlatformIO project for an ESP32 that joins your Wi-Fi network, logs in to SQL Server and prints rows from a table. On the way, you'll see how SQL Server tells you about a mistake in a query. **You need:** - An ESP32 development board (any ESP32 DevKit will do) and a USB cable - [PlatformIO](https://platformio.org/install): the VS Code extension, or PlatformIO Core on the command line - A 2.4 GHz Wi-Fi network that your computer is on too - A SQL Server: see [Before you start](https://tdslite.github.io/tdslite/latest/tutorials/#before-you-start-a-sql-server-to-talk-to) ## 1. Create the project Create an empty folder called `first-query`, with a `platformio.ini` file in it: ```ini [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino monitor_speed = 115200 lib_deps = mustafakemalgilor/tdslite ``` `lib_deps` tells PlatformIO to download tdslite from its registry the first time you build. Create a `src` folder next to it, and a `src/main.cpp` file. You'll fill it in the next steps. ## 2. Set up the driver Start `main.cpp` with the headers: ```c++ #include #include #include ``` Add your Wi-Fi network's name and password, and your computer's IP address: ```c++ // Your Wi-Fi network static const char * wifi_ssid = ""; static const char * wifi_password = ""; // The computer that runs SQL Server static const char db_server [] = "192.168.1.10"; ``` Create the network buffer and the driver. On Arduino-style boards, the driver works with the board's own network client; here it's `WiFiClient`: ```c++ // The buffer that tdslite uses to send and receive data static tdsl::uint8_t net_buf [4096] = {}; // The driver, talking over Wi-Fi static tdsl::arduino_driver driver{net_buf}; ``` ## 3. Add the callbacks SQL Server sends messages along with its answers: a note that the database changed, or the reason a query failed. tdslite passes each one to an *info callback*: ```c++ // Called for each message that SQL Server sends, errors included static void print_message(void *, const tdsl::tds_info_token & token) noexcept { Serial.print(token.is_error() ? "server error: " : "server info: "); // The message text is UTF-16; this prints its ASCII characters for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } ``` And it passes each row of a result set to a *row callback*: ```c++ // Called once for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto id = row [0].as(); const auto name = row [1].as(); Serial.printf("%d: %.*s\n", static_cast(id), static_cast(name.size()), name.data()); } ``` ## 4. Connect Write `setup()`. Join the Wi-Fi network first: ```c++ void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); Serial.print("Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(500); } Serial.print(" connected, IP address "); Serial.println(WiFi.localIP()); ``` Then register the info callback and log in: ```c++ driver.set_info_callback(print_message); decltype(driver)::connection_parameters params; params.server_name = db_server; params.port = 1433; params.user_name = "sa"; params.password = "Tutorial-Passw0rd"; const auto cr = driver.connect(params); if (not(cr == decltype(driver)::e_driver_error_code::success)) { Serial.printf("Could not connect to SQL Server (error %d)\n", static_cast(cr)); return; } Serial.println("Connected to SQL Server"); ``` ## 5. Run queries Create a table, fill it, and read it back: ```c++ driver.execute_query("CREATE TABLE #fruits(id INT, name VARCHAR(16))"); driver.execute_query("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')"); const auto result = driver.execute_query("SELECT id, name FROM #fruits", print_row); Serial.printf("%u row(s)\n", static_cast(result.affected_rows)); ``` Now make a mistake on purpose: select from a table that doesn't exist. ```c++ // This table doesn't exist: SQL Server answers with an error message const auto bad = driver.execute_query("SELECT * FROM #vegetables"); if (not bad) { Serial.println("The query failed, see the server error above"); } } void loop() { delay(1000); } ``` ## 6. Build, upload and watch Plug in the board, then run: ```bash pio run --target upload pio device monitor ``` In VS Code, click **PlatformIO: Upload** and then **PlatformIO: Serial Monitor** in the status bar instead. You'll see something like: ```text Connecting to Wi-Fi..... connected, IP address 192.168.1.42 server info: Changed database context to 'master'. server info: Changed language setting to us_english. Connected to SQL Server 1: apple 2: banana 3: cherry 3 row(s) server error: Invalid object name '#vegetables'. The query failed, see the server error above ``` The `server info` lines are SQL Server confirming the login. The `server error` line is its answer to the bad query: the result of `execute_query` told you that the query failed, and the info callback told you why. ## What you've done You've built a PlatformIO project that pulls tdslite from the registry, connected an ESP32 to SQL Server over Wi-Fi, read rows, and seen how a failed query reports its error. **The complete program** ```c++ #include #include #include // Your Wi-Fi network static const char * wifi_ssid = ""; static const char * wifi_password = ""; // The computer that runs SQL Server static const char db_server [] = "192.168.1.10"; // The buffer that tdslite uses to send and receive data static tdsl::uint8_t net_buf [4096] = {}; // The driver, talking over Wi-Fi static tdsl::arduino_driver driver{net_buf}; // Called for each message that SQL Server sends, errors included static void print_message(void *, const tdsl::tds_info_token & token) noexcept { Serial.print(token.is_error() ? "server error: " : "server info: "); // The message text is UTF-16; this prints its ASCII characters for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } // Called once for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto id = row [0].as(); const auto name = row [1].as(); Serial.printf("%d: %.*s\n", static_cast(id), static_cast(name.size()), name.data()); } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); Serial.print("Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(500); } Serial.print(" connected, IP address "); Serial.println(WiFi.localIP()); driver.set_info_callback(print_message); decltype(driver)::connection_parameters params; params.server_name = db_server; params.port = 1433; params.user_name = "sa"; params.password = "Tutorial-Passw0rd"; const auto cr = driver.connect(params); if (not(cr == decltype(driver)::e_driver_error_code::success)) { Serial.printf("Could not connect to SQL Server (error %d)\n", static_cast(cr)); return; } Serial.println("Connected to SQL Server"); driver.execute_query("CREATE TABLE #fruits(id INT, name VARCHAR(16))"); driver.execute_query("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')"); const auto result = driver.execute_query("SELECT id, name FROM #fruits", print_row); Serial.printf("%u row(s)\n", static_cast(result.affected_rows)); // This table doesn't exist: SQL Server answers with an error message const auto bad = driver.execute_query("SELECT * FROM #vegetables"); if (not bad) { Serial.println("The query failed, see the server error above"); } } void loop() { delay(1000); } ``` ## Next steps - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md) to put sensor readings into a table safely. - [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md) to encrypt the connection with `WiFiClientSecure`. - [Handle errors and server messages](https://tdslite.github.io/tdslite/latest/how-to/handle-errors/index.md) for all the ways a query can fail. # Your first query on ESP-IDF In this tutorial you'll build an ESP-IDF application that connects to your network, logs in to SQL Server, and logs the rows of a table. You'll set the connection details in `menuconfig`, the way ESP-IDF projects usually do. **You need:** - An ESP32, ESP32-C3 or ESP32-S3 board and a USB cable - [ESP-IDF](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/get-started/) 5.0 or newer, installed and set up in your shell (`idf.py --version` works) - A Wi-Fi network that your computer is on too - A SQL Server: see [Before you start](https://tdslite.github.io/tdslite/latest/tutorials/#before-you-start-a-sql-server-to-talk-to) ## 1. Create the project Create a project and choose your chip: ```bash idf.py create-project first-query cd first-query idf.py set-target esp32 # or esp32c3, esp32s3 ``` tdslite is C++, so rename the generated source file: ```bash mv main/first-query.c main/main.cpp ``` and replace `main/CMakeLists.txt` with: ```cmake idf_component_register(SRCS "main.cpp" INCLUDE_DIRS "." PRIV_REQUIRES nvs_flash esp_netif esp_event) ``` ## 2. Add the dependencies Add tdslite from the ESP Component Registry: ```bash idf.py add-dependency "tdslite/tdslite" ``` This creates `main/idf_component.yml`. The program also uses the Wi-Fi helper that comes with ESP-IDF's examples. Add it to the `dependencies` in `main/idf_component.yml`: ```yaml dependencies: tdslite/tdslite: "*" protocol_examples_common: path: ${IDF_PATH}/examples/common_components/protocol_examples_common ``` tdslite reports errors through return values, so exceptions and RTTI can stay off. Create `sdkconfig.defaults` in the project folder: ```ini # Wi-Fi is the default connection type of protocol_examples_common. # Set the SSID/password in menuconfig -> Example Connection Configuration, # and the server details in menuconfig -> tdslite example. # tdslite reports errors with return values; no exceptions or RTTI needed. CONFIG_COMPILER_CXX_EXCEPTIONS=n CONFIG_COMPILER_CXX_RTTI=n ``` ## 3. Add the settings Create `main/Kconfig.projbuild`. It adds a **tdslite example** menu to `menuconfig`, where you'll enter the server's details: ```kconfig menu "tdslite example" config TDSLITE_EXAMPLE_SERVER string "SQL Server host name or IP address" default "192.168.1.100" config TDSLITE_EXAMPLE_PORT int "SQL Server port" range 1 65535 default 1433 config TDSLITE_EXAMPLE_USER string "User name (SQL Server authentication)" default "sa" config TDSLITE_EXAMPLE_PASSWORD string "Password" default "" config TDSLITE_EXAMPLE_DATABASE string "Database" default "master" endmenu ``` ## 4. Write the program Open `main/main.cpp` and replace its contents. Start with the headers. The driver comes from the BSD sockets backend, which works on top of ESP-IDF's lwIP: ```c++ #include #include #include #include #include #include #include #include #include #include static const char * TAG = "tdslite-example"; ``` Create the network buffer and the driver, outside any function: ```c++ // The network buffer. Each row of a result set must fit into it. // Kept off the stack: the main task's stack is small. static tdsl::uint8_t net_buf [4096] = {}; static tdsl::socket_driver driver{net_buf}; ``` Add a callback for the messages SQL Server sends, and one for the rows of a result set: ```c++ // Print INFO and ERROR messages that the server sends (e.g. "Changed database // context to 'master'", or the reason of a failed login) static void info_callback(void *, const tdsl::tds_info_token & token) noexcept { char msg [128]; size_t n = 0; for (const auto ch : token.msgtext) { if (n == sizeof(msg) - 1) { break; } msg [n++] = static_cast(ch); // ASCII is enough for an example } msg [n] = '\0'; ESP_LOGI(TAG, "server %s: %s", token.is_info() ? "info" : "error", msg); } // Called for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto id = row [0].as(); const auto name = row [1].as(); ESP_LOGI(TAG, " row: id=%ld name=%.*s", static_cast(id), static_cast(name.size()), name.data()); } ``` Now `app_main`. Bring up the network first: ```c++ extern "C" void app_main(void) { ESP_ERROR_CHECK(nvs_flash_init()); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); ESP_ERROR_CHECK(example_connect()); ``` Log in with the settings from `menuconfig`: ```c++ driver.set_info_callback(&info_callback, nullptr); tdsl::socket_driver::connection_parameters params; params.server_name = CONFIG_TDSLITE_EXAMPLE_SERVER; params.port = CONFIG_TDSLITE_EXAMPLE_PORT; params.user_name = CONFIG_TDSLITE_EXAMPLE_USER; params.password = CONFIG_TDSLITE_EXAMPLE_PASSWORD; params.db_name = CONFIG_TDSLITE_EXAMPLE_DATABASE; params.app_name = "tdslite esp-idf example"; ESP_LOGI(TAG, "connecting to %s:%d", CONFIG_TDSLITE_EXAMPLE_SERVER, CONFIG_TDSLITE_EXAMPLE_PORT); const auto cr = driver.connect(params); if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) { ESP_LOGE(TAG, "connect failed (%d)", static_cast(cr)); return; } ESP_LOGI(TAG, "logged in"); ``` Then create a table, fill it, and read it back: ```c++ // `#` makes it a temporary table that's dropped when the session ends const auto ct = driver.execute_query("CREATE TABLE #example(id INT NOT NULL, name VARCHAR(32) NOT NULL);"); if (not ct) { ESP_LOGE(TAG, "CREATE TABLE failed"); return; } const auto ir = driver.execute_query("INSERT INTO #example VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry');"); if (not ir) { ESP_LOGE(TAG, "INSERT failed"); return; } ESP_LOGI(TAG, "inserted %lu row(s)", static_cast(ir.affected_rows)); const auto sr = driver.execute_query("SELECT id, name FROM #example ORDER BY id;", &print_row); if (not sr) { ESP_LOGE(TAG, "SELECT failed"); return; } ESP_LOGI(TAG, "selected %lu row(s)", static_cast(sr.affected_rows)); } ``` ## 5. Configure, build and run Open the configuration menu: ```bash idf.py menuconfig ``` - In **Example Connection Configuration**, enter your Wi-Fi network's name and password. - In **tdslite example**, enter your computer's IP address as the host name, and `Tutorial-Passw0rd` as the password. Save with `S` and quit with `Q`. Then build, flash and watch the log: ```bash idf.py flash monitor ``` After the Wi-Fi connection, you'll see something like this (the timestamps will differ): ```text I (3021) tdslite-example: connecting to 192.168.1.10:1433 I (3215) tdslite-example: server info: Changed database context to 'master'. I (3216) tdslite-example: server info: Changed language setting to us_english. I (3218) tdslite-example: logged in I (3260) tdslite-example: inserted 3 row(s) I (3281) tdslite-example: row: id=1 name=apple I (3282) tdslite-example: row: id=2 name=banana I (3283) tdslite-example: row: id=3 name=cherry I (3284) tdslite-example: selected 3 row(s) ``` Quit the monitor with `Ctrl`+`]`. ## What you've done You've built an ESP-IDF application with tdslite from the component registry, configured it through `menuconfig`, and run queries on SQL Server from an ESP32. **The complete program** This is [examples/esp-idf/query](https://github.com/tdslite/tdslite/tree/main/examples/esp-idf/query) in the tdslite repository, which also prints the free heap and stack at the end. ```c++ /** * ____________________________________________________ * tdslite ESP-IDF example * * Connects to a network (Wi-Fi or Ethernet, see menuconfig -> * "Example Connection Configuration"), logs in to SQL Server * (menuconfig -> "tdslite example") and runs a few queries. * * The --8<-- lines mark the parts that the ESP-IDF tutorial * shows (docs/tutorials/esp-idf.md). * * SPDX-License-Identifier: MIT * ____________________________________________________ */ #include #include #include #include #include #include #include #include #include #include static const char * TAG = "tdslite-example"; // The network buffer. Each row of a result set must fit into it. // Kept off the stack: the main task's stack is small. static tdsl::uint8_t net_buf [4096] = {}; static tdsl::socket_driver driver{net_buf}; // Print INFO and ERROR messages that the server sends (e.g. "Changed database // context to 'master'", or the reason of a failed login) static void info_callback(void *, const tdsl::tds_info_token & token) noexcept { char msg [128]; size_t n = 0; for (const auto ch : token.msgtext) { if (n == sizeof(msg) - 1) { break; } msg [n++] = static_cast(ch); // ASCII is enough for an example } msg [n] = '\0'; ESP_LOGI(TAG, "server %s: %s", token.is_info() ? "info" : "error", msg); } // Called for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto id = row [0].as(); const auto name = row [1].as(); ESP_LOGI(TAG, " row: id=%ld name=%.*s", static_cast(id), static_cast(name.size()), name.data()); } extern "C" void app_main(void) { ESP_ERROR_CHECK(nvs_flash_init()); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); ESP_ERROR_CHECK(example_connect()); driver.set_info_callback(&info_callback, nullptr); tdsl::socket_driver::connection_parameters params; params.server_name = CONFIG_TDSLITE_EXAMPLE_SERVER; params.port = CONFIG_TDSLITE_EXAMPLE_PORT; params.user_name = CONFIG_TDSLITE_EXAMPLE_USER; params.password = CONFIG_TDSLITE_EXAMPLE_PASSWORD; params.db_name = CONFIG_TDSLITE_EXAMPLE_DATABASE; params.app_name = "tdslite esp-idf example"; ESP_LOGI(TAG, "connecting to %s:%d", CONFIG_TDSLITE_EXAMPLE_SERVER, CONFIG_TDSLITE_EXAMPLE_PORT); const auto cr = driver.connect(params); if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) { ESP_LOGE(TAG, "connect failed (%d)", static_cast(cr)); return; } ESP_LOGI(TAG, "logged in"); // `#` makes it a temporary table that's dropped when the session ends const auto ct = driver.execute_query("CREATE TABLE #example(id INT NOT NULL, name VARCHAR(32) NOT NULL);"); if (not ct) { ESP_LOGE(TAG, "CREATE TABLE failed"); return; } const auto ir = driver.execute_query("INSERT INTO #example VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry');"); if (not ir) { ESP_LOGE(TAG, "INSERT failed"); return; } ESP_LOGI(TAG, "inserted %lu row(s)", static_cast(ir.affected_rows)); const auto sr = driver.execute_query("SELECT id, name FROM #example ORDER BY id;", &print_row); if (not sr) { ESP_LOGE(TAG, "SELECT failed"); return; } ESP_LOGI(TAG, "selected %lu row(s)", static_cast(sr.affected_rows)); ESP_LOGI(TAG, "done. free heap: %lu bytes, main task stack high water mark: %lu bytes", static_cast(esp_get_free_heap_size()), static_cast(uxTaskGetStackHighWaterMark(nullptr))); } ``` ## Next steps - [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md) to encrypt the connection with `esp_tls_driver`. - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md). - [Fit tdslite into a small RAM budget](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md) to size the network buffer for your queries. # Your first query on desktop In this tutorial you'll write a small command line program that logs in to SQL Server, creates a table and prints its rows. You need no hardware, and because tdslite is header-only, nothing to build or install except your own program. **You need:** - Linux or macOS, with `git` and a C++11 compiler (`g++` or `clang++`) - A SQL Server: see [Before you start](https://tdslite.github.io/tdslite/latest/tutorials/#before-you-start-a-sql-server-to-talk-to). Running it in Docker on the same computer is the easiest. > **Note: Windows** > > The backend this tutorial uses is written against BSD sockets, which Windows doesn't provide. On Windows, follow the tutorial inside [WSL](https://learn.microsoft.com/windows/wsl/install). ## 1. Get tdslite Make a folder for the tutorial and clone tdslite into it: ```bash mkdir first-query && cd first-query git clone --depth 1 https://github.com/tdslite/tdslite.git ``` That's all the setup: the program only needs `tdslite/src` on its include path. ## 2. Write the program Create `first_query.cpp` next to the `tdslite` folder. Start with the header of the BSD sockets backend, which brings in the rest of tdslite: ```c++ #include #include ``` tdslite sends and receives through a buffer that you give it: ```c++ // The buffer that tdslite uses to send and receive data static tdsl::uint8_t net_buf [8192] = {}; ``` SQL Server sends messages along with its answers, such as the reason a login failed. tdslite passes each one to an *info callback*: ```c++ // Called for each message that SQL Server sends, errors included static void print_message(void *, const tdsl::tds_info_token & token) noexcept { std::printf("server %s %u: ", token.is_error() ? "error" : "info", static_cast(token.number)); // The message text is UTF-16; this prints its ASCII characters for (const char16_t c : token.msgtext) { std::putchar(static_cast(c)); } std::putchar('\n'); } ``` and each row of a result set to a *row callback*: ```c++ // Called once for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto id = row [0].as(); const auto name = row [1].as(); std::printf("%d: %.*s\n", static_cast(id), static_cast(name.size()), name.data()); } ``` In `main`, create the driver, register the info callback and log in: ```c++ int main() { tdsl::socket_driver driver{net_buf}; driver.set_info_callback(print_message); tdsl::socket_driver::connection_parameters params; params.server_name = "127.0.0.1"; params.port = 1433; params.user_name = "sa"; params.password = "Tutorial-Passw0rd"; params.conn_retry_count = 1; const auto cr = driver.connect(params); if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) { std::printf("could not connect to SQL Server (error %d)\n", static_cast(cr)); return 1; } std::printf("connected\n"); ``` Then create a table, fill it and read it back: ```c++ driver.execute_query("CREATE TABLE #fruits(id INT, name VARCHAR(16))"); driver.execute_query("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')"); const auto result = driver.execute_query("SELECT id, name FROM #fruits", print_row); if (not result) { std::printf("the query failed\n"); return 1; } std::printf("%u row(s)\n", static_cast(result.affected_rows)); return 0; } ``` ## 3. Build and run ```bash c++ -std=c++11 -I tdslite/src first_query.cpp -o first_query ./first_query ``` You'll see: ```text server info 5701: Changed database context to 'master'. server info 5703: Changed language setting to us_english. connected 1: apple 2: banana 3: cherry 3 row(s) ``` The first two lines are SQL Server confirming the login, through your info callback. ## 4. See a failed login Change the password in `first_query.cpp` to something wrong, build and run again: ```text server error 18456: Login failed for user 'sa'. could not connect to SQL Server (error 2) ``` `connect` returned `login_failed` (2), and the info callback received SQL Server's explanation. Put the right password back. ## What you've done You've built a program with tdslite straight from its source folder, logged in to SQL Server, read rows, and seen how tdslite reports a failed login. **The complete program** ```c++ #include #include // The buffer that tdslite uses to send and receive data static tdsl::uint8_t net_buf [8192] = {}; // Called for each message that SQL Server sends, errors included static void print_message(void *, const tdsl::tds_info_token & token) noexcept { std::printf("server %s %u: ", token.is_error() ? "error" : "info", static_cast(token.number)); // The message text is UTF-16; this prints its ASCII characters for (const char16_t c : token.msgtext) { std::putchar(static_cast(c)); } std::putchar('\n'); } // Called once for each row of a result set static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto id = row [0].as(); const auto name = row [1].as(); std::printf("%d: %.*s\n", static_cast(id), static_cast(name.size()), name.data()); } int main() { tdsl::socket_driver driver{net_buf}; driver.set_info_callback(print_message); tdsl::socket_driver::connection_parameters params; params.server_name = "127.0.0.1"; params.port = 1433; params.user_name = "sa"; params.password = "Tutorial-Passw0rd"; params.conn_retry_count = 1; const auto cr = driver.connect(params); if (not(cr == tdsl::socket_driver::e_driver_error_code::success)) { std::printf("could not connect to SQL Server (error %d)\n", static_cast(cr)); return 1; } std::printf("connected\n"); driver.execute_query("CREATE TABLE #fruits(id INT, name VARCHAR(16))"); driver.execute_query("INSERT INTO #fruits VALUES (1, 'apple'), (2, 'banana'), (3, 'cherry')"); const auto result = driver.execute_query("SELECT id, name FROM #fruits", print_row); if (not result) { std::printf("the query failed\n"); return 1; } std::printf("%u row(s)\n", static_cast(result.affected_rows)); return 0; } ``` ## Next steps - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md). - [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md) using the Boost.ASIO backend. - [Handle errors and server messages](https://tdslite.github.io/tdslite/latest/how-to/handle-errors/index.md). - [Results and error codes](https://tdslite.github.io/tdslite/latest/reference/errors/index.md) lists every value `connect` and the queries can return. # How-to guides # How-to guides Recipes for specific jobs. They assume you've got tdslite running; if not, start with a [tutorial](https://tdslite.github.io/tdslite/latest/tutorials/index.md). **Getting set up** - [Install the library](https://tdslite.github.io/tdslite/latest/how-to/install/index.md) in the Arduino IDE, PlatformIO, ESP-IDF or a CMake project - [Connect an ESP8266](https://tdslite.github.io/tdslite/latest/how-to/esp8266/index.md) (NodeMCU, Wemos D1 mini), with or without TLS - [Connect to Azure SQL Database](https://tdslite.github.io/tdslite/latest/how-to/azure-sql/index.md) (not tested in CI) **Working with data** - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md) - [Read column values](https://tdslite.github.io/tdslite/latest/how-to/read-columns/index.md): numbers, strings, NULLs, column names - [Call a stored procedure](https://tdslite.github.io/tdslite/latest/how-to/stored-procedures/index.md): parameters, result sets, OUTPUT parameters and errors - [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/index.md): insert readings on a schedule, and reconnect when the connection drops **Projects** - [Complete projects](https://tdslite.github.io/tdslite/latest/how-to/projects/index.md) for the ESP32 and the ESP8266: an MQTT to SQL Server bridge, a battery weather station, RFID attendance, and an energy monitor **When things go wrong** - [Handle errors and server messages](https://tdslite.github.io/tdslite/latest/how-to/handle-errors/index.md) - [Troubleshoot](https://tdslite.github.io/tdslite/latest/how-to/troubleshooting/index.md) common problems **Security** - [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md) on ESP32/ESP8266, ESP-IDF and desktop **Constrained devices** - [Fit tdslite into a small RAM budget](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md) - [Use your own memory allocator](https://tdslite.github.io/tdslite/latest/how-to/custom-allocator/index.md) **Extending tdslite** - [Write a network backend](https://tdslite.github.io/tdslite/latest/how-to/custom-backend/index.md) for a network stack tdslite doesn't support yet # Install the library tdslite is header-only: installing it means making its `src` folder available to your compiler. Pick your build system. **Arduino IDE:** **From the Library Manager:** 1. Open **Tools → Manage Libraries...** 1. Search for `tdslite` and click **Install**. **From a release zip**, e.g. for a version that isn't in the Library Manager yet: 1. Download `tdslite-.zip` from the [releases page](https://github.com/tdslite/tdslite/releases). 1. Open **Sketch → Include Library → Add .ZIP Library...** and select the file. Then include the library in your sketch: ```c++ #include ``` **PlatformIO:** Add tdslite to `lib_deps` in `platformio.ini`: ```ini [env:myboard] lib_deps = mustafakemalgilor/tdslite ``` or install it from the command line: ```bash pio pkg install --library "mustafakemalgilor/tdslite" ``` Then include the library: ```c++ #include ``` See [the registry page](https://registry.platformio.org/libraries/mustafakemalgilor/tdslite) for the available versions. **ESP-IDF:** Add the component from the [ESP Component Registry](https://components.espressif.com/components/tdslite/tdslite): ```bash idf.py add-dependency "tdslite/tdslite" ``` ESP-IDF 5.0 or newer is required. Include the backend you use: ```c++ // plaintext, over lwIP sockets #include // or TLS, over esp-tls #include ``` **CMake / desktop:** Get the source, e.g. as a git submodule: ```bash git submodule add https://github.com/tdslite/tdslite.git third_party/tdslite ``` and add its `src` folder to your target's include path: ```cmake target_include_directories(my_app PRIVATE third_party/tdslite/src) target_compile_features(my_app PRIVATE cxx_std_11) ``` Include the backend you use: ```c++ #include ``` The BSD sockets backend is header-only too. The Boost.ASIO backends (`tdslite.net.asio`, `tdslite.net.asio.tls`) are compiled libraries built by tdslite's own CMake project; see [the contributing guide](https://github.com/tdslite/tdslite/blob/main/CONTRIBUTING.md) for building it. ## Check the installation Compile a program that creates a driver. If it builds, tdslite is installed: **Arduino / PlatformIO:** ```c++ #include #include tdsl::uint8_t net_buf [512] = {}; tdsl::arduino_driver driver{net_buf}; void setup() {} void loop() {} ``` **ESP-IDF / desktop:** ```c++ #include static tdsl::uint8_t net_buf [4096] = {}; static tdsl::socket_driver driver{net_buf}; int main() {} ``` ## Related - [Network backends](https://tdslite.github.io/tdslite/latest/reference/network-backends/index.md): which header and driver type to use on each platform. - [Tested hardware](https://tdslite.github.io/tdslite/latest/reference/tested-hardware/index.md) # Connect an ESP8266 to SQL Server The ESP8266 works like the ESP32 with the Arduino core, as in the [PlatformIO tutorial](https://tdslite.github.io/tdslite/latest/tutorials/platformio/index.md), with three differences: the Wi-Fi header, less RAM, and a TLS client (BearSSL) that needs some setup. This guide covers those differences. It applies to any ESP8266 board: NodeMCU, Wemos D1 mini, ESP-01 and others. ## Install Install tdslite and the ESP8266 core: - **Arduino IDE:** install the [ESP8266 board package](https://arduino-esp8266.readthedocs.io/en/latest/installing.html), then tdslite from the Library Manager. See [Install the library](https://tdslite.github.io/tdslite/latest/how-to/install/index.md). - **PlatformIO:** use `platform = espressif8266`, e.g. with `board = nodemcuv2` or `board = d1_mini`, and add tdslite to `lib_deps`: ```ini [env:nodemcuv2] platform = espressif8266 board = nodemcuv2 framework = arduino lib_deps = mustafakemalgilor/tdslite monitor_speed = 115200 ``` ## Connect without TLS The Wi-Fi client is `WiFiClient` from `ESP8266WiFi.h`: ```c++ #include #include ``` The ESP8266 has about 80 kB of RAM, of which around 50 kB is free once Wi-Fi runs. Keep the network buffer at 2 kB and the TDS packet size at 1 kB: ```c++ #if not SKETCH_USE_TLS // 2048 bytes of buffer, 1024-byte packets: plenty for typical rows, // and light on the ESP8266's ~50 kB of free heap static tdsl::uint8_t net_buf [2048] = {}; static tdsl::arduino_driver driver{net_buf}; static constexpr tdsl::uint32_t packet_size = 1024; #endif ``` Then connect and query as on any board: ```c++ driver.set_info_callback(print_message); decltype(driver)::connection_parameters params; params.server_name = db_server; params.user_name = db_user; params.password = db_password; params.packet_size = packet_size; if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) { Serial.println("Could not connect to SQL Server"); return; } // varchar(128): the server's version, e.g. "16.0.4135.4" driver.execute_query("SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(128))", print_row); Serial.printf("Free heap: %u bytes\n", ESP.getFreeHeap()); ``` `ESP.getFreeHeap()` shows how much RAM is left. tdslite allocates the fields of each row while it's processed, so check it after a query on your widest rows. [Fit tdslite into a small RAM budget](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md) explains what takes the space. ## Connect with TLS `BearSSL::WiFiClientSecure` does the TLS part. It needs four things: 1. **The CA certificate**, as a `BearSSL::X509List` that outlives the connection: a global or `static`, not a local variable. 1. **A record size that fits a TDS packet.** BearSSL puts at most 512 bytes into a TLS record by default, and SQL Server drops a strict connection when a TDS packet is split over several records. Raise the send buffer to the packet size with `setBufferSizes`, tell tdslite that limit with `set_tls_client(true, packet_size)`, and use the same `packet_size` in the connection parameters. 1. **The current time**, to check the certificate's dates. Get it over NTP before connecting. 1. **A host name that the certificate lists**, as `server_name`, and that the ESP8266 can resolve. Not an IP address: BearSSL checks only the certificate's DNS names, so it refuses an IP address even when the certificate lists it ("Expected server name was not found in the chain"). The globals: ```c++ #if SKETCH_USE_TLS // PEM text of the CA that signed the server's certificate static const char ca_pem [] = R"(-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- )"; // BearSSL's trust anchors must outlive the connection static BearSSL::X509List trusted_ca{ca_pem}; static tdsl::uint8_t net_buf [4096] = {}; static tdsl::arduino_driver driver{net_buf}; // A TDS packet must fit into one TLS record (see setBufferSizes below) static constexpr tdsl::uint32_t packet_size = 2048; #endif ``` and in `setup()`, after Wi-Fi is up and before `connect`: ```c++ #if SKETCH_USE_TLS // Checking the certificate needs the current time configTime(0, 0, "pool.ntp.org"); while (time(nullptr) < 1700000000) { delay(500); } auto & tls = driver.network().client(); tls.setTrustAnchors(&trusted_ca); // BearSSL puts at most 512 bytes into a TLS record by default: raise // it to the TDS packet size, and tell tdslite the limit tls.setBufferSizes(16384, packet_size); driver.network().set_tls_client(true, packet_size); #endif ``` The server must accept TDS 8.0 strict connections: see [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/#check-the-server-first) for what that needs. With TLS, the sketch's static RAM grows by about 2.6 kB (mostly the larger network buffer), and BearSSL takes about 31 kB of heap when it connects, its 16 kB receive buffer included: of the ~45 kB free, about 12 kB is left. With `setBufferSizes(4096, 1024)` (below), about 25 kB is left. ## The complete sketch `SKETCH_USE_TLS` switches between the two ways to connect. CI builds both, for `nodemcuv2`. **esp8266.ino** ```c++ #include #include #include #ifndef SKETCH_USE_TLS #define SKETCH_USE_TLS 0 // 1: TLS (TDS 8.0 strict), needs SQL Server 2022+ with a certificate #endif static const char * wifi_ssid = ""; static const char * wifi_password = ""; static const char db_server [] = "192.168.1.10"; // with TLS: a host name the certificate lists static const char db_user [] = "sa"; static const char db_password [] = ""; #if not SKETCH_USE_TLS // 2048 bytes of buffer, 1024-byte packets: plenty for typical rows, // and light on the ESP8266's ~50 kB of free heap static tdsl::uint8_t net_buf [2048] = {}; static tdsl::arduino_driver driver{net_buf}; static constexpr tdsl::uint32_t packet_size = 1024; #endif #if SKETCH_USE_TLS // PEM text of the CA that signed the server's certificate static const char ca_pem [] = R"(-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- )"; // BearSSL's trust anchors must outlive the connection static BearSSL::X509List trusted_ca{ca_pem}; static tdsl::uint8_t net_buf [4096] = {}; static tdsl::arduino_driver driver{net_buf}; // A TDS packet must fit into one TLS record (see setBufferSizes below) static constexpr tdsl::uint32_t packet_size = 2048; #endif static void print_message(void *, const tdsl::tds_info_token & token) noexcept { Serial.print(token.is_error() ? "server error: " : "server info: "); for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } static void print_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const auto version = row [0].as(); Serial.write(version.data(), version.size()); Serial.println(); } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); } Serial.print("Wi-Fi connected, IP address "); Serial.println(WiFi.localIP()); #if SKETCH_USE_TLS // Checking the certificate needs the current time configTime(0, 0, "pool.ntp.org"); while (time(nullptr) < 1700000000) { delay(500); } auto & tls = driver.network().client(); tls.setTrustAnchors(&trusted_ca); // BearSSL puts at most 512 bytes into a TLS record by default: raise // it to the TDS packet size, and tell tdslite the limit tls.setBufferSizes(16384, packet_size); driver.network().set_tls_client(true, packet_size); #endif driver.set_info_callback(print_message); decltype(driver)::connection_parameters params; params.server_name = db_server; params.user_name = db_user; params.password = db_password; params.packet_size = packet_size; if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) { Serial.println("Could not connect to SQL Server"); return; } // varchar(128): the server's version, e.g. "16.0.4135.4" driver.execute_query("SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(128))", print_row); Serial.printf("Free heap: %u bytes\n", ESP.getFreeHeap()); } void loop() { delay(1000); } ``` ## If it doesn't work - **It resets while connecting, or `connect` fails with TLS:** the heap is probably exhausted. Lower `packet_size` (e.g. to 1024, in both `setBufferSizes` and `set_tls_client`) and the receive buffer, e.g. `setBufferSizes(4096, 1024)`. TLS records can be up to 16 kB, so a smaller receive buffer only works if the server never sends larger ones: try it, and go back to 16384 if the connection fails. - **The sketch hangs before connecting:** the NTP loop waits until the clock is set; check that the network can reach `pool.ntp.org`, or use a local NTP server. - For everything else, see [Troubleshoot](https://tdslite.github.io/tdslite/latest/how-to/troubleshooting/index.md). ## Related - [examples/boards/esp_wifi](https://github.com/tdslite/tdslite/blob/main/examples/boards/esp_wifi/esp_wifi.ino) and [esp_wifi_tls](https://github.com/tdslite/tdslite/blob/main/examples/boards/esp_wifi_tls/esp_wifi_tls.ino): examples that build for both the ESP32 and the ESP8266. - [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md): TLS on the other platforms. - [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/index.md): a sketch that inserts readings and reconnects; it works on the ESP8266 with `ESP8266WiFi.h`. # Connect to Azure SQL Database > **Warning: Not tested** > > tdslite's tests run against SQL Server 2017 to 2025, not against Azure SQL. These steps follow Microsoft's documentation and the [TLS guide](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md), which is tested against SQL Server. If you try them, please report what happened in a [GitHub issue](https://github.com/tdslite/tdslite/issues), whether it worked or not. Azure SQL Database accepts only encrypted connections, so this is the [TLS guide](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md) with Azure's settings. You need: - A device or program that tdslite can encrypt the connection on: ESP32 or ESP8266 (Arduino core), ESP-IDF, or desktop with Boost.ASIO and OpenSSL. Boards without a TLS client, such as the Arduino Uno with an Ethernet shield, can't connect to Azure SQL. - A database with **SQL authentication** on. tdslite logs in with a user name and a password; it doesn't support Microsoft Entra ID (Azure AD) logins. ## Set up Azure 1. **Allow the device's address.** In the Azure portal, open the SQL server (the logical server, not the database), then **Security → Networking**. Under **Public access**, select **Selected networks**, and add a firewall rule with the public IP address that your device's network uses. Your router's address is the one that counts, not the device's local one. 1. **Keep the connection policy at Default or Proxy**, on the same page. With **Redirect**, the server tells the client to reconnect to another address, which tdslite doesn't do. 1. **Note the server name and a SQL login.** The server name is `.database.windows.net`, the login is the admin login you chose when creating the server, or one you create: ```sql -- In the master database CREATE LOGIN device WITH PASSWORD = ''; -- In your database CREATE USER device FOR LOGIN device; GRANT INSERT ON dbo.readings TO device; ``` Give devices a login with only the permissions they need, as in [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/#create-the-table-and-a-login). ## Get the CA certificates Azure SQL's certificates are issued by public CAs. Trust the root CAs that Microsoft lists for Azure SQL Database; at the time of writing, they are **DigiCert Global Root G2** and **Microsoft RSA Root Certificate Authority 2017**. Download both as PEM and put them, one after the other, into one string. Check Microsoft's [Azure TLS certificate changes](https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details) page for the current list, as Azure changes CAs from time to time. ## Connect Set `server_name` to the full host name, which the certificate lists, and `db_name` to your database. In Azure SQL Database, a connection stays in the database it logs in to (`USE` can't switch databases), so without `db_name` you end up in `master`. ```c++ params.server_name = ".database.windows.net"; params.port = 1433; params.db_name = ""; params.user_name = "device"; params.password = ""; ``` Then set up TLS for your platform: **ESP32 (Arduino):** ```c++ #include #include // DigiCert Global Root G2, then Microsoft RSA Root Certificate Authority 2017 static const char azure_ca_pem [] = R"(-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- )"; static tdsl::uint8_t net_buf [4096] = {}; static tdsl::arduino_driver driver{net_buf}; // In setup(), after Wi-Fi is up and the clock is set over NTP: auto & tls = driver.network().client(); tls.setCACert(azure_ca_pem); static const char * alpn [] = {"tds/8.0", nullptr}; tls.setAlpnProtocols(alpn); driver.network().set_tls_client(true); ``` **ESP8266 (Arduino):** ```c++ #include #include static const char azure_ca_pem [] = R"(...both certificates, as for the ESP32...)"; static BearSSL::X509List trusted_ca{azure_ca_pem}; // must outlive the connection static tdsl::uint8_t net_buf [4096] = {}; static tdsl::arduino_driver driver{net_buf}; // In setup(), after Wi-Fi is up and the clock is set over NTP: auto & tls = driver.network().client(); tls.setTrustAnchors(&trusted_ca); tls.setBufferSizes(16384, 2048); driver.network().set_tls_client(true, 2048); params.packet_size = 2048; ``` [Connect an ESP8266](https://tdslite.github.io/tdslite/latest/how-to/esp8266/#connect-with-tls) explains the buffer sizes. **ESP-IDF:** ESP-IDF's certificate bundle includes the public root CAs, so there's no PEM to embed. Enable `CONFIG_MBEDTLS_CERTIFICATE_BUNDLE` (on by default), then: ```c++ #include static tdsl::uint8_t net_buf [4096] = {}; static tdsl::esp_tls_driver driver{net_buf}; tdsl::net::tdsl_esp_tls_options tls; tls.use_crt_bundle = true; driver.network().set_tls_options(tls); ``` **Desktop (Boost.ASIO):** The system's certificate store usually has the public root CAs: ```c++ #include #include tdsl::detail::tdsl_driver driver; tdsl::net::tdsl_asio_tls_options tls; // empty ca_file: the system's store driver.network().set_tls_options(tls); ``` Then call `driver.connect(params)` as usual. ## Errors you may see Azure reports these to the info callback, with `connect` returning `login_failed`: | Error | Meaning | What to do | | ----- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | 40615 | The firewall doesn't allow the device's address. The message names the address the server saw. | Add a firewall rule for that address. | | 18456 | The user name or password is wrong, or the login has no user in `db_name`. | Check the login, and create its user in your database. | | 40613 | The database isn't available right now, e.g. a serverless database resuming from auto-pause. | Retry after a minute. | | 40531 | The server name couldn't be determined. | Use the full `.database.windows.net` name. If that doesn't help, try `device@` as the user name. | If `connect` returns `connection_failed` with no server message, the TLS connection didn't come up: check the CA certificates, the clock, and the host name, as in [Troubleshoot](https://tdslite.github.io/tdslite/latest/how-to/troubleshooting/#a-tls-connection-fails). ## Keep in mind - **Serverless databases pause** when unused, and the first connection after a pause fails while the database resumes. A device that logs every few minutes keeps it from pausing, which costs compute time; if that matters, log less often or use a provisioned database. - **Idle connections are closed** after a while by Azure's gateway. Expect `network_error` on the next request, and reconnect, as in [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/#reconnect-when-the-connection-drops). - **Transactions** must start and end within one request on a TLS connection; see [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/#keep-transactions-inside-one-query). ## Related - [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md) - [Direct connections and gateways](https://tdslite.github.io/tdslite/latest/explanation/direct-vs-gateway/index.md): whether devices should connect to Azure SQL directly - [TDS versions and encryption](https://tdslite.github.io/tdslite/latest/explanation/tds-and-tls/index.md) # Run parameterized queries Use `execute_rpc` when a query contains values that come from outside the program: sensor readings, user input, anything you'd otherwise paste into the SQL text. The values travel separately from the query, so they can't change what the query does, and you don't have to quote or escape them. ## Bind the parameters 1. Create one `tdsl::sql_parameter_*` object per value, of the type of the column it goes into. 1. Put them in a `tdsl::sql_parameter_binding` array. The first is `@p0` in the query, the second `@p1`, and so on. 1. Pass the query and the array to `execute_rpc`. ```c++ tdsl::sql_parameter_varchar name{"apple"}; tdsl::sql_parameter_int stock{12}; tdsl::sql_parameter_binding params []{name, stock}; auto result = driver.execute_rpc( TDSL_PMEMSTR("INSERT INTO fruits(name, stock) VALUES (@p0, @p1)"), params); ``` `execute_rpc` doesn't take a plain string literal. Wrap the query in `TDSL_PMEMSTR(...)` to keep it in flash (on AVR boards this saves RAM), or in `tdsl::string_view{...}`. ## Read rows with parameters Pass a row callback as the fourth argument, after the mode: ```c++ tdsl::sql_parameter_int min_stock{10}; tdsl::sql_parameter_binding params []{min_stock}; auto result = driver.execute_rpc( TDSL_PMEMSTR("SELECT name, stock FROM fruits WHERE stock >= @p0"), params, tdsl::rpc_mode::executesql, print_row); ``` ## Check the result The result of `execute_rpc` converts to `true` on success. Then `get()` is the number of rows the query affected or returned; otherwise `error()` tells why it failed: ```c++ if (result) { Serial.println(result.get()); } else if (result.error() == tdsl::detail::e_rpc_error_code::server_error) { // SQL Server rejected the query; the info callback received its message } ``` All the error codes are listed in [Results and error codes](https://tdslite.github.io/tdslite/latest/reference/errors/#execute_rpc). ## Pass strings and bytes String and byte parameters hold a view of your data, not a copy. Keep the data alive until `execute_rpc` returns. ```c++ // varchar, char: 8-bit characters tdsl::sql_parameter_varchar a{"hello"}; // nvarchar, nchar: UTF-16 tdsl::sql_parameter_nvarchar b{tdsl::wstring_view{u"héllo"}}; // varbinary, binary, uniqueidentifier: raw bytes const tdsl::uint8_t payload [] = {0xDE, 0xAD, 0xBE, 0xEF}; tdsl::sql_parameter_varbinary c{tdsl::byte_view{payload}}; ``` ## Reuse parameters in a loop Parameters can be assigned a new value. A binding records where each parameter's data is and, for strings and bytes, how long it is, so build the binding array after the assignment: ```c++ tdsl::sql_parameter_int reading{}; void loop() { reading = analogRead(A0); tdsl::sql_parameter_binding params []{reading}; driver.execute_rpc(TDSL_PMEMSTR("INSERT INTO readings VALUES (@p0)"), params); delay(1000); } ``` ## Related - [Data types](https://tdslite.github.io/tdslite/latest/reference/data-types/#query-parameters): which parameter type goes with which SQL type, and which types can't be bound yet. - [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/index.md): the length limit of a query. - Example sketch: [05 - Execute query with parameters](https://github.com/tdslite/tdslite/tree/main/examples/arduino/05-query-with-parameters) # Read column values The row callback receives each row of a result set. Read a field with `row[i].as()`, where `i` is the column's position in the `SELECT` list and `T` matches the column's SQL type. ## Read numbers Use the C++ type with the same size as the column: ```c++ static void on_row(void *, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { const bool active = row [0].as(); // bit const tdsl::int16_t year = row [1].as(); // smallint const tdsl::int32_t id = row [2].as(); // int const tdsl::int64_t total = row [3].as(); // bigint const float temp = row [4].as(); // real } ``` > **Warning: The size must match** > > A type that is wider than the column reads as zero: `as()` on a `smallint` column returns 0. If a number reads as zero, check the column type. The full mapping is in [Data types](https://tdslite.github.io/tdslite/latest/reference/data-types/#reading-columns). ## Read strings `varchar` and `char` columns read as `tdsl::char_view`. The view is not null-terminated, so print it with its size: ```c++ const auto name = row [1].as(); Serial.write(name.data(), name.size()); // or: printf("%.*s", static_cast(name.size()), name.data()); ``` `nvarchar` and `nchar` columns are UTF-16. Read them as `tdsl::u16le_view`, whose elements are UTF-16 code units: ```c++ const auto city = row [2].as(); for (const char16_t c : city) { Serial.print(static_cast(c)); // fine for ASCII text } ``` The views point into the network buffer. Copy the data if you need it after the callback returns. ## Tell NULL from zero A `NULL` field reads as zero or as an empty view. Check `is_null()` first: ```c++ if (row [3].is_null()) { Serial.println(F("no value")); } else { Serial.println(row [3].as()); } ``` ## Read raw bytes For `binary`, `varbinary`, `uniqueidentifier` and `timestamp` columns, the field itself is a view of the bytes: ```c++ const auto & blob = row [0]; for (tdsl::uint32_t i = 0; i < blob.size_bytes(); i++) { Serial.print(blob.data() [i], HEX); } ``` ## Read money ```c++ const auto price = row [0].as(); // price.integer() is the whole part, price.fraction() four decimal digits ``` ## Get the column names Column names aren't read by default, to save memory. Turn them on before the query, and read them from the column metadata in the callback: ```c++ driver.option_set_read_column_names(true); static void on_row(void *, const tdsl::tds_colmetadata_token & meta, const tdsl::tdsl_row & row) { for (tdsl::uint32_t i = 0; i < meta.columns.size(); i++) { for (const char16_t c : meta.column_names [i]) { // UTF-16 Serial.print(static_cast(c)); } Serial.print(' '); } Serial.println(); } ``` ## Pass your own data to the callback The last argument of `execute_query` (and of `execute_rpc`) is a pointer that tdslite hands to every call of the row callback, as its first argument. Use it instead of a global variable: ```c++ struct totals { tdsl::int64_t sum = 0; }; static void add_up(void * user, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { static_cast(user)->sum += row [0].as(); } totals t; driver.execute_query("SELECT stock FROM fruits", add_up, &t); ``` ## Related - [Data types](https://tdslite.github.io/tdslite/latest/reference/data-types/index.md): how each SQL type is read, and how SQL Server converts the newer types for tdslite. - [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/index.md): every row must fit into the network buffer. # Call a stored procedure Run a stored procedure with `EXEC`, through `execute_query` or, with parameters, `execute_rpc`. The examples use two procedures: ```c++ run("CREATE PROCEDURE dbo.add_reading @device VARCHAR(32), @temperature REAL AS " "BEGIN SET NOCOUNT ON; " "IF @temperature > 80 RAISERROR('temperature out of range', 16, 1); " "ELSE INSERT INTO dbo.readings (device, temperature) VALUES (@device, @temperature); END"); run("CREATE PROCEDURE dbo.count_readings @device VARCHAR(32), @total INT OUTPUT AS " "BEGIN SELECT COUNT(*), @device FROM dbo.readings WHERE device = @device; " "SELECT @total = COUNT(*) FROM dbo.readings; RETURN 7; END"); ``` `add_reading` inserts a reading, or raises an error if the temperature is out of range. `count_readings` returns a result set, an `OUTPUT` parameter and a return value. ## Call it with fixed arguments When the arguments are part of your code, put the whole `EXEC` in a query: ```c++ // Fixed arguments: EXEC in a plain query const auto qr = driver.execute_query("EXEC dbo.add_reading 'greenhouse-1', 21.5"); std::printf("exec: %s\n", qr ? "ok" : "failed"); ``` ## Pass values from your program For values that come from your program (sensor readings, user input), use parameters: `@p0`, `@p1`, ... in the order of the bindings, passed on to the procedure's parameters by name. Don't paste the values into the SQL text; see [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md) for why. ```c++ // Values from the program: parameters, passed on to the procedure tdsl::sql_parameter_varchar device{"greenhouse-1"}; tdsl::sql_parameter_float4 temperature{22.0f}; tdsl::sql_parameter_binding args []{device, temperature}; const auto rr = driver.execute_rpc( tdsl::string_view{"EXEC dbo.add_reading @device = @p0, @temperature = @p1"}, args); std::printf("exec with parameters: %s\n", rr ? "ok" : "failed"); ``` ## Read what it returns Every `SELECT` in the procedure returns a result set, and each row arrives at the row callback. When a procedure returns several result sets, the callback receives them in order; use the column metadata to tell them apart: ```c++ // One callback receives the rows of every result set the procedure // returns. The column metadata tells them apart, e.g. by column count. static void print_row(void *, const tdsl::tds_colmetadata_token & columns, const tdsl::tdsl_row & row) { if (columns.columns.size() == 2) { const auto device = row [1].as(); std::printf("count: %d (%.*s)\n", static_cast(row [0].as()), static_cast(device.size()), device.data()); } else { std::printf("value: %d\n", static_cast(row [0].as())); } } ``` tdslite has no bindings for `OUTPUT` parameters or the return value. Catch them in variables in the same request, then `SELECT` them: ```c++ // Result sets, the OUTPUT parameter and the return value. tdslite // has no OUTPUT bindings: catch them in variables, then SELECT them. tdsl::sql_parameter_binding count_args []{device}; const auto cr = driver.execute_rpc( tdsl::string_view{"DECLARE @total INT, @status INT; " "EXEC @status = dbo.count_readings " " @device = @p0, @total = @total OUTPUT; " "SELECT @total; SELECT @status;"}, count_args, tdsl::rpc_mode::executesql, print_row); std::printf("count: %s\n", cr ? "ok" : "failed"); ``` This prints: ```text count: 2 (greenhouse-1) value: 2 value: 7 ``` The first line comes from the procedure's own `SELECT`, then the `OUTPUT` parameter (`@total`), then the return value (`@status`). ## Detect errors inside the procedure An error raised inside a procedure goes to the info callback, as usual. The result of the call does **not** always report it: when the procedure uses `SET NOCOUNT ON` (most do) and the error doesn't end it, e.g. a `RAISERROR` or a failed `INSERT`, the call reports success. `THROW`, and errors that end the procedure, do make the call fail with `server_error`. To catch every error, count them in the info callback: ```c++ // Errors the server reported for the current request static int server_errors = 0; static void print_message(void *, const tdsl::tds_info_token & token) noexcept { if (not token.is_error()) { return; } server_errors++; std::printf("server error %u: ", static_cast(token.number)); for (const char16_t c : token.msgtext) { std::putchar(static_cast(c)); } std::putchar('\n'); } ``` and check the count along with the result: ```c++ // RAISERROR in a procedure with SET NOCOUNT ON: the result can say // success, so count the errors that reach the info callback too temperature = 95.0f; server_errors = 0; const auto er = driver.execute_rpc( tdsl::string_view{"EXEC dbo.add_reading @device = @p0, @temperature = @p1"}, args); const bool rejected = not er || server_errors > 0; if (rejected) { std::puts("rejected by the procedure"); } ``` In your own procedures, `THROW` (SQL Server 2012 and later) is the simpler choice: it ends the procedure, and the call fails with `server_error`. ## Let a device run only the procedure A login that may only run the procedure can't read or change the tables directly, which limits what a stolen device password can do: ```sql CREATE LOGIN device WITH PASSWORD = ''; CREATE USER device FOR LOGIN device; GRANT EXECUTE ON dbo.add_reading TO device; ``` The procedure can still insert into its table: when a procedure and the tables it uses have the same owner (e.g. both in `dbo`), SQL Server doesn't check the caller's permissions on those tables. This is called ownership chaining. ## Related - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md): parameter types and binding - [Read column values](https://tdslite.github.io/tdslite/latest/how-to/read-columns/index.md) - [Handle errors and server messages](https://tdslite.github.io/tdslite/latest/how-to/handle-errors/index.md) - [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/index.md) # Log sensor readings to SQL Server Send a reading to SQL Server every few seconds: the table, a login that may only insert, the insert itself, and reconnecting when the connection drops. The sketch is for an ESP32. For an ESP8266, include `ESP8266WiFi.h` in place of `WiFi.h`; for other boards, see [Install the library](https://tdslite.github.io/tdslite/latest/how-to/install/index.md) and the [Arduino tutorial](https://tdslite.github.io/tdslite/latest/tutorials/arduino/index.md). ## Create the table and a login Let the server set the time of each reading: the device then needs no clock, and every reading uses the same one. ```sql CREATE DATABASE sensors; GO USE sensors; CREATE TABLE dbo.readings ( id INT IDENTITY PRIMARY KEY, device VARCHAR(32) NOT NULL, temperature REAL NOT NULL, humidity REAL NOT NULL, recorded_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); ``` Give the devices a login of their own that can insert into this table and nothing else. Anyone with the device can read the password from its flash, so don't use `sa` or your own login: ```sql CREATE LOGIN logger WITH PASSWORD = ''; CREATE USER logger FOR LOGIN logger; GRANT INSERT ON dbo.readings TO logger; ``` [Direct connections and gateways](https://tdslite.github.io/tdslite/latest/explanation/direct-vs-gateway/index.md) explains what else to consider before putting a database login on a device. ## Connect Set the database in the connection parameters, so the inserts don't depend on the login's default database. `app_name` names the device in `sys.dm_exec_sessions`, which helps when several devices log to one server: ```c++ static bool connect_to_db() { decltype(driver)::connection_parameters params; params.server_name = db_server; params.db_name = db_name; params.user_name = db_user; params.password = db_password; params.app_name = device_name; // shows up in sys.dm_exec_sessions params.conn_retry_count = 3; params.conn_retry_delay_ms = 2000; return driver.connect(params) == decltype(driver)::e_driver_error_code::success; } ``` ## Insert a reading Use a parameterized `INSERT`. Bind the parameters once; `execute_rpc` reads their current values each time, so set them and send again: ```c++ // Bound once: execute_rpc reads the parameters' current values static tdsl::sql_parameter_varchar device{device_name}; static tdsl::sql_parameter_float4 temperature{}; static tdsl::sql_parameter_float4 humidity{}; static tdsl::sql_parameter_binding parameters []{device, temperature, humidity}; static bool log_reading(const reading & r) { temperature = r.temperature; humidity = r.humidity; for (int attempt = 0; attempt < 2; attempt++) { const auto result = driver.execute_rpc( tdsl::string_view{"INSERT INTO dbo.readings (device, temperature, humidity) " "VALUES (@p0, @p1, @p2)"}, parameters); if (result) { return true; } // A server error (e.g. a constraint) won't go away by retrying; // the message went to print_message if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error)) { return false; } // The connection dropped (server restart, Wi-Fi, idle timeout): // connect() starts a new session on the same driver Serial.println("Connection lost, reconnecting"); if (not connect_to_db()) { return false; } } return false; } ``` `REAL` columns take `sql_parameter_float4`. For other column types, see the parameter types in [Data types](https://tdslite.github.io/tdslite/latest/reference/data-types/index.md). ## Reconnect when the connection drops Connections drop: the server restarts, Wi-Fi goes away for a while, a firewall closes idle connections. A request on a dropped connection fails with `network_error`, and calling `connect` again starts a new session on the same driver. `log_reading` above does that, then sends the reading once more. Retry only on `network_error`. A `server_error` (e.g. a value that breaks a constraint, or a missing permission) fails the same way every time, and its message went to the info callback. With `network_error`, the server may still have run the insert before the connection broke, so a retry can, rarely, store a reading twice. If that matters, send a reading ID from the device and make it unique in the table. ## Send it every 30 seconds Use `millis()` rather than `delay()`, so the loop is free for other work: ```c++ void loop() { static unsigned long last = 0; if (last != 0 && millis() - last < 30000) { return; } last = millis(); const reading r = read_sensor(); Serial.printf("%.2f C, %.2f %% -> %s\n", r.temperature, r.humidity, log_reading(r) ? "logged" : "not logged"); } ``` `read_sensor()` is a stand-in; replace it with your sensor library's code: ```c++ struct reading { float temperature; float humidity; }; // Replace with your sensor's code (DHT22, BME280, ...) static reading read_sensor() { return {21.5f, 40.25f}; } ``` ## The complete sketch CI builds it for `esp32dev`. **sensor-logging.ino** ```c++ #include #include static const char * wifi_ssid = ""; static const char * wifi_password = ""; static const char db_server [] = "192.168.1.10"; static const char db_name [] = "sensors"; static const char db_user [] = "logger"; static const char db_password [] = ""; static const char device_name [] = "greenhouse-1"; static tdsl::uint8_t net_buf [4096] = {}; static tdsl::arduino_driver driver{net_buf}; struct reading { float temperature; float humidity; }; // Replace with your sensor's code (DHT22, BME280, ...) static reading read_sensor() { return {21.5f, 40.25f}; } static void print_message(void *, const tdsl::tds_info_token & token) noexcept { Serial.print(token.is_error() ? "server error: " : "server info: "); for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } static bool connect_to_db() { decltype(driver)::connection_parameters params; params.server_name = db_server; params.db_name = db_name; params.user_name = db_user; params.password = db_password; params.app_name = device_name; // shows up in sys.dm_exec_sessions params.conn_retry_count = 3; params.conn_retry_delay_ms = 2000; return driver.connect(params) == decltype(driver)::e_driver_error_code::success; } // Bound once: execute_rpc reads the parameters' current values static tdsl::sql_parameter_varchar device{device_name}; static tdsl::sql_parameter_float4 temperature{}; static tdsl::sql_parameter_float4 humidity{}; static tdsl::sql_parameter_binding parameters []{device, temperature, humidity}; static bool log_reading(const reading & r) { temperature = r.temperature; humidity = r.humidity; for (int attempt = 0; attempt < 2; attempt++) { const auto result = driver.execute_rpc( tdsl::string_view{"INSERT INTO dbo.readings (device, temperature, humidity) " "VALUES (@p0, @p1, @p2)"}, parameters); if (result) { return true; } // A server error (e.g. a constraint) won't go away by retrying; // the message went to print_message if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error)) { return false; } // The connection dropped (server restart, Wi-Fi, idle timeout): // connect() starts a new session on the same driver Serial.println("Connection lost, reconnecting"); if (not connect_to_db()) { return false; } } return false; } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); } driver.set_info_callback(print_message); if (not connect_to_db()) { Serial.println("Could not connect to SQL Server; retrying in loop()"); } } void loop() { static unsigned long last = 0; if (last != 0 && millis() - last < 30000) { return; } last = millis(); const reading r = read_sensor(); Serial.printf("%.2f C, %.2f %% -> %s\n", r.temperature, r.humidity, log_reading(r) ? "logged" : "not logged"); } ``` ## Going further - **Readings while offline:** if a reading can't be sent, keep it in a small array and send the backlog after reconnecting. Without a clock on the device, add the age of each reading to the insert, e.g. `DATEADD(SECOND, -@p3, SYSUTCDATETIME())`. - **Several readings at once:** one `INSERT ... VALUES (@p0, @p1, @p2), (@p3, @p4, @p5)` takes fewer round trips than one insert per reading. - **A stored procedure** keeps the SQL on the server, so you can change the table without updating the firmware. See [Call a stored procedure](https://tdslite.github.io/tdslite/latest/how-to/stored-procedures/index.md). - **Encrypt the connection** when the network isn't yours: see [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md). ## Related - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md) - [Handle errors and server messages](https://tdslite.github.io/tdslite/latest/how-to/handle-errors/index.md) - [Fit tdslite into a small RAM budget](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md), for boards smaller than the ESP32 # Send ESPHome sensor data to SQL Server [ESPHome](https://esphome.io) builds firmware for ESP32 boards from a YAML file. tdslite's `sql_server` component connects it to SQL Server: - the action `sql_server.execute` sends a query or a stored procedure call, for example each time a sensor has a new reading, and can act on the result; - the `sql_server` sensor, text sensor and binary sensor platforms show a query's result as a sensor's state, in Home Assistant too. There's no code to write, and nothing runs between the board and the server. > **Warning: Experimental** > > The component is new. It's built in CI with the current ESPHome and tested against a real server there, and it has run on ESP32 boards with both frameworks, with and without TLS, including a soak test with sessions killed under it (see [Tested hardware](https://tdslite.github.io/tdslite/latest/reference/tested-hardware/#esphome-component)). It hasn't run on many other boards yet. Please [report problems](https://github.com/tdslite/tdslite/issues). What it does and doesn't do: - **Boards:** ESP32 boards (ESP32, -S2, -S3, -C3, ...), with either of ESPHome's frameworks (ESP-IDF, the default, or Arduino). Not the ESP8266 or RP2040: the queries run on a thread of their own, which these don't have. - **The first row:** of a query's result, ESPHome sees the first row, and how many rows there were. - **Encryption:** with [`tls:`](#encrypt-the-connection), on servers that support TDS 8.0 strict mode (SQL Server 2025, SQL Server 2022 on Windows, Azure SQL). Without it, the connection isn't encrypted. Either way, give the device a login that may do one thing only (below). - **Size:** a request (the query and its parameters) and each row of a result must fit in the component's 4 KB network buffer. Text travels as UTF-16, two bytes a character, so a query and its text parameters can be about 2000 characters long together. See [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/#esphome-component). - **Not durable:** requests wait in RAM while the server is unreachable, up to `queue_size`, and the oldest are dropped first. A restart loses them. - **Several servers:** add one `sql_server` per server or login; see [Several servers or logins](#several-servers-or-logins). ## Prepare the database This guide reuses the [battery weather station](https://tdslite.github.io/tdslite/latest/how-to/projects/weather-station/index.md)'s database: a table, a procedure that checks and stores a reading, and a login that may only call that procedure. Run the station's `setup.sql`: ```sql CREATE TABLE dbo.weather ( id INT IDENTITY PRIMARY KEY, station VARCHAR(32) NOT NULL, temperature REAL NOT NULL, humidity REAL NOT NULL, pressure_hpa REAL NOT NULL, recorded_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); CREATE INDEX ix_weather_station ON dbo.weather (station, recorded_at); GO -- Rejects readings that a working BME280 can't produce (e.g. after -- a loose wire). THROW makes the call fail on the device. CREATE PROCEDURE dbo.add_weather @station VARCHAR(32), @temperature REAL, @humidity REAL, @pressure_hpa REAL AS BEGIN IF @temperature NOT BETWEEN -40 AND 85 OR @humidity NOT BETWEEN 0 AND 100 OR @pressure_hpa NOT BETWEEN 300 AND 1100 THROW 50001, 'Reading out of the BME280''s range', 1; INSERT INTO dbo.weather (station, temperature, humidity, pressure_hpa) VALUES (@station, @temperature, @humidity, @pressure_hpa); END GO ``` ```sql -- The station may only add readings. Run CREATE LOGIN in master. CREATE LOGIN weather WITH PASSWORD = ''; CREATE USER weather FOR LOGIN weather; GRANT EXECUTE ON dbo.add_weather TO weather; GO ``` SQL Server must accept SQL Server logins and TCP connections; see [Troubleshoot](https://tdslite.github.io/tdslite/latest/how-to/troubleshooting/index.md) if the device can't connect. ## Add the component Load the component from the tdslite repository, and tell it where the server is: ```yaml external_components: - source: type: git url: https://github.com/tdslite/tdslite ref: main path: extras/esphome/components components: [sql_server] sql_server: host: 192.168.1.10 database: home username: weather password: !secret sql_password ``` `ref` picks the tdslite version. `main` is the latest; once a release includes the component, use its tag (for example `v0.10.0`) so that your firmware doesn't change when the repository does. | Option | Default | Meaning | | ------------------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `host` | required | The server's name or IP address | | `port` | `1433` | The server's TCP port | | `database` | the login's default | The database to use | | `username` | required | A SQL Server login (not a Windows account) | | `password` | required | Its password; keep it in `secrets.yaml` | | `app_name` | `esphome` | Shown as the program name in SQL Server's session list | | `id` | | Names this server, when there are [several](#several-servers-or-logins) | | `queue_size` | `16` | Requests that may wait for the server; beyond this, the oldest are dropped | | `max_text_size` | `255` | Text values of a result are cut to this many bytes. The row must still fit in the 4 KB network buffer: a longer value can't be read whatever this is | | `connect_timeout` | `5s` | How long a connection attempt may take | | `response_timeout` | `10s` | How long each wait for the server may take: set it above the time your slowest query takes | | `tls` | | Encrypt the connection; see [below](#encrypt-the-connection) | The component connects when the first request comes, stays connected, and reconnects when the connection drops, waiting longer after each failure (2 seconds at first, up to a minute). It doesn't try while the device's network is down, and when the network comes back, it connects at once. ## Store readings Call `sql_server.execute` from any automation. The query refers to the parameters as `@p0`, `@p1`, ... in the order of the `parameters` list: ```yaml sensor: - platform: bme280_i2c address: 0x76 update_interval: 60s temperature: id: temperature name: "Temperature" pressure: id: pressure name: "Pressure" humidity: id: humidity name: "Humidity" # The BME280 publishes temperature, pressure, then humidity: store # all three readings once the humidity arrives on_value: - sql_server.execute: query: >- EXEC dbo.add_weather @station = @p0, @temperature = @p1, @humidity = @p2, @pressure_hpa = @p3 parameters: - "greenhouse" - !lambda "return id(temperature).state;" - !lambda "return x;" - !lambda "return id(pressure).state;" ``` Each parameter is a constant or a `!lambda`. Its C++ type picks the SQL type: | Value | Sent as | | ------------------------------------------------ | ---------------------- | | `float` (a sensor's state) | `REAL` | | `double`, a constant number with a decimal point | `FLOAT` | | integers (`int`, `uint32_t`, ...) | `BIGINT` | | `bool` | `BIT` | | `std::string`, text | `NVARCHAR`, from UTF-8 | SQL Server converts them to the procedure's or the column's types, so a `BIGINT` parameter can go into an `INT` column, for example. Comparing a text parameter with an indexed `VARCHAR` column, `CAST` the parameter, so that the index is used: `WHERE code = CAST(@p0 AS VARCHAR(20))`. > **Warning: Many requests at once** > > The queue holds `queue_size` requests: send more at once, and the oldest are dropped. And ESPHome's `repeat` runs its body one level deeper on the loop task's stack for each iteration, unless the body waits (`delay`, `wait_until`). Measured on an ESP32: about 140 bytes an iteration, of an 8 KB stack, so more than about 40 `sql_server.execute` actions in one `repeat` without a wait crash the device. To store many rows, put them in one request (a stored procedure, or `INSERT ... VALUES (...), (...)`), or let each iteration `wait_until` the previous one is done. A sensor that has no reading yet has the state `NaN`. SQL Server can't store it, so a request with a `NaN` or infinite parameter is skipped, with a warning in the log, and so is one with an unsigned value beyond `BIGINT`'s range. `on_error` runs for them. Two more options of `sql_server.execute` say what happens when the server can't be reached; see [When a request fails](#when-a-request-fails): | Option | Default | Meaning | | --------------------- | ------- | -------------------------------------------------------------------------------------- | | `wait_for_connection` | `true` | While the server is unreachable, wait in the queue (`true`), or fail at once (`false`) | | `retry` | `false` | If the connection is lost after sending, send it again (up to 3 times in all) | ## Act on the result Give `sql_server.execute` an `on_result`, an `on_error`, or both. They run when the server has answered, in ESPHome's loop as any other automation. In them, `result` is the outcome and the first row of the result, and the trigger's own variables (such as `x`) still have the values they had when the action ran. This check-in reader asks SQL Server about each card, and lights a "welcome" LED for a known one. It uses the [RFID attendance](https://tdslite.github.io/tdslite/latest/how-to/projects/rfid-attendance/index.md) project's database, whose `dbo.scan_card` logs the scan and returns one row: `accepted` and `holder`. The reader's login may only call that procedure, and the connection uses [TLS](#encrypt-the-connection), so that nobody on the network can answer in the server's place: ```yaml rc522_spi: cs_pin: GPIO5 reset_pin: GPIO27 on_tag: # x is the card's UID, e.g. "04-A2-3B-1C". dbo.scan_card logs the scan, # and returns one row: accepted (bit) and holder (NULL for unknown cards). - sql_server.execute: query: >- DECLARE @uid VARCHAR(20) = REPLACE(@p0, '-', ''); EXEC dbo.scan_card @uid = @uid, @reader = @p1 parameters: - !lambda "return x;" - "front-desk" # Someone is waiting at the reader: if the server is unreachable, # say so at once (on_error), rather than answer minutes later wait_for_connection: false on_result: - if: condition: lambda: "return result.get_bool(0);" then: - text_sensor.template.publish: id: last_holder state: !lambda "return result.get_string(1);" - switch.turn_on: welcome_light - delay: 3s - switch.turn_off: welcome_light else: - logger.log: format: "Card %s refused" args: ["x.c_str()"] on_error: # The server is unreachable, or reported an error - logger.log: format: "Card %s not checked: %s" args: ["x.c_str()", "result.error.c_str()"] ``` The whole config is in [`extras/esphome/rfid-checkin.yaml`](https://github.com/tdslite/tdslite/blob/main/extras/esphome/rfid-checkin.yaml). > **Warning: Not for a door lock** > > The reader knows a card by its UID, which is easy to copy. For a door, use cards with cryptographic authentication; see [Before you use it for a door](https://tdslite.github.io/tdslite/latest/how-to/projects/rfid-attendance/#before-you-use-it-for-a-door). `on_error` runs instead of `on_result` when the request failed: a server error, a lost connection, a request dropped from a full queue, or a `NaN` parameter. While the server is unreachable, a request with `wait_for_connection: true` waits in the queue, and neither runs yet. The check-in reader sets it to `false`, so that someone at the reader hears at once that the server can't be reached. An action in `on_result` or `on_error` can be another `sql_server.execute`. In its own `on_result` and `on_error`, `result` is its result, and `outer_result` the enclosing one's. ### Read the values Columns are numbered from 0, in the order of the `SELECT` list: | In a lambda | Gives | | ----------------------------------- | ------------------------------------------------------------------------------------ | | `result.get_float(i)` | The value as a number; `NAN` for `NULL`, text that isn't a number, or no such column | | `result.get_double(i)` | The same, with a `float` column's full precision | | `result.get_int(i)` | A whole number, exact also for `BIGINT`; 0 for `NULL` | | `result.get_bool(i)` | `true` for non-zero numbers and the text `1` or `true` | | `result.get_string(i)` | Text, or a number written out; `""` for `NULL` | | `result.is_null(i)` | `true` for `NULL`, or if there's no such column | | `result.has_row()` | `false` if the query returned no rows | | `result.row_count` | How many rows the query returned (all result sets) | | `result.ok` | `true` in `on_result`, `false` in `on_error` | | `result.error`, `result.error_code` | In `on_error`: the message, and SQL Server's error number (0 for other errors) | `nchar`, `nvarchar` and `ntext` arrive as UTF-8. `char`, `varchar` and `text` arrive as stored, which is UTF-8 only under a UTF-8 collation: for other text than ASCII, `CAST(x AS NVARCHAR(100))` in the query. Text longer than `max_text_size` is cut, at a character boundary. A `uniqueidentifier` arrives in its usual text form; binary values as hex. Most column types read as you'd expect; a few need a `CAST` in the query: - `decimal` and `numeric`: `CAST(x AS FLOAT)`, or read them as text with `CAST(x AS VARCHAR(40))`. - `datetime` and `smalldatetime`: `CAST(x AS VARCHAR(30))`, or compute what you need on the server, for example `DATEDIFF(MINUTE, x, SYSUTCDATETIME())`. - `datetime2`, `date` and `time` arrive as text. ## Show database values as sensors The `sql_server` platforms run a query on an interval, and publish a column of its first row: ```yaml # Needs: GRANT SELECT ON dbo.scans TO door_reader; sensor: - platform: sql_server name: "Scans today" query: >- SELECT COUNT(*) FROM dbo.scans WHERE scanned_at >= CAST(SYSUTCDATETIME() AS DATE) update_interval: 5min binary_sensor: - platform: sql_server name: "Refused card in the last hour" query: >- SELECT CASE WHEN EXISTS (SELECT 1 FROM dbo.scans WHERE accepted = 0 AND scanned_at > DATEADD(HOUR, -1, SYSUTCDATETIME())) THEN 1 ELSE 0 END update_interval: 1min ``` | Option | Default | Meaning | | ----------------- | -------- | ---------------------------------------------------------------- | | `query` | required | The query; use `SELECT` or a stored procedure that returns a row | | `column` | `0` | The column to publish | | `update_interval` | `60s` | How often to run the query | Plus the usual options of [sensors](https://esphome.io/components/sensor/), [text sensors](https://esphome.io/components/text_sensor/) and [binary sensors](https://esphome.io/components/binary_sensor/) (`name`, `unit_of_measurement`, `filters`, ...). | Platform | Publishes | For `NULL`, no rows, or an error | | --------------- | -------------------- | -------------------------------- | | `sensor` | `get_float(column)` | unknown (`NaN`) | | `text_sensor` | `get_string(column)` | keeps the last state | | `binary_sensor` | `get_bool(column)` | unknown | Errors are also logged (the same error again only at debug level), and set the component's warning status. While the server is unreachable, a sensor's query fails at once, so the sensor doesn't keep showing an old value. A query that runs into a lost connection is sent again: it only reads. If a query is still running at the next interval, that run is skipped. ## Encrypt the connection Add `tls:`, and say which certificate authority (CA) to trust. The component then makes a TDS 8.0 *strict* connection: TLS first, before the login, with the server's certificate verified. There's no option to skip the verification. The certificate's validity dates are checked too, against the device's clock, so the configuration needs a time component to set it. The component doesn't connect until the clock is set: ```yaml time: - platform: sntp ``` For a server with a certificate from your own CA, give the CA's certificate: ```yaml sql_server: host: 192.168.1.10 database: home username: weather password: !secret sql_password tls: ca_certificate: | -----BEGIN CERTIFICATE----- MIIDBTCCAe2gAwIBAgIUQ... -----END CERTIFICATE----- # Connecting by IP address: the name in the server's certificate server_name: sql.home.lan ``` For a server with a certificate from a public CA, such as Azure SQL Database, use ESP-IDF's certificate bundle: ```yaml sql_server: host: myserver.database.windows.net database: mydb username: esphome password: "" tls: # Azure SQL's certificate is from a public CA use_certificate_bundle: true ``` | Option | Meaning | | ------------------------ | ------------------------------------------------------------------------------- | | `ca_certificate` | PEM text of the CA certificate(s) to trust | | `use_certificate_bundle` | `true`: trust the public CAs of ESP-IDF's bundle | | `server_name` | The name to check the certificate against (and to send as SNI); default: `host` | Give exactly one of `ca_certificate` and `use_certificate_bundle`. ESPHome's bundle has only the most common CAs; if the certificate isn't accepted, set `use_full_certificate_bundle: true` under `esp32:` → `advanced:`. The certificate is checked against `server_name`, or `host` without it: connecting by IP address works when the IP address is in the certificate's subject alternative names. What it costs, measured on ESP32 boards: about 68 KB of flash with Wi-Fi (Wi-Fi already uses part of mbedTLS; about 125 KB with Ethernet), and about 28 KB more heap while connected. The first connection, with the handshake and the login, took about 0.6 s over Wi-Fi; after that, requests are as fast as without TLS. The server must support strict mode, and have a certificate: see [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/#check-the-server-first). If it doesn't connect, the warning says why, for example: ```text [W][sql_server]: could not connect to 192.168.1.10:1433: TLS: the server's certificate was rejected, not signed by a CA you trust (mbedTLS -0x2700) ``` TLS is for ESP32 only; the `host` platform has no TLS. ## Check that it works The log shows the connection, and each error the server reports: ```text [I][sql_server]: Connected to 192.168.1.10, database home [E][sql_server]: SQL Server error 50001: Reading out of the BME280's range ``` The component's settings, and the counts of succeeded, failed and dropped requests, are in the configuration dump at the top of the log. On the server, check the latest rows: ```sql -- The latest reading of each station, and how old it is SELECT station, temperature, humidity, pressure_hpa, recorded_at, DATEDIFF(MINUTE, recorded_at, SYSUTCDATETIME()) AS minutes_ago FROM ( SELECT station, temperature, humidity, pressure_hpa, recorded_at, ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at DESC, id DESC) AS n FROM dbo.weather ) AS w WHERE n = 1; ``` To act on the connection state in an automation, use the `sql_server.is_connected` condition: ```yaml interval: - interval: 5min then: - if: condition: not: sql_server.is_connected then: - logger.log: "SQL Server unreachable; readings are waiting" ``` ## When a request fails - **Server errors** (a `THROW` in the procedure, a missing permission, a wrong column) are logged and counted as failed. The request isn't sent again: it would fail the same way. - **A connection the server closed while it was idle** (a `KILL`, a restart): the component notices before sending, reconnects, and sends the request. - **A lost connection after sending:** the request fails, and the component reconnects for the next one. The same goes for a session the server ends during the request (a `KILL`, error 596, or an error of severity 20 or more): `on_error` sees the server's error. The server may or may not have run it, so it isn't sent again unless the action has `retry: true`. Use that only where running twice does no harm, or have the procedure ignore repeats, for example by a unique key on the device and the reading's time. With `retry: true`, a request that loses the connection 3 times in a row is given up, in case it's what breaks the connection. - **A slow query:** one that takes longer than `response_timeout` counts as a lost connection. The server may still finish it. - **Too large:** a request that doesn't fit in the network buffer isn't sent (`Request rejected by tdslite: too large for the 4 KB network buffer`). A row of the result that doesn't fit ends the request with `Response too large`; the server ran it, so it isn't sent again, and the component reconnects. - **An unreachable server:** the component keeps trying to connect, waiting longer after each failure; while the network is down, it doesn't try, and once it's back, it connects at once. Requests with `wait_for_connection: true` (the default for `sql_server.execute`) wait in the queue; others, and the sensors' queries, fail at once. The request being sent when the server became unreachable waits too, so `queue_size` more can wait behind it. - **A transaction left open over TLS:** after a `BEGIN TRAN` sent on its own, every later request of a strict TLS session fails with error 3989 (see [Transactions over TLS](https://tdslite.github.io/tdslite/latest/explanation/tds-and-tls/#transactions-over-tls)). The component then reconnects. Begin and end each transaction in one request, or in a stored procedure. - **A restart or an OTA update:** requests still waiting fail; `on_error` may not run before the restart. ## Several servers or logins Add a `sql_server` for each server, or each login on one server: for example, so that each part of the device has a login that may do only its own job, or a different database or `tls:` setting. Give each an `id`, and say which one each action uses with `id`, and each sensor with `sql_server_id`: ```yaml sql_server: - id: weather_db host: 192.168.1.10 database: home username: weather password: !secret weather_password - id: door_db host: 192.168.1.10 database: home username: door_reader password: !secret door_reader_password tls: ca_certificate: !secret sql_ca sensor: - platform: bme280_i2c # ... humidity: name: "Humidity" on_value: - sql_server.execute: id: weather_db query: "EXEC dbo.add_weather @station = @p0, @temperature = @p1, @humidity = @p2, @pressure_hpa = @p3" parameters: [...] - platform: sql_server sql_server_id: door_db name: "Scans today" query: "SELECT COUNT(*) FROM dbo.scans WHERE scanned_at >= CAST(SYSUTCDATETIME() AS DATE)" ``` Each has its own connection, thread and queue: about 14 KB of RAM each, and 28 KB more for one with TLS. With more than one, ESPHome asks for the `id` in every action and sensor. ## How it works ESPHome runs all components in one loop, which must not wait: a component that blocks for more than a few milliseconds holds up Wi-Fi, the API connection and every other sensor. tdslite waits for each response. So the component runs tdslite on a thread of its own, with a queue between the two: `sql_server.execute` puts the request in the queue and returns at once, and the thread sends the requests one at a time. Results go back the same way: the thread queues them and wakes ESPHome's loop, which runs `on_result`, `on_error` and the sensor updates. The component builds against the tdslite headers in the same repository (`src/`), so the component and the library are always the same version. ## See also - [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/index.md): the same in an Arduino sketch. - [MQTT to SQL Server bridge](https://tdslite.github.io/tdslite/latest/how-to/projects/mqtt-sql-bridge/index.md): for devices that already publish to an MQTT broker. - [Direct connections and gateways](https://tdslite.github.io/tdslite/latest/explanation/direct-vs-gateway/index.md): when a device should talk to the database itself. # Projects Complete projects that store their data in SQL Server with tdslite. Many projects like these send their data through an MQTT broker, a PHP script or a cloud service to reach a database. These versions talk to SQL Server directly; the bridge keeps MQTT and adds SQL Server to it. - [MQTT to SQL Server bridge](https://tdslite.github.io/tdslite/latest/how-to/projects/mqtt-sql-bridge/index.md): store every message of your MQTT devices (Tasmota, ESPHome, your own sketches), with an ESP32 instead of a PC running Node-RED or a script. - [Battery weather station](https://tdslite.github.io/tdslite/latest/how-to/projects/weather-station/index.md): a BME280 that reports every 10 minutes and sleeps in between. - [RFID attendance](https://tdslite.github.io/tdslite/latest/how-to/projects/rfid-attendance/index.md): an RC522 reader that checks cards against SQL Server and logs every scan. - [Energy monitor](https://tdslite.github.io/tdslite/latest/how-to/projects/energy-monitor/index.md): a PZEM-004T power meter, with daily and monthly consumption from SQL queries. Each project runs on the ESP32 and the ESP8266, and comes with: - the sketch, in [examples/projects](https://github.com/tdslite/tdslite/tree/main/examples/projects) - `setup.sql`: the tables, a stored procedure, and a login that may only call that procedure - `queries.sql`: reports to run in SQL Server Management Studio, a dashboard tool, or anything else that talks to SQL Server **What's tested:** CI builds every sketch for the ESP32 and the ESP8266. It also runs each `setup.sql` against SQL Server, makes the calls each sketch makes with the same parameter types and the device's own login, and checks the results of the reports. The sensors and readers themselves aren't part of the tests. Before you start, a [tutorial](https://tdslite.github.io/tdslite/latest/tutorials/index.md) shows the basics, and [Direct connections and gateways](https://tdslite.github.io/tdslite/latest/explanation/direct-vs-gateway/index.md) helps decide whether your devices should talk to SQL Server directly. # MQTT to SQL Server bridge Keep your MQTT devices as they are, and get their history into SQL Server: an ESP32 subscribes to the topics, and stores each message in a table. It replaces the PC that usually does this with Node-RED, Telegraf or a script. SQL Server's JSON functions then pull the values out of the payloads. **You need:** an ESP32 or ESP8266, an MQTT broker (e.g. Mosquitto), and SQL Server 2016 or later on the same network. ## Set up the database Run [setup.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/mqtt_sql_bridge/setup.sql) in your database. It creates the table, the procedure that stores a message, and a login that may only call that procedure: ```sql CREATE TABLE dbo.mqtt_messages ( id BIGINT IDENTITY PRIMARY KEY, topic VARCHAR(128) NOT NULL, payload VARCHAR(512) NOT NULL, received_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); CREATE INDEX ix_mqtt_messages_topic ON dbo.mqtt_messages (topic, received_at); GO CREATE PROCEDURE dbo.store_message @topic VARCHAR(128), @payload VARCHAR(512) AS INSERT INTO dbo.mqtt_messages (topic, payload) VALUES (@topic, @payload); GO ``` ```sql -- The bridge may only store messages. Run CREATE LOGIN in master. CREATE LOGIN mqtt_bridge WITH PASSWORD = ''; CREATE USER mqtt_bridge FOR LOGIN mqtt_bridge; GRANT EXECUTE ON dbo.store_message TO mqtt_bridge; GO ``` ## Configure the sketch Install the **PubSubClient** library (by Nick O'Leary), open [mqtt_sql_bridge.ino](https://github.com/tdslite/tdslite/blob/main/examples/projects/mqtt_sql_bridge/mqtt_sql_bridge.ino), and fill in the settings: ```c++ static const char * wifi_ssid = ""; static const char * wifi_password = ""; static const char * mqtt_broker = "192.168.1.20"; static const uint16_t mqtt_port = 1883; static const char * mqtt_user = nullptr; // or "" static const char * mqtt_password = nullptr; // or "" static const char * mqtt_topic = "tele/+/SENSOR"; // Tasmota; or e.g. "sensors/#" static const char db_server [] = "192.168.1.10"; static const char db_name [] = "home"; static const char db_user [] = "mqtt_bridge"; static const char db_password [] = ""; ``` `mqtt_topic` takes MQTT wildcards: `+` for one level, `#` for the rest. The default, `tele/+/SENSOR`, gets the sensor readings of every Tasmota device. For ESPHome, use e.g. `esphome/#` or your devices' topic prefix. With PlatformIO, add the library to `lib_deps`: ```ini lib_deps = mustafakemalgilor/tdslite knolleary/PubSubClient@^2.8 ``` ## How it works The MQTT callback runs inside `mqtt.loop()`. A database round trip there would hold up the MQTT client, so the callback only copies the message into a queue: ```c++ // Messages wait here until loop() stores them. The MQTT callback only // copies: a database round trip inside it would hold up the MQTT client. struct message { char topic [128]; char payload [512]; unsigned int payload_size; }; static constexpr int queue_capacity = 8; static message queue [queue_capacity]; static int queue_head = 0, queue_count = 0; static unsigned long dropped = 0; static void on_mqtt_message(char * topic, uint8_t * payload, unsigned int size) { if (queue_count == queue_capacity || strlen(topic) >= sizeof(message::topic) || size > sizeof(message::payload)) { dropped++; return; } message & m = queue [(queue_head + queue_count) % queue_capacity]; strcpy(m.topic, topic); memcpy(m.payload, payload, size); m.payload_size = size; queue_count++; } ``` `loop()` stores one queued message per pass. A message that can't be stored stays in the queue, and is tried again: ```c++ void loop() { if (not mqtt.connected()) { connect_mqtt(); } mqtt.loop(); // Store one message per pass, so the MQTT client gets its turn if (queue_count > 0) { const message & m = queue [queue_head]; if (store(m)) { queue_head = (queue_head + 1) % queue_capacity; queue_count--; } else { // Kept in the queue; try again shortly delay(1000); } } static unsigned long last_report = 0; if (dropped > 0 && millis() - last_report > 60000) { last_report = millis(); Serial.printf("%lu message(s) dropped: queue full or message too large\n", dropped); } } ``` Storing binds the topic and the payload as `varchar` parameters that point at the queued message, and reconnects once if the connection dropped: ```c++ static bool store(const message & m) { // The parameters point at the message; nothing is copied tdsl::sql_parameter_varchar topic{tdsl::string_view{m.topic, strlen(m.topic)}}; tdsl::sql_parameter_varchar payload{tdsl::string_view{m.payload, m.payload_size}}; tdsl::sql_parameter_binding params []{topic, payload}; for (int attempt = 0; attempt < 2; attempt++) { const auto result = driver.execute_rpc( tdsl::string_view{"EXEC dbo.store_message @topic = @p0, @payload = @p1"}, params); if (result) { return true; } if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) || not connect_to_db()) { return false; } } return false; } ``` Messages larger than 512 bytes, and messages that arrive while the queue is full, are dropped and counted; the sketch reports the count every minute. For larger payloads, raise the sizes in `struct message` and in the table, and keep an eye on the RAM: each queued message takes about 650 bytes. ## Read the messages The payloads are stored as they arrived. SQL Server's `JSON_VALUE` reads values out of them; these examples use Tasmota's `SENSOR` messages, so adjust the JSON paths for your devices. More in [queries.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/mqtt_sql_bridge/queries.sql). The latest message of each topic: ```sql -- The latest message of each topic SELECT topic, payload, received_at FROM ( SELECT topic, payload, received_at, ROW_NUMBER() OVER (PARTITION BY topic ORDER BY received_at DESC, id DESC) AS n FROM dbo.mqtt_messages ) AS m WHERE n = 1; ``` The values, with the device name taken from the topic: ```sql -- Values out of the JSON payloads, one row per message SELECT PARSENAME(REPLACE(topic, '/', '.'), 2) AS device, CAST(JSON_VALUE(payload, '$.AM2301.Temperature') AS REAL) AS temperature, CAST(JSON_VALUE(payload, '$.AM2301.Humidity') AS REAL) AS humidity, received_at FROM dbo.mqtt_messages WHERE topic LIKE 'tele/%/SENSOR' AND ISJSON(payload) = 1; ``` Hourly averages: ```sql -- Hourly average temperature per device, over the last day SELECT PARSENAME(REPLACE(topic, '/', '.'), 2) AS device, DATEADD(HOUR, DATEDIFF(HOUR, 0, received_at), 0) AS hour, AVG(CAST(JSON_VALUE(payload, '$.AM2301.Temperature') AS REAL)) AS temperature FROM dbo.mqtt_messages WHERE topic LIKE 'tele/%/SENSOR' AND ISJSON(payload) = 1 AND received_at > DATEADD(DAY, -1, SYSUTCDATETIME()) GROUP BY PARSENAME(REPLACE(topic, '/', '.'), 2), DATEADD(HOUR, DATEDIFF(HOUR, 0, received_at), 0) ORDER BY device, hour; ``` The table grows with every message. Delete old ones from time to time, e.g. with a SQL Server Agent job: ```sql -- Delete messages older than 90 days (e.g. from a SQL Server Agent job) DELETE FROM dbo.mqtt_messages WHERE received_at < DATEADD(DAY, -90, SYSUTCDATETIME()); ``` ## The complete sketch **mqtt_sql_bridge.ino** ```c++ #if defined(ESP32) #include #elif defined(ESP8266) #include #else #error "This sketch is for the ESP32 and the ESP8266" #endif #include #include static const char * wifi_ssid = ""; static const char * wifi_password = ""; static const char * mqtt_broker = "192.168.1.20"; static const uint16_t mqtt_port = 1883; static const char * mqtt_user = nullptr; // or "" static const char * mqtt_password = nullptr; // or "" static const char * mqtt_topic = "tele/+/SENSOR"; // Tasmota; or e.g. "sensors/#" static const char db_server [] = "192.168.1.10"; static const char db_name [] = "home"; static const char db_user [] = "mqtt_bridge"; static const char db_password [] = ""; static tdsl::uint8_t net_buf [2048] = {}; static tdsl::arduino_driver driver{net_buf}; static WiFiClient mqtt_net; static PubSubClient mqtt{mqtt_net}; // Messages wait here until loop() stores them. The MQTT callback only // copies: a database round trip inside it would hold up the MQTT client. struct message { char topic [128]; char payload [512]; unsigned int payload_size; }; static constexpr int queue_capacity = 8; static message queue [queue_capacity]; static int queue_head = 0, queue_count = 0; static unsigned long dropped = 0; static void on_mqtt_message(char * topic, uint8_t * payload, unsigned int size) { if (queue_count == queue_capacity || strlen(topic) >= sizeof(message::topic) || size > sizeof(message::payload)) { dropped++; return; } message & m = queue [(queue_head + queue_count) % queue_capacity]; strcpy(m.topic, topic); memcpy(m.payload, payload, size); m.payload_size = size; queue_count++; } static void print_message(void *, const tdsl::tds_info_token & token) noexcept { if (not token.is_error()) { return; } Serial.print("SQL Server error: "); for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } static bool connect_to_db() { decltype(driver)::connection_parameters params; params.server_name = db_server; params.db_name = db_name; params.user_name = db_user; params.password = db_password; params.app_name = "mqtt-sql-bridge"; params.packet_size = 1024; return driver.connect(params) == decltype(driver)::e_driver_error_code::success; } static bool store(const message & m) { // The parameters point at the message; nothing is copied tdsl::sql_parameter_varchar topic{tdsl::string_view{m.topic, strlen(m.topic)}}; tdsl::sql_parameter_varchar payload{tdsl::string_view{m.payload, m.payload_size}}; tdsl::sql_parameter_binding params []{topic, payload}; for (int attempt = 0; attempt < 2; attempt++) { const auto result = driver.execute_rpc( tdsl::string_view{"EXEC dbo.store_message @topic = @p0, @payload = @p1"}, params); if (result) { return true; } if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) || not connect_to_db()) { return false; } } return false; } static void connect_mqtt() { String client_id = "tdslite-bridge-" + String(WiFi.macAddress()); while (not mqtt.connected()) { if (mqtt.connect(client_id.c_str(), mqtt_user, mqtt_password)) { mqtt.subscribe(mqtt_topic); Serial.printf("MQTT: subscribed to %s\n", mqtt_topic); } else { Serial.printf("MQTT: connect failed (%d), retrying\n", mqtt.state()); delay(2000); } } } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); } driver.set_info_callback(print_message); while (not connect_to_db()) { Serial.println("SQL Server: connect failed, retrying"); delay(5000); } mqtt.setServer(mqtt_broker, mqtt_port); // PubSubClient's default buffer (256 bytes) is too small for many // JSON payloads; it holds the topic and the payload mqtt.setBufferSize(sizeof(message::topic) + sizeof(message::payload) + 16); mqtt.setCallback(on_mqtt_message); connect_mqtt(); } void loop() { if (not mqtt.connected()) { connect_mqtt(); } mqtt.loop(); // Store one message per pass, so the MQTT client gets its turn if (queue_count > 0) { const message & m = queue [queue_head]; if (store(m)) { queue_head = (queue_head + 1) % queue_capacity; queue_count--; } else { // Kept in the queue; try again shortly delay(1000); } } static unsigned long last_report = 0; if (dropped > 0 && millis() - last_report > 60000) { last_report = millis(); Serial.printf("%lu message(s) dropped: queue full or message too large\n", dropped); } } ``` ## Going further - **Store only what you need:** subscribe to specific topics, or filter in `on_mqtt_message`, rather than storing everything. - **Parse on the device:** if your devices send plain numbers, add columns for them and a procedure that takes numbers, instead of storing text. - **Encrypt:** for a broker or a SQL Server outside your network, use TLS on both connections; see [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md). ## Related - [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/index.md): the same reconnect logic, without MQTT - [Call a stored procedure](https://tdslite.github.io/tdslite/latest/how-to/stored-procedures/index.md) - [Direct connections and gateways](https://tdslite.github.io/tdslite/latest/explanation/direct-vs-gateway/index.md) # Battery weather station A BME280 measures temperature, humidity and air pressure; the board wakes up every 10 minutes, stores a reading in SQL Server and goes back to deep sleep. No MQTT broker or cloud service in between, and SQL queries for the daily summary, the pressure trend, and stations that stopped reporting. ## Parts and wiring - ESP32 or ESP8266 board. For battery use, pick one with a low-power regulator; many development boards draw several mA even while the chip sleeps. - BME280 breakout, on I2C: | BME280 | ESP32 | ESP8266 | | ------ | ------ | ---------- | | VIN | 3V3 | 3V3 | | GND | GND | GND | | SDA | GPIO21 | D2 (GPIO4) | | SCL | GPIO22 | D1 (GPIO5) | On the ESP8266, also connect **D0 (GPIO16) to RST**: the chip wakes from deep sleep by resetting itself through that pin. Disconnect it while uploading if the upload fails. ## Set up the database Run [setup.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/weather_station/setup.sql) in your database: ```sql CREATE TABLE dbo.weather ( id INT IDENTITY PRIMARY KEY, station VARCHAR(32) NOT NULL, temperature REAL NOT NULL, humidity REAL NOT NULL, pressure_hpa REAL NOT NULL, recorded_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); CREATE INDEX ix_weather_station ON dbo.weather (station, recorded_at); GO -- Rejects readings that a working BME280 can't produce (e.g. after -- a loose wire). THROW makes the call fail on the device. CREATE PROCEDURE dbo.add_weather @station VARCHAR(32), @temperature REAL, @humidity REAL, @pressure_hpa REAL AS BEGIN IF @temperature NOT BETWEEN -40 AND 85 OR @humidity NOT BETWEEN 0 AND 100 OR @pressure_hpa NOT BETWEEN 300 AND 1100 THROW 50001, 'Reading out of the BME280''s range', 1; INSERT INTO dbo.weather (station, temperature, humidity, pressure_hpa) VALUES (@station, @temperature, @humidity, @pressure_hpa); END GO ``` ```sql -- The station may only add readings. Run CREATE LOGIN in master. CREATE LOGIN weather WITH PASSWORD = ''; CREATE USER weather FOR LOGIN weather; GRANT EXECUTE ON dbo.add_weather TO weather; GO ``` The procedure rejects readings that a BME280 can't produce, with `THROW`, so a faulty sensor shows up as failed calls rather than as bad data. ## Configure the sketch Install the **Adafruit BME280 Library**, open [weather_station.ino](https://github.com/tdslite/tdslite/blob/main/examples/projects/weather_station/weather_station.ino), and fill in the Wi-Fi and database settings at the top. With PlatformIO: ```ini lib_deps = mustafakemalgilor/tdslite adafruit/Adafruit BME280 Library@^2.2 ``` ## How it works After deep sleep, the board starts from the beginning, so everything happens in `setup()`: read the sensor, connect, store, sleep. Nothing is kept from one wake-up to the next. ```c++ // Everything happens in setup(): each wake-up starts the sketch anew void setup() { Serial.begin(115200); if (not bme.begin(0x76) && not bme.begin(0x77)) { Serial.println("No BME280 found; check the wiring"); sleep_until_next_reading(); } // Forced mode: one measurement on request, then the sensor sleeps too bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::FILTER_OFF); bme.takeForcedMeasurement(); const float temperature = bme.readTemperature(); const float humidity = bme.readHumidity(); const float pressure = bme.readPressure() / 100.0f; // Pa -> hPa Serial.printf("%.2f C, %.1f %%, %.1f hPa\n", temperature, humidity, pressure); if (isnan(temperature) || isnan(humidity) || isnan(pressure)) { // SQL Server can't store NaN; the sensor didn't answer Serial.println("The BME280 returned no reading"); } else if (not connect_wifi()) { Serial.println("No Wi-Fi; this reading is lost"); } else if (not store_reading(temperature, humidity, pressure)) { Serial.println("Could not store the reading"); } else { Serial.println("Stored"); } sleep_until_next_reading(); } void loop() { // Not reached: deep sleep ends with a restart } ``` Each wake-up logs in afresh, with few retries: a station that can't reach the server gives up and sleeps, rather than draining the battery. ```c++ static bool store_reading(float temperature, float humidity, float pressure_hpa) { decltype(driver)::connection_parameters params; params.server_name = db_server; params.db_name = db_name; params.user_name = db_user; params.password = db_password; params.app_name = station_name; params.packet_size = 1024; params.conn_retry_count = 2; params.conn_retry_delay_ms = 1000; if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) { return false; } tdsl::sql_parameter_varchar station{station_name}; tdsl::sql_parameter_float4 t{temperature}, h{humidity}, p{pressure_hpa}; tdsl::sql_parameter_binding values []{station, t, h, p}; return static_cast(driver.execute_rpc( tdsl::string_view{"EXEC dbo.add_weather @station = @p0, @temperature = @p1, " "@humidity = @p2, @pressure_hpa = @p3"}, values)); } ``` ```c++ static void sleep_until_next_reading() { Serial.printf("Sleeping for %u minute(s)\n", static_cast(sleep_minutes)); Serial.flush(); const uint64_t us = uint64_t{sleep_minutes} * 60u * 1000000u; #if defined(ESP32) esp_sleep_enable_timer_wakeup(us); esp_deep_sleep_start(); #else ESP.deepSleep(us); // wakes up through GPIO16 -> RST #endif } ``` The server stamps each reading with its own clock (`DEFAULT SYSUTCDATETIME()`), so the station needs no clock and no NTP. ## Reports From [queries.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/weather_station/queries.sql). The times are in UTC. The latest reading of each station: ```sql -- The latest reading of each station, and how old it is SELECT station, temperature, humidity, pressure_hpa, recorded_at, DATEDIFF(MINUTE, recorded_at, SYSUTCDATETIME()) AS minutes_ago FROM ( SELECT station, temperature, humidity, pressure_hpa, recorded_at, ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at DESC, id DESC) AS n FROM dbo.weather ) AS w WHERE n = 1; ``` Daily minimum, maximum and average: ```sql -- Daily minimum, maximum and average, over the last 30 days SELECT station, CAST(recorded_at AS DATE) AS day, MIN(temperature) AS min_temperature, MAX(temperature) AS max_temperature, AVG(temperature) AS avg_temperature, AVG(humidity) AS avg_humidity FROM dbo.weather WHERE recorded_at > DATEADD(DAY, -30, SYSUTCDATETIME()) GROUP BY station, CAST(recorded_at AS DATE) ORDER BY station, day; ``` The pressure trend over the last 3 hours: ```sql -- Pressure change over the last 3 hours: a fall of more than -- 3 hPa often means worse weather is on its way SELECT station, MAX(CASE WHEN n_new = 1 THEN pressure_hpa END) - MAX(CASE WHEN n_old = 1 THEN pressure_hpa END) AS change_hpa FROM ( SELECT station, pressure_hpa, ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at DESC, id DESC) AS n_new, ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at ASC, id ASC) AS n_old FROM dbo.weather WHERE recorded_at > DATEADD(HOUR, -3, SYSUTCDATETIME()) ) AS w GROUP BY station; ``` Stations that stopped reporting: ```sql -- Stations that haven't reported for an hour: a flat battery, -- or out of Wi-Fi range SELECT station, MAX(recorded_at) AS last_reading FROM dbo.weather GROUP BY station HAVING MAX(recorded_at) < DATEADD(HOUR, -1, SYSUTCDATETIME()); ``` ## The complete sketch **weather_station.ino** ```c++ #if defined(ESP32) #include #elif defined(ESP8266) #include #else #error "This sketch is for the ESP32 and the ESP8266" #endif #include #include #include static const char * wifi_ssid = ""; static const char * wifi_password = ""; static const char db_server [] = "192.168.1.10"; static const char db_name [] = "home"; static const char db_user [] = "weather"; static const char db_password [] = ""; static const char station_name [] = "garden"; // Minutes between readings static constexpr uint32_t sleep_minutes = 10; static tdsl::uint8_t net_buf [2048] = {}; static tdsl::arduino_driver driver{net_buf}; static Adafruit_BME280 bme; static void sleep_until_next_reading() { Serial.printf("Sleeping for %u minute(s)\n", static_cast(sleep_minutes)); Serial.flush(); const uint64_t us = uint64_t{sleep_minutes} * 60u * 1000000u; #if defined(ESP32) esp_sleep_enable_timer_wakeup(us); esp_deep_sleep_start(); #else ESP.deepSleep(us); // wakes up through GPIO16 -> RST #endif } static bool connect_wifi() { WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); // Don't drain the battery waiting for a network that isn't there for (int i = 0; i < 30 && WiFi.status() != WL_CONNECTED; i++) { delay(500); } return WiFi.status() == WL_CONNECTED; } static bool store_reading(float temperature, float humidity, float pressure_hpa) { decltype(driver)::connection_parameters params; params.server_name = db_server; params.db_name = db_name; params.user_name = db_user; params.password = db_password; params.app_name = station_name; params.packet_size = 1024; params.conn_retry_count = 2; params.conn_retry_delay_ms = 1000; if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) { return false; } tdsl::sql_parameter_varchar station{station_name}; tdsl::sql_parameter_float4 t{temperature}, h{humidity}, p{pressure_hpa}; tdsl::sql_parameter_binding values []{station, t, h, p}; return static_cast(driver.execute_rpc( tdsl::string_view{"EXEC dbo.add_weather @station = @p0, @temperature = @p1, " "@humidity = @p2, @pressure_hpa = @p3"}, values)); } // Everything happens in setup(): each wake-up starts the sketch anew void setup() { Serial.begin(115200); if (not bme.begin(0x76) && not bme.begin(0x77)) { Serial.println("No BME280 found; check the wiring"); sleep_until_next_reading(); } // Forced mode: one measurement on request, then the sensor sleeps too bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::FILTER_OFF); bme.takeForcedMeasurement(); const float temperature = bme.readTemperature(); const float humidity = bme.readHumidity(); const float pressure = bme.readPressure() / 100.0f; // Pa -> hPa Serial.printf("%.2f C, %.1f %%, %.1f hPa\n", temperature, humidity, pressure); if (isnan(temperature) || isnan(humidity) || isnan(pressure)) { // SQL Server can't store NaN; the sensor didn't answer Serial.println("The BME280 returned no reading"); } else if (not connect_wifi()) { Serial.println("No Wi-Fi; this reading is lost"); } else if (not store_reading(temperature, humidity, pressure)) { Serial.println("Could not store the reading"); } else { Serial.println("Stored"); } sleep_until_next_reading(); } void loop() { // Not reached: deep sleep ends with a restart } ``` ## Going further - **Battery life:** most of the energy goes into Wi-Fi and the login, a few seconds per wake-up. A longer `sleep_minutes` helps the most. A static IP address saves the time DHCP takes. - **Several stations:** give each its own `station_name`; the reports group by it. - **Readings while offline:** a reading that can't be sent is lost. To keep them, store them in RTC memory and send them on the next wake-up. ## Related - [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/index.md): a station that stays connected - [Fit tdslite into a small RAM budget](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md) # RFID attendance Hold a card to an RC522 reader, and the board asks SQL Server whose card it is, logs the scan, and lights a green or red LED. One stored procedure call per scan does the lookup and the logging; there's no web server or PHP script in between. SQL queries give the attendance: who came in today, and when each person arrived and left. ## Parts and wiring - ESP32 or ESP8266 board - RC522 RFID reader (13.56 MHz, MIFARE cards and tags). It runs on **3.3 V**; 5 V damages it. - Optional: a green and a red LED, each with a resistor (220 Ω to 1 kΩ) | RC522 | ESP32 | ESP8266 | | --------- | ------ | ------- | | SDA (SS) | GPIO5 | D8 | | SCK | GPIO18 | D5 | | MOSI | GPIO23 | D7 | | MISO | GPIO19 | D6 | | RST | GPIO22 | D3 | | 3.3V | 3V3 | 3V3 | | GND | GND | GND | | green LED | GPIO25 | D1 | | red LED | GPIO26 | D2 | ## Set up the database Run [setup.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/rfid_attendance/setup.sql) in your database: ```sql CREATE TABLE dbo.cards ( uid VARCHAR(20) NOT NULL PRIMARY KEY, -- hex, as the reader sends it holder NVARCHAR(64) NOT NULL, active BIT NOT NULL DEFAULT 1 ); CREATE TABLE dbo.scans ( id INT IDENTITY PRIMARY KEY, uid VARCHAR(20) NOT NULL, reader VARCHAR(32) NOT NULL, accepted BIT NOT NULL, scanned_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); CREATE INDEX ix_scans_uid ON dbo.scans (uid, scanned_at); GO -- Logs the scan, and returns one row: accepted (1 or 0) and the -- card holder (NULL for unknown cards). Unknown cards are logged -- too, so you can see who tried, and add their cards. CREATE PROCEDURE dbo.scan_card @uid VARCHAR(20), @reader VARCHAR(32) AS BEGIN SET NOCOUNT ON; DECLARE @holder NVARCHAR(64), @active BIT; SELECT @holder = holder, @active = active FROM dbo.cards WHERE uid = @uid; DECLARE @accepted BIT = CASE WHEN @active = 1 THEN 1 ELSE 0 END; INSERT INTO dbo.scans (uid, reader, accepted) VALUES (@uid, @reader, @accepted); SELECT @accepted AS accepted, @holder AS holder; END GO ``` ```sql -- The reader may only report scans. Run CREATE LOGIN in master. CREATE LOGIN door_reader WITH PASSWORD = ''; CREATE USER door_reader FOR LOGIN door_reader; GRANT EXECUTE ON dbo.scan_card TO door_reader; GO ``` The reader's login can only call `scan_card`. It can't list the cards or the scans, and can't add cards. ## Configure the sketch Install the **MFRC522** library (by GithubCommunity / miguelbalboa), open [rfid_attendance.ino](https://github.com/tdslite/tdslite/blob/main/examples/projects/rfid_attendance/rfid_attendance.ino), and fill in the settings at the top. With PlatformIO: ```ini lib_deps = mustafakemalgilor/tdslite miguelbalboa/MFRC522@^1.4 ``` ## Add cards Scan a card: the serial monitor shows its UID, e.g. `04A23B1C: unknown or blocked card`. Add it, and block lost cards: ```sql -- Add a card: the UID is printed on the serial monitor when an -- unknown card is scanned, and logged in dbo.scans INSERT INTO dbo.cards (uid, holder) VALUES ('04A23B1C', N'Ada Lovelace'); -- Block a lost card; its scans are still logged UPDATE dbo.cards SET active = 0 WHERE uid = '04A23B1C'; -- Unknown cards scanned in the last week SELECT uid, COUNT(*) AS scans, MAX(scanned_at) AS last_scan FROM dbo.scans WHERE accepted = 0 AND uid NOT IN (SELECT uid FROM dbo.cards) AND scanned_at > DATEADD(DAY, -7, SYSUTCDATETIME()) GROUP BY uid; ``` ## How it works The card's UID becomes hex text: ```c++ // The card's UID as hex text, e.g. "04A23B1C" static void uid_to_hex(const MFRC522::Uid & uid, char (&out) [21]) { static const char digits [] = "0123456789ABCDEF"; uint8_t n = 0; for (uint8_t i = 0; i < uid.size && i < 10; i++) { out [n++] = digits [uid.uidByte [i] >> 4]; out [n++] = digits [uid.uidByte [i] & 0x0F]; } out [n] = '\0'; } ``` `check_card` calls the procedure, and its row callback reads the answer: `accepted` is a `bit`, the holder's name an `nvarchar` (UTF-16), or `NULL` for an unknown card: ```c++ // What SQL Server answered for a card. (Declared before the // functions: the Arduino IDE puts its prototypes there.) struct scan_result { bool answered = false; // the procedure returned its row bool accepted = false; char holder [65] = {}; // the card holder's name, ASCII only }; ``` ```c++ static void read_result(void * user, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { scan_result & r = *static_cast(user); r.answered = true; r.accepted = row [0].as(); if (not row [1].is_null()) { // nvarchar: UTF-16. Keep the ASCII characters for the serial // monitor; a display library could take all of them. const auto name = row [1].as(); size_t n = 0; for (const char16_t c : name) { if (n + 1 < sizeof(r.holder)) { r.holder [n++] = c < 0x80 ? static_cast(c) : '?'; } } } } // Logs the scan and returns whether the card is allowed in static scan_result check_card(const char * uid) { tdsl::sql_parameter_varchar card{tdsl::string_view{uid, strlen(uid)}}; tdsl::sql_parameter_varchar where{reader_name}; tdsl::sql_parameter_binding params []{card, where}; for (int attempt = 0; attempt < 2; attempt++) { scan_result r; const auto result = driver.execute_rpc( tdsl::string_view{"EXEC dbo.scan_card @uid = @p0, @reader = @p1"}, params, tdsl::rpc_mode::executesql, read_result, &r); if (result || not(result.error() == tdsl::detail::e_rpc_error_code::network_error) || not connect_to_db()) { return r; } } return {}; } ``` If SQL Server doesn't answer, the sketch fails closed: red LED, as for an unknown card. ```c++ void loop() { if (not reader.PICC_IsNewCardPresent() || not reader.PICC_ReadCardSerial()) { delay(50); return; } char uid [21]; uid_to_hex(reader.uid, uid); reader.PICC_HaltA(); // one scan per tap const scan_result r = check_card(uid); if (not r.answered) { // No answer from the database: fail closed Serial.printf("%s: no answer from SQL Server\n", uid); signal(pin_red); } else if (r.accepted) { Serial.printf("%s: welcome, %s\n", uid, r.holder); signal(pin_green); } else { Serial.printf("%s: unknown or blocked card\n", uid); signal(pin_red); } } ``` ## Reports From [queries.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/rfid_attendance/queries.sql). The times are in UTC. First and last scan per person and day: ```sql -- Attendance: first and last scan of each person per day, over the -- last 30 days SELECT c.holder, CAST(s.scanned_at AS DATE) AS day, MIN(s.scanned_at) AS first_scan, MAX(s.scanned_at) AS last_scan, DATEDIFF(MINUTE, MIN(s.scanned_at), MAX(s.scanned_at)) / 60.0 AS hours FROM dbo.scans AS s JOIN dbo.cards AS c ON c.uid = s.uid WHERE s.accepted = 1 AND s.scanned_at > DATEADD(DAY, -30, SYSUTCDATETIME()) GROUP BY c.holder, CAST(s.scanned_at AS DATE) ORDER BY day, c.holder; ``` Who has scanned in today: ```sql -- Who has scanned in today SELECT DISTINCT c.holder FROM dbo.scans AS s JOIN dbo.cards AS c ON c.uid = s.uid WHERE s.accepted = 1 AND s.scanned_at >= CAST(SYSUTCDATETIME() AS DATE); ``` ## The complete sketch **rfid_attendance.ino** ```c++ #if defined(ESP32) #include #elif defined(ESP8266) #include #else #error "This sketch is for the ESP32 and the ESP8266" #endif #include #include #include static const char * wifi_ssid = ""; static const char * wifi_password = ""; static const char db_server [] = "192.168.1.10"; static const char db_name [] = "office"; static const char db_user [] = "door_reader"; static const char db_password [] = ""; static const char reader_name [] = "front-door"; #if defined(ESP32) static constexpr uint8_t pin_ss = 5, pin_rst = 22, pin_green = 25, pin_red = 26; #else static constexpr uint8_t pin_ss = D8, pin_rst = D3, pin_green = D1, pin_red = D2; #endif static tdsl::uint8_t net_buf [2048] = {}; static tdsl::arduino_driver driver{net_buf}; static MFRC522 reader{pin_ss, pin_rst}; // What SQL Server answered for a card. (Declared before the // functions: the Arduino IDE puts its prototypes there.) struct scan_result { bool answered = false; // the procedure returned its row bool accepted = false; char holder [65] = {}; // the card holder's name, ASCII only }; static void print_message(void *, const tdsl::tds_info_token & token) noexcept { if (not token.is_error()) { return; } Serial.print("SQL Server error: "); for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } static bool connect_to_db() { decltype(driver)::connection_parameters params; params.server_name = db_server; params.db_name = db_name; params.user_name = db_user; params.password = db_password; params.app_name = reader_name; params.packet_size = 1024; return driver.connect(params) == decltype(driver)::e_driver_error_code::success; } // The card's UID as hex text, e.g. "04A23B1C" static void uid_to_hex(const MFRC522::Uid & uid, char (&out) [21]) { static const char digits [] = "0123456789ABCDEF"; uint8_t n = 0; for (uint8_t i = 0; i < uid.size && i < 10; i++) { out [n++] = digits [uid.uidByte [i] >> 4]; out [n++] = digits [uid.uidByte [i] & 0x0F]; } out [n] = '\0'; } static void read_result(void * user, const tdsl::tds_colmetadata_token &, const tdsl::tdsl_row & row) { scan_result & r = *static_cast(user); r.answered = true; r.accepted = row [0].as(); if (not row [1].is_null()) { // nvarchar: UTF-16. Keep the ASCII characters for the serial // monitor; a display library could take all of them. const auto name = row [1].as(); size_t n = 0; for (const char16_t c : name) { if (n + 1 < sizeof(r.holder)) { r.holder [n++] = c < 0x80 ? static_cast(c) : '?'; } } } } // Logs the scan and returns whether the card is allowed in static scan_result check_card(const char * uid) { tdsl::sql_parameter_varchar card{tdsl::string_view{uid, strlen(uid)}}; tdsl::sql_parameter_varchar where{reader_name}; tdsl::sql_parameter_binding params []{card, where}; for (int attempt = 0; attempt < 2; attempt++) { scan_result r; const auto result = driver.execute_rpc( tdsl::string_view{"EXEC dbo.scan_card @uid = @p0, @reader = @p1"}, params, tdsl::rpc_mode::executesql, read_result, &r); if (result || not(result.error() == tdsl::detail::e_rpc_error_code::network_error) || not connect_to_db()) { return r; } } return {}; } static void signal(uint8_t pin) { digitalWrite(pin, HIGH); delay(1500); digitalWrite(pin, LOW); } void setup() { Serial.begin(115200); pinMode(pin_green, OUTPUT); pinMode(pin_red, OUTPUT); SPI.begin(); reader.PCD_Init(); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); } driver.set_info_callback(print_message); while (not connect_to_db()) { Serial.println("SQL Server: connect failed, retrying"); delay(5000); } Serial.println("Ready: hold a card to the reader"); } void loop() { if (not reader.PICC_IsNewCardPresent() || not reader.PICC_ReadCardSerial()) { delay(50); return; } char uid [21]; uid_to_hex(reader.uid, uid); reader.PICC_HaltA(); // one scan per tap const scan_result r = check_card(uid); if (not r.answered) { // No answer from the database: fail closed Serial.printf("%s: no answer from SQL Server\n", uid); signal(pin_red); } else if (r.accepted) { Serial.printf("%s: welcome, %s\n", uid, r.holder); signal(pin_green); } else { Serial.printf("%s: unknown or blocked card\n", uid); signal(pin_red); } } ``` ## Before you use it for a door A card's UID is easy to copy: cheap cards and phones can pretend to have any UID. That's fine for attendance, where the worst case is a wrong entry in a report. For a door lock, use cards with cryptographic authentication (e.g. MIFARE DESFire), keep the lock working when the network is down, and follow the fire safety rules for doors. ## Related - [Call a stored procedure](https://tdslite.github.io/tdslite/latest/how-to/stored-procedures/index.md): result sets and errors - [Read column values](https://tdslite.github.io/tdslite/latest/how-to/read-columns/index.md): `bit`, `nvarchar` and `NULL` # Energy monitor A PZEM-004T v3 meter measures voltage, current, power and energy; the board stores a reading every 10 seconds in SQL Server. SQL queries turn them into daily and monthly consumption, the cost, the power use by hour of the day, and the standby load at night. > **Danger: Mains voltage** > > The PZEM-004T's measuring side connects to mains voltage. Wire it only if you're qualified to, with the power off, in a closed enclosure, and as your local rules require. The current is measured with a clamp (current transformer) around one wire; nothing has to be cut. ## Parts and wiring - ESP32 or ESP8266 board - PZEM-004T **v3** with its current transformer. The v3 uses Modbus; older versions need another library. The TTL side, at 5 V: | PZEM-004T | ESP32 | ESP8266 | | --------- | ------------------- | ---------------------- | | 5V | 5V (VIN) | 5V (VIN) | | GND | GND | GND | | TX | GPIO16 (Serial2 RX) | D5 (SoftwareSerial RX) | | RX | GPIO17 (Serial2 TX) | D6 (SoftwareSerial TX) | ## Set up the database Run [setup.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/energy_monitor/setup.sql) in your database: ```sql CREATE TABLE dbo.energy ( id BIGINT IDENTITY PRIMARY KEY, meter VARCHAR(32) NOT NULL, voltage REAL NOT NULL, current_a REAL NOT NULL, power_w REAL NOT NULL, energy_wh INT NOT NULL, -- the meter's counter, in Wh frequency REAL NOT NULL, power_factor REAL NOT NULL, recorded_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); CREATE INDEX ix_energy_meter ON dbo.energy (meter, recorded_at); GO CREATE PROCEDURE dbo.add_energy @meter VARCHAR(32), @voltage REAL, @current_a REAL, @power_w REAL, @energy_wh INT, @frequency REAL, @power_factor REAL AS INSERT INTO dbo.energy (meter, voltage, current_a, power_w, energy_wh, frequency, power_factor) VALUES (@meter, @voltage, @current_a, @power_w, @energy_wh, @frequency, @power_factor); GO ``` ```sql -- The monitor may only add readings. Run CREATE LOGIN in master. CREATE LOGIN energy WITH PASSWORD = ''; CREATE USER energy FOR LOGIN energy; GRANT EXECUTE ON dbo.add_energy TO energy; GO ``` ## Configure the sketch Install the **PZEM-004T-v30** library (by Jakub Mandula), open [energy_monitor.ino](https://github.com/tdslite/tdslite/blob/main/examples/projects/energy_monitor/energy_monitor.ino), and fill in the settings at the top. With PlatformIO: ```ini lib_deps = mustafakemalgilor/tdslite mandulaj/PZEM-004T-v30@^1.1 ``` ## How it works The meter is on a serial port: a hardware one on the ESP32, a software one on the ESP8266: ```c++ #if defined(ESP32) static PZEM004Tv30 meter{Serial2, 16, 17}; #else static SoftwareSerial meter_serial{D5, D6}; // RX, TX static PZEM004Tv30 meter{meter_serial}; #endif ``` The parameters are bound once; each reading sets their values and calls the procedure. The energy counter goes into an `int`, in Wh: tdslite has no 8-byte `float` parameter, and a 4-byte `float` loses precision on a large kWh counter. ```c++ // Bound once; set the values before each call static tdsl::sql_parameter_varchar p_meter{meter_name}; static tdsl::sql_parameter_float4 p_voltage{}, p_current{}, p_power{}, p_frequency{}, p_pf{}; static tdsl::sql_parameter_int p_energy_wh{}; static tdsl::sql_parameter_binding params []{p_meter, p_voltage, p_current, p_power, p_energy_wh, p_frequency, p_pf}; static bool store_reading() { for (int attempt = 0; attempt < 2; attempt++) { const auto result = driver.execute_rpc( tdsl::string_view{"EXEC dbo.add_energy @meter = @p0, @voltage = @p1, " "@current_a = @p2, @power_w = @p3, @energy_wh = @p4, " "@frequency = @p5, @power_factor = @p6"}, params); if (result) { return true; } if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) || not connect_to_db()) { return false; } } return false; } ``` The meter answers with NaN when it can't measure, e.g. without mains power. Those readings are skipped: ```c++ void loop() { static unsigned long last = 0; if (last != 0 && millis() - last < interval_ms) { return; } last = millis(); const float voltage = meter.voltage(); const float energy = meter.energy(); // kWh since the meter's last reset if (isnan(voltage) || isnan(energy)) { // No answer: wiring, or the meter has no mains power Serial.println("No reading from the PZEM-004T"); return; } p_voltage = voltage; p_current = meter.current(); p_power = meter.power(); p_energy_wh = static_cast(energy * 1000.0f + 0.5f); p_frequency = meter.frequency(); p_pf = meter.pf(); Serial.printf("%.1f V, %.0f W, %.3f kWh -> %s\n", voltage, static_cast(p_power), energy, store_reading() ? "stored" : "not stored"); } ``` At one reading every 10 seconds, the table grows by about 8,600 rows a day, which SQL Server handles easily. Raise `interval_ms` if you don't need that detail. ## Reports From [queries.sql](https://github.com/tdslite/tdslite/blob/main/examples/projects/energy_monitor/queries.sql). The meter's counter only goes up, unless it's reset; the reports add up the increases between readings, so a reset doesn't count as negative use. Daily consumption: ```sql -- Daily consumption in kWh, over the last 30 days WITH steps AS ( SELECT meter, recorded_at, energy_wh - LAG(energy_wh) OVER (PARTITION BY meter ORDER BY recorded_at, id) AS step_wh FROM dbo.energy WHERE recorded_at > DATEADD(DAY, -31, SYSUTCDATETIME()) ) SELECT meter, CAST(recorded_at AS DATE) AS day, SUM(CASE WHEN step_wh > 0 THEN step_wh ELSE 0 END) / 1000.0 AS kwh FROM steps WHERE recorded_at > DATEADD(DAY, -30, SYSUTCDATETIME()) GROUP BY meter, CAST(recorded_at AS DATE) ORDER BY meter, day; ``` Monthly consumption and cost: ```sql -- Monthly consumption and cost; set your price per kWh DECLARE @price_per_kwh DECIMAL(6, 4) = 0.30; WITH steps AS ( SELECT meter, recorded_at, energy_wh - LAG(energy_wh) OVER (PARTITION BY meter ORDER BY recorded_at, id) AS step_wh FROM dbo.energy ) SELECT meter, DATEFROMPARTS(YEAR(recorded_at), MONTH(recorded_at), 1) AS month, SUM(CASE WHEN step_wh > 0 THEN step_wh ELSE 0 END) / 1000.0 AS kwh, SUM(CASE WHEN step_wh > 0 THEN step_wh ELSE 0 END) / 1000.0 * @price_per_kwh AS cost FROM steps GROUP BY meter, DATEFROMPARTS(YEAR(recorded_at), MONTH(recorded_at), 1) ORDER BY meter, month; ``` Power use by hour of the day (UTC): ```sql -- Average power by hour of the day, over the last 7 days: when -- the house uses the most SELECT meter, DATEPART(HOUR, recorded_at) AS hour_utc, AVG(power_w) AS avg_power_w, MAX(power_w) AS peak_power_w FROM dbo.energy WHERE recorded_at > DATEADD(DAY, -7, SYSUTCDATETIME()) GROUP BY meter, DATEPART(HOUR, recorded_at) ORDER BY meter, hour_utc; ``` The standby load: what the house draws when everything should be off: ```sql -- Standby load: the lowest 5-minute average power of each night -- (00:00 - 05:00 UTC), over the last 7 nights SELECT meter, CAST(slot AS DATE) AS night, MIN(avg_w) AS standby_w FROM ( SELECT meter, DATEADD(MINUTE, DATEDIFF(MINUTE, 0, recorded_at) / 5 * 5, 0) AS slot, AVG(power_w) AS avg_w FROM dbo.energy WHERE recorded_at > DATEADD(DAY, -7, SYSUTCDATETIME()) AND DATEPART(HOUR, recorded_at) < 5 GROUP BY meter, DATEADD(MINUTE, DATEDIFF(MINUTE, 0, recorded_at) / 5 * 5, 0) ) AS s GROUP BY meter, CAST(slot AS DATE) ORDER BY meter, night; ``` ## The complete sketch **energy_monitor.ino** ```c++ #if defined(ESP32) #include #elif defined(ESP8266) #include #else #error "This sketch is for the ESP32 and the ESP8266" #endif #if defined(ESP8266) #include #endif #include #include static const char * wifi_ssid = ""; static const char * wifi_password = ""; static const char db_server [] = "192.168.1.10"; static const char db_name [] = "home"; static const char db_user [] = "energy"; static const char db_password [] = ""; static const char meter_name [] = "main"; static constexpr unsigned long interval_ms = 10000; static tdsl::uint8_t net_buf [2048] = {}; static tdsl::arduino_driver driver{net_buf}; #if defined(ESP32) static PZEM004Tv30 meter{Serial2, 16, 17}; #else static SoftwareSerial meter_serial{D5, D6}; // RX, TX static PZEM004Tv30 meter{meter_serial}; #endif static void print_message(void *, const tdsl::tds_info_token & token) noexcept { if (not token.is_error()) { return; } Serial.print("SQL Server error: "); for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } static bool connect_to_db() { decltype(driver)::connection_parameters params; params.server_name = db_server; params.db_name = db_name; params.user_name = db_user; params.password = db_password; params.app_name = meter_name; params.packet_size = 1024; return driver.connect(params) == decltype(driver)::e_driver_error_code::success; } // Bound once; set the values before each call static tdsl::sql_parameter_varchar p_meter{meter_name}; static tdsl::sql_parameter_float4 p_voltage{}, p_current{}, p_power{}, p_frequency{}, p_pf{}; static tdsl::sql_parameter_int p_energy_wh{}; static tdsl::sql_parameter_binding params []{p_meter, p_voltage, p_current, p_power, p_energy_wh, p_frequency, p_pf}; static bool store_reading() { for (int attempt = 0; attempt < 2; attempt++) { const auto result = driver.execute_rpc( tdsl::string_view{"EXEC dbo.add_energy @meter = @p0, @voltage = @p1, " "@current_a = @p2, @power_w = @p3, @energy_wh = @p4, " "@frequency = @p5, @power_factor = @p6"}, params); if (result) { return true; } if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) || not connect_to_db()) { return false; } } return false; } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); } driver.set_info_callback(print_message); while (not connect_to_db()) { Serial.println("SQL Server: connect failed, retrying"); delay(5000); } } void loop() { static unsigned long last = 0; if (last != 0 && millis() - last < interval_ms) { return; } last = millis(); const float voltage = meter.voltage(); const float energy = meter.energy(); // kWh since the meter's last reset if (isnan(voltage) || isnan(energy)) { // No answer: wiring, or the meter has no mains power Serial.println("No reading from the PZEM-004T"); return; } p_voltage = voltage; p_current = meter.current(); p_power = meter.power(); p_energy_wh = static_cast(energy * 1000.0f + 0.5f); p_frequency = meter.frequency(); p_pf = meter.pf(); Serial.printf("%.1f V, %.0f W, %.3f kWh -> %s\n", voltage, static_cast(p_power), energy, store_reading() ? "stored" : "not stored"); } ``` ## Going further - **Several circuits:** several PZEM-004T meters can share one serial port with different Modbus addresses; give each its own `meter` name. - **Local time:** the reports group by UTC. On SQL Server 2016 and later, `recorded_at AT TIME ZONE 'UTC' AT TIME ZONE 'W. Europe Standard Time'` converts to a local time zone. ## Related - [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/index.md) - [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/index.md): the parameter types # Handle errors and server messages tdslite doesn't throw exceptions. `connect`, `execute_query` and `execute_rpc` return a value that tells whether they worked, and SQL Server's own messages, the reasons for failures among them, go to an *info callback*. ## Receive SQL Server's messages Register an info callback before connecting, so you also see why a login fails: ```c++ // Called for each message that SQL Server sends, errors included static void print_message(void *, const tdsl::tds_info_token & token) noexcept { Serial.print(token.is_error() ? "server error: " : "server info: "); // The message text is UTF-16; this prints its ASCII characters for (const char16_t c : token.msgtext) { Serial.print(static_cast(c)); } Serial.println(); } driver.set_info_callback(print_message); ``` `token.number` is SQL Server's error number (e.g. 18456 for a failed login, 208 for an unknown table), and `token.is_error()` tells an error from an informational message. ## Check the connection ```c++ const auto cr = driver.connect(params); if (not(cr == decltype(driver)::e_driver_error_code::success)) { // connection_failed: the server could not be reached // login_failed: the server refused the login (see the info callback) // connection_param_*: a connection parameter is invalid } ``` ## Check a query The result of `execute_query` converts to `false` when the query failed. Its flags tell why: ```c++ auto result = driver.execute_query("SELECT * FROM fruits", print_row); if (not result) { if (result.request_too_large) { // The query doesn't fit into the network buffer. Nothing was sent. } else if (result.response_too_large) { // A row, the column list or a message is larger than the network // buffer. The query ran. tdslite closed the connection: call // driver.connect(...) again, and select less. } else if (result.network_error) { // The connection is lost (or timed out), and closed. Call // driver.connect(...) again. } else if (result.response_error) { // The response could not be processed (e.g. unsupported column // type, out of memory). The result set might be incomplete. } else { // SQL Server reported an error. Its message went to the info // callback. } } ``` For `execute_rpc`, check `result.error()` instead; see [Run parameterized queries](https://tdslite.github.io/tdslite/latest/how-to/parameterized-queries/#check-the-result). > **Warning: Errors inside stored procedures** > > In a stored procedure with `SET NOCOUNT ON`, an error that doesn't end the procedure (e.g. `RAISERROR`, or a failed `INSERT`) reaches the info callback, but the result reports success. Count the errors in the info callback to catch them; see [Call a stored procedure](https://tdslite.github.io/tdslite/latest/how-to/stored-procedures/#detect-errors-inside-the-procedure). ## Recover | What happened | The connection | What to do | | ------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------- | | SQL Server reported an error | still usable | Fix the query and carry on. | | `request_too_large` | still usable | Shorten the query, or enlarge the network buffer. | | `response_error` | still usable | Avoid the column type, or free some memory. | | `network_error` | closed | Call `driver.connect(params)` again. | | `response_too_large` (with `network_error`) | closed | Reconnect. Select less per row, or enlarge the network buffer: the same query fails the same way. | A reconnect starts a new session: temporary (`#`) tables of the old session are gone, and an open transaction of the old session isn't carried over. A small pattern for long-running devices: ```c++ void loop() { auto result = driver.execute_query(TDSL_PMEMSTR("SELECT ..."), on_row); if (result.network_error) { while (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) { delay(5000); } } delay(1000); } ``` `connect` itself makes `params.conn_retry_count` attempts, waiting `params.conn_retry_delay_ms` between them. It blocks the whole time: with the defaults and an unreachable server, that can be minutes. See [how long `connect` blocks](https://tdslite.github.io/tdslite/latest/reference/connection-parameters/#how-long-connect-blocks). ## Related - [Results and error codes](https://tdslite.github.io/tdslite/latest/reference/errors/index.md): every value these calls return. - [Troubleshoot](https://tdslite.github.io/tdslite/latest/how-to/troubleshooting/index.md): what common errors mean. - Example sketch: [04 - Read info/error messages](https://github.com/tdslite/tdslite/tree/main/examples/arduino/04-info-callback) # Connect with TLS Encrypt the connection when the network between your device and SQL Server isn't one you trust, or when the server requires encryption. tdslite uses TDS 8.0 *strict* mode: the TLS handshake comes first, and everything after it, the password included, is encrypted. ## Check the server first Strict mode needs: - SQL Server 2025, SQL Server 2022 on Windows, or Azure SQL. SQL Server 2022 on Linux doesn't accept strict connections. - A TLS certificate configured on the server: on Linux, `network.tlscert` and `network.tlskey` in `mssql-conf`. SQL Server's self-generated certificate isn't enough; with it, the server closes the connection (error 17821 in its log). - The PEM file of the CA that signed the server's certificate, to give to your device. ## Connect **ESP32 / ESP8266 (Arduino):** Use `WiFiClientSecure` as the client. It does the TLS part, so configure it through `driver.network().client()`, then tell tdslite that the connection is encrypted with `set_tls_client(true)`: ```c++ #include #include tdsl::uint8_t net_buf [4096] = {}; tdsl::arduino_driver driver{net_buf}; // PEM text of the CA that signed the server's certificate static const char ca_pem [] = R"(-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- )"; void setup() { // ... connect to Wi-Fi, and set the clock (see below) driver.network().client().setCACert(ca_pem); driver.network().set_tls_client(true); // then driver.connect(params) as usual } ``` **On ESP8266**, BearSSL puts at most 512 bytes into a TLS record by default, and SQL Server drops a strict connection when a TDS packet is split over several records. Raise the buffer, and tell tdslite the limit: ```c++ static BearSSL::X509List trusted_ca{ca_pem}; // must outlive the connection driver.network().client().setTrustAnchors(&trusted_ca); driver.network().client().setBufferSizes(16384, 2048); driver.network().set_tls_client(true, 2048); params.packet_size = 2048; ``` **Set the clock.** Checking a certificate needs the current time. Before connecting, get it over NTP: ```c++ configTime(0, 0, "pool.ntp.org"); while (time(nullptr) < 1700000000) { delay(500); } ``` The complete sketch is [examples/boards/esp_wifi_tls](https://github.com/tdslite/tdslite/blob/main/examples/boards/esp_wifi_tls/esp_wifi_tls.ino). **ESP-IDF:** Use `tdsl::esp_tls_driver` in place of `tdsl::socket_driver`. The tdslite component already depends on esp-tls. Embed the CA certificate in your component's `CMakeLists.txt`: ```cmake idf_component_register(SRCS "main.cpp" INCLUDE_DIRS "." EMBED_TXTFILES "ca.pem") ``` and give it to the driver before connecting: ```c++ #include extern const char ca_pem [] asm("_binary_ca_pem_start"); static tdsl::uint8_t net_buf [2048] = {}; static tdsl::esp_tls_driver driver{net_buf}; tdsl::net::tdsl_esp_tls_options tls; tls.ca_pem = ca_pem; // or tls.use_crt_bundle = true for public CAs (Azure SQL) driver.network().set_tls_options(tls); // then driver.connect(params) as usual ``` **Check certificate dates.** By default ESP-IDF doesn't check a certificate's validity dates (`CONFIG_MBEDTLS_HAVE_TIME_DATE=n`), so an expired certificate from a trusted CA is accepted. To check them, enable `CONFIG_MBEDTLS_HAVE_TIME_DATE` and set the clock (e.g. over SNTP, with `esp_sntp`) before connecting. Without a set clock, every certificate then looks not yet valid, and the connection fails. The ESPHome component does both for you. **Record size.** `CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN` must be at least the TDS packet size (`params.packet_size`, 4096 by default, which is also mbedTLS's default). The complete project is [examples/esp-idf/query-tls](https://github.com/tdslite/tdslite/tree/main/examples/esp-idf/query-tls). **Desktop (Boost.ASIO):** Link with the `tdslite.net.asio.tls` CMake target. It exists when CMake finds OpenSSL: look for `tdslite.net.asio.tls: enabled` in the CMake output. tdslite's own CMake project gets OpenSSL from conan, so there's nothing to install. ```c++ #include #include tdsl::detail::tdsl_driver driver; tdsl::net::tdsl_asio_tls_options tls; tls.ca_file = "/path/to/ca.pem"; // empty: the system's certificate store driver.network().set_tls_options(tls); // then driver.connect(params) as usual ``` ## Connect by IP address The certificate is checked against the host name you give to `connect`. If you connect by IP address, either the certificate must list that address, or you name a host that it lists: **ESP-IDF:** ```c++ tls.host_name = "db.example"; ``` **Desktop (Boost.ASIO):** ```c++ tls.host_name = "db.example"; ``` On Arduino, `WiFiClientSecure` checks the certificate against the name you connect to, so connect by a host name that the certificate lists, as the example sketch does. ## Keep transactions inside one query On a TLS connection, a transaction must start and end within one `execute_query` (or one stored procedure): ```c++ driver.execute_query( "BEGIN TRAN; UPDATE stock SET n = n - 1 WHERE id = 7; INSERT INTO log VALUES (7); COMMIT;"); ``` A `BEGIN TRAN` on its own makes every later request fail with error 3989, until the driver reconnects. [TDS versions and encryption](https://tdslite.github.io/tdslite/latest/explanation/tds-and-tls/#transactions-over-tls) explains why. ## If it doesn't connect A failed TLS connection makes `connect` return `connection_failed`. See [Troubleshoot](https://tdslite.github.io/tdslite/latest/how-to/troubleshooting/#a-tls-connection-fails) and the TLS error codes in [Results and error codes](https://tdslite.github.io/tdslite/latest/reference/errors/#tls-backends). ## Related - [TDS versions and encryption](https://tdslite.github.io/tdslite/latest/explanation/tds-and-tls/index.md): what strict mode is, and why tdslite uses it. - [Network backends](https://tdslite.github.io/tdslite/latest/reference/network-backends/index.md): the TLS options of each backend. # 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: ```text 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: ```c++ 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`: ```c++ 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(""); 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](https://github.com/McNeight/MemoryFree) library, while a query is running (inside the row callback). For reference, the [tested numbers on an Uno](https://tdslite.github.io/tdslite/latest/reference/limits/#memory-on-an-arduino-uno). ## Related - [Memory model](https://tdslite.github.io/tdslite/latest/explanation/memory-model/index.md): where tdslite keeps what, and why. - [Use your own memory allocator](https://tdslite.github.io/tdslite/latest/how-to/custom-allocator/index.md) - [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/index.md) # Use your own memory allocator tdslite takes a little heap memory while a query runs, for the descriptors of the result set's columns and fields. By default it calls `malloc` and `free`. Replace them when you want to trace allocations, serve them from a static pool, or run on a platform without a heap. ## Set the functions Write a pair of functions with these signatures, and hand them to tdslite once, before the first `connect`: ```c++ void * my_malloc(unsigned long amount) noexcept { return ::malloc(amount); } void my_free(void * ptr) noexcept { ::free(ptr); } void setup() { tdsl::tdslite_malloc_free(my_malloc, my_free); // ... then connect as usual } ``` Set both or neither: passing only one of them is an error. If `my_malloc` returns `nullptr`, the query that needed the memory fails with `response_error`, and the connection stays usable. ## Remove the default allocator To make sure nothing in your program pulls in `malloc` through tdslite, define `TDSL_DISABLE_DEFAULT_ALLOCATOR` before including tdslite, e.g. in your build flags: **PlatformIO:** ```ini build_flags = -DTDSL_DISABLE_DEFAULT_ALLOCATOR ``` **CMake:** ```cmake target_compile_definitions(my_app PRIVATE TDSL_DISABLE_DEFAULT_ALLOCATOR) ``` You must then call `tdsl::tdslite_malloc_free(...)` before using the driver. ## Related - [Memory model](https://tdslite.github.io/tdslite/latest/explanation/memory-model/index.md): what tdslite allocates and when. - Example sketch: [06 - Custom memory allocator functions](https://github.com/tdslite/tdslite/tree/main/examples/arduino/06-custom-malloc) # Write a network backend tdslite doesn't open network connections itself. It talks through a *backend*, and you can plug in your own when none of the [built-in ones](https://tdslite.github.io/tdslite/latest/reference/network-backends/index.md) fits your network stack. There are two ways, depending on what your stack looks like. ## Your client looks like Arduino's `EthernetClient` Many Arduino networking libraries copy the `EthernetClient` interface. If yours has these members, use it with `tdsl::arduino_driver` as it is: ```c++ struct my_client { int connect(const char * host, unsigned short port); bool connected(); int available(); void flush(); void stop(); tdsl::size_t write(const unsigned char * buf, tdsl::size_t len); int read(unsigned char * buf, unsigned long amount); // Only needed with debug printing on (TDSL_DEBUG_PRINT_ENABLED): tdsl::uint16_t remotePort(); IPAddress remoteIP(); }; tdsl::uint8_t net_buf [768] = {}; tdsl::arduino_driver driver{net_buf}; ``` If your client has most of these under other names, write a small wrapper class with these members that calls into it. ## Anything else: implement the backend A backend is a class that derives from `tdsl::net::network_io_base` and has five functions: `do_connect`, `do_disconnect`, `do_send` and two `do_recv`. The library checks at compile time that they exist with the right signatures. This guide builds a backend on top of four functions of an imaginary network stack: ```c++ // Your network stack. Each returns a negative value on error. int my_transport_open(const char * host, unsigned short port); int my_transport_write(const unsigned char * data, unsigned long len); int my_transport_read(unsigned char * data, unsigned long len); // blocks until len bytes arrive void my_transport_close(); ``` ### 1. Write the class ```c++ #include #include namespace my { struct netimpl : public tdsl::net::network_io_base { using network_io_result = typename network_io_base::network_io_result; // The caller supplies the network buffer template explicit netimpl(tdsl::uint8_t (&buf) [N]) noexcept { this->network_buffer = tdsl::tdsl_buffer_object{buf}; } // Connect to target:port. Called by driver.connect(). template tdsl::expected do_connect(T target, tdsl::uint16_t port) noexcept { do_disconnect(); this->network_buffer.get_writer()->reset(); // target can be a flash, wide or plain string: copy it out char host [256] = {}; tdsl::size_t n = 0; for (auto c : target) { if (c == 0 || n == sizeof(host) - 1) { break; } host [n++] = static_cast(c); } if (my_transport_open(host, port) < 0) { return tdsl::unexpected(-1); } connected = true; return tdsl::traits::true_type{}; } tdsl::int32_t do_disconnect() noexcept { if (connected) { my_transport_close(); connected = false; } return 0; } // Send one TDS packet: its 8-byte header, then its data. The driver // puts the header directly in front of the data, so as_packet() // joins them into one block for a single write. tdsl::int32_t do_send(tdsl::byte_view header, tdsl::byte_view message) noexcept { if (not connected) { return -1; } const auto packet = this->as_packet(header, message); const bool ok = packet.size_bytes() ? my_transport_write(packet.data(), packet.size_bytes()) >= 0 : (my_transport_write(header.data(), header.size_bytes()) >= 0 && my_transport_write(message.data(), message.size_bytes()) >= 0); if (not ok) { do_disconnect(); return -1; } return 0; } // Receive exactly `amount` bytes into dst network_io_result do_recv(tdsl::uint32_t amount, tdsl::byte_span dst) noexcept { if (amount > dst.size_bytes() || not connected) { return tdsl::unexpected(-1); } if (my_transport_read(dst.data(), amount) < 0) { do_disconnect(); return tdsl::unexpected(-2); } return amount; } // Receive exactly `amount` bytes into the free space of the network buffer network_io_result do_recv(tdsl::uint32_t amount) noexcept { auto writer = this->network_buffer.get_writer(); if (amount > writer->remaining_bytes()) { return tdsl::unexpected(-3); } auto result = do_recv(amount, writer->free_span()); if (result) { writer->advance(static_cast(amount)); } return result; } private: bool connected = {false}; }; using driver = tdsl::driver; } // namespace my ``` Things that matter: - **The network buffer.** Set `this->network_buffer` in the constructor. The library reads all its data from it. - **`do_recv` reads exactly.** Both overloads return only after exactly `amount` bytes have arrived, or with an error. The one-argument overload appends to the network buffer and advances its writer. - **One write per packet.** Send each packet with a single write where you can. On TLS connections this is required: SQL Server drops a strict connection when a packet arrives split over several TLS records. - **Close on error.** After a failed send or receive, close the connection. The driver reports `network_error`, and the application reconnects. ### 2. Use it ```c++ static tdsl::uint8_t net_buf [2048] = {}; static my::driver driver{net_buf}; int run() { my::driver::connection_parameters params; params.server_name = "192.168.1.10"; params.user_name = "sa"; params.password = ""; if (not(driver.connect(params) == my::driver::e_driver_error_code::success)) { return 1; } return driver.execute_query("SELECT 1") ? 0 : 1; } ``` `driver.network()` returns your backend object, if you need to configure it before connecting. ### 3. Learn from the built-in backends The [BSD sockets backend](https://github.com/tdslite/tdslite/blob/main/src/tdslite-net/socket/tdsl_netimpl_socket.hpp) is the closest to this skeleton, with timeouts and retries added. The [ESP-IDF TLS backend](https://github.com/tdslite/tdslite/blob/main/src/tdslite-net/esp-idf/tdsl_netimpl_esp_tls.hpp) shows how a backend handles TLS. ## Related - [The network abstraction](https://tdslite.github.io/tdslite/latest/explanation/network-abstraction/index.md): why tdslite is split this way. - [Network backends](https://tdslite.github.io/tdslite/latest/reference/network-backends/index.md) # Troubleshoot Start by registering an [info callback](https://tdslite.github.io/tdslite/latest/how-to/handle-errors/#receive-sql-servers-messages): most failures come with a message from SQL Server that names the problem. ## Connecting ### `connect` returns `connection_failed` The TCP connection couldn't be established. - Check the server address and the port (1433 by default). - From a board, use your computer's IP address, not `localhost`. - Check that the computer's firewall lets port 1433 in. - Check that SQL Server accepts TCP connections. In SQL Server Configuration Manager (Windows), TCP/IP must be enabled. ### `connect` returns `login_failed` The server was reached, but refused the login. - Error 18456 (`Login failed for user ...`) in the info callback: the user name or password is wrong, or the user can't use SQL Server authentication. Windows authentication isn't supported. - The user name and password are right: the server may require encryption, and it refuses unencrypted logins. Connect with [TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md). ### `connect` returns `connection_param_*` A connection parameter is invalid: - `connection_param_server_name_empty`: `server_name` isn't set. - `connection_param_packet_size_invalid`: `packet_size` isn't between 512 and 32767. - `connection_param_retry_invalid`: `conn_retry_count` or `conn_retry_delay_ms` is above 65535. ### A TLS connection fails TLS failures make `connect` return `connection_failed`. - Check the SQL Server error log. Error 17821 means the server has no certificate configured for strict connections. - Otherwise the certificate was probably rejected: the CA you gave the device must be the one that signed the server's certificate, and the host name (or IP address) you connect to must be in the certificate. - On boards, the clock must be set before connecting, or every certificate looks not yet valid. - The backend's `do_connect` result names the reason; see [TLS error codes](https://tdslite.github.io/tdslite/latest/reference/errors/#tls-backends). ## Queries ### A number reads as zero The type given to `as()` is wider than the column: a `smallint` column reads as zero with `as()`. Use `as()`. See [Data types](https://tdslite.github.io/tdslite/latest/reference/data-types/#reading-columns). ### A string is garbled, or has a `\0` after every character The column is `nchar` or `nvarchar`, which are UTF-16. Read it with `as()` instead of `as()`. ### A date reads as a string That's expected: SQL Server sends `date`, `time`, `datetime2` and `datetimeoffset` to tdslite as `nvarchar`. See [Data types](https://tdslite.github.io/tdslite/latest/reference/data-types/#types-sql-server-converts). ### The result reports `request_too_large` The query doesn't fit into the network buffer. Shorten it, or enlarge the buffer; see [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/index.md). ### The result reports `network_error` while reading rows The connection was lost, the response took longer than the receive timeout, or, with `response_too_large` set too, a row, the column list or a message (e.g. from `PRINT`) is larger than the network buffer. In each case tdslite closes the connection, so that the rest of the response is never read as the next query's result. Reconnect with `driver.connect(...)`. For `response_too_large`, enlarge the buffer, select shorter values or fewer columns, or shorten the message: running the query again ends the same way. For a slow query on an Arduino-core board, raise the timeout with `driver.network().set_receive_timeout(ms)`. ### The result reports `response_error` The response couldn't be processed: it has a column of an unsupported type (e.g. `sql_variant`), or there wasn't enough memory. ### Error 3989 after `BEGIN TRAN` on a TLS connection On TLS connections, a transaction must start and end within one query. See [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/#keep-transactions-inside-one-query). ## Hardware ### My Ethernet library isn't supported Most Ethernet libraries implement the `EthernetClient` interface and work with `tdsl::arduino_driver` directly. If yours doesn't, you can: 1. write a wrapper class for it, see [Write a network backend](https://tdslite.github.io/tdslite/latest/how-to/custom-backend/index.md); 1. ask the library's author to implement a compatible interface; 1. [open an issue](https://github.com/tdslite/tdslite/issues) to suggest support in tdslite, if the library is widely used. ### Still stuck? [Open an issue](https://github.com/tdslite/tdslite/issues) with your board, backend, SQL Server version and what the info callback printed. # Reference # Reference Facts about tdslite, to look up while you work. - [Connection parameters](https://tdslite.github.io/tdslite/latest/reference/connection-parameters/index.md): every field of `connection_parameters`, with its default - [Data types](https://tdslite.github.io/tdslite/latest/reference/data-types/index.md): how SQL types are read and bound - [Results and error codes](https://tdslite.github.io/tdslite/latest/reference/errors/index.md): what `connect`, `execute_query`, `execute_rpc` and the backends return - [Network backends](https://tdslite.github.io/tdslite/latest/reference/network-backends/index.md): headers, driver types and options per platform - [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/index.md): query and row sizes, packet size, memory figures - [Examples](https://tdslite.github.io/tdslite/latest/reference/examples/index.md): the example programs in the repository - [Tested hardware](https://tdslite.github.io/tdslite/latest/reference/tested-hardware/index.md) - [C++ API](https://tdslite.github.io/tdslite/latest/reference/api/index.md): the classes and functions, generated from the source ## For AI assistants The whole documentation is also available as plain Markdown, in the [llms.txt](https://llmstxt.org) format: [llms.txt](https://tdslite.github.io/tdslite/latest/llms.txt) lists every page with a summary, and [llms-full.txt](https://tdslite.github.io/tdslite/latest/llms-full.txt) has all of them in one file, to give to an AI assistant or coding agent. Every page is also available as Markdown: add `index.md` to its address. # Connection parameters `driver.connect(params)` takes one of three parameter structs. They have the same fields and differ in the string type: | Type | Strings are | Use it | | ------------------------------------------------- | ------------------------------------ | -------------------------------- | | `decltype(driver)::connection_parameters` | `const char *` / `tdsl::string_view` | Most of the time | | `decltype(driver)::progmem_connection_parameters` | `TDSL_PMEMSTR("...")`, kept in flash | On AVR boards, to save RAM | | `decltype(driver)::wconnection_parameters` | `tdsl::wstring_view` (UTF-16) | For non-ASCII names or passwords | ## Fields | Field | Type | Default | Description | | --------------------- | ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `server_name` | string | (required) | Host name or IP address of the server | | `port` | `uint16_t` | `1433` | TCP port of the server | | `user_name` | string | empty | SQL Server login name | | `password` | string | empty | Password of the login | | `db_name` | string | empty | Database to use after logging in. Empty: the login's default database | | `app_name` | string | empty | Application name, shown in SQL Server's session list | | `client_name` | string | empty | Client machine name, shown in SQL Server's session list | | `library_name` | string | `"tdslite"` | Client library name sent to the server | | `packet_size` | `uint32_t` | `4096` | TDS packet size to ask the server for, 512 – 32767 | | `conn_retry_count` | `uint32_t` | `10` | Connection attempts before `connect` gives up, at most 65535. `0` makes no attempt: `connect` fails at once with `connection_failed` | | `conn_retry_delay_ms` | `uint32_t` | `3000` | Milliseconds between connection attempts, at most 65535 | `connect` checks the parameters before connecting, and returns an [error code](https://tdslite.github.io/tdslite/latest/reference/errors/#connect) when one is out of range. The login struct has more fields (`client_program_version`, `client_pid`, option flags, ...) that map directly to the TDS login packet. Leave them at their defaults unless you know the protocol; see the [C++ API](https://tdslite.github.io/tdslite/latest/reference/api/index.md). ## Packet size The packet size is the size of the TDS packets that client and server exchange. The server may grant a different size than the one asked for. The login itself is sent in packets of at most 4096 bytes. - On small boards, use 512 with a network buffer somewhat larger than that. - On TLS connections, the packet size must not exceed what one TLS record can hold; see [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md). ## How long `connect` blocks `connect` doesn't return until it's logged in or its last attempt has failed. The worst case is about ```text conn_retry_count × (time of one failed attempt + conn_retry_delay_ms) ``` One failed attempt takes as long as the network library takes to give up: | Situation | Measured time of one attempt | | ------------------------------------------- | ------------------------------------------------------ | | Host name doesn't resolve | ~2 s (ESP8266) | | Server refuses the connection (port closed) | ~12 s for 2 attempts (ESP8266) | | Server unreachable (no reply at all) | ~21 s (Uno WiFi Rev. 2), the library's connect timeout | With the defaults (10 attempts, 3 s apart) and an unreachable server, that is about 4 minutes, during which the sketch does nothing else. To keep a sketch responsive, use few attempts (e.g. `conn_retry_count = 1`) and retry from `loop()` instead; on the socket backends, set a shorter connect timeout with `set_socket_timeouts`. # Data types ## Reading columns Read a field with `row[i].as()`. For integer and floating point types, `T` must have the same size as the column: a narrower column, or a `NULL`, reads as zero. `row[i].is_null()` tells a `NULL` from a zero or an empty value. | SQL type | Read as | | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | `bit` | `as()` | | `tinyint` | `as()` | | `smallint` | `as()` | | `int` | `as()` | | `bigint` | `as()` | | `real` | `as()` | | `float` | `as()`, on platforms where `double` is 8 bytes | | `char`, `varchar`, `text` | `as()`: not null-terminated, use `data()` and `size()` | | `nchar`, `nvarchar`, `ntext` | `as()`: UTF-16 code units | | `money`, `smallmoney` | `as()`, with `integer()`, `fraction()` (four decimal digits) and `raw()` | | `binary`, `varbinary`, `image`, `uniqueidentifier`, `timestamp` | the field itself: a view of the raw bytes (`data()`, `size_bytes()`) | | `sql_variant` | not supported: the query reports `response_error` | Views point into the network buffer and are valid until the row callback returns. ## Types SQL Server converts tdslite logs in as a TDS 7.1 client, so SQL Server converts the types that came after TDS 7.1 before sending them: | Column type | Arrives as | Read as | | --------------------------------------------- | ---------------------------------------------- | ------------------------ | | `date`, `time`, `datetime2`, `datetimeoffset` | `nvarchar`, e.g. `2020-01-02 03:04:05.0000000` | `as()` | | `varchar(max)` | `text` | `as()` | | `nvarchar(max)`, `xml` | `ntext` | `as()` | | `varbinary(max)` | `image` | the field itself | ## Query parameters `execute_rpc` accepts these parameter types: | SQL type | Parameter type | Constructed from | | --------------------- | ------------------------------------------------------------- | ---------------------------- | | `bit` | `tdsl::sql_parameter_bit` | `bool` | | `tinyint` | `tdsl::sql_parameter_tinyint` | `tdsl::uint8_t` | | `smallint` | `tdsl::sql_parameter_smallint` | `tdsl::int16_t` | | `int` | `tdsl::sql_parameter_int` | `tdsl::int32_t` | | `bigint` | `tdsl::sql_parameter_bigint` | `tdsl::int64_t` | | `real` | `tdsl::sql_parameter_float4` | `float` | | `char`, `varchar` | `tdsl::sql_parameter_char`, `tdsl::sql_parameter_varchar` | `tdsl::string_view` | | `nchar`, `nvarchar` | `tdsl::sql_parameter_nchar`, `tdsl::sql_parameter_nvarchar` | `tdsl::wstring_view` | | `binary`, `varbinary` | `tdsl::sql_parameter_binary`, `tdsl::sql_parameter_varbinary` | `tdsl::byte_view` | | `uniqueidentifier` | `tdsl::sql_parameter_guid` | `tdsl::byte_view` (16 bytes) | `float` (8 bytes), `decimal`, `numeric`, `money` and the date and time types can't be bound as parameters yet, and neither can `NULL`. # Results and error codes ## `connect` `driver.connect(params)` returns a `decltype(driver)::e_driver_error_code`: | Value | Meaning | | -------------------------------------- | --------------------------------------------------------------------------------------- | | `success` | Connected and logged in | | `connection_failed` | Every connection attempt failed, TLS failures included | | `login_failed` | Connected, but the server refused the login. The reason went to the info callback | | `connection_param_server_name_empty` | `server_name` is empty | | `connection_param_packet_size_invalid` | `packet_size` is not between 512 and 32767 | | `connection_param_retry_invalid` | `conn_retry_count` or `conn_retry_delay_ms` is above 65535 | | `busy` | Called from one of the driver's callbacks, while a request is running. Nothing was done | `connect` blocks until it succeeds or the last attempt fails. See [Connection parameters](https://tdslite.github.io/tdslite/latest/reference/connection-parameters/#how-long-connect-blocks) for the worst case. ## `execute_query` `execute_query` returns a query result. It converts to `true` when the query succeeded. | Member | Type | Meaning | | -------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `affected_rows` | `uint32_t` | Rows affected or returned by the last statement that reports a count | | `request_too_large` | `bool` | The query doesn't fit into the network buffer. Nothing was sent | | `network_error` | `bool` | Sending or receiving failed, or SQL Server ended the session with a fatal error (severity 20 or above, e.g. the session was killed), and the connection is closed. The query may or may not have run. Also set when the driver isn't logged in (e.g. `connect` failed). Reconnect | | `response_too_large` | `bool` | A row, the column list or a message of the response is larger than the network buffer. The query ran. The connection is closed, so `network_error` is set too. Reconnect | | `response_error` | `bool` | The response couldn't be processed (unsupported column type, out of memory). The result set may be incomplete. The connection stays usable | | `busy` | `bool` | Called from one of the driver's callbacks (e.g. the row callback), while another request is running. Nothing was sent, and the running request isn't affected | | `status` | `tds_done_token::status_type` | The status of SQL Server's last DONE token | When the result is `false` and none of the flags is set, SQL Server reported an error; its message went to the info callback. The connection stays usable. ## `execute_rpc` `execute_rpc` returns a `tdsl::expected`. When it converts to `true`, `get()` is the number of rows affected or returned. Otherwise `error()` is a `tdsl::detail::e_rpc_error_code`: | Value | Meaning | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `invalid_mode` | The mode isn't supported. Only `tdsl::rpc_mode::executesql` is | | `request_too_large` | The request doesn't fit into the network buffer, or its query text or parameter declarations are longer than 4000 characters (see [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/index.md)). Nothing was sent | | `invalid_response` | The response couldn't be processed completely | | `server_error` | SQL Server reported an error. Its message went to the info callback. Not reported for some errors inside stored procedures; see [Call a stored procedure](https://tdslite.github.io/tdslite/latest/how-to/stored-procedures/#detect-errors-inside-the-procedure) | | `network_error` | Sending or receiving failed, or SQL Server ended the session with a fatal error (severity 20 or above), and the connection is closed; or the driver isn't logged in. Reconnect | | `response_too_large` | A row, the column list or a message of the response is larger than the network buffer. The request ran. The connection is closed. Reconnect | | `invalid_parameter` | A parameter has an unsupported type or an invalid size. Nothing was sent | | `busy` | Called from one of the driver's callbacks, while another request is running. Nothing was sent | The driver can't be called from its own callbacks (row, info, column names): the running request uses the connection and the network buffer. Store what you need in the callback, and send the next request after the running one returns. ## Info callback The info callback receives a `tdsl::tds_info_token` for each message from SQL Server: | Member | Meaning | | ------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `number` | SQL Server's message number, e.g. 18456 (login failed), 208 (invalid object name) | | `state` | The error state | | `class_` | The severity. Above 10 is an error; 20 and above is fatal: SQL Server ends the session and closes the connection | | `line_number` | Line of the batch or procedure the message is about | | `msgtext` | The message, as `tdsl::u16le_view` (UTF-16) | | `server_name` | The server's name, UTF-16 | | `proc_name` | The stored procedure's name, if any, UTF-16 | | `is_error()`, `is_info()` | Whether the severity makes it an error | | `is_fatal()` | Severity 20 or above: the session ends. The request then reports a network error | ## Backends `connect` reports every network failure as `connection_failed`. The backend's own error code tells more. To see it, call the backend's `do_connect` yourself while you investigate: ```c++ auto r = driver.network().do_connect(tdsl::string_view{"db.example"}, 1433); if (not r) { printf("do_connect failed: %d\n", r.error()); } ``` ### BSD sockets `tdsl::net::tdsl_netimpl_socket::e_socket_error`: | Value | Code | Meaning | | --------------------- | ---- | -------------------------------------------- | | `host_too_long` | -1 | The host name is longer than 255 characters | | `resolve_failed` | -2 | The host name couldn't be resolved | | `connection_failed` | -3 | The TCP connection couldn't be established | | `disconnected` | -4 | The server closed the connection | | `timeout` | -5 | No data arrived within the I/O timeout | | `io_error` | -6 | A socket call failed | | `not_enough_capacity` | -7 | The data doesn't fit into the network buffer | | `not_connected` | -8 | Not connected | ### TLS backends ESP-IDF (`tdsl::net::tdsl_netimpl_esp_tls::e_socket_error`) has the codes of the BSD sockets backend, plus: | Value | Code | Meaning | | ---------------------- | ---- | ------------------------------------------------------------------------------------------------------ | | `tls_handshake_failed` | -9 | The TLS handshake failed, e.g. the server doesn't support strict mode | | `tls_verify_failed` | -10 | The server's certificate was rejected: unknown CA, wrong host name, expired... `connect` doesn't retry | | `tls_setup_failed` | -11 | The TLS settings couldn't be applied, e.g. no CA given, or it can't be parsed. `connect` doesn't retry | | `packet_too_large` | -12 | A TDS packet doesn't fit into one TLS record. Nothing was sent | | `tls_init_failed` | -13 | The TLS session couldn't be set up, e.g. not enough heap. Retrying may help | | `not_contiguous` | -14 | Internal: the packet header wasn't in front of its data. Nothing was sent | Boost.ASIO (`tdsl::net::tdsl_netimpl_asio_tls::e_connect_error`): | Value | Code | Meaning | | ---------------------- | ---- | -------------------------------------------------------------------- | | `resolve_failed` | -2 | The host name couldn't be resolved | | `connection_failed` | -3 | The TCP connection couldn't be established | | `tls_handshake_failed` | -4 | The TLS handshake failed | | `tls_verify_failed` | -5 | The server's certificate was rejected | | `tls_setup_failed` | -6 | The TLS settings couldn't be applied, e.g. the CA file can't be read | ### Arduino `do_send` of `tdsl::net::tdsl_netimpl_arduino` returns an `e_send_error`: | Value | Code | Meaning | | ------------------ | ---- | ------------------------------------------------------------------------------------------------------------------------- | | `write_failed` | -1 | Writing failed. The connection is closed | | `packet_too_large` | -2 | A TDS packet is larger than the TLS client's record (see `set_tls_client`). Nothing was sent; the connection stays usable | | `not_contiguous` | -3 | Internal: the packet header wasn't in front of its data. Nothing was sent | # Network backends A backend is the part of tdslite that moves bytes over the network. Choose it by platform; the rest of the API is the same for all of them. | Backend | Platform | Header | Driver type | Encryption | Network buffer | | -------------- | ----------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------ | -------------------------------------------- | --------------- | | Arduino | Arduino, ESP32, ESP8266 (Arduino core) | `` | `tdsl::arduino_driver` | With a TLS client such as `WiFiClientSecure` | Yours | | BSD sockets | Linux, macOS, ESP-IDF (lwIP), Zephyr, FreeRTOS + lwIP | `` | `tdsl::socket_driver` | No | Yours | | ESP-IDF TLS | ESP-IDF 5.0+ | `` | `tdsl::esp_tls_driver` | Always (esp-tls) | Yours | | Boost.ASIO | Desktop | `` | `tdsl::driver` | No | 16 kB, internal | | Boost.ASIO TLS | Desktop | `` | `tdsl::driver` | Always (OpenSSL) | 16 kB, internal | "Yours" means you pass the buffer to the driver's constructor: ```c++ tdsl::uint8_t net_buf [768] = {}; tdsl::arduino_driver driver{net_buf}; ``` Backend options are set through `driver.network()`, before `connect`. ## Arduino `tdsl::arduino_driver` works with any client type that has the `EthernetClient` interface: `EthernetClient`, `WiFiClient`, `WiFiClientSecure`, or your own (see [Write a network backend](https://tdslite.github.io/tdslite/latest/how-to/custom-backend/index.md)). The network interface (e.g. `Ethernet.begin()`) must be up before `connect`. | Function | Description | | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `driver.network().client()` | The client object, e.g. to configure a TLS client | | `driver.network().set_tls_client(enabled, max_record_payload = 4096)` | Tell tdslite that the client encrypts the connection, and the most data the client puts into one TLS record. A larger TDS packet is refused instead of being sent split | | `driver.network().set_receive_timeout(ms)` | How long a receive waits for data (default 30000 ms). A receive that times out closes the connection | ## BSD sockets Header-only, nothing to link. CI tests it on Linux, and on ESP-IDF (in QEMU); the other platforms in the table aren't covered by CI yet. | Function | Description | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `driver.network().set_socket_timeouts(connect_ms, io_ms)` | Timeout of each connection attempt (default 10000 ms), and of each send and receive (default 30000 ms). A receive that times out closes the connection | ## ESP-IDF TLS Like the BSD sockets backend, with esp-tls underneath. Every connection is a TDS 8.0 strict one. Needs about 30 kB of heap while connected (mbedTLS's), and about 500 bytes more stack than the BSD sockets backend. | Function | Description | | --------------------------------------------------------- | ------------------------- | | `driver.network().set_tls_options(options)` | Set the TLS options below | | `driver.network().set_socket_timeouts(connect_ms, io_ms)` | As for BSD sockets | `tdsl::net::tdsl_esp_tls_options`: | Field | Default | Description | | ---------------- | --------- | -------------------------------------------------------------------------------------------------------------- | | `ca_pem` | `nullptr` | PEM text of the CA certificate(s) to trust, NUL-terminated. Takes precedence over `use_crt_bundle` | | `use_crt_bundle` | `false` | Trust the public CAs of ESP-IDF's certificate bundle (`CONFIG_MBEDTLS_CERTIFICATE_BUNDLE`), e.g. for Azure SQL | | `host_name` | `nullptr` | Host name to check the certificate against and send as SNI. `nullptr`: the host given to `connect` | | `alpn` | `true` | Send the `tds/8.0` ALPN protocol ID (needs `CONFIG_MBEDTLS_SSL_ALPN`) | `CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN` must be at least the TDS packet size. ## Boost.ASIO Compiled libraries, built by tdslite's CMake project: link with `tdslite.net.asio` or `tdslite.net.asio.tls`. The TLS target exists only when CMake finds OpenSSL. `tdsl::net::tdsl_asio_tls_options`, set with `driver.network().set_tls_options(options)`: | Field | Default | Description | | ----------- | ------- | -------------------------------------------------------------------------------------------------------------- | | `verify` | `true` | Check the server's certificate chain and host name. `false` leaves the connection open to anyone in the middle | | `ca_file` | empty | PEM file with the CA certificate(s) to trust. Empty: the system's certificate store | | `host_name` | empty | Host name to check the certificate against and send as SNI. Empty: the host given to `connect` | | `alpn` | `true` | Send the `tds/8.0` ALPN protocol ID | ## Related - [Results and error codes](https://tdslite.github.io/tdslite/latest/reference/errors/#backends): each backend's error codes - [The network abstraction](https://tdslite.github.io/tdslite/latest/explanation/network-abstraction/index.md) # Limits ## Queries | Limit | Value | | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | Longest `execute_query` text | (network buffer size − 8) / 2 characters. 380 with a 768-byte buffer | | ... on a TLS connection | 11 characters fewer (a 22-byte header) | | Longest `execute_rpc` query text | 4000 characters, and the request must fit into the network buffer | | Longest `execute_rpc` parameter declarations | 4000 characters. tdslite declares each parameter as `@p0 INT`, `@p1 VARCHAR(30)` and so on, joined with commas: about 400 `INT` parameters | | Query that doesn't fit | Not sent; the result reports `request_too_large` | Queries are sent as UTF-16, so every character takes two bytes. 8 bytes of the buffer are kept for the packet header. ## Result sets | Limit | Value | | -------------------------------------------- | ------------------------------------------------------------------------------------------------- | | Rows per result set | No limit: rows go to the callback one at a time | | Size of one row | Must fit into the network buffer | | Row, column list or message that doesn't fit | The query ends with `response_too_large` and `network_error`; the connection is closed; reconnect | For example, a row with a single `varchar` of 760 characters can be read with a 768-byte buffer, one of 800 characters can't. A 500-row result set reads through a 256-byte buffer. ## Connection | Limit | Value | | ----------------------------------------- | --------------------------------------------------------------- | | `packet_size` | 512 – 32767. The login is sent in packets of at most 4096 bytes | | `conn_retry_count`, `conn_retry_delay_ms` | At most 65535 | | Host name (BSD sockets, ESP-IDF backends) | 255 characters | ## Platform | | | | ----------------- | ------------------------------------------------------------------------------------ | | C++ standard | C++11 or newer. The unit tests are also built as C++14, C++17 and C++20 | | SQL Server | 2017, 2019, 2022 (plaintext) and 2025 (TLS) are tested in CI on every pull request | | TLS (strict mode) | SQL Server 2025, SQL Server 2022 on Windows, Azure SQL. Not SQL Server 2022 on Linux | | Authentication | SQL Server authentication. Windows (integrated) authentication isn't supported | | Protocol | tdslite logs in as a TDS 7.1 client, on TLS (TDS 8.0 strict) connections too | | ESP-IDF | 5.0 or newer | ## Memory on an Arduino Uno Measured on an ATmega328P (2 kB of SRAM): | Sketch | Network buffer | Packet size | RAM | Flash | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | ----------- | -------------------------------------------- | ----------- | | A minimal query sketch with the Ethernet library (2.0.2) | 768 bytes | 512 | 1236 bytes used by global variables, of 2048 | 23296 bytes | | The [simulation test firmware](https://github.com/tdslite/tdslite/tree/main/tests/simulation/avr): queries, parameterized queries and multi-packet result sets on a simulated Uno | 640 bytes | 512 | 501 bytes free while running | 25848 bytes | ## ESP-IDF TLS Measured on an ESP32 (in QEMU) with ESP-IDF 5.5's default mbedTLS settings: | | | | -------------------- | ----------------------------------------------------- | | Heap while connected | About 30 kB, all of it mbedTLS's. Freed on disconnect | | Stack | About 500 bytes more than the plaintext backend | ## ESPHome component The [`sql_server` component](https://tdslite.github.io/tdslite/latest/how-to/esphome/index.md) has a 4096-byte network buffer. Measured on an ESP32 (ESP-IDF and Arduino frameworks) over Wi-Fi, against SQL Server 2025: | Limit | Value | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Query text without parameters | 2044 characters; 2033 over TLS | | A query with parameters | The query and all parameters must fit in 4 KB. Text is UTF-16: a 1900-character parameter fits, a 4000-character one doesn't | | One row of a result | Must fit in 4 KB. A `VARCHAR(4000)` value fits; a full `NVARCHAR(4000)` value (8000 bytes) doesn't, whatever `max_text_size` is | | Rows of a result | No limit: 20,000 rows read in 0.6 s (only the first is kept) | | Requests a second | About 75 one after another; about 95 with the queue kept full. The same with TLS | | Requests waiting | `queue_size` (16 by default, up to 256), plus the one being sent | | RAM, each `sql_server` | About 14 kB: the worker thread's 8 kB stack, the network buffer and the queue | | TLS | About 28 kB more heap while connected, and about 68 kB of flash | A request that doesn't fit isn't sent: `on_error` says `too large for the 4 KB network buffer`. A row that doesn't fit ends the request with `Response too large`, and the component reconnects. An 8-minute soak test (10 inserts a second, three sensors polling every second, the session killed every 45 s) stored every insert that succeeded exactly once, and the free heap was the same at the end as after the first minute. # Examples Complete programs in the [examples](https://github.com/tdslite/tdslite/tree/main/examples) folder of the repository. CI builds the board, ESP-IDF and desktop examples on every pull request. ## Arduino In the Arduino IDE, they're under **File → Examples → tdslite** once the library is installed. Written for an Arduino Uno with an Ethernet shield. | Example | Shows | | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | [01 - Initialize library](https://github.com/tdslite/tdslite/tree/main/examples/arduino/01-initialize-library) | Every connection parameter, explained | | [02 - CRUD with tdslite](https://github.com/tdslite/tdslite/tree/main/examples/arduino/02-create-insert-select-delete) | Create, read, update and delete | | [03 - Read rows from table](https://github.com/tdslite/tdslite/tree/main/examples/arduino/03-select-rows) | Reading a result set with a row callback | | [04 - Read info/error messages](https://github.com/tdslite/tdslite/tree/main/examples/arduino/04-info-callback) | The info callback | | [05 - Execute query with parameters](https://github.com/tdslite/tdslite/tree/main/examples/arduino/05-query-with-parameters) | `execute_rpc` with bound parameters | | [06 - Custom memory allocator functions](https://github.com/tdslite/tdslite/tree/main/examples/arduino/06-custom-malloc) | Your own malloc and free | ## Boards | Example | Board | Shows | | ---------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------ | | [esp_wifi](https://github.com/tdslite/tdslite/blob/main/examples/boards/esp_wifi/esp_wifi.ino) | ESP32, ESP8266 | `WiFiClient`, parameterized inserts, reading rows back | | [esp_wifi_tls](https://github.com/tdslite/tdslite/blob/main/examples/boards/esp_wifi_tls/esp_wifi_tls.ino) | ESP32, ESP8266 | `WiFiClientSecure`, TDS 8.0 strict mode | | [uno_wifi_r2](https://github.com/tdslite/tdslite/blob/main/examples/boards/uno_wifi_r2/uno_wifi_r2.ino) | Arduino Uno WiFi Rev. 2 | WiFiNINA, insert and select | ## Projects Complete projects for the ESP32 and the ESP8266, each with a sketch, `setup.sql` and `queries.sql`. Their guides are under [Projects](https://tdslite.github.io/tdslite/latest/how-to/projects/index.md). | Example | Libraries | Shows | | ------------------------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------- | | [mqtt_sql_bridge](https://github.com/tdslite/tdslite/tree/main/examples/projects/mqtt_sql_bridge) | PubSubClient | Storing MQTT messages; reading JSON payloads in SQL | | [weather_station](https://github.com/tdslite/tdslite/tree/main/examples/projects/weather_station) | Adafruit BME280 | Deep sleep between readings; checks in a stored procedure | | [rfid_attendance](https://github.com/tdslite/tdslite/tree/main/examples/projects/rfid_attendance) | MFRC522 | A lookup and a log in one call; reading `bit`, `nvarchar` and `NULL` | | [energy_monitor](https://github.com/tdslite/tdslite/tree/main/examples/projects/energy_monitor) | PZEM-004T-v30 | Readings every 10 seconds; consumption reports with window functions | ## ESP-IDF | Example | Shows | | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | [esp-idf/query](https://github.com/tdslite/tdslite/tree/main/examples/esp-idf/query) | `socket_driver` over Wi-Fi or Ethernet, settings in `menuconfig` | | [esp-idf/query-tls](https://github.com/tdslite/tdslite/tree/main/examples/esp-idf/query-tls) | `esp_tls_driver`, an embedded CA certificate, SNTP for certificate dates | CI builds both with ESP-IDF 5.3 and the latest ESP-IDF, for ESP32, ESP32-C3 and ESP32-S3, and runs an end-to-end test in QEMU. ## Desktop | Example | Shows | | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | [minimal-sql-shell](https://github.com/tdslite/tdslite/tree/main/examples/minimal-sql-shell) | An interactive SQL shell over the Boost.ASIO backend, printing results as tables | Build tdslite's CMake project (see [the contributing guide](https://github.com/tdslite/tdslite/blob/main/CONTRIBUTING.md)) and run `./build/bin/tdslite.examples.minimal`. # Tested hardware Before each release, the [verification sketches](https://github.com/tdslite/tdslite/tree/main/tests/sketches) must run stable for at least three days straight on this hardware: | Board | Sketch | | ----------------------- | ------------------------------------------------------------------------------------------------- | | Arduino Mega | [Arduino sketch](https://github.com/tdslite/tdslite/blob/main/tests/sketches/arduino/arduino.cpp) | | Arduino Nano | Arduino sketch | | Arduino Uno | Arduino sketch | | Arduino Uno WiFi Rev. 2 | ESP sketch (its WiFiNINA variant) | | Arduino Portenta H7 | Arduino sketch | | NodeMCU-32 (ESP32S) | [ESP sketch](https://github.com/tdslite/tdslite/blob/main/tests/sketches/esp/esp.cpp) | | NodeMCU V3 (ESP8266MOD) | ESP sketch | ## Built in CI On every pull request, CI also compiles the sketches for these PlatformIO boards: - **AVR:** `nanoatmega328`, `uno`, `megaatmega1280`, `megaatmega2560`, `miniatmega328`, `micro`, `yun`, `nanoatmega328new`, `pro8MHzatmega328`, `ethernet` - **ESP:** `nodemcu-32s`, `nodemcuv2` - **RP2040:** `nanorp2040connect` - **nRF52:** `nano33ble`, `nicla_sense_me` - **STM32:** `portenta_h7_m4`, `portenta_h7_m7` - **SAMD:** `zero` - **megaAVR:** `uno_wifi_rev2` and runs a test firmware on a simulated Arduino Uno and in QEMU for ESP32. ## ESPHome component The [`sql_server` component](https://tdslite.github.io/tdslite/latest/how-to/esphome/index.md) has run on: | Board | Frameworks | Checked | | ----------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ESP32-D0WDQ6 (rev. 1), 4 MB flash, Wi-Fi (two boards) | ESP-IDF, Arduino | Every claim of the guide, its examples, TLS against SQL Server 2025 (expired and not yet valid certificates rejected), limits, stress, and a 45-minute soak test: 26,984 inserts while the server killed the session 60 times, at most one request lost per kill, no heap growth | The on-device tests are in [`extras/esphome`](https://github.com/tdslite/tdslite/tree/main/extras/esphome#on-real-hardware). ## Help this list grow You can donate hardware, or a few bucks, to get more boards tested. See [the contributing guide](https://github.com/tdslite/tdslite/blob/main/CONTRIBUTING.md). # C++ API The classes and functions of tdslite, generated from the comments in the headers with Doxygen. [Open the C++ API reference](https://tdslite.github.io/tdslite/latest/reference/cpp-api/index.md) It covers the user-facing headers: | Header | Contents | | ----------------------------------------------- | --------------------------------------------------------------------------------------- | | `tdslite.h` | `tdsl::arduino_driver`, for Arduino sketches | | `tdslite/tdslite.hpp` | `tdsl::driver`, the parameter types, `tdsl::rpc_mode` | | `tdslite/detail/tdsl_driver.hpp` | The driver: `connect`, `execute_query`, `execute_rpc`, `set_info_callback`, `network()` | | `tdslite/detail/tdsl_row.hpp`, `tdsl_field.hpp` | Rows and fields of a result set | | `tdslite/detail/tdsl_sql_parameter.hpp` | Query parameters | | `tdslite/detail/token/tds_info_token.hpp` | Server messages | | `tdslite-net/...` | The network backends and their base class | ## API at a glance Every public call of the driver, with the types involved. This file is compiled in CI, so it matches the library: ```c++ // The driver: tdsl::driver, with a network backend as NetImpl. // tdsl::socket_driver, tdsl::esp_tls_driver and tdsl::arduino_driver // are ready-made aliases. static tdsl::uint8_t net_buf [4096] = {}; static tdsl::socket_driver driver{net_buf}; // the backend takes the buffer // Callback types void on_info(void * user, const tdsl::tds_info_token & msg) noexcept; void on_row(void * user, const tdsl::tds_colmetadata_token & columns, const tdsl::tdsl_row & row); void api_at_a_glance() { using driver_t = decltype(driver); // Server messages (errors included) go to the info callback driver.set_info_callback(on_info, /*user=*/nullptr); // Read column names into tds_colmetadata_token::column_names (off by default) driver.option_set_read_column_names(true); // Backend options, before connect (here: BSD sockets timeouts) driver.network().set_socket_timeouts(/*connect_ms=*/10000, /*io_ms=*/30000); // Connect and log in. Also progmem_connection_parameters (TDSL_PMEMSTR // strings) and wconnection_parameters (UTF-16 strings). driver_t::connection_parameters params; params.server_name = "db.example"; // required params.port = 1433; params.user_name = "sa"; params.password = ""; params.db_name = "master"; params.app_name = "my app"; params.packet_size = 4096; // 512 - 32767 params.conn_retry_count = 10; params.conn_retry_delay_ms = 3000; const driver_t::e_driver_error_code cr = driver.connect(params); if (not(cr == driver_t::e_driver_error_code::success)) { // connection_failed, login_failed, connection_param_* return; } // A SQL batch. The row callback and its user pointer are optional. const auto qr = driver.execute_query("SELECT id, name FROM fruits", on_row, /*user=*/nullptr); if (qr) { const tdsl::uint32_t rows = qr.affected_rows; (void) rows; } else { // qr.request_too_large, qr.network_error, qr.response_error, // or none of them: SQL Server reported an error } // A parameterized query (sp_executesql). Parameters are @p0, @p1, ... tdsl::sql_parameter_varchar name{"apple"}; tdsl::sql_parameter_int stock{12}; tdsl::sql_parameter_binding bindings []{name, stock}; const auto rr = driver.execute_rpc( tdsl::string_view{"SELECT id FROM fruits WHERE name = @p0 AND stock > @p1"}, bindings, tdsl::rpc_mode::executesql, on_row, /*user=*/nullptr); if (rr) { const tdsl::uint32_t rows = rr.get(); (void) rows; } else { const tdsl::detail::e_rpc_error_code why = rr.error(); // e.g. server_error (void) why; } } void on_row(void *, const tdsl::tds_colmetadata_token & columns, const tdsl::tdsl_row & row) { const tdsl::uint32_t column_count = columns.columns.size(); const tdsl::uint32_t field_count = row.size(); const tdsl::tdsl_field & field = row [0]; const bool is_null = field.is_null(); // Numbers: the C++ type must have the size of the column const tdsl::int32_t number = field.as(); // varchar: not NUL-terminated const tdsl::char_view text = row [1].as(); // nvarchar: UTF-16 const tdsl::u16le_view wide = row [1].as(); // money: integer(), fraction() const tdsl::sql_money money = row [1].as(); // binary and other raw types: the field itself, data() and size_bytes() const tdsl::uint32_t raw_size = field.size_bytes(); (void) column_count, (void) field_count, (void) is_null, (void) number; (void) text, (void) wide, (void) money, (void) raw_size; } void on_info(void *, const tdsl::tds_info_token & msg) noexcept { // msg.number (e.g. 18456), msg.state, msg.class_ (severity), msg.line_number, // msg.msgtext, msg.server_name, msg.proc_name (UTF-16 views) const bool error = msg.is_error(); // severity above 10 (void) error; } ``` ## Namespaces Several public types are declared in the `tdsl::detail` namespace and re-exported in `tdsl` under shorter names, e.g. `tdsl::driver` for `tdsl::detail::tdsl_driver`. Prefer the `tdsl` names in your code. # Explanation # Explanation Background reading: why tdslite works the way it does. None of this is needed to use the library, but it helps you make good choices with it. - [Design goals](https://tdslite.github.io/tdslite/latest/explanation/design/index.md): what tdslite is for, and what it leaves out - [The network abstraction](https://tdslite.github.io/tdslite/latest/explanation/network-abstraction/index.md): why the library doesn't do its own networking - [Memory model](https://tdslite.github.io/tdslite/latest/explanation/memory-model/index.md): where the bytes go, and why rows arrive through a callback - [TDS versions and encryption](https://tdslite.github.io/tdslite/latest/explanation/tds-and-tls/index.md): what TDS 7.1 and TDS 8.0 strict mode mean for you - [Direct connections and gateways](https://tdslite.github.io/tdslite/latest/explanation/direct-vs-gateway/index.md): when a device should talk to SQL Server itself, and when through an API # Design goals tdslite exists so that small, constrained devices (microcontrollers, IoT nodes) can talk to Microsoft SQL Server directly, without a gateway or a web service in between. ## Only pay for what you use Most SQL Server clients assume a computer with megabytes of memory, threads and a full C++ standard library. An Arduino Uno has 2 kB of RAM and none of that. So tdslite is built around C++'s "zero cost" idea: a feature you don't use costs no flash and no RAM. That shapes the API: - **You own the big allocations.** The network buffer is yours, sized by you, often a global array. tdslite never grows it. - **Rows aren't collected.** They go to a callback, one at a time, and are gone when it returns. See the [memory model](https://tdslite.github.io/tdslite/latest/explanation/memory-model/index.md). - **Optional work is opt-in.** Column names, for example, aren't stored unless you ask for them. - **No exceptions, no RTTI.** Errors are return values, so tdslite builds with `-fno-exceptions -fno-rtti`, the default on many embedded toolchains. ## No dependencies tdslite doesn't need the C++ standard library. The few pieces it needs, such as type traits, `span` and `expected`, are implemented in the library itself. From the toolchain, it uses a handful of C headers (`stdint.h`, `stddef.h`, `string.h`, `stdlib.h`). The requirement is a C++11 compiler, nothing more, which is what lets the same code run on an 8-bit AVR and on a 64-bit server. It's also header-only: there is no library to build and link, and the compiler removes what your program doesn't call. ## Not all of TDS The protocol tdslite speaks, MS-TDS, is decades old and carries many features that small devices never need. tdslite doesn't aim to implement the specification to the letter. It implements what typical embedded use needs (logging in, running queries and parameterized queries, reading result sets, encryption) and adds the rest as it's needed, rather than up front. That's why, for example, it logs in as a TDS 7.1 client: it's enough for the common data types, and SQL Server converts the newer ones to types a 7.1 client understands. [TDS versions and encryption](https://tdslite.github.io/tdslite/latest/explanation/tds-and-tls/index.md) has the details. ## Two parts tdslite is made of two parts, in two folders of the repository: - [`src/tdslite`](https://github.com/tdslite/tdslite/tree/main/src/tdslite): the protocol. It builds TDS packets and parses responses, and knows nothing about networks. - [`src/tdslite-net`](https://github.com/tdslite/tdslite/tree/main/src/tdslite-net): the network backends that carry the packets: Arduino clients, BSD sockets, ESP-IDF's esp-tls, Boost.ASIO. The main class, `tdsl::driver`, joins the two: `NetImpl` is the backend. [The network abstraction](https://tdslite.github.io/tdslite/latest/explanation/network-abstraction/index.md) explains why they are kept apart. # 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` is a template, and `NetImpl` is the backend. The backend derives from `tdsl::net::network_io_base`, 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. ## Related - [Write a network backend](https://tdslite.github.io/tdslite/latest/how-to/custom-backend/index.md) - [Network backends](https://tdslite.github.io/tdslite/latest/reference/network-backends/index.md) # 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: ```c++ tdsl::uint8_t net_buf [768] = {}; tdsl::arduino_driver 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](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md) 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](https://tdslite.github.io/tdslite/latest/how-to/custom-allocator/index.md), 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. ## Related - [Fit tdslite into a small RAM budget](https://tdslite.github.io/tdslite/latest/how-to/memory/index.md) - [Limits](https://tdslite.github.io/tdslite/latest/reference/limits/index.md) # TDS versions and encryption SQL Server speaks TDS, the *Tabular Data Stream* protocol, described in Microsoft's [MS-TDS](https://learn.microsoft.com/openspecs/windows_protocols/ms-tds/) specification. tdslite's implementation follows revision 33 of it. Two version numbers matter to you: the one tdslite logs in with, and the one its encrypted connections use. ## Logging in as TDS 7.1 A client tells SQL Server which TDS version it speaks when it logs in, and the server shapes its answers to fit. tdslite logs in as TDS 7.1, the version of SQL Server 2000. That's a deliberate trade. TDS 7.1 covers the classic data types, and its messages are simple to parse, which keeps the library small. For the types that came later, SQL Server does the work: it converts them into types a 7.1 client understands before sending them. A `datetime2` arrives as a string, a `varchar(max)` as `text`. The [data types reference](https://tdslite.github.io/tdslite/latest/reference/data-types/#types-sql-server-converts) lists the conversions. What a 7.1 client can't have is the newer protocol features. One of them shows up with encryption; see [transactions over TLS](#transactions-over-tls) below. ## Encryption before TDS 8.0 Older TDS versions encrypt by switching to TLS in the middle of the conversation: the client and server first exchange a plaintext "prelogin" packet, then do a TLS handshake *wrapped inside TDS packets*, and then continue. It works, but the handshake has to be tunneled through TDS framing, which a TLS library can't do on its own: every client needs custom glue between TDS and TLS. tdslite doesn't implement this mode. Its plaintext backends send everything, the login included, unencrypted, so use them only on networks you trust. A server configured to force encryption refuses them at login. ## TDS 8.0 strict mode SQL Server 2022 introduced TDS 8.0 and *strict* encryption, which turns the order around: the TLS handshake comes first, right after the TCP connection, exactly as in HTTPS. Only then does TDS start, inside the encrypted channel. For a small client, that's a much better fit: - The TLS layer is an ordinary TLS client: esp-tls, OpenSSL, or a board's `WiFiClientSecure`, with no TDS-specific glue. - Nothing, not even the prelogin, travels in plaintext. - The server's certificate is checked like any HTTPS server's: it must be signed by a CA you trust and name the host you connect to. So every encrypted tdslite connection is a strict one. The price is the server requirement: strict mode needs SQL Server 2025, SQL Server 2022 on Windows, or Azure SQL, with a proper certificate. Inside the encrypted channel, tdslite still logs in as TDS 7.1. ## One packet per record Under strict mode, SQL Server expects each TDS packet to arrive in a single TLS record, and drops the connection when one is split. That's why the packet size and the TLS client's record size have to agree, and why tdslite's TLS support refuses a packet larger than a record instead of sending it in pieces. See [Connect with TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md). ## Transactions over TLS When a transaction starts, SQL Server gives it a descriptor, and from then on expects each request in the session to carry it. On a plaintext TDS 7.1 connection, the server doesn't insist on it. On a strict connection, it does, but it doesn't send the descriptor to a client that logged in as TDS 7.1. The result: after a `BEGIN TRAN` sent on its own, every later request, `COMMIT` and `ROLLBACK` included, fails with error 3989 ("New request is not allowed to start because it should come with valid transaction descriptor"), until the driver reconnects. A transaction that begins and ends within one request has no "later request", so it isn't affected. That's why, on TLS connections, a transaction must start and end within one `execute_query`, or one stored procedure. # Direct connections and gateways A device can store its data in SQL Server in two ways: connect to the server itself, as tdslite does, or send the data to a service in between (a REST API, an MQTT broker with a subscriber, a cloud IoT hub) that writes it to the database. Both are reasonable. Which one fits depends mostly on who can reach the device, who can reach the server, and how many devices there are. ## What a direct connection gives you - **Fewer parts.** No service to write, host, update and monitor; the device and the database are the whole system. - **The full SQL language.** Queries, transactions, stored procedures, and reading data back, not only the calls an API happens to offer. - **Lower latency and less code on the device.** One protocol, one connection, no JSON to build or parse. - **Server tools work as they are.** Logins, permissions, auditing, `sys.dm_exec_sessions`: SQL Server sees each device as a client. ## What it costs - **The device holds a database login.** Anyone with the device can read the password from its flash. The login can do whatever its permissions allow, from anywhere that can reach the server, until you change the password. With a gateway, the device holds a token that only works on the gateway, and that you can revoke on its own. - **The server must be reachable from the device.** On the same network that's a given. Over the internet, it means opening SQL Server's port, which exposes it to password guessing and to any flaw in the server. Don't do that for an on-premises server; use a VPN, or a gateway. Azure SQL is made to be reached over the internet, behind its firewall rules. - **Without TLS, the traffic can be read.** TDS sends the password obfuscated, not encrypted, and the data in plain text. On a network you don't control, use [TLS](https://tdslite.github.io/tdslite/latest/how-to/tls/index.md), which needs a board that can do it and a server that accepts TDS 8.0 strict connections. - **The firmware knows the schema.** An `INSERT` in the firmware has to change when the table does. A stored procedure moves that SQL to the server, so you can change the table without updating the devices. - **Each device holds a connection.** SQL Server handles hundreds of connections without trouble. For thousands of devices, or devices that connect and disconnect all the time, a gateway that collects the data and writes it in batches is easier on the server. ## When a direct connection fits A direct connection is a good fit when the devices and the server share a network that you control: a lab, a workshop, a factory floor, a building, a home. It's also a good fit for prototypes and small fleets, where running a separate service would be most of the work. A gateway is the better choice when devices are spread over networks you don't control, when there are many of them, when a device could be stolen and its credentials must be revoked on their own, or when other systems need the data too. ## If you connect directly - Give the devices a login of their own, with only the permissions they need: `INSERT` on one table, or `EXECUTE` on one stored procedure. See [Log sensor readings](https://tdslite.github.io/tdslite/latest/how-to/log-sensor-data/#create-the-table-and-a-login) and [Call a stored procedure](https://tdslite.github.io/tdslite/latest/how-to/stored-procedures/#let-a-device-run-only-the-procedure). - Use TLS whenever the network isn't fully yours. - Don't expose an on-premises SQL Server's port to the internet. - Plan to change the password: keep it in one place in the firmware, or in a configuration the device reads at startup, so a new one is easy to deploy. ## Related - [Design goals](https://tdslite.github.io/tdslite/latest/explanation/design/index.md): what tdslite is for - [TDS versions and encryption](https://tdslite.github.io/tdslite/latest/explanation/tds-and-tls/index.md) - [Connect to Azure SQL Database](https://tdslite.github.io/tdslite/latest/how-to/azure-sql/index.md)