Skip to content

Field Note 6 — Search, JSONPath, Lateral & Multi-Table DML#

Field Notes · ORM Design · 🕛 Post-Launch · 17:45 · ⏱ 9 min read · 🥜🥜🥜🥜◌

ts_match() & ts_rank() · jsonb_path_exists() · LATERAL & QUALIFY · WITHIN GROUP percentiles · Data-modifying CTEs · DEFERRABLE FKs

▶ Run it yourself: examples/311_fts_jsonpath_and_dml.py

Post-Launch, 18:00. The concierge desk wants ranked full-text search, deep JSONPath filtering, correlated top-1 lateral lookups, atomic multi-table archival, and circular herd-pair links — all without dropping into raw SQL.

Post-Launch, 18:00. The concierge desk wants ranked full-text search, deep JSONPath filtering, correlated top-1 lateral lookups, atomic multi-table archival, and circular herd-pair links — all without dropping into raw SQL.

Maya: Every time a feature asks for websearch_to_tsquery, LATERAL, UPDATE ... FROM, or a writable CTE, other ORMs tell us to fall back to text("...").

Ferris: Not here. Every one of those is a first-class, statically typed AST node in pgdorm, compiled in Rust to canonical 1-RTT PostgreSQL.

1. Full-Text Search (to_tsvector, websearch_to_tsquery, ts_rank_cd)#

Build tsvector expressions with pg.to_tsvector(...), parse user queries with pg.websearch_to_tsquery, pg.plainto_tsquery, or pg.phraseto_tsquery, match with .ts_match(...) (@@), and score with pg.ts_rank or cover-density pg.ts_rank_cd:

examples/311_fts_jsonpath_and_dml.py · full_text_search
async def full_text_search(pool: pg.Pool) -> None:
    vec = pg.to_tsvector(GuestArticle.body, config="english")
    q_web = pg.websearch_to_tsquery("mud spa OR roasted peanuts", config="english")
    q_plain = pg.plainto_tsquery("mud bath", config="english")
    q_phrase = pg.phraseto_tsquery("warm mud spa", config="english")

    async with pool.trace() as tr:
        ranked = await pool.all(
            pg.select(GuestArticle)
            .columns(
                GuestArticle.title,
                pg.ts_rank(vec, q_web).alias("rank"),
                pg.ts_rank_cd(vec, q_phrase).alias("cd_rank"),
            )
            .where(pg.or_(vec.ts_match(q_web), vec.ts_match(q_plain)))
            .order_by(pg.ts_rank(vec, q_web).desc(), GuestArticle.guest_article_id.asc())
        )
    assert tr.rtts == 1
    print(f"fts ({tr.rtts} RTT): {[title for title, _r, _cd in ranked]}")
    # => fts (1 RTT): ['Warm Mud Spa Guide', 'Mud Bath Checklist']

2. SQL/JSON Path & JSONB Operators (#>>, ?&, ?|, #-)#

Combine PostgreSQL's SQL/JSON path functions (pg.jsonb_path_exists, pg.jsonb_path_match, pg.jsonb_path_query_first, pg.jsonb_path_query_array) with typed JSONB operators (.json_path_text(...) for #>>, .json_has_all_keys(...) for ?&, .json_has_any_key(...) for ?|, and .json_delete_path(...) for #-):

examples/311_fts_jsonpath_and_dml.py · jsonpath_and_jsonb_ops
async def jsonpath_and_jsonb_ops(pool: pg.Pool) -> None:
    async with pool.trace() as tr:
        rows = await pool.all(
            pg.select(GuestArticle)
            .columns(
                GuestArticle.title,
                GuestArticle.meta.json_path_text("wing", "floor").alias("floor"),
                pg.jsonb_path_query_first(GuestArticle.meta, "$.tags[0]").alias("first_tag"),
                pg.jsonb_path_query_array(GuestArticle.meta, "$.tags[*]").alias("all_tags"),
                GuestArticle.meta.json_delete_path(["internal", "draft"]).alias("cleaned"),
            )
            .where(
                pg.and_(
                    pg.jsonb_path_exists(GuestArticle.meta, "$.vip ? (@ == true)"),
                    pg.jsonb_path_match(GuestArticle.meta, "$.priority >= 2"),
                    GuestArticle.meta.json_has_all_keys(["vip", "wing"]),
                    GuestArticle.meta.json_has_any_key(["tags", "legacy"]),
                )
            )
            .order_by(GuestArticle.guest_article_id.asc())
        )
    assert tr.rtts == 1
    summary = [(fl, ft, len(tags)) for _t, fl, ft, tags, _c in rows]
    print(f"jsonpath ({tr.rtts} RTT): {summary}")
    # => jsonpath (1 RTT): [('penthouse', 'spa', 2), ('east', 'bath', 1)]

3. Correlated LATERAL, Hoisted QUALIFY, and .pipe()#

  • pg.lateral(..., alias=...) + Select.join_lateral(..., kind="left") expresses correlated top-K subqueries with typed .col(name, py_type) references.
  • Select.qualify(predicate) hoists window-function filters (ROW_NUMBER() OVER (...) = 1) into a clean wrapping subquery automatically.
  • Select.pipe(fn) composes reusable query filters without subclassing.
examples/311_fts_jsonpath_and_dml.py · lateral_qualify_and_pipe
async def lateral_qualify_and_pipe(pool: pg.Pool) -> None:
    top_note = pg.lateral(
        pg.select(GuestArticle)
        .columns(GuestArticle.title, GuestArticle.score)
        .where(GuestArticle.guest_id == Guest.guest_id)
        .order_by(GuestArticle.score.desc())
        .limit(1),
        alias="top_note",
    )

    def only_high_points(q: pg.Select[pg.ResultRow]) -> pg.Select[pg.ResultRow]:
        return q.where(Guest.peanut_points >= 100)

    async with pool.trace() as tr_lat:
        lat_rows = await pool.all(
            pg.select(Guest)
            .join_lateral(top_note, kind=pg.enums.LateralJoinKind.LEFT)
            .columns(
                Guest.first_name,
                top_note.col("title", str),
                top_note.col("score", Decimal),
            )
            .pipe(only_high_points)
            .order_by(Guest.guest_id.asc())
        )
    assert tr_lat.rtts == 1
    print(f"lateral ({tr_lat.rtts} RTT): {[(n, t) for n, t, _s in lat_rows]}")
    # => lateral (1 RTT): []

    async with pool.trace() as tr_qual:
        best_per_guest = await pool.all(
            pg.select(GuestArticle)
            .columns(GuestArticle.title, GuestArticle.score)
            .qualify(
                pg.row_number().over(
                    partition_by=[GuestArticle.guest_id],
                    order_by=[GuestArticle.score.desc()],
                )
                == 1
            )
            .order_by(GuestArticle.score.desc())
        )
    assert tr_qual.rtts == 1
    print(f"qualify ({tr_qual.rtts} RTT): {[t for t, _s in best_per_guest]}")
    # => qualify (1 RTT): ['Warm Mud Spa Guide', 'Mud Bath Checklist']

4. Ordered & Percentile Aggregates (string_agg, percentile_cont)#

Pass order_by=[...] to pg.string_agg(...) for deterministic concatenation, and use pg.percentile_cont(0.95, order_by=...) for PostgreSQL WITHIN GROUP (ORDER BY ...) percentiles:

examples/311_fts_jsonpath_and_dml.py · ordered_and_percentile_aggregates
async def ordered_and_percentile_aggregates(pool: pg.Pool) -> None:
    async with pool.trace() as tr:
        row = await pool.one(
            pg.select(GuestArticle).columns(
                pg.string_agg(
                    GuestArticle.title,
                    " | ",
                    order_by=[GuestArticle.score.desc()],
                ).alias("titles"),
                pg.percentile_cont(0.95, order_by=GuestArticle.score.asc()).alias("p95"),
            )
        )
    assert tr.rtts == 1
    titles, p95 = row
    print(f"agg ({tr.rtts} RTT): p95={p95:.2f} titles={titles}")
    # => agg (1 RTT): p95=91.20 titles=Warm Mud Spa Guide | Mud Bath Checklist | Sunset Terrace

5. Multi-Table DML & Writable CTEs (INSERT ... SELECT, UPDATE ... FROM, DELETE ... USING)#

Move and mutate data set-at-a-time in 1 RTT:

  • pg.insert(Target).from_select(src) emits INSERT INTO ... SELECT ....
  • pg.update(Target).from_(Other) emits UPDATE ... SET ... FROM ... WHERE ....
  • pg.cte("purged", pg.delete(Target).using(Other)...returning(...)) paired with pg.with_(purged, query=pg.insert(Archive).from_select(...)) atomically deletes and archives in a single statement.
examples/311_fts_jsonpath_and_dml.py · multi_table_dml_and_write_cte
async def multi_table_dml_and_write_cte(pool: pg.Pool) -> None:
    # 1. INSERT ... SELECT
    src = (
        pg.select(GuestArticle)
        .columns(GuestArticle.guest_id, GuestArticle.title, GuestArticle.score)
        .where(GuestArticle.score >= Decimal("80.00"))
    )
    async with pool.trace() as tr_ins:
        inserted = await pool.all(
            pg.insert(FeaturedArticle).from_select(src).returning(FeaturedArticle.title)
        )
    assert tr_ins.rtts == 1

    # 2. UPDATE ... FROM
    async with pool.trace() as tr_upd:
        boosted = await pool.all(
            pg.update(FeaturedArticle)
            .from_(Guest)
            .set(score=FeaturedArticle.score + Decimal("5.00"))
            .where(
                pg.and_(
                    FeaturedArticle.guest_id == Guest.guest_id,
                    Guest.peanut_points >= 200,
                )
            )
            .returning(FeaturedArticle.title, FeaturedArticle.score)
        )
    assert tr_upd.rtts == 1

    # 3. Writable CTE: DELETE ... USING ... RETURNING -> INSERT ... SELECT in 1 RTT.
    purged = pg.cte(
        "purged",
        pg.delete(FeaturedArticle)
        .using(Guest)
        .where(
            pg.and_(
                FeaturedArticle.guest_id == Guest.guest_id,
                FeaturedArticle.score >= Decimal("90.00"),
            )
        )
        .returning(FeaturedArticle.title, FeaturedArticle.score),
    )
    async with pool.trace() as tr_wcte:
        archived = await pool.all(
            pg.with_(
                purged,
                query=pg.insert(ArchivedArticle)
                .from_select(pg.select(purged).columns(purged.col("title"), purged.col("score")))
                .returning(ArchivedArticle.title, ArchivedArticle.score),
            )
        )
    assert tr_wcte.rtts == 1
    print(
        f"dml ({tr_ins.rtts}+{tr_upd.rtts}+{tr_wcte.rtts} RTTs): "
        f"inserted={len(inserted)} boosted={len(boosted)} archived={[t for t, _s in archived]}"
    )
    # => dml (1+1+1 RTTs): inserted=2 boosted=0 archived=['Warm Mud Spa Guide']

6. Deferrable Foreign Keys (DEFERRABLE INITIALLY DEFERRED)#

When two rows reference each other (or a self-referencing pair swaps pointers), declare pg.ForeignKey(..., deferrable=True, initially_deferred=True) so PostgreSQL validates the constraint at COMMIT rather than per statement:

examples/311_fts_jsonpath_and_dml.py · deferrable_foreign_keys
async def deferrable_foreign_keys(pool: pg.Pool) -> None:
    # Self-referencing pair inserted in a single transaction: INITIALLY DEFERRED
    # validates the circular FK at COMMIT rather than per-statement.
    async with pool.transaction() as tx:
        await tx.execute(
            pg.insert_many(
                HerdPair,
                [
                    HerdPair(herd_pair_id=10, code="ALPHA", partner_id=20),
                    HerdPair(herd_pair_id=20, code="BETA", partner_id=10),
                ],
            )
        )
    pairs = await pool.all(
        pg.select(HerdPair)
        .columns(HerdPair.code, HerdPair.partner_id)
        .order_by(HerdPair.herd_pair_id.asc())
    )
    print(f"deferrable fk: {pairs}")
    # => deferrable fk: [('ALPHA', 20), ('BETA', 10)]