Skip to content

🐛 Fixed mongo-knex dropping a condition on a join table's column - #315

Closed
rob-ghost wants to merge 1 commit into
mainfrom
fix/dya-308-join-table-conditions
Closed

rob-ghost wants to merge 1 commit into
mainfrom
fix/dya-308-join-table-conditions

Conversation

@rob-ghost

@rob-ghost rob-ghost commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

ref https://linear.app/ghost/issue/DYA-308

Problem

A condition on a join table's column, such as posts_tags.sort_order:0, is one the converter resolves to the many-to-many relation whose join table it names. In an $and, mongo-knex took every such condition out of the relation grouping and added it to the join of every relation subquery built at the same level. That went wrong in three ways:

  • With no condition on a relation at the same level, nothing took it and it was dropped. {'posts_tags.sort_order': 1} selected every post. A group of tag conditions with the join table condition outside the group lost the condition. Inside a $nor the dropped condition left NOT EXISTS (SELECT 1), which matches no rows at all.
  • Beside a condition on a relation that doesn't read that table, it was added to that relation's subquery anyway: {$and: [{'authors.slug': 'sam'}, {'posts_tags.sort_order': 1}]} failed with no such column: posts_tags.sort_order, and so did the same beside a one-to-one relation.
  • An aggregate beside it checked for itself whether it reads the table and ignored the condition if not, so beside an aggregate of another table, or one that names the table by an alias, the condition was dropped.

In Ghost, email_recipients.opened_at:>=0 on the members list returned every member, and beside status:paid every paid member. Members bulk edit and bulk delete select their members with the same filters. posts_tags.sort_order:0 on posts returned every post.

Solution

One rule decides where a join table condition goes: it restricts the subquery of a condition beside it, at the same level, whose relation reads that table. With no such condition, it is a condition on its own relation, the first in the config whose join table it is, which is how an $or already builds it.

A relation reads a join table when it is a many-to-many relation with that join table, or an aggregate whose table or joined tables are that table under the name the condition uses. A one-to-one relation reads no join table. readsTable is the one place that decides this. The aggregate builder's own check and the one-to-one builder's join conditions are gone: the one-to-one builder added join table conditions to a join that never reads a join table, which is what built the invalid SQL.

{'posts_tags.sort_order': 1}
// posts.id in (select posts_tags.post_id from posts_tags
//   inner join tags on tags.id = posts_tags.tag_id where posts_tags.sort_order = 1)

{$and: [{'authors.slug': 'sam'}, {'posts_tags.sort_order': 1}]}
// posts.id in (<authors subquery, slug = 'sam'>) and posts.id in (<tags subquery, sort_order = 1>)

{$and: [{'tags.slug': 'cgi'}, {'posts_tags.sort_order': 0}]}
// unchanged: ... inner join tags on tags.id = posts_tags.tag_id and posts_tags.sort_order = 0 where tags.slug = 'cgi'

What changes, for which filters

Exposure says who can send the filter:

  • Admin-built: Ghost or Admin writes it, such as primary_tag, opened_emails.post_id, the free-subscriber rewrite and the members filter builder.
  • Stored: saved and run again later, such as a member segment. Only one written by hand through the API can hold a join table key.
  • Hand-written private: an Admin API filter, including members bulk edit and bulk delete.
  • Hand-written public: the Content API filter, a theme's {{#get}} and routes.yaml. The Content API removes roles_users keys, but not posts_tags.* or posts_authors.*.
Filter Before After Exposure
primary_tag:… and primary_author:… in every form (negated, listed, combined, in a group), opened_emails.post_id:…, tag:a+posts_tags.sort_order:0 Join table condition in its relation's join Identical SQL Admin-built, stored, hand-written
posts_tags.sort_order:0, alone or beside columns Condition ignored: every post the rest matches Posts with a tag first Hand-written public and private
email_recipients.opened_at:>=0, members_click_events.created_at:>'…', members_newsletters.created_at:>'…', members_labels.label_id:…, alone or beside status:paid Condition ignored: every member, or every paid member Members with a matching row Hand-written private, stored
roles_users.role_id:… on staff Condition ignored Staff with that role Hand-written private
posts_tags.sort_order:-0 Condition ignored Posts with no tag first, including posts with no tags, as tag:-a means posts without tag a Hand-written public and private
email_recipients.opened_at:-null Condition ignored: every member Members with no recipient row that has an open: members who never opened an email, including members never sent one. This is the opposite of what the filter reads as, and follows how label:-null already means "no label" Hand-written private, stored
-(posts_tags.sort_order:0), -(members_labels.label_id:x), -(email_recipients.opened_at:>=0) No rows More rows: the rows without such a join row Hand-written public and private, stored
-(posts_tags.sort_order:0+featured:true) Left out every featured post More rows: leaves out only the featured posts with a tag first Hand-written public and private
(posts_tags.sort_order:1+posts_authors.sort_order:1),status:draft The group was dropped: drafts only More rows: also posts with a tag second and an author second Hand-written public and private
(tags.slug:a+featured:true)+posts_tags.sort_order:1 Condition ignored Featured posts tagged a that have some tag second Hand-written public and private
authors.slug:joe+posts_tags.sort_order:0, posts_meta.feature_image_alt:x+posts_tags.sort_order:0, -(authors.slug:joe+posts_tags.sort_order:1) SQL error Each condition applied Hand-written public and private
count.active_stripe_customers:>0+email_recipients.opened_at:>=0 Condition ignored Applied Hand-written private
tag:-a+tag:-b+posts_tags.sort_order:1 Condition ignored: posts with neither tag Posts with neither tag that have some tag second. See the second known fault Hand-written public and private
An aggregate with tableNameAs beside a condition on its real table name Condition ignored A condition of its own None in Ghost: no aggregate there uses an alias

Filters Ghost builds itself compile to identical SQL

I compiled filters through Ghost's own models with mongo-knex 0.13.0 and with this branch, redirecting every require of @tryghost/mongo-knex to the branch: Ghost's own copy, which compiles every model's filter, and @tryghost/nql's. Ghost was at a commit 18 commits behind main, none of which touch the models, the filter steps or the API filter utils. Nothing connected to a database: the comparison is the SQL text and bindings.

  • 1,207 cases: the members filters Ghost's test suites send (harvested for DYA-295, with the transformers they use), segment, subscribed, label, tier, newsletter and opened_emails.post_id forms, and post and staff filters. 1,191 are identical. The 16 that differ are all hand-written join table filters in the table above.
  • 10 negated, listed and combined primary_tag and primary_author filters: identical.
  • No Ghost code or test writes a join table key, apart from Ghost's own expansions above and Content API tests that check roles_users keys are removed before the query is built.

Release

This needs a minor of @tryghost/mongo-knex (0.14.0), with @tryghost/nql republished to depend on it. The change returns different rows for valid filters, some of them more rows, and under 0.x a minor is what signals that. nql 0.14.0 depends on ^0.13.0, which accepts any 0.13.x and not 0.14.0, so a patch would reach anyone who installs nql without a lockfile, or refreshes one, without them choosing it.

In Ghost that path is narrower than it looks. Since Ghost's filter pipeline moved into lib/filters (2026-11-25), every model's filter compiles with Ghost's own copy of mongo-knex, which Ghost pins exactly in its catalog. Ghost's callers of nql(...).querySQL (bulk filters, raw knex) pass no relations, so a join table key there is a plain column and this change doesn't reach them. Released Ghost builds also ship a lockfile seeded from the root one. So the minor is right on semver grounds and for consumers outside Ghost, and Ghost takes the change only with a deliberate bump either way. pnpm ship minor bumps the packages and rewrites nql's range, as the last release did.

After the release, in Ghost

Ghost bumps @tryghost/mongo-knex in its catalog, the copy every model filter compiles with, and @tryghost/nql with it so the lockfile keeps one copy of mongo-knex. With the bump it adds e2e-api tests for email_recipients.opened_at:>=0 on the members list and in a members bulk edit, and for posts_tags.sort_order:1 on the Admin posts list. Those tests fail until the bump, so nothing lands in Ghost first. The Content API change, where posts_tags.* and posts_authors.* filters now apply, belongs in Ghost's release notes.

Known faults this leaves

  • Beside its relation, a join table condition is applied in the join's ON with knex's andOn, which reads the value as a column name. {$and: [{'tags.slug': 'a'}, {'posts_tags.created_at': {$gt: '2026-01-01'}}]} compiles to posts_tags.created_at > `2026-01-01` , so in Ghost clicked_links.post_id:abc+members_click_events.created_at:>'2026-01-01' fails. A null, $in or $regex value builds invalid SQL there, and on a relation with joinType: 'leftJoin' a condition in the join removes no rows. The three places that apply a join table condition also read it differently: in the join's ON beside a many-to-many relation, bound in an aggregate's inner query, and as a full comparison with applyComparison when it is on its own. So posts_tags.sort_order:-0 means "no tag first" on its own and "tagged a at another position" beside tag:a.
  • Keys of one object are built one at a time, so a join table condition and its relation written as keys of one object don't meet. {'tags.slug': 'classic', 'posts_tags.sort_order': 1} matches posts tagged classic that have some tag second, and its $and form matches posts with classic second. nql's combineNeFilters writes that shape: it puts the combined $nin beside the $and, so tag:-a+tag:-b+posts_tags.sort_order:1 means "neither tag, and some tag second", while the same filter with $ne conditions in one $and means "neither tag is second".
  • In @tryghost/nql, primary_tag:-a+primary_tag:-b+featured:true parses without featured:true, on the released packages: expandFilters replaces the $and that combineNeFilters left beside its $nin.

#306, #307 and #308 change the same file and will need a rebase after this, or this after them.

Decisions

  • A condition one bracket level away from its relation stays at its own level. (tags.slug:classic+featured:true)+posts_tags.sort_order:1 means "a featured classic post that has some tag second", not "classic is its second tag". A bracketed group already scopes relation conditions this way: (tags.slug:a+featured:true)+tags.visibility:public is two tag subqueries, "has tag a" and "has a public tag". The alternative, pushing the condition into the group's subqueries or flattening nested $and before grouping, would change the SQL of filters that work today.
  • On its own, a negated condition means "no such join row", as a negated condition on any relation does: posts_tags.sort_order:-0 matches the posts with no tag first, as tags.slug:-a matches the posts without tag a. -null follows the same rule, as label:-null does, which Ghost's members filter tests pin as "no label at all". A negated and a positive condition on one join table are two subqueries, as on a relation. The alternative, rejecting a join table condition that has no relation beside it, would make an $and refuse what an $or already builds.
  • An aggregate that aliases its table (tableNameAs) doesn't take a condition that names the real table, as before. Its config refers to its tables by alias. The condition now becomes a subquery of its own instead of being dropped. The alternative is to map the real name to the alias inside the aggregate subquery.
  • The subquery is built through the relation whose join table it is, the first in the config when several share a table, as processStatement already resolves it. It uses that relation's join type, so through an inner-joined relation a join row whose related row is gone doesn't match. Ghost's join tables, except roles_users, reference their related tables with foreign keys, so they have no such rows.

Validation

There is no review site: this is a library change. Run in this repository:

  1. pnpm --filter @tryghost/mongo-knex exec mocha ./test/integration/relations.test.js --exit passes on this branch. With main's lib/convertor.js, 23 of the 26 tests under "A condition on a joining table's column" fail. The 3 that pass pin behaviour that doesn't change: another relation through the same join table, an aggregate that joins the join table, and a condition beside its relation when the queried table is the join table.
  2. pnpm --filter @tryghost/mongo-knex test passes: unit, integration on SQLite, and lint.
  3. pnpm --filter @tryghost/nql test passes. nql uses this package through the workspace link, and its two new tests fail with main's convertor.
  4. Not run locally: the integration tests on MySQL, because the local MySQL is shared with other checkouts. CI runs them on MySQL 8.

I also mutated the routing (readsTable and the two filters in groupRelationStatements) 23 ways, such as an aggregate ignoring tableNameAs, a one-to-one relation reading every table, any relation beside taking the condition, and every group getting every condition. Each one fails at least one test, except removing the r.joinTable guard, which can't change a result: a condition that isn't on a join table never matches readsTable.

Testing

The integration tests under "A condition on a joining table's column" run against the database and check the rows returned:

  • On its own: alone and beside a column; negated, with $in, $nin and not null; a string value that is bound rather than read as a column; a regex; two conditions on one join table, which must hold on the same join row; and a negated condition beside a positive one, which is a subquery of its own.
  • Beside a relation: a group that holds its relation; a many-to-many relation with another join table; a one-to-one relation; an aggregate of another table; an aggregate that names its table by an alias; an aggregate that joins the join table, plain and aliased; another relation through the same join table; and its own relation when another relation has its own join table condition.
  • In a group: a group of only join table conditions inside an $or, and negated groups, alone, beside a column and beside a relation with another join table.
  • Ghost's shapes: a query of the join table itself, as Ghost's event models are built, and a relation that left-joins its related table, as MemberCreatedEvent's does.

In nql, two tests on members tables run -(members_labels.label_id:2) and -(members_labels.label_id:1+status:free) from the filter string to the members returned, both of which return more members than before. The unit test that was skipped because a join table condition on its own "doesn't work" now asserts its SQL.

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0262f534-f9cf-4dc2-ae1b-55409b7caa7b
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@codecov-commenter

codecov-commenter commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.10345% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.54%. Comparing base (e0689bd) to head (3a4ccc1).

Files with missing lines Patch % Lines
packages/mongo-knex/lib/convertor.js 93.10% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #315      +/-   ##
==========================================
- Coverage   85.56%   85.54%   -0.03%     
==========================================
  Files           9        9              
  Lines        2418     2421       +3     
  Branches      510      513       +3     
==========================================
+ Hits         2069     2071       +2     
- Misses        343      344       +1     
  Partials        6        6              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@rob-ghost
rob-ghost marked this pull request as ready for review November 27, 2026 01:35
ref https://linear.app/ghost/issue/DYA-308

In an $and, mongo-knex kept a condition on a join table's column, such as {'posts_tags.sort_order': 0}, out of the conditions it groups into relation subqueries, and added it to the join of every relation subquery built beside it. When no condition on a relation sat beside it, nothing took it and the query ran without it, so it matched more rows than the filter said: the condition on its own matched every post, and so did a group of tag conditions with the join table condition outside the group. In Ghost, email_recipients.opened_at:>=0 on the members list returned every member, and members bulk edit and bulk delete select their members with the same filters. Inside a $nor the condition was dropped too, and the query then matched no rows at all. Beside a condition on a different relation, it was added to that relation's subquery, which doesn't join its table, so the query failed. A condition on a join table's column now restricts only the subqueries beside it whose relation reads that table, which the aggregate relation already checked for itself. With none beside it, it is built as a condition on its own relation, the way an $or already builds it: it matches the posts that have a tag at that sort order, and a negated one matches the posts that have no tag at it, as any negated condition on a relation does. A condition beside its own relation builds the same SQL as before, and that is how Ghost's primary_tag, primary_author and opened_emails.post_id use one.
@rob-ghost
rob-ghost force-pushed the fix/dya-308-join-table-conditions branch from 9f91654 to 3a4ccc1 Compare November 30, 2026 10:11
@rob-ghost rob-ghost closed this Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants