Primary keys as a separate section

This commit is contained in:
Dr. Patrick Urbanke
2025-04-27 07:40:44 +02:00
parent d4c9a9cef1
commit a262437a37
3 changed files with 43 additions and 41 deletions

View File

@@ -8,15 +8,17 @@
[Writing](writing.md) - How to write data to a database.
[Result](result.md) - How sqlgen handles errors.
[sqlgen::Result](result.md) - How sqlgen handles errors.
[Timestamp](timestamp.md) - How timestamps work in sqlgen.
[sqlgen::PrimaryKey](primary_key.md) - How to define primary keys in sqlgen.
[Varchar](varchar.md) - How varchars work in sqlgen.
[sqlgen::Timestamp](timestamp.md) - How timestamps work in sqlgen.
[Flatten](flatten.md) - How to "inherit" fields from other structs.
[sqlgen::Varchar](varchar.md) - How varchars work in sqlgen.
[Literal](literal.md) - How to define fields that only allow for a fixed set of values.
[sqlgen::Flatten](flatten.md) - How to "inherit" fields from other structs.
[sqlgen::Literal](literal.md) - How to define fields that only allow for a fixed set of values.
## Supported databases

View File

@@ -78,42 +78,6 @@ CREATE TABLE IF NOT EXISTS "my_schema"."People"("first_name" TEXT NOT NULL,
"age" INTEGER NOT NULL);
```
## Primary keys
Of course, you would also like to set primary keys on your
tables. This is possible as well:
```cpp
struct People {
rfl::PrimaryKey<std::string> first_name;
std::string last_name;
uint age;
};
```
Now, the generated SQL code will look something like this:
```sql
CREATE TABLE IF NOT EXISTS "People"("first_name" TEXT NOT NULL,
"last_name" TEXT NOT NULL,
"age" INTEGER NOT NULL,
PRIMARY_KEY("first_name"));
```
`rfl::PrimaryKey<...>` is a simple wrapper. You can simply assign to it as follows:
```cpp
const auto person = People{.first_name = "Homer", ...};
```
And you can retrieve the underlying value using any of the following:
```cpp
person.first_name();
person.first_name.get();
person.first_name.value();
```
## Nullable types
As we have seen, all columns are non-nullable by default. But what if we do want

36
docs/primary_key.md Normal file
View File

@@ -0,0 +1,36 @@
# `sqlgen::PrimaryKey`
Sometimes you would like to set primary keys on your
tables. This is possible as well:
```cpp
struct People {
rfl::PrimaryKey<std::string> first_name;
std::string last_name;
uint age;
};
```
Now, the generated SQL code will look something like this:
```sql
CREATE TABLE IF NOT EXISTS "People"("first_name" TEXT NOT NULL,
"last_name" TEXT NOT NULL,
"age" INTEGER NOT NULL,
PRIMARY_KEY("first_name"));
```
`rfl::PrimaryKey<...>` is a simple wrapper. You can simply assign to it as follows:
```cpp
const auto person = People{.first_name = "Homer", ...};
```
And you can retrieve the underlying value using any of the following:
```cpp
person.first_name();
person.first_name.get();
person.first_name.value();
```