ORM C++
Loading...
Searching...
No Matches
contracts.cppm
Go to the documentation of this file.
1module;
2
3#include <algorithm>
4#include <chrono>
5#include <compare>
6#include <cstddef>
7#include <optional>
8#include <span>
9#include <stdexcept>
10#include <string>
11#include <string_view>
12#include <type_traits>
13#include <variant>
14#include <vector>
15
16#include "../../detail/SociTypes.inc"
17
18export module orm:sql_contracts;
19
20import :foundation;
21import :connection_config;
22import :model;
23import :expressions;
24
25// Runtime command inputs form the source-level backend extension contract.
26export namespace orm::db
27{
28using SelectSpec = query::detail::SelectSpec;
29using UpdateSpec = query::detail::UpdateSpec;
30using Predicate = query::detail::Predicate;
31}
32
33export namespace orm::db::ast
34{
35using Column = orm::query::detail::Column;
36using PredicateNode = orm::query::detail::PredicateNode;
37using PredicateNodePtr = orm::query::detail::PredicateNodePtr;
38using ComparisonOperator = orm::query::detail::ComparisonOperator;
39using NullOperator = orm::query::detail::NullOperator;
40using ListOperator = orm::query::detail::ListOperator;
41using BetweenOperator = orm::query::detail::BetweenOperator;
42using LogicalOperator = orm::query::detail::LogicalOperator;
43using CollectionOperator = orm::query::detail::CollectionOperator;
44using ComparisonExpression = orm::query::detail::ComparisonExpression;
45using NullExpression = orm::query::detail::NullExpression;
46using ListExpression = orm::query::detail::ListExpression;
47using BetweenExpression = orm::query::detail::BetweenExpression;
48using LogicalExpression = orm::query::detail::LogicalExpression;
49using NotExpression = orm::query::detail::NotExpression;
50using RawExpression = orm::query::detail::RawExpression;
51using CollectionExpression = orm::query::detail::CollectionExpression;
52using AggregateFunction = orm::query::detail::AggregateFunction;
53using AggregateExpression = orm::query::detail::AggregateExpression;
54using AggregatePredicate = orm::query::detail::AggregatePredicate;
55using AggregatePredicateNode = orm::query::detail::AggregatePredicateNode;
56using AggregatePredicateNodePtr = orm::query::detail::AggregatePredicateNodePtr;
57using AggregateComparisonExpression = orm::query::detail::AggregateComparisonExpression;
58using AggregateLogicalExpression = orm::query::detail::AggregateLogicalExpression;
59using AggregateNotExpression = orm::query::detail::AggregateNotExpression;
60using OrderDirection = orm::query::detail::OrderDirection;
61using OrderBy = orm::query::detail::OrderBy;
62using ProjectionSource = orm::query::detail::ProjectionSource;
63using Projection = orm::query::detail::Projection;
64using UpdateValue = orm::query::detail::UpdateValue;
65using UpdateAssignment = orm::query::detail::UpdateAssignment;
66}
67namespace orm::db
68{
69export
70{
76 };
79 {
81 bool dropTableIfExists = false;
84 bool foreignKeys = false;
85 bool onDeleteCascade = false;
86 bool transactionalDdl = false;
87 bool boundedStringKeys = false;
89 auto operator==(const SchemaCapabilities&) const -> bool = default;
90 };
93 {
94 bool limit = false;
95 bool offset = false;
96 bool offsetWithoutLimit = false;
98 bool projections = false;
99 bool groupBy = false;
100 bool having = false;
102 bool fullModelGrouping = false;
105 std::optional<std::size_t> maxOrderedStringLength = {};
107 auto operator==(const QueryCapabilities&) const -> bool = default;
108 };
112 bool insert = false;
113 bool insertMany = false;
114 bool update = false;
115 bool remove = false;
119 auto operator==(const MutationCapabilities&) const -> bool = default;
120 };
124 bool toOne = false;
125 bool oneToMany = false;
126 bool manyToMany = false;
127 bool collectionIncludes = false;
129 bool junctionTables = false;
130 bool compositeEndpointKeys = false;
132 auto operator==(const RelationCapabilities&) const -> bool = default;
133 };
135 struct BackendValueLimits
136 {
137 /**
138 * Largest unsigned 64-bit value that can be exchanged without loss.
139 * An empty value means that the full C++ range is supported.
140 */
141 std::optional<unsigned long long> maxUnsignedLongLong;
142 std::optional<Date> minDate{};
143 std::optional<Date> maxDate{};
144 std::optional<LocalDateTime> minLocalDateTime{};
145 std::optional<LocalDateTime> maxLocalDateTime{};
146 std::optional<UtcTimestamp> minUtcTimestamp{};
147 std::optional<UtcTimestamp> maxUtcTimestamp{};
149 auto operator==(const BackendValueLimits&) const -> bool = default;
150 };
156 };
164 };
183 };
187 std::optional<std::size_t> maxBindParameters{};
188 std::optional<std::size_t> maxIndexBytes{};
189 std::optional<UtcTimestamp> minUtcTimestamp{};
190 std::optional<UtcTimestamp> maxUtcTimestamp{};
192 auto operator==(const BackendRuntimeLimits&) const -> bool = default;
193 };
194}
195} // namespace orm::db
196
197namespace orm::db
198{
199export
200{
201
202 class BackendRuntime;
203 class CommandGenerator;
204 class SqlDialect;
205 struct InsertIfAbsentSpec;
207 class BackendProvider
208 {
209 public:
210 virtual ~BackendProvider() = default;
212 [[nodiscard]] virtual auto type() const noexcept -> BackendType = 0;
213 [[nodiscard]] virtual auto capabilities() const noexcept -> const BackendCapabilities& = 0;
214 [[nodiscard]] virtual auto dialect() const noexcept -> const SqlDialect& = 0;
215 [[nodiscard]] virtual auto runtime() const noexcept -> const BackendRuntime& = 0;
216 [[nodiscard]] virtual auto commandGenerator() const noexcept -> const CommandGenerator& = 0;
217 [[nodiscard]] virtual auto compiledSqlFlavor() const noexcept -> CompiledSqlFlavor
218 {
220 }
221 };
222}
223} // namespace orm::db
224namespace orm::db
225{
226export
227{
229 struct BoundValue
232 std::optional<query::QueryValue::Value> value;
235 [[nodiscard]] auto isNull() const noexcept -> bool
236 {
237 return not value.has_value();
238 }
239 };
241 struct StatementParameter
243 std::string name;
244 std::optional<query::QueryValue> value;
245 std::optional<model::ColumnType> nullType;
248 [[nodiscard]] auto getLogicalType() const -> model::ColumnType
249 {
250 if (value.has_value())
251 {
252 return value->getLogicalType();
253 }
254 if (nullType.has_value())
255 {
256 return nullType.value();
257 }
258 throw std::invalid_argument{"A NULL statement parameter requires an explicit logical type"};
259 }
261 [[nodiscard]] auto getBoundValue() const -> BoundValue
262 {
263 if (value.has_value())
264 {
265 return BoundValue{
266 .logicalType = value->getLogicalType(), .value = value->get(), .uuidStorage = uuidStorage};
267 }
268
269 return BoundValue{.logicalType = getLogicalType(), .value = std::nullopt, .uuidStorage = uuidStorage};
270 }
271 };
273 struct Statement
275 std::string sql;
276 std::vector<StatementParameter> parameters;
277 };
278
279 /** Non-owning statement input; compiled SQL has static storage duration. */
280 struct StatementView
282 std::string_view sql;
283 std::span<const StatementParameter> parameters;
284 };
285}
286} // namespace orm::db
287namespace orm::db
288{
289export
290{
292 class BackendRuntime
293 {
294 public:
295 virtual ~BackendRuntime() = default;
296
297 /** Migration hooks are opt-in for application-supplied backends. */
298 /** Checks session parsing and binding invariants before history access. */
299 virtual auto validateMigrationSession(soci::session&) const -> void {}
300 virtual auto migrationTable(soci::session&) const -> std::string
301 {
303 "Backend does not support migrations"};
305 virtual auto beginMigration(soci::session&, std::string_view) const -> void
306 {
308 "Backend does not support migrations"};
310 virtual auto executeMigrationScript(soci::session&, std::string_view) const -> void
311 {
313 "Backend does not support migrations"};
314 }
316 [[nodiscard]] virtual auto migrationHistoryExists(soci::session&, std::string_view) const -> bool
317 {
319 "Backend does not support migration history inspection"};
321 virtual auto createMigrationHistory(soci::session&, std::string_view) const -> void
322 {
324 "Backend does not support migration history creation"};
325 }
326 /** Nontransactional engines return a qualified durable journal table. */
327 [[nodiscard]] virtual auto migrationJournalTable(soci::session&, std::string_view) const -> std::string
328 {
329 return {};
330 }
331 /** Releases session-scoped locks; transaction-scoped locks need no hook. */
332 virtual auto endMigration(soci::session&, std::string_view) const -> void {}
334 virtual auto open(soci::session& session, ConnectionConfigView config) const -> void = 0;
335 virtual auto onConnect(soci::session& session) const -> void = 0;
336 [[nodiscard]] virtual auto tableExists(soci::session& session, std::string_view tableName) const -> bool = 0;
337 [[nodiscard]] virtual auto limits(soci::session& session) const -> BackendRuntimeLimits = 0;
338 [[nodiscard]] virtual auto normalizeAffectedRows(long long affectedRows) const -> std::size_t = 0;
339 /** Executes an atomic, idempotent insertion without hiding unrelated constraints. */
340 [[nodiscard]] virtual auto executeInsertIfAbsent(soci::session& session, StatementView statement,
341 const InsertIfAbsentSpec& conflict) const -> std::size_t;
342 [[nodiscard]] virtual auto
343 statementErrorInvalidatesTransaction(const soci::soci_error& /*error*/) const noexcept -> bool
344 {
345 return false;
347 virtual auto bind(soci::values& values, std::string_view name, const BoundValue& value) const -> void = 0;
348 /** Tests the backend's prepared parameter names, without interpreting raw SQL in the ORM. */
349 [[nodiscard]] virtual auto hasStatementParameter(soci::statement&, std::string_view) const -> bool
350 {
352 "Backend does not support Binary16 parameter inspection"};
354 [[nodiscard]] virtual auto translateError(const soci::soci_error& error, DatabaseErrorCode fallback,
355 std::string_view operation) const -> DatabaseError = 0;
356 };
357}
358} // namespace orm::db
359// Primary-key storage shared by SQL statements and model binding.
360namespace orm::db::binding
361{
362using PrimaryKey = std::vector<query::QueryValue>;
363}
364
365export namespace orm::db
366{
368}
369namespace orm::db
370{
371export
372{
374 struct PaginationSpec
376 std::optional<std::size_t> limit;
377 std::optional<std::size_t> offset;
378 bool hasOrderBy = false;
380 auto operator==(const PaginationSpec&) const -> bool = default;
381 };
383 struct InsertIfAbsentSpec
385 std::string tableName;
386 std::vector<std::string> columns;
387 std::vector<std::string> valueExpressions;
388 std::vector<std::string> conflictColumns;
390 auto operator==(const InsertIfAbsentSpec&) const -> bool = default;
391 };
393 class SqlDialect
394 {
395 public:
396 virtual ~SqlDialect() = default;
398 [[nodiscard]] virtual auto quoteIdentifier(std::string_view identifier) const -> std::string = 0;
399 [[nodiscard]] virtual auto bindMarker(std::string_view logicalName) const -> std::string = 0;
400 [[nodiscard]] virtual auto
402 std::optional<std::size_t> maxStringLength = std::nullopt) const -> std::string = 0;
403 [[nodiscard]] virtual auto renderStringLengthConstraint(std::string_view,
404 std::optional<std::size_t>) const -> std::string
405 {
406 return {};
408 [[nodiscard]] virtual auto renderCreateTablePrefix(std::string_view tableName,
409 bool ifNotExists) const -> std::string = 0;
410 [[nodiscard]] virtual auto renderCreateTableSuffix() const -> std::string
411 {
412 return "\n);";
414 [[nodiscard]] virtual auto renderDefaultInsert(std::string_view tableName) const -> std::string
415 {
416 return "INSERT INTO " + quoteIdentifier(tableName) + " DEFAULT VALUES;";
418 [[nodiscard]] virtual auto renderDropTable(std::string_view tableName, bool ifExists) const -> std::string = 0;
419 [[nodiscard]] virtual auto renderAutoIncrementPrimaryKey(std::string_view columnName) const -> std::string = 0;
420 [[nodiscard]] virtual auto renderPagination(const PaginationSpec& pagination) const -> std::string = 0;
421 [[nodiscard]] virtual auto renderInsertIfAbsent(const InsertIfAbsentSpec& insert) const -> std::string = 0;
422 [[nodiscard]] virtual auto renderAggregateResult(std::string_view expression,
423 bool /*preserveExactNumeric*/) const -> std::string
424 {
425 return std::string{expression};
426 }
427 };
428}
429} // namespace orm::db
430namespace orm::db
431{
432export
433{
435 class TypeTranslator
436 {
437 public:
438 virtual ~TypeTranslator() = default;
439
440 [[nodiscard]] virtual auto
442 std::optional<std::size_t> maxStringLength = std::nullopt) const -> std::string = 0;
443 };
444}
445} // namespace orm::db
446
447export namespace orm::db::binding
448{
449auto isWithinValueLimits(const BoundValue& bound, const BackendValueLimits& limits,
450 const BackendRuntimeLimits& runtime = {}) noexcept -> bool;
451}
A backend-neutral database runtime error.
Definition types.cppm:121
virtual auto compiledSqlFlavor() const noexcept -> CompiledSqlFlavor
virtual auto capabilities() const noexcept -> const BackendCapabilities &=0
virtual auto type() const noexcept -> BackendType=0
virtual auto runtime() const noexcept -> const BackendRuntime &=0
virtual auto dialect() const noexcept -> const SqlDialect &=0
virtual auto commandGenerator() const noexcept -> const CommandGenerator &=0
virtual auto hasStatementParameter(soci::statement &, std::string_view) const -> bool
virtual auto open(soci::session &session, ConnectionConfigView config) const -> void=0
virtual auto migrationTable(soci::session &) const -> std::string
virtual auto bind(soci::values &values, std::string_view name, const BoundValue &value) const -> void=0
virtual auto executeInsertIfAbsent(soci::session &session, StatementView statement, const InsertIfAbsentSpec &conflict) const -> std::size_t
virtual auto onConnect(soci::session &session) const -> void=0
virtual auto endMigration(soci::session &, std::string_view) const -> void
virtual auto migrationJournalTable(soci::session &, std::string_view) const -> std::string
virtual auto executeMigrationScript(soci::session &, std::string_view) const -> void
virtual auto migrationHistoryExists(soci::session &, std::string_view) const -> bool
virtual auto validateMigrationSession(soci::session &) const -> void
virtual auto translateError(const soci::soci_error &error, DatabaseErrorCode fallback, std::string_view operation) const -> DatabaseError=0
virtual auto limits(soci::session &session) const -> BackendRuntimeLimits=0
virtual auto normalizeAffectedRows(long long affectedRows) const -> std::size_t=0
virtual auto beginMigration(soci::session &, std::string_view) const -> void
virtual auto createMigrationHistory(soci::session &, std::string_view) const -> void
virtual auto statementErrorInvalidatesTransaction(const soci::soci_error &) const noexcept -> bool
virtual auto tableExists(soci::session &session, std::string_view tableName) const -> bool=0
virtual auto renderStringLengthConstraint(std::string_view, std::optional< std::size_t >) const -> std::string
virtual auto renderCreateTablePrefix(std::string_view tableName, bool ifNotExists) const -> std::string=0
virtual auto bindMarker(std::string_view logicalName) const -> std::string=0
virtual auto renderPagination(const PaginationSpec &pagination) const -> std::string=0
virtual auto renderDefaultInsert(std::string_view tableName) const -> std::string
virtual auto renderInsertIfAbsent(const InsertIfAbsentSpec &insert) const -> std::string=0
virtual auto renderAutoIncrementPrimaryKey(std::string_view columnName) const -> std::string=0
virtual auto toSqlType(model::ColumnType type, std::optional< std::size_t > maxStringLength=std::nullopt) const -> std::string=0
virtual auto quoteIdentifier(std::string_view identifier) const -> std::string=0
virtual auto renderAggregateResult(std::string_view expression, bool) const -> std::string
virtual auto renderCreateTableSuffix() const -> std::string
virtual auto renderDropTable(std::string_view tableName, bool ifExists) const -> std::string=0
virtual auto toSqlType(model::ColumnType type, std::optional< std::size_t > maxStringLength=std::nullopt) const -> std::string=0
orm::query::detail::Column Column
orm::query::detail::PredicateNode PredicateNode
orm::query::detail::Projection Projection
orm::query::detail::AggregateLogicalExpression AggregateLogicalExpression
orm::query::detail::AggregatePredicate AggregatePredicate
orm::query::detail::BetweenExpression BetweenExpression
orm::query::detail::RawExpression RawExpression
orm::query::detail::NullOperator NullOperator
orm::query::detail::ProjectionSource ProjectionSource
orm::query::detail::LogicalOperator LogicalOperator
orm::query::detail::OrderDirection OrderDirection
orm::query::detail::ComparisonOperator ComparisonOperator
orm::query::detail::AggregateNotExpression AggregateNotExpression
orm::query::detail::LogicalExpression LogicalExpression
orm::query::detail::AggregateExpression AggregateExpression
orm::query::detail::AggregatePredicateNodePtr AggregatePredicateNodePtr
orm::query::detail::AggregatePredicateNode AggregatePredicateNode
orm::query::detail::PredicateNodePtr PredicateNodePtr
orm::query::detail::AggregateFunction AggregateFunction
orm::query::detail::NotExpression NotExpression
orm::query::detail::NullExpression NullExpression
orm::query::detail::ListExpression ListExpression
orm::query::detail::ComparisonExpression ComparisonExpression
orm::query::detail::UpdateValue UpdateValue
orm::query::detail::OrderBy OrderBy
orm::query::detail::UpdateAssignment UpdateAssignment
orm::query::detail::AggregateComparisonExpression AggregateComparisonExpression
orm::query::detail::ListOperator ListOperator
orm::query::detail::BetweenOperator BetweenOperator
orm::query::detail::CollectionExpression CollectionExpression
orm::query::detail::CollectionOperator CollectionOperator
auto isWithinValueLimits(const BoundValue &bound, const BackendValueLimits &limits, const BackendRuntimeLimits &runtime={}) noexcept -> bool
std::vector< query::QueryValue > PrimaryKey
query::detail::UpdateSpec UpdateSpec
BackendType
Definition types.cppm:62
query::detail::Predicate Predicate
query::detail::SelectSpec SelectSpec
CompiledSqlFlavor
Definition types.cppm:83
AffectedRowsSupport
binding::PrimaryKey PrimaryKey
DatabaseErrorCode
Definition types.cppm:99
consteval auto columnName()
Definition mapping.cppm:563
MigrationCapabilities migrations
auto supportsColumnType(model::ColumnType type) const -> bool
SchemaCapabilities schema
BackendValueLimits valueLimits
std::vector< model::ColumnType > supportedColumnTypes
MutationCapabilities mutations
RelationCapabilities relations
auto operator==(const BackendCapabilities &) const -> bool=default
std::optional< UtcTimestamp > minUtcTimestamp
auto operator==(const BackendRuntimeLimits &) const -> bool=default
std::optional< std::size_t > maxBindParameters
std::optional< UtcTimestamp > maxUtcTimestamp
std::optional< std::size_t > maxIndexBytes
std::optional< LocalDateTime > minLocalDateTime
std::optional< Date > minDate
std::optional< unsigned long long > maxUnsignedLongLong
std::optional< UtcTimestamp > maxUtcTimestamp
std::optional< UtcTimestamp > minUtcTimestamp
auto operator==(const BackendValueLimits &) const -> bool=default
std::optional< LocalDateTime > maxLocalDateTime
std::optional< Date > maxDate
std::optional< query::QueryValue::Value > value
model::UuidStorage uuidStorage
model::ColumnType logicalType
auto isNull() const noexcept -> bool
std::vector< std::string > columns
std::vector< std::string > valueExpressions
std::vector< std::string > conflictColumns
auto operator==(const InsertIfAbsentSpec &) const -> bool=default
auto operator==(const MigrationCapabilities &) const -> bool=default
AffectedRowsSupport affectedRows
auto operator==(const MutationCapabilities &) const -> bool=default
auto operator==(const PaginationSpec &) const -> bool=default
std::optional< std::size_t > offset
std::optional< std::size_t > limit
auto operator==(const QueryCapabilities &) const -> bool=default
std::optional< std::size_t > maxOrderedStringLength
auto operator==(const RelationCapabilities &) const -> bool=default
auto operator==(const SchemaCapabilities &) const -> bool=default
std::optional< query::QueryValue > value
auto getBoundValue() const -> BoundValue
model::UuidStorage uuidStorage
auto getLogicalType() const -> model::ColumnType
std::optional< model::ColumnType > nullType
std::string_view sql
std::span< const StatementParameter > parameters
std::vector< StatementParameter > parameters