Repository navigation
Conversation
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
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
force-pushed
the
fix/dya-308-join-table-conditions
branch
from
November 30, 2026 10:11
9f91654 to
3a4ccc1
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:{'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$northe dropped condition leftNOT EXISTS (SELECT 1), which matches no rows at all.{$and: [{'authors.slug': 'sam'}, {'posts_tags.sort_order': 1}]}failed withno such column: posts_tags.sort_order, and so did the same beside a one-to-one relation.In Ghost,
email_recipients.opened_at:>=0on the members list returned every member, and besidestatus:paidevery paid member. Members bulk edit and bulk delete select their members with the same filters.posts_tags.sort_order:0on 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
$oralready 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.
readsTableis 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.What changes, for which filters
Exposure says who can send the filter:
primary_tag,opened_emails.post_id, the free-subscriber rewrite and the members filter builder.filter, including members bulk edit and bulk delete.filter, a theme's{{#get}}androutes.yaml. The Content API removesroles_userskeys, but notposts_tags.*orposts_authors.*.primary_tag:…andprimary_author:…in every form (negated, listed, combined, in a group),opened_emails.post_id:…,tag:a+posts_tags.sort_order:0posts_tags.sort_order:0, alone or beside columnsemail_recipients.opened_at:>=0,members_click_events.created_at:>'…',members_newsletters.created_at:>'…',members_labels.label_id:…, alone or besidestatus:paidroles_users.role_id:…on staffposts_tags.sort_order:-0tag:-ameans posts without tag aemail_recipients.opened_at:-nulllabel:-nullalready means "no label"-(posts_tags.sort_order:0),-(members_labels.label_id:x),-(email_recipients.opened_at:>=0)-(posts_tags.sort_order:0+featured:true)(posts_tags.sort_order:1+posts_authors.sort_order:1),status:draft(tags.slug:a+featured:true)+posts_tags.sort_order:1authors.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)count.active_stripe_customers:>0+email_recipients.opened_at:>=0tag:-a+tag:-b+posts_tags.sort_order:1tableNameAsbeside a condition on its real table nameFilters 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-knexto 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.subscribed, label, tier, newsletter andopened_emails.post_idforms, and post and staff filters. 1,191 are identical. The 16 that differ are all hand-written join table filters in the table above.primary_tagandprimary_authorfilters: identical.roles_userskeys are removed before the query is built.Release
This needs a minor of
@tryghost/mongo-knex(0.14.0), with@tryghost/nqlrepublished 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.nql0.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 installsnqlwithout 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 ofnql(...).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 minorbumps the packages and rewritesnql's range, as the last release did.After the release, in Ghost
Ghost bumps
@tryghost/mongo-knexin its catalog, the copy every model filter compiles with, and@tryghost/nqlwith it so the lockfile keeps one copy of mongo-knex. With the bump it adds e2e-api tests foremail_recipients.opened_at:>=0on the members list and in a members bulk edit, and forposts_tags.sort_order:1on the Admin posts list. Those tests fail until the bump, so nothing lands in Ghost first. The Content API change, whereposts_tags.*andposts_authors.*filters now apply, belongs in Ghost's release notes.Known faults this leaves
ONwith knex'sandOn, which reads the value as a column name.{$and: [{'tags.slug': 'a'}, {'posts_tags.created_at': {$gt: '2026-01-01'}}]}compiles toposts_tags.created_at > `2026-01-01`, so in Ghostclicked_links.post_id:abc+members_click_events.created_at:>'2026-01-01'fails. A null,$inor$regexvalue builds invalid SQL there, and on a relation withjoinType: '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'sONbeside a many-to-many relation, bound in an aggregate's inner query, and as a full comparison withapplyComparisonwhen it is on its own. Soposts_tags.sort_order:-0means "no tag first" on its own and "tagged a at another position" besidetag:a.{'tags.slug': 'classic', 'posts_tags.sort_order': 1}matches posts tagged classic that have some tag second, and its$andform matches posts with classic second. nql'scombineNeFilterswrites that shape: it puts the combined$ninbeside the$and, sotag:-a+tag:-b+posts_tags.sort_order:1means "neither tag, and some tag second", while the same filter with$neconditions in one$andmeans "neither tag is second".@tryghost/nql,primary_tag:-a+primary_tag:-b+featured:trueparses withoutfeatured:true, on the released packages:expandFiltersreplaces the$andthatcombineNeFiltersleft beside its$nin.#306, #307 and #308 change the same file and will need a rebase after this, or this after them.
Decisions
(tags.slug:classic+featured:true)+posts_tags.sort_order:1means "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:publicis two tag subqueries, "has tag a" and "has a public tag". The alternative, pushing the condition into the group's subqueries or flattening nested$andbefore grouping, would change the SQL of filters that work today.posts_tags.sort_order:-0matches the posts with no tag first, astags.slug:-amatches the posts without tag a.-nullfollows the same rule, aslabel:-nulldoes, 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$andrefuse what an$oralready builds.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.processStatementalready 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, exceptroles_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:
pnpm --filter @tryghost/mongo-knex exec mocha ./test/integration/relations.test.js --exitpasses on this branch. Withmain'slib/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.pnpm --filter @tryghost/mongo-knex testpasses: unit, integration on SQLite, and lint.pnpm --filter @tryghost/nql testpasses. nql uses this package through the workspace link, and its two new tests fail withmain's convertor.I also mutated the routing (
readsTableand the two filters ingroupRelationStatements) 23 ways, such as an aggregate ignoringtableNameAs, 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 ther.joinTableguard, which can't change a result: a condition that isn't on a join table never matchesreadsTable.Testing
The integration tests under "A condition on a joining table's column" run against the database and check the rows returned:
$in,$ninand 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.$or, and negated groups, alone, beside a column and beside a relation with another join table.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.