Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

CTEs and unions

Two tools for queries that a chain of filters cannot say:

  • a CTE (common table expression, SQL’s WITH) names a query, so that another query can read it, join it, or call it recursively;
  • a union puts the rows of two queries together.

Django has union(), and CTEs only through the django-cte package.

CTEs

A named query: Cte::new

#![allow(unused)]
fn main() {
let busy = Cte::new("busy", &["station"], Query::<Journey>::new().select(Journey::origin_id()));

Query::<Station>::new()
    .with(&busy)
    .filter(Station::id().in_sub(busy.select("station")))
}
WITH "busy"("station") AS (SELECT "t0"."origin_id" FROM "timetable_journey" AS "t0")
SELECT "t0"."id", …
FROM "network_station" AS "t0"
WHERE "t0"."id" IN (SELECT "busy"."station" FROM "busy")
-- → stations 1, 2, 3
  • Cte::new(name, columns, query) names a query and its columns. The query selects as many values as there are columns.
  • .with(&cte) adds it to a query’s WITH.
  • cte.select("col") is SELECT col FROM cte, for in_sub; cte.col::<T>("col") is one of its columns as an expression; cte.r() is a reference to it, to join it.

Joining a CTE: join_cte

#![allow(unused)]
fn main() {
let below = Region::descendants(2);
Query::<Station>::new()
    .with(&below)
    .join_cte(&below.r(), Station::region_id().eq(below.col::<i64>("id")))
}
WITH RECURSIVE "region_tree"(…) AS (…)
SELECT "t0"."id", …
FROM "network_station" AS "t0"
INNER JOIN "region_tree" ON "t0"."region_id" = "region_tree"."id"

join_cte(&cte.r(), on) is an INNER JOIN on a condition. A CTE can be joined inside a sub-query too, and filtered on its columns: see the “stations below each region” example in Trees.

A recursive CTE: Cte::recursive

The tree functions cover the usual walks. For a walk of your own, Cte::recursive writes WITH RECURSIVE: a base query, and a step that receives the CTE itself to join to it.

#![allow(unused)]
fn main() {
// The regions under Bretagne, by hand.
let below = Cte::recursive(
    "below",
    &["id"],
    Query::<Region>::new().filter(Region::id().eq(2)).select(Region::id()),
    |below| {
        Query::<Region>::new()
            .join_cte(below, Region::parent_id().eq(below.col::<i64>("id")))
            .select(Region::id())
    },
);
Query::<Station>::new()
    .with(&below)
    .filter(Station::region_id().in_sub(below.select("id")))
// → stations 2, 3, 4
}
WITH RECURSIVE "below"("id") AS (
  SELECT "t0"."id" FROM "network_region" AS "t0" WHERE "t0"."id" = $1
  UNION ALL
  SELECT "t0"."id" FROM "network_region" AS "t0" INNER JOIN "below" ON "t0"."parent_id" = "below"."id")
SELECT …
WHERE "t0"."region_id" IN (SELECT "below"."id" FROM "below")

The step runs again on the rows the previous step found, until it finds none. Unlike rind’s own walks, this one does not protect itself against cycles: a row that is its own ancestor makes it run forever. Use it on data that cannot have cycles, or keep the keys seen, as rind’s walks do.

Unions

union and union_all

#![allow(unused)]
fn main() {
let paris_or_big = Query::<Station>::new()
    .filter(Station::city().eq("Paris"))
    .union(Query::<Station>::new().filter(Station::platforms().ge(20)));
}
SELECT "t0"."id", …
FROM ((SELECT … FROM "network_station" AS "t0" WHERE "t0"."city" = $1)
      UNION
      (SELECT … FROM "network_station" AS "t0" WHERE "t0"."platforms" >= $2)) AS "t0"
-- → stations 1, 6; count 2

Paris Montparnasse is in both branches, but comes once: UNION removes rows that are the same in every column. union_all keeps every row of both (here, 3 rows: Paris twice).

Both branches are queries on the same model. Each keeps its own filters, order and limit.

A union is a query

A union is a Query<Station> like any other: it is filtered (through relations too), ordered, counted, paginated and read as models.

#![allow(unused)]
fn main() {
paris_or_big
    .filter(Station::region().name().eq("Italia"))
    .order_by([Station::id().asc()])
    .limit(5)
}
SELECT "t0"."id", …
FROM ((…) UNION (…)) AS "t0"
INNER JOIN "network_region" AS "region" ON "region"."id" = "t0"."region_id"
WHERE "region"."name" = $3
ORDER BY "t0"."id"
LIMIT 5
-- → station 6

So a union can be a resource’s base query, or the result of a scope.

When the two branches are on the same table, a filter with | is usually simpler and faster than a union. A union is for branches that need different joins, orders, limits, or a value of their own.

Telling the branches apart: extra

To know which branch a row came from, give each branch a value with extra, and read it with extra_value:

#![allow(unused)]
fn main() {
// sample/tests/db.rs
let scored = |q: Query<Station>, score: i64| q.extra("score", func::int(score));
let score = || Query::<Station>::extra_value::<i64>("score");

let union = scored(Query::<Station>::new().filter(Station::departures().count().ge(1)), 10)
    .union(scored(Query::<Station>::new().filter(Station::stops().count().ge(1)), 0));

let select = union
    .order_by([score().desc(), Station::id().asc()])
    .select((Station::id(), score()))
    .into_select();
let rows: Vec<(i64, i64)> = db.rows(&select).await?;
// [(1, 10), (2, 10), (3, 10), (1, 0), (2, 0)]
}
SELECT "t0"."id", "t0"."score"
FROM ((SELECT "t0"."id", …, CAST($1 AS bigint) AS "score" FROM "network_station" AS "t0" WHERE …)
      UNION
      (SELECT "t0"."id", …, CAST($3 AS bigint) AS "score" FROM "network_station" AS "t0" WHERE …)) AS "t0"
ORDER BY "t0"."score" DESC, "t0"."id"

Stations 1 and 2 are in both branches, so they come twice, once per score: the rows differ in score, so UNION keeps both. This is how a search ranks its results: one branch per kind of match, each with its score, the best first.

Both branches must give the same extra values, by name.

Next: Transactions and locks.