relx 0.1.0
A Modern C++23 Type-Safe SQL Query Builder
Loading...
Searching...
No Matches
primary_key.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "core.hpp"
4#include "meta.hpp"
5
6#include <string_view>
7#include <type_traits>
8
9namespace relx::schema {
10
13template <auto ColumnPtr>
15public:
17 table_primary_key() = default;
18
21 std::string sql_definition() const {
22 // Extract the column name from the pointer
23 using table_type = typename member_pointer_class<decltype(ColumnPtr)>::type;
24 using column_type = typename member_pointer_type<decltype(ColumnPtr)>::type;
25
26 return "PRIMARY KEY (" + std::string(column_type::name) + ")";
27 }
28
29private:
30};
31
34template <auto... ColumnPtrs>
36public:
39
42 std::string sql_definition() const {
43 std::string result = "PRIMARY KEY (";
44 result += get_column_names();
45 result += ")";
46 return result;
47 }
48
49private:
50 // Helper to get comma-separated column names
51 std::string get_column_names() const {
52 // Using fold expression to concatenate column names
53 std::string names;
54 (append_column_name<ColumnPtrs>(names, names.empty() ? "" : ", "), ...);
55 return names;
56 }
57
58 // Helper to append a single column name
59 template <auto ColumnPtr>
60 void append_column_name(std::string& names, const std::string& separator) const {
61 using column_type = typename member_pointer_type<decltype(ColumnPtr)>::type;
62 names += separator + std::string(column_type::name);
63 }
64};
65
69template <auto... ColumnPtrs>
70auto make_pk() {
71 if constexpr (sizeof...(ColumnPtrs) == 1) {
72 // Use fold expression to extract the single column pointer
73 return table_primary_key<(
74 []<auto Ptr>() {
75 return Ptr;
76 }.template operator()<ColumnPtrs>(),
77 ...)>();
78 } else {
79 return composite_primary_key<ColumnPtrs...>();
80 }
81}
82
86template <auto... ColumnPtrs>
87using pk = decltype(make_pk<ColumnPtrs...>());
88
89} // namespace relx::schema
Represents a composite primary key constraint on multiple columns.
std::string sql_definition() const
Get SQL definition for the composite PRIMARY KEY constraint.
composite_primary_key()=default
Default constructor.
Represents a primary key constraint on a table.
table_primary_key()=default
Default constructor.
std::string sql_definition() const
Get SQL definition for the PRIMARY KEY constraint.
decltype(make_pk< ColumnPtrs... >()) pk
Helper type alias for primary key constraints.
auto make_pk()
Helper function to create a primary key.
Helper to extract the class type from a member pointer.
Definition meta.hpp:10
Helper to extract the member type from a member pointer.
Definition meta.hpp:28