Skip to content

fix(query): DSL, full-text, advanced queries and query functions - #13871

Open
yuxi-liu-wired wants to merge 12 commits into
logseq:masterfrom
yuxi-liu-wired:fix/query-combined
Open

yuxi-liu-wired wants to merge 12 commits into
logseq:masterfrom
yuxi-liu-wired:fix/query-combined

Conversation

@yuxi-liu-wired

@yuxi-liu-wired yuxi-liu-wired commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

153
ines the PRs of this theme, to keep the number of open PRs down; the commits are unchanged. CI's unit suite passes on the combined branch.

fix(query): quotes, backslashes and [[...]] in titles and queries; malformed queries get a query error (was #13871)

Query fixes, combined from #13617 and #13863 (closed in favour of this one). Each section below is the original description; the commits are unchanged.

fix(query): a ", \ or [[...]] in a title no longer breaks the query; a malformed query gets a query error (was #13617)

Fixes logseq/db-test#1374.

A ", \ or [[...]] in a page or tag title

A tag Project, a query {{query (tags [[Project]])}}, then the tag renamed to Project" on its page. The query, never edited, shows "Query error" with (tags [[Project"]]), and the worker logs Unmatched delimiter ].. A title with a \ gives Unsupported escape character, one with "#... gives No reader function for tag, and one with a [[...]] inside, such as Project[[Gremlin Garden]], is cut at the first ]].

pre-transform in deps/db/src/logseq/db/frontend/query_dsl.cljs turns each [[page]] of the query into an EDN string, "[[page]]":

  • It did not escape the title, so a " in the title ended the string early and a \ started an escape. The title is now escaped (\ and ") before it is quoted.
  • It found refs with \[\[(.*?)\]\], which stops at the first ]]. Refs are now found by a scan that counts [[ / ]] pairs, so a nested pair stays inside the title; strings in the query are still copied through untouched, escapes included.
  • A later step, which protects # inside strings, matched strings with "[^"]+"; it now skips escaped quotes.

The test tags-query-with-a-quote-or-backslash-in-the-tag-title in src/test/frontend/db/query_dsl_test.cljs covers this: 4 tags renamed to Project", back\slash, say "#hi" and Project[[Gremlin Garden]], each found by (tags [[...]]). It also checks the pre-transform output for an escaped title, for a nested pair, and for a [[...]] inside a string, which is left as it was. On master it fails with the reader errors above; with the change it passes.

A malformed query gets a query error

A simple query with a malformed form failed deep inside build-query or datascript with a raw error such as alpha is not ISeqable, Insufficient bindings or All clauses in 'or' must use same set of free vars. parse now checks the read form against a malli schema of the query grammar before translating it, and a bad query throws one ex-info built from the malli explanation:

  • Invalid query: alpha is not a query form
  • Invalid query: between needs two dates, or created-at or updated-at and one or two dates

query-operators in frontend.worker.query-dsl is now the one list of operators: each entry holds the operator's argument schema, its error message, its build-* fn, and whether it queries blocks. build-query dispatches through the table instead of a cond branch per operator, and query-schema is built from it. Operators: and, or, not, task/todo, priority, tags, page, property, private-property, between, sample. A string is a [[page]] ref or a full-text search.

Behavior changes, for review:

  • Operators that build-query never translated in DB graphs (page-tags, page-ref, page-property, namespace, sort-by, full-text-search, all-page-tags) returned nothing silently. They are now rejected as "not a query form".
  • Raw datalog clauses ([?b ...], [(pred ...)], ((...))) are not part of the grammar.
  • pre-transform treats an empty "" as a string. Before, a #tag after one was left unexpanded and the reader threw No reader function for tag ....

Tests: invalid-queries runs the reported queries (alpha, TODO, (and todo [[A]]), [(or)], (not [((page-tags #nope))]), (between [[A]] B), (and (and 3.14) "x"), (or ((task)) "x"), (between (page "") (sample (priority #nope "alpha")))) plus (sort-by created-at), and checks each message; pre-transform-test has a case for "" followed by a tag. frontend.db.query-dsl-test: 27 tests, 125 assertions, 0 failures. The namespaces that run DSL queries (query-api, datalog, db-core, render-resource, db-worker, logseq.api.db) pass. clj-kondo and the large-vars lint are clean.

fix(query): a plain-text query with a backslash searches instead of showing a query error (was #13863)

What the user sees

A plain-text query such as {{query foo\cbar}} (any text with a backslash escape the EDN reader rejects, e.g. \c, or a trailing \) shows a "Query error:" box with Unsupported escape character: \c. instead of running a full-text search for foo\cbar. Plain text without a backslash runs the full-text search as expected.

Cause

The query builder's sanitize-q wraps plain text in double quotes, so foo\cbar reaches the worker as "foo\cbar", which marks it as a full-text search. The worker's quoted-query-text reads that string with safe-read-string, which returns nil when the reader rejects the escape. With nil, execute-query-spec treats the text as a DSL query and passes it to query-dsl/execute-query, whose cljs.reader/read-string throws the reader exception. The worker turns that into a per-resource query error, and the query's error boundary shows it.

Change

quoted-query-text in frontend.worker.handler.render-resource.query now falls back to the raw text between the quotes when the reader cannot read the quoted string, so the full-text search runs on the text as typed. Strings the reader can read are unchanged, and malformed DSL queries such as ((and) still report their query error through the existing error boundary.

Tests

quoted-full-text-query-with-unreadable-escape-searches-raw-text-test in src/test/frontend/worker/handler/render_resource_test.cljs renders a :query resource for "foo\cbar" with a stubbed search-blocks. It checks that the resource has no error, that the search received foo\cbar, and that the matching block is returned; it also checks that ((and) still reports a query error. The test fails without the change (the resource carries the Unsupported escape character error and no search runs) and passes with it.


Devin Review

fix(query): a {{function}} child keeps its parent query's result after a re-render (was #13879)

Fixes #12949.

Each render of a block made a new :query-result atom when its config had none (build-config in components/block.cljs). The query component fills the atom of the parent's latest render, while a {{function ...}} child can still hold the atom from an earlier render; that one stays nil and the child falls back to the raw yellow macro text. It happens mostly after a reload, when the query block renders again before its rows arrive, which matches the report (works when first created, fails after a reload, scrolling "rerolls" it).

The block container now keeps one atom per mounted block (hooks/use-memo) and passes it to build-config, so every render of the query block, and every child, shares it.

Test: frontend.components.block.macros-test/function-macro-child-sees-query-result-after-parent-rerender: a child holding the first render's config sees the rows published after the second render. It fails without the change.


Devin Review

fix(query): advanced queries skip recycled nodes, text property node values match (was #13894)

Fixes logseq/db-test#1208 and logseq/db-test#1085.

Two independent query fixes on branch fix/dbtest-query, one commit each (a PR can take them together or split them by commit). A third, logseq/db-test#1383 (:current-page in a zoomed block), is dropped: master fixed it in #13558 (6fe95de), whose page-render-config-uses-host-page-title-when-zoomed-test pins the same behaviour.

logseq/db-test#1085: a text property with nodes could not be queried for those nodes

What the user sees

A text property with multiple values can hold plain text and nodes ([[x]]). (property note [[x]]) found the blocks whose value is the plain text x but not the ones where x is a node.

Cause

A node in a text property is a value block titled [[<uuid of x>]]. The query strips [[x]] to the name x, and the ref->val rule (deps/db/src/logseq/db/frontend/rules.cljc) compares it with the value block's :block/title, which only equals x for plain text.

Change

ref->val gets a third branch: a value block whose whole title is a reference to a node ([[<uuid>]] in :block/refs) has that node's title as its value, as for a :node property. The change does not touch query_dsl.cljs, so it does not interact with #13871. The extra branch costs one :block/refs lookup per property value.

Tests

property-default-type-node-value-queries in frontend.db.query-dsl-test: a text property with a plain x, a node x and a plain y. (property note [[x]]) and (property note x) both find the plain value and the node; (property note [[y]]) finds only the y block. Fails without the change (the node block is missing), passes with it.

logseq/db-test#1208: recycled pages and blocks still affected advanced queries

What the user sees

After deleting a page or block (moved to the Recycle page), advanced queries still counted it inside joins, not clauses and aggregates until it was permanently deleted. For example, with the issue's "leaf streams" query, deleting the only child of a stream did not make the parent a leaf; the child was hidden from the output, so the parent was simply missing.

Cause

Recycling keeps every attribute of the entity (including user node property values), puts :logseq.property/deleted-at on the root only, and its descendants carry nothing. execute-custom-query (src/main/frontend/worker/handler/query.cljs) ran the query on the full db and only dropped recycled rows from the final output.

Change

execute-custom-query runs the query on a d/filtered db with no datom of a recycled root or its descendants and none that points to one (only for ref attributes: the schema's and the ref-typed properties), as if they had been permanently deleted. The recycled ids are computed once per query from the deleted-at index and the :block/parent index; when nothing is recycled the db is used as is, so graphs without a Recycle bin pay nothing. The query inputs (:current-page, :today, ...) are still resolved on the unfiltered db.
Invalidation needs no change: the watch keys of a datalog query already include :logseq.property/deleted-at and :block/parent (query-watch-keys in render_resource/query.cljs), and queries with opaque rules watch the whole graph.
This covers the advanced (datalog) queries, which is what the issue reports (:thread-api/query-custom and the rendered query blocks). The simple DSL queries (query-dsl/execute-query) are unchanged. Plugin calls to :thread-api/query-custom also no longer see recycled entities.

Tests

New frontend.worker.handler.query-test:

  • custom-query-ignores-recycled-page-test is the issue's reproduction: a recycled child page no longer makes its parent a non-leaf, and a restored child counts again.
  • custom-query-ignores-descendants-of-recycled-block-test: the reference sits on a nested block under a recycled block, which carries no deleted-at itself.
    Both fail without the change (#{"child"} / #{} instead of #{"parent"}), pass with it.

Validation

  • Build with the three source fixes reverted and the tests kept: query-test 2 failures, query-dsl-test 2 failures, page-first-paint-test 1 failure (the assertions above). With the fixes: the three namespaces pass (2 tests/8 assertions, 26/112, 6/28).
  • Whole unit suite (pnpm cljs:run-test) passes with the fixes. deps/db suite (pnpm test, nbb) passes: 200 tests, 763 assertions.
  • clj-kondo on the changed files: 0 errors, 0 warnings. typos clean.

Recycled roots are read by attribute (CLI graphs)

The recycled filter read its roots with (d/datoms db :avet :logseq.property/deleted-at). That attribute is not indexed in every graph; in the CLI's the read throws "Attribute :logseq.property/deleted-at should be marked as :db/index true", so every advanced query failed there. Master's shared query parity suite (pnpm --dir cli test:query-integration, added on master 11-11) caught it. The roots are now read with :aevt, which needs no index: the parity suite passes 40/40, and frontend.worker.handler.query-test and frontend.db.query-dsl-test (33 tests) pass.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 potential issues.

Devin Review

Comment thread src/main/frontend/worker/query_dsl.cljs Outdated

(def ^:private name-like [:or :string :symbol :keyword])

(def ^:private page-name [:or [:string {:min 1}] :symbol :keyword :int])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Decimal page titles break existing queries

For a page titled 3.14, (page 3.14) now fails query-schema validation. build-page previously converted the number to a page name, so the query no longer returns its blocks.

Suggested change
(def ^:private page-name [:or [:string {:min 1}] :symbol :keyword :int])
(def ^:private page-name [:or [:string {:min 1}] :symbol :keyword :int :double])

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +125 to +130
(let [value (or (common-util/safe-read-string {:log-error? false}
query-string)
;; Plain text quoted by the query builder can hold
;; escapes the EDN reader rejects, e.g. `\c`. Search the
;; text between the quotes as typed.
(subs query-string 1 (dec (count query-string))))]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Malformed quoted queries become searches

When EDN parsing fails inside outer quotes, quoted-query-text searches the raw contents. An explicitly entered malformed quoted query now yields search results instead of a parse error; the worker cannot distinguish it from builder-wrapped text.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@yuxi-liu-wired

Copy link
Copy Markdown
Contributor Author
  • (page 3.14): agreed, fixed in the latest commit (a double is a page name; page-query-with-a-number-title covers 3.14 and 42).
  • Malformed quoted queries: by the time a query reaches the worker, a quoted string is what sanitize-q makes of plain text, and a reader failure inside it means the text holds a backslash escape the reader rejects (foo\cbar). Searching that text is the intended reading; a malformed query written as a form (((and)) still gets its query error, and the test checks both.

@yuxi-liu-wired yuxi-liu-wired changed the title fix(query): quotes, backslashes and [[...]] in titles and queries; malformed queries get a query error fix(query): DSL, full-text, advanced queries and query functions Oct 28, 2026
@yuxi-liu-wired
yuxi-liu-wired force-pushed the fix/query-combined branch 3 times, most recently from 4143a90 to 471a488 Compare November 3, 2026 12:01
@yuxi-liu-wired
yuxi-liu-wired force-pushed the fix/query-combined branch 6 times, most recently from 6a7fd92 to 90b1291 Compare November 18, 2026 13:59
@yuxi-liu-wired
yuxi-liu-wired force-pushed the fix/query-combined branch 2 times, most recently from 111686a to a150413 Compare November 18, 2026 14:38
pre-transform quoted [[title]] as an EDN string without escaping it, so
a tag renamed to Project" broke every (tags [[...]]) query on it with a
reader error (db-test logseq#1374). The title is now escaped; the string match
that protects # inside strings skips escaped quotes.
The page-ref match \[\[(.*?)\]\] stopped at the first ]], so a tag
renamed to Project[[Gremlin Garden]] broke its queries (db-test logseq#1374).
Refs are now found by a scan that counts [[ / ]] pairs, outside strings.
A malformed simple query failed deep in build-query or datascript with a
raw error (alpha is not ISeqable, Insufficient bindings, ...). parse now
validates the read form against a malli schema of the query grammar and
throws one "Invalid query: ..." error naming the bad form or operator.

Raw datalog clauses are no longer part of the simple query grammar, so
build-query drops its datalog-clause? branch. pre-transform now matches
an empty "" as a string, so a # after one is read as a tag.
…table

query-operators now holds each operator's argument schema, error
message, build fn and whether it queries blocks. build-query dispatches
through it instead of a cond per operator, and query-schema is built
from it, so the operators are listed once. The file-graph operators
that build-query never translated in DB graphs (page-tags, page-ref,
page-property, namespace, sort-by, full-text-search, all-page-tags) are
now rejected instead of silently returning nothing.
A plain-text query such as {{query foo\cbar}} showed a "Query error:"
box with "Unsupported escape character: \c." instead of running a
full-text search for foo\cbar.

The query builder's sanitize-q wraps plain text in double quotes to mark
it as a full-text search. The worker's quoted-query-text read that
string with safe-read-string, which returns nil when the EDN reader
rejects an escape such as \c. The query then fell through to the DSL
parser, whose reader threw, and the worker reported a query error.

quoted-query-text now falls back to the raw text between the quotes when
the reader cannot read the quoted string. Readable strings are
unchanged, and malformed DSL queries such as ((and) still report their
query error.

Test: quoted-full-text-query-with-unreadable-escape-searches-raw-text-test
checks that a "foo\cbar" query resource has no error, searches for
foo\cbar and returns the matching block, and that ((and) still reports
a query error. It fails without the change and passes with it.
The query schema took a page name as a string, symbol, keyword or
integer, so `(page 3.14)` (the reader gives a double) failed validation
where build-page used to turn the number into the page's name. A double
is a page name too now.

page-query-with-a-number-title: `(page 3.14)` and `(page 42)` find the
blocks of pages titled "3.14" and "42"; the first failed before.
…lt after a re-render

Each render of a block made a new `:query-result` atom when the incoming config had none. The query component filled the atom of the parent's latest render, while a `{{function ...}}` child still held the atom from an earlier render, so it stayed nil and fell back to the raw yellow macro text. It happened mostly after a reload, when the query block renders again before its rows arrive.

The block container now keeps one atom per mounted block and passes it to `build-config`.

Fixes logseq#12949
…hout a per-call fallback

Its only caller, the block container, always passes the atom it keeps for the mounted block; a fresh atom per call was the behaviour that lost the result.
In a DB graph, a text property can hold both plain text and nodes (typing [[x]] in the value). A query such as (property note [[x]]) found only the plain-text values and missed the nodes.

A node in a text property is a value block titled [[<uuid of x>]], while the query compares the value with the plain name "x", which only equals the title of a plain-text value block. The ref->val rule now also accepts a value block whose whole title is a reference to a node, with that node's title as the value, as a :node property already does.

The new test in query_dsl_test builds a text property with a plain value, a node value and another plain value, and checks that both query forms (page ref and text) find the plain value and the node, and that an unrelated value still matches only its own text.

Fixes logseq/db-test#1085
After deleting a page or block, an advanced query still counted it inside joins, not clauses and aggregates until the item was permanently deleted from the Recycle bin. For example a "leaf" query (not [?child :streamOf ?parent]) did not return a parent whose only child was recycled. Only the final result was filtered, and so the recycled child just vanished from it.

Recycling keeps every attribute on the entity, adds :logseq.property/deleted-at to the root only, and the descendants of the root carry nothing. execute-custom-query ran the query on the full db. It now runs on a filtered db that has no datom of a recycled root or its descendants and none that points to one, as if they were permanently deleted. When nothing is recycled the db is used as is. The filtering needs no new invalidation: the watch keys of a query already include :logseq.property/deleted-at and :block/parent.

The new tests (frontend.worker.handler.query-test) recycle a page, and a block with a nested child that holds the reference, check that the parent becomes a leaf, and check that it stops being one once the page is restored.

Fixes logseq/db-test#1208
With recycled entities in the graph, every advanced query block of a page recomputed the recycled subtree and the reference attributes, although they all run on the same db snapshot.

The filtered db is now cached per db value in a WeakMap, as logseq.db.common.view does for its exclusion sets. A transaction gives a new db value, so the next query filters again, and the entry goes away with its snapshot.

The new test checks that two lookups on one snapshot return the same filtered db, that running a query does not replace it, and that a snapshot after a transaction is filtered again while the older one keeps its own.

Refs logseq/db-test#1208
… graph lacks

The recycled filter found recycled roots with an :avet read of
:logseq.property/deleted-at. That attribute is not indexed in every graph:
in the CLI's, the read throws "Attribute :logseq.property/deleted-at should
be marked as :db/index true", so every advanced query failed there (master's
shared query parity suite, `pnpm --dir cli test:query-integration`). The
roots are now read with :aevt, which needs no index.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

1 participant