Method GenerateStreamsCte(IReadOnlyList<FieldInfo>, string, string, string?, string, string, bool, IReadOnlyCollection<string>?, bool, string?, string?, (long StructureId, string DbColumn)?)
Generates the streams form of the pivot CTE: the objects of the scheme drive, and every field
is a LEFT JOIN to its own structure range of _values. No aggregate, no GROUP BY.
Example output:
WITH pvt_cte AS (
SELECT pvt._id_object, pvt."Age", pvt."Salary" FROM (
SELECT o_src._id AS _id_object, f0._long AS "Age", f1._numeric AS "Salary"
FROM _objects o_src
LEFT JOIN _values f0 ON f0._id_object = o_src._id AND f0._id_structure = $5 AND f0._array_index IS NULL
LEFT JOIN _values f1 ON f1._id_object = o_src._id AND f1._id_structure = $6 AND f1._array_index IS NULL
WHERE o_src._id_scheme = $1
OFFSET 0
) pvt
WHERE pvt."Age" >= $2
ORDER BY pvt."Salary" DESC
LIMIT 100
)
OFFSET 0 is an optimization fence, not pagination. Without it PostgreSQL pushes the filter
into the stream scans and estimates them 30-40 times too low (structure, _array_index and
the value column are correlated, the statistics treat them as independent), which turns the
joins into nested loops or hash joins over the whole scheme. With the fence each stream is
estimated by its structure alone and the planner picks merge joins over ordered index scans
on its own. Measured in docs/pvt_LEAD_value/PG_LEAD_VALUE.md, section 14.
The price of the fence is that the filter is checked above the streams, after every object
of the scheme has been joined. A narrow leaf ()
is better pushed down to the index of values, so the caller drops the fence for it: one order
number among 689 thousand points, 2.4 s with the fence, 31 ms without.
ORDER BY and LIMIT sit INSIDE the CTE: joining _objects for every row that passed the filter
and sorting outside is what makes this form slower than the aggregate one.
The caller guarantees every field has at most one _values row per object
(PvtPrefilterPlanner.BuildStreams): a top-level scalar, a dictionary entry, or a field of a
class stored in a dictionary. The three differ only in how the row is addressed.
public PvtSqlGenerator.PvtCteResult GenerateStreamsCte(IReadOnlyList<FieldInfo> fields, string whereCondition, string schemeIdParam, string? additionalObjectFilter, string orderByClause, string paginationClause, bool overTree = false, IReadOnlyCollection<string>? baseColumns = null, bool fence = true, string? chainedName = null, string? drivingCondition = null, (long StructureId, string DbColumn)? drivingField = null)