Method GenerateLeadingCte(IReadOnlyList<FieldInfo>, FieldInfo, bool, string, string, string, string, int, int, string?, string?)
The leading form of a page sorted by one Props field: the index of values of that field is
walked in the order of the page, every other field is read for the object at hand, the filter
is checked, and the walk stops once the page is full. No join of every object of the scheme,
no hash, no sort: E015 (three wide conditions, by Salary, Take 100) 229 ms -> 2.5 ms.
The walk is capped at walkCap entries of the index, and the statement holds
the streams form of the same page next to it. If the capped walk filled the page, that page is
exact (the walk goes in the order of the page, so the first rows that pass within the cap are
the first rows of the answer) and the streams branch never runs. If it did not, the walk is
discarded and only the streams branch runs. One statement, the branch is chosen by a one-time
filter at run time: a filter that is wide by its shape and passes almost nothing no longer
walks the whole index (examples 381 ms -> 173 ms, the streams alone take 150-200).
Only for a key whose NULLs the filter rejects (the caller checks): the walk reads the index
of values, which holds no NULL, so an object without a value could not take its place in the
page. The ORDER BY of the walk carries no NULLS clause for the same reason, and so PostgreSQL
reads that order off the walk instead of sorting.
Example output:
WITH pvt_lead AS MATERIALIZED (
SELECT pvt._id_object, pvt."Age", pvt."Salary" FROM (
SELECT d._id_object, d._id_object AS _id, d.val AS "Salary", l0.v AS "Age"
FROM (SELECT v._id_object, v._numeric AS val FROM _values v
WHERE v._id_structure = $3 AND v._numeric IS NOT NULL AND v._array_index IS NULL
ORDER BY v._numeric DESC LIMIT 5000) d
JOIN LATERAL (SELECT o_src._id FROM _objects o_src WHERE o_src._id = d._id_object AND o_src._id_scheme = $1 OFFSET 0) o_src ON true
LEFT JOIN LATERAL (SELECT f._long AS v FROM _values f WHERE f._id_object = d._id_object AND f._id_structure = $4 AND f._array_index IS NULL OFFSET 0) l0 ON true
) pvt
WHERE pvt."Age" >= $2 AND pvt."Salary" > $5
ORDER BY pvt."Salary" DESC
LIMIT 100
),
pvt_wide AS ( the streams form of the same page, fenced ),
pvt_cte AS (
SELECT * FROM pvt_lead WHERE (SELECT count() FROM pvt_lead) = 100
UNION ALL
SELECT * FROM pvt_wide WHERE (SELECT count() FROM pvt_lead) < 100
)
public PvtSqlGenerator.PvtCteResult GenerateLeadingCte(IReadOnlyList<FieldInfo> fields, FieldInfo sortField, bool descending, string whereCondition, string schemeIdParam, string streamsOrderBy, string paginationClause, int limit, int walkCap, string? walkCondition = null, string? thenByClause = null)