ORM C++
Loading...
Searching...
No Matches
Partial-result queries

Partial-result queries select a subset of model fields into a flat user-defined DTO. Use them when you do not need to hydrate a full model object.

For immutable DTO plans, use query::selectAs<Source, Result> with literal as<"alias"> projections as described in static query plans.

Contract

Full-model selects keep the existing API and result type:

std::vector<User> users = context.select(query);
A template class representing a select query in the ORM framework.
Definition select.cppm:39

Partial-result selects use a separate query type:

template <typename Source, typename Result>
A select query that returns a user-defined DTO instead of the full source model.

Source is the mapped ORM model. Result is a user-defined DTO with the exact fields returned by the projection. ProjectionQuery<Source, Result> is the mutable builder for partial-result queries; query::selectAs<Source, Result> creates an immutable plan. Both return DTOs through context.select. orm::Query<Model> remains reserved for full-model results.

Projection and aggregate helpers live in orm::query. as("dtoField", expression) accepts a typed column or aggregate and retains its source model. count(column), sum(column), avg(column), min(column), and max(column) take typed column references. countAll<Model>() explicitly names the source model because it has no column argument.

Projection aliases are explicit. The alias passed to as names a field on the DTO result type, while col references a field path on the source model.

using namespace orm::query;
struct User
{
int id;
std::string displayName;
std::optional<std::string> email;
};
struct UserSummary
{
int id;
std::string name;
};
query.project(as("id", col<&User::id>()),
std::vector<UserSummary> rows = context.select(query);
constexpr auto as(std::string alias, S source)
constexpr auto col() -> TypedColumn< Members... >
Definition columns.cppm:336

Query behavior

ProjectionQuery supports the same filtering, ordering, paging, distinct, and join controls as Query:

using namespace orm::query;
query.project(as("id", col<&User::id>()),
.where(col<&User::email>().isNotNull())
.orderBy(asc(col<&User::id>()))
.limit(25)
.offset(50);
constexpr auto asc(TypedColumn< Members... > column)

The supported builder methods are:

  • where
  • andWhere
  • orWhere
  • orderBy
  • distinct
  • limit
  • offset
  • disableJoining
  • groupBy
  • having
  • andHaving
  • orHaving

Projection field paths use the same one-level relation rules as the existing query DSL. Relation fields are flattened into DTO fields through aliases:

struct Profile
{
int id;
std::string city;
};
struct User
{
int id;
Profile profile;
};
struct UserLocation
{
int id;
std::string city;
};
query.project(as("id", col<&User::id>()),

Nullable result fields are represented with std::optional<T>:

struct UserEmail
{
int id;
std::optional<std::string> email;
};
query.project(as("id", col<&User::id>()),
as("email", col<&User::email>()));

Aggregate result queries

Use ProjectionQuery<Source, Result> when aggregated values must be returned. They are projected into DTO fields through the same explicit as("dtoField", ...) aliases:

using namespace orm::query;
struct CityStats
{
std::string city;
long long users;
std::optional<double> averageAge;
};
struct Profile
{
int id;
std::string city;
};
struct User
{
int id;
int age;
Profile profile;
};
as("users", countAll<User>()),
as("averageAge", avg(col<&User::age>())))
.having(countAll<User>() > 1);
constexpr auto countAll()
constexpr auto avg(TypedColumn< Members... > column)

Supported aggregate helpers are count(col(...)), countAll<User>(), sum(col(...)), avg(col(...)), min(col(...)), and max(col(...)). countAll<User>() renders COUNT(*); the other helpers validate and render a source column path.

HAVING uses aggregate predicates instead of regular column predicates:

query.having(countAll<User>() > 1)
.andHaving(avg(col<&User::age>()) >= 18.0)
.orHaving(!(max(col<&User::age>()) < 65));
constexpr auto max(TypedColumn< Members... > column)

Comparison values are bound as SQL parameters, the same way WHERE predicate values are bound.

The same aggregate helpers, groupBy, having, andHaving, and orHaving are available on full-model Query<Model>. That query still returns std::vector<Model> and uses aggregates only for HAVING; it does not require a DTO unless aggregate values are selected as result fields.

Common DTO field choices are:

  • long long for count and countAll,
  • double for avg,
  • long long for integral sum, and the column scalar type for min and max,
  • std::optional<T> when the aggregate can return SQL NULL, such as avg or sum over an empty result set.

Result DTO rules

Projection DTOs are flat result objects. Supported DTO field types are the scalar types already supported by model binding plus std::optional<T> for SQL NULL values.

This includes orm::Date, orm::TimeOfDay, orm::LocalDateTime, orm::UtcTimestamp and orm::Uuid on supporting backends. Project into the same logical type as the source column; native values are not implicitly converted to strings or to another temporal type. Temporal MIN/MAX retain that type; use std::optional<T> when an empty input can return NULL. COUNT uses its existing integer result type. UUID MIN/MAX and typed ordering are unavailable. Result hydration preserves six fractional digits without adding formatting expressions to the query, so DISTINCT, grouping and native ordering keep their original SQL semantics. See Value types.

Alias validation is part of the public contract:

  • every DTO field must have exactly one projection alias,
  • every projection alias must match a DTO field,
  • duplicate aliases are invalid,
  • source column paths and their root model are checked at compile time,
  • relation fields must be projected as flat DTO fields.

DTO aliases remain runtime strings. Alias validation failures throw std::invalid_argument before executing SQL.

Limitations

Projection DTOs are flat. Relation fields must be flattened through aliases, for example as("city", col<&User::profile, &Profile::city>()).

ProjectionQuery does not expose include; collection wrappers are model state and are never hydrated into a flat DTO. A projection WHERE predicate may still use the dedicated any, exists, and none helpers to filter by a mapped source-model collection, but the collection itself cannot be projected.

Aggregate ORDER BY, COUNT(DISTINCT ...), raw aggregate expressions, and general subqueries are not part of this version. Correlated EXISTS is available only through the collection predicate helpers.

Fields and relation paths use typed member pointers.