# C++ Use the installed SDK to query an Arrow array from a C++20 application. Build the supplied example from the source root, replacing `/path/to/sdk` with the SDK prefix: ``` cmake -S examples/cpp -B build/quickstart -G Ninja -DCMAKE_PREFIX_PATH=/path/to/sdk cmake --build build/quickstart ./build/quickstart/quixote_quickstart ``` The program prints `total=36 rows=3`. Its CMake file links `Quixote::interchange`, which also links the core query engine. ``` cmake_minimum_required(VERSION 3.28) project(QuixoteQuickstart LANGUAGES CXX) find_package(Quixote CONFIG REQUIRED) add_executable(quixote_quickstart main.cc) target_link_libraries(quixote_quickstart PRIVATE Quixote::interchange) ``` The program imports a nullable Int64 array, filters it, computes a total and exports the result through Arrow C Data. The input buffers stay in scope while the query uses them. ``` // SPDX-License-Identifier: Apache-2.0 #include #include #include #include struct ExportedBatch { ArrowSchema schema{}; ArrowArray array{}; ~ExportedBatch() { if (array.release) array.release(&array); if (schema.release) schema.release(&schema); } }; int main() { using namespace quixote; const int64_t values[]{1, 2, 0, 600, 3}; const uint8_t valid = 0b11011; const void* buffers[]{&valid, values}; ArrowSchema schema{"l", "x", nullptr, ARROW_FLAG_NULLABLE, 0, nullptr, nullptr, [](ArrowSchema* p) noexcept { p->release = nullptr; }, nullptr}; ArrowArray array{5, 1, 0, 2, 0, buffers, nullptr, nullptr, [](ArrowArray* p) noexcept { p->release = nullptr; }, nullptr}; auto input = ImportArray(&schema, &array); auto runtime = Runtime::Make({2, 1, 4 * 1024 * 1024}); Session session(runtime, 1024 * 1024); auto result = session.FromTable(Table::FromBatches(input.schema(), {input})) .Filter(Col("x").Less(Lit(int64_t{512}))) .Select({Col("x").Add(Lit(int64_t{10})).Alias("value")}) .Select({Col("value").Sum().Alias("total"), CountRows().Alias("rows")}) .Collect(); ExportedBatch output; ExportArray(result.batches().front(), &output.schema, &output.array); session.Close(); runtime->Close(); int64_t total, rows; const auto* totals = output.array.children[0]; const auto* counts = output.array.children[1]; std::memcpy(&total, static_cast(totals->buffers[1]) + totals->offset * 8, sizeof(total)); std::memcpy(&rows, static_cast(counts->buffers[1]) + counts->offset * 8, sizeof(rows)); if (total != 36 || rows != 3) return 1; std::cout << "total=" << total << " rows=" << rows << '\n'; } ``` ## Build a query Start with `Session::FromTable`, `Session::FromSource` or `ScanParquet`. Use `Filter` to keep rows and `Select` to compute columns, or `GroupBy(keys, aggregates)` to reduce rows by key. Use `Lit(int64_t{10})` for an Int64 literal, `LitInt8(-128)` for Int8, `LitUInt64(UINT64_MAX)` for UInt64, `LitFloat32(1.5f)` for `Type::Float32`, `LitUtf8("west")` for text and `LitDecimal("0.05")` for an exact decimal. For opaque bytes, pass a length-aware `std::string_view` to `LitBinary`. Use `LitTimestamp({micros, true})` for UTC and `LitTimestamp({micros, false})` for a naive timestamp. Use `Type::Date64()`, `Type::LargeUtf8()` and `Type::LargeBinary()` for millisecond dates and 64-bit byte offsets. Check timestamp and binary types with `Type::Binary()`, `Type::TimestampUtc()` and `Type::TimestampUs()`. Dates use `std::chrono::sys_days`. Use `Col("shipped").DateDiffDays(Col("ordered"))` for elapsed days or `Col("ordered").DateAddDays(Lit(int64_t{7}))` for a date one week later. `Month()` and `Day()` extract calendar parts. For text, use `Trim()`, `LTrim()`, `RTrim()`, `Lower()`, `Upper()` and `Concat(other)`. `Length()` counts code points and `ByteLength()` counts bytes. Use `query.Limit(rows, offset)` to page through a sorted query. `Coalesce({a, b})` picks the first non-null value. Numeric expressions support `Abs()`, `Floor()`, `Ceil()` and `Round(digits)`. Use `Col("time").DateTrunc("hour")` to group timestamps by hour. Use `NullIf(a, b)` to clear matching values and `a.Modulo(b)` for remainders. Call `Replace(old, replacement)` on text or `SplitPart(delimiter, part)` to extract a field. In `Select` or `GroupBy`, use `StddevSamp()`, `StddevPop()`, `VarSamp()` and `VarPop()` to measure spread. Use `AnyValue()` to keep one non-null value in its original type. See [Behavior and limits](<../semantics/index.md>) for case and whitespace rules. Use `left.Intersect(right)` to keep common rows or `left.Except(right)` to keep rows found only on the left. Both return one copy per distinct row. Pass `true` as the second argument to intersect or subtract duplicate counts. `Query::Join` takes the right query, two lists of key names, a `JoinType`, an optional filter and a suffix for duplicate names. Use `JoinType::Right` to keep unmatched right rows or `JoinType::Full` to keep unmatched rows from both inputs. Key lists must be empty for `JoinType::Cross`. Use `query.Sort({{"key"}, {"total", true}})` to sort by ascending key and then descending total. Call `Collect()` for a table or `Stream()` for a move-only cursor. Both accept `ExecutionOptions` with `memory_limit` and `max_contexts`. Use `auto profile = query.Collect({.profile = true}).profile();` to capture one execution. Print `profile->Summary()` for operator timings and row counts. `ToJson()` returns the counters, `ToOtelJson()` returns OTLP/JSON, and `ToChromeTraceJson()` returns a trace you can open in Perfetto. A profiled stream exposes its profile after EOF or `Close()`. Use `WriteParquetWithProfile` to include writing in the profile. `FilterAggregate` times a fused predicate and partial sum. Trace storage uses the query budget, and `spans_dropped` reports omitted phases. Retained snapshots and their copies count toward caller-held memory. Read `Runtime::stats()` after a query finishes. In the returned `MemoryStats`, `peak_working_bytes` is the most working memory in use at once, `peak_reserved_bytes` is the largest total of active query reservations, and `peak_held_bytes` is the most memory held by callers. Each peak covers the lifetime of the runtime. Use `Expr::RegexpLike` to filter strings, `Expr::RegexpExtract` to select a match or capture, and `Expr::RegexpReplace` to replace it. Pass `true` as the third replacement argument to change every match. See [Behavior and limits](<../semantics/index.md>). ## Exchange Arrow data On success, `ImportArray` and `ImportStream` take ownership of the C structs and clear their release callbacks. On failure the caller retains ownership. Keep imported buffers immutable until release. Pass empty output structs to `ExportArray`, `ExportTable` and `ExportStream`. Each export stays valid after the runtime closes. Call each release callback when finished. Serialize all calls on a C Stream, including release. Check the return status of `get_schema` and `get_next`. At end of stream, `get_next` succeeds with a null array release callback. For a native `ResultStream`, `Next()` blocks until a batch, end of stream or failure. Use `WaitFor(duration)` for a bounded wait and `Close()` to stop early. Call blocking waits and close from application threads. ## Window functions Call `query.Window({"region"}, {{"sales", true}}, {Rank().Alias("place")})` to rank sales within each region, highest first. Use an empty vector for either set of keys. Each expression needs a unique output alias. Add `Col("sales").Lag(1, Lit(int64_t{0})).Alias("previous")` to the same call to read the preceding Int64 sale, with zero for the first sale in each region. ## Disk spilling Set `RuntimeOptions::spill_directory` to a writable directory to let sorts and grouped aggregates write temporary runs. Set `max_spill_bytes` to limit their combined live size across queries. ## Nested Arrow columns `Type::Struct({{"id", Type::Int64}, {"items", Type::List(Type::Utf8)}})` describes a record containing a list. Use `Type::LargeList` for 64-bit offsets. Pass a `Field` to either list constructor to preserve the item name, nullability and metadata. Use `StructField`, `ListLength`, `ListElement` and `ListContains` on expressions. `StructPack({{"id", Col("id")}, {"items", Col("items")}})` constructs a non-null struct in the given order. Build a map with `Type::Map(key_type, item_type)`. The overload taking two fields preserves their names, nullability and metadata. The key field must be required. Pass `true` as the third argument for sorted keys. Use `MapKeys()`, `MapValues()`, `MapGet(key)` or `ListLength()` on a map expression.