Files
sqlgen/docs/string_operations.md
Dr. Patrick Urbanke (劉自成) f95156df77 Added operations on time stamps (#24)
2025-07-02 20:04:50 +02:00

1.8 KiB

String Operations

The sqlgen library provides a set of string functions for use in queries. These functions are type-safe and map to the appropriate SQL operations for the target database.

Motivating Example

Suppose you want to create a report of people with their full names in uppercase, and also want to trim any whitespace from their last names:

struct PersonReport {
  std::string full_name;
  std::string last_name_trimmed;
};

const auto get_reports =
    select_from<Person>(
        concat(upper("last_name"_c), ", ", "first_name"_c).as<"full_name">(),
        trim("last_name"_c).as<"last_name_trimmed">()
    )
    | to<std::vector<PersonReport>>;

This query produces a list of people with their full names in the format "LASTNAME, Firstname" (with the last name in uppercase) and ensures the last name has no leading or trailing whitespace.

String Functions

length

Returns the length of a string.

length(trim("first_name"_c)) | as<"length_first_name">

lower / upper

Converts a string to lowercase or uppercase.

lower("first_name"_c) | as<"first_name_lower">
upper("first_name"_c) | as<"first_name_upper">

ltrim, rtrim, trim

Removes whitespace (or a specified character) from the left, right, or both sides of a string.

ltrim("first_name"_c) | as<"ltrimmed_name">
rtrim("last_name"_c) | as<"rtrimmed_name">
trim("nickname"_c) | as<"trimmed_nickname">
// With custom characters:
ltrim("field"_c, "_ ") | as<"ltrimmed_field">

replace

Replaces all occurrences of a substring with another substring.

replace("first_name"_c, "Bart", "Hugo") | as<"first_name_replaced">

concat

Concatenates multiple strings or expressions.

concat("first_name"_c, " ", "last_name"_c) | as<"full_name">
concat(upper("last_name"_c), ", ", "first_name"_c) | as<"full_name">