mirror of
https://github.com/getml/sqlgen.git
synced 2026-01-06 09:30:07 -06:00
Added SQL snippets to the README
This commit is contained in:
46
README.md
46
README.md
@@ -20,7 +20,7 @@ struct People {
|
||||
};
|
||||
|
||||
const auto people = std::vector<People>({
|
||||
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<std::vector<People>> |
|
||||
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<Person> get_people(const auto& conn,
|
||||
const sqlgen::AlphaNumeric& first_name) {
|
||||
using namespace sqlgen;
|
||||
const auto query = sqlgen::read<std::vector<Person>> |
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user