From d9f91b30f484babb69f41727ee6589f9429104a1 Mon Sep 17 00:00:00 2001 From: "Dr. Patrick Urbanke" Date: Fri, 9 May 2025 18:19:57 +0200 Subject: [PATCH] Added SQL snippets to the README --- README.md | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6432720..129685b 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ struct People { }; const auto people = std::vector({ - person{.first_name = "Homer", + People{.first_name = "Homer", .last_name = "Simpson", .age = 45}}); @@ -40,6 +40,18 @@ if (!result) { } ``` +The resulting SQL code (will vary from dialect to dialect): + +```sql +CREATE TABLE IF NOT EXISTS "People" ( + "first_name" TEXT NOT NULL, + "last_name" TEXT NOT NULL, + "age" INTEGER NOT NULL +); + +INSERT INTO "Person" ("first_name", "last_name", "age") VALUES (?, ?, ?); +``` + ## Retrieving data Here is how you retrieve the same data from the database @@ -71,6 +83,16 @@ if (result) { } ``` +The resulting SQL code: + +```sql +SELECT "first_name", "last_name", "age" +FROM "Person" +WHERE "age" < 18 +ORDER BY "age", "first_name" +LIMIT 100; +``` + ## Compile-time checks sqlgen protects you from various mistakes through comprehensive @@ -88,6 +110,28 @@ const auto get_children = sqlgen::read> | where("age"_c < 18 and "color"_c != 'green'); ``` +## Protection against SQL injections + +sqlgen provides input validation to protect against SQL injection. + +```cpp +// Safe query function using AlphaNumeric for filtering +std::vector get_people(const auto& conn, + const sqlgen::AlphaNumeric& first_name) { + using namespace sqlgen; + const auto query = sqlgen::read> | + where("first_name"_c == first_name); + return query(conn).value(); +} +``` + +Without `AlphaNumeric` validation, this code would be vulnerable to SQL injection during query filtering: + +```cpp +// Malicious query parameter that would be rejected by AlphaNumeric +get_people(conn, "Homer' OR '1'='1"); // Attempt to bypass filtering +``` + ## Installation These three libraries are needed for PostgreSQL support: