Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 75 additions & 76 deletions src/components/databrowser/components/ui-query-builder/query-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,48 +189,75 @@ const parseMultiFieldObject = (
let boost: number | undefined

for (const [key, value] of Object.entries(obj)) {
if (key === "$boost") {
boost = value as number
} else if (key === "$and" || key === "$or") {
const nestedOp: GroupOperator = key === "$and" ? "and" : "or"
const nestedGroup = parseGroup(value, nestedOp)
if (nestedGroup) children.push(nestedGroup)
} else if (!isOperatorKey(key)) {
children.push(parseFieldCondition(key, value))
switch (key) {
case "$boost": {
boost = value as number
break
}
case "$and":
case "$or": {
const nestedGroup = parseGroup(value, key === "$and" ? "and" : "or")
if (nestedGroup) children.push(nestedGroup)
break
}
case "$mustNot": {
const negated = parseNegatedChildren(value)
// In an OR, all the exclusions together are one alternative
if (operator === "or" && negated.length > 1) {
children.push({
id: generateId(),
type: "group",
groupOperator: "and",
children: negated,
})
} else {
children.push(...negated)
}
break
}
default: {
if (!isOperatorKey(key)) children.push(parseFieldCondition(key, value))
}
}
}

return { id: generateId(), type: "group", groupOperator: operator, children, boost }
}

/** Parse $mustNot wrapper, returns node with not=true */
const parseMustNot = (notValue: unknown): QueryNode | null => {
if (Array.isArray(notValue)) {
if (notValue.length === 0) return null

if (notValue.length === 1) {
const innerNode = objectToQueryNode(notValue[0] as Record<string, unknown>)
if (innerNode) innerNode.not = true
return innerNode
}
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value)

// Multiple elements: OR semantics within $mustNot
const children = notValue
.map((child) => objectToQueryNode(child as Record<string, unknown>))
.filter((n): n is QueryNode => n !== null)
/** Negate a node, a node that is already negated is wrapped so both negations are kept */
const negate = (node: QueryNode): QueryNode =>
node.not
? { id: generateId(), type: "group", groupOperator: "and", children: [node], not: true }
: { ...node, not: true }

if (children.length === 0) return null
return { id: generateId(), type: "group", groupOperator: "or", children, not: true }
}
/**
* The nodes a $mustNot value excludes. Each array item is excluded on its own, and so is
* each key of an object form: { a: 1, b: 2 } excludes a and b, not (a and b).
*/
const parseExcludedNodes = (mustNotValue: unknown): QueryNode[] => {
const items = Array.isArray(mustNotValue)
? mustNotValue.filter((item) => isPlainObject(item))
: isPlainObject(mustNotValue)
? Object.entries(mustNotValue)
.filter(([key]) => key !== "$boost")
.map(([key, value]) => ({ [key]: value }))
: []
return items.map((item) => objectToQueryNode(item)).filter((n): n is QueryNode => n !== null)
}

// Object form: { $mustNot: { field: value } }
if (typeof notValue === "object" && notValue !== null) {
const innerNode = objectToQueryNode(notValue as Record<string, unknown>)
if (innerNode) innerNode.not = true
return innerNode
}
/** The nodes a $mustNot value excludes, as negated children of an AND */
const parseNegatedChildren = (mustNotValue: unknown): QueryNode[] =>
parseExcludedNodes(mustNotValue).map((node) => negate(node))

return null
/** Parse a standalone $mustNot: excluding a and b is not (a or b) */
const parseMustNot = (notValue: unknown): QueryNode | null => {
const excluded = parseExcludedNodes(notValue)
if (excluded.length === 0) return null
if (excluded.length === 1) return negate(excluded[0])
return { id: generateId(), type: "group", groupOperator: "or", children: excluded, not: true }
}

/** Parse $and/$or group */
Expand Down Expand Up @@ -262,25 +289,6 @@ const parseGroup = (
return null
}

/** Add $mustNot entries as negated children to a group */
const addMustNotChildren = (group: QueryNode & { type: "group" }, mustNotValue: unknown): void => {
if (Array.isArray(mustNotValue)) {
for (const item of mustNotValue) {
const child = objectToQueryNode(item as Record<string, unknown>)
if (child) {
child.not = true
group.children.push(child)
}
}
} else if (typeof mustNotValue === "object" && mustNotValue !== null) {
const child = objectToQueryNode(mustNotValue as Record<string, unknown>)
if (child) {
child.not = true
group.children.push(child)
}
}
}

/** Parse a raw query object into a QueryNode */
const objectToQueryNode = (obj: Record<string, unknown>): QueryNode | null => {
if (!obj || typeof obj !== "object") return null
Expand All @@ -297,46 +305,37 @@ const objectToQueryNode = (obj: Record<string, unknown>): QueryNode | null => {
const operator: GroupOperator = "$and" in obj ? "and" : "or"
const groupValue = obj["$and"] ?? obj["$or"]
const boost = "$boost" in obj ? (obj.$boost as number) : undefined
const groupNode = parseGroup(
groupValue,
operator,
nonOperatorKeys.length === 0 ? boost : undefined
)
const negatedChildren = hasMustNot ? parseNegatedChildren(obj.$mustNot) : []

if (groupNode && groupNode.type === "group" && hasMustNot) {
addMustNotChildren(groupNode, obj.$mustNot)
}
// An $and takes the sibling $mustNot as negated children. The server ANDs an $or with
// its siblings ({ $or: a, $mustNot: b } is a and not b), so then it is wrapped in an AND.
const isLoneGroup =
nonOperatorKeys.length === 0 && (operator === "and" || negatedChildren.length === 0)
const groupNode = parseGroup(groupValue, operator, isLoneGroup ? boost : undefined)
if (!groupNode || groupNode.type !== "group") return groupNode

// No sibling field conditions → return group directly
if (!groupNode || nonOperatorKeys.length === 0) {
if (isLoneGroup) {
groupNode.children.push(...negatedChildren)
return groupNode
}

// Sibling field conditions: { field: value, $and: [...] } → wrap in AND
// Sibling field conditions: { field: value, $and: [...] } → wrap in AND.
// An $or without conditions ([{}]) matches every document, so it adds nothing.
const fieldChildren = nonOperatorKeys.map((key) => parseFieldCondition(key, obj[key]))
const group: QueryNode & { type: "group" } = {
const isMatchAll = groupNode.groupOperator === "or" && groupNode.children.length === 0
return {
id: generateId(),
type: "group",
groupOperator: "and",
children: [...fieldChildren, groupNode],
children: [...fieldChildren, ...(isMatchAll ? [] : [groupNode]), ...negatedChildren],
boost,
}

if (hasMustNot) {
addMustNotChildren(group, obj.$mustNot)
}

return group
}

// Handle $mustNot (possibly with field conditions at the same level)
if (hasMustNot) {
if (nonOperatorKeys.length > 0) {
// Field conditions + $mustNot → AND group with negated children
const group = parseMultiFieldObject(obj, "and")
addMustNotChildren(group, obj.$mustNot)
return group
}
// Field conditions + $mustNot → AND group with negated children
if (nonOperatorKeys.length > 0) return parseMultiFieldObject(obj, "and")
// Standalone $mustNot
return parseMustNot(obj.$mustNot)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { parseJSObjectLiteral } from "@/lib/utils"

import { parseQueryString } from "./query-parser"
import { stringifyQueryState } from "./query-stringify"
import type { QueryNode } from "./types"

const roundtrip = (input: Record<string, unknown>) => {
const state = parseQueryString(JSON.stringify(input))
Expand Down Expand Up @@ -204,14 +205,64 @@ const queries: (Record<string, unknown> | [Record<string, unknown>, Record<strin

// --- $mustNot ---

// $and stays with mustNot
{ $and: {}, $mustNot: { name: "foo" } },
{ $or: {}, $mustNot: { name: "foo" } },
// must not flattened
// only negated children: [{}] matches all documents for $mustNot to exclude from
[
{ $and: {}, $mustNot: [{ name: "foo" }] },
{ $and: {}, $mustNot: { name: "foo" } },
{ $and: [{}], $mustNot: { name: "foo" } },
],
{ $and: [{}], $mustNot: { name: "foo" } },
// next to $or the server ANDs $mustNot, so it is read (and written back) as an AND
[
{ $or: [{}], $mustNot: { name: "foo" } },
{ $and: [{}], $mustNot: { name: "foo" } },
],
[
{ $or: { name: "foo" }, $mustNot: { age: 18 } },
{ $and: [{ $or: { name: "foo" } }], $mustNot: { age: 18 } },
],
[
{ $or: [{ name: "foo" }, { title: "bar" }], $mustNot: { age: 18 }, $boost: 2 },
{ $and: [{ $or: { name: "foo", title: "bar" } }], $mustNot: { age: 18 }, $boost: 2 },
],
// negated children of an OR are alternatives inside the $or array
{ $or: [{ name: "foo" }, { $mustNot: { age: 18 } }] },
{ $or: [{ $mustNot: { name: "foo" } }, { $mustNot: { age: 18 } }] },
{ $or: [{ $mustNot: { name: "foo" } }], $boost: 2 },
[
{ $or: { name: "foo", $mustNot: { age: 18 } } },
{ $or: [{ name: "foo" }, { $mustNot: { age: 18 } }] },
],
// in an OR object, all exclusions together are one alternative
[
{ $or: { name: "foo", $mustNot: [{ age: 18 }, { title: "bar" }] } },
{ $or: [{ name: "foo" }, { $and: [{}], $mustNot: [{ age: 18 }, { title: "bar" }] }] },
],
[
{ $and: { name: "foo", $mustNot: { age: 18 } } },
{ $and: { name: "foo" }, $mustNot: { age: 18 } },
],
// each key of a $mustNot object is excluded on its own
[{ $mustNot: { name: "foo", age: 18 } }, { $mustNot: [{ name: "foo" }, { age: 18 }] }],
[
{ name: "foo", $mustNot: { age: 18, title: "bar" } },
{ $and: { name: "foo" }, $mustNot: [{ age: 18 }, { title: "bar" }] },
],
// a double negation keeps both negations
[
{ $mustNot: [{ $mustNot: { name: "foo" } }] },
{ $mustNot: [{ $and: [{}], $mustNot: { name: "foo" } }] },
],
// fields, $and and $mustNot siblings: each $mustNot item is excluded once
[
{ name: "foo", $and: [{ age: 18 }, { title: "bar" }], $mustNot: { status: "x" } },
{ $and: [{ name: "foo" }, { age: 18, title: "bar" }], $mustNot: { status: "x" } },
],
// must not flattened
[
{ $and: [{}], $mustNot: [{ name: "foo" }] },
{ $and: [{}], $mustNot: { name: "foo" } },
],
{ $or: [{ name: "foo" }, { $and: [{}], $mustNot: { age: 18 } }] },
// both flattened
[
{ $and: [{ name: "foo" }], $mustNot: [{ age: 18 }] },
Expand Down Expand Up @@ -239,3 +290,77 @@ describe("query roundtrip: parse → stringify", () => {
})
}
})

const cond = (field: string, value: string | number, not?: boolean): QueryNode => ({
id: field,
type: "condition",
not,
condition: { field, operator: "eq", value },
})
const group = (groupOperator: "and" | "or", children: QueryNode[], boost?: number): QueryNode => ({
id: groupOperator,
type: "group",
groupOperator,
children,
boost,
})

// Builder states that the parser never produces from the expected output directly
const builderStates: [QueryNode, Record<string, unknown>][] = [
[
group("or", [cond("a", "1"), group("and", [cond("b", "2", true)])]),
{ $or: [{ a: { $eq: "1" } }, { $and: [{}], $mustNot: { b: { $eq: "2" } } }] },
],

// Negated children of an OR are alternatives inside the $or array, not a sibling $mustNot
// (which the server ANDs with the $or)
[
group("or", [cond("a", "1", true), cond("b", "2", true)]),
{ $or: [{ $mustNot: { a: { $eq: "1" } } }, { $mustNot: { b: { $eq: "2" } } }] },
],
[
group("or", [cond("a", "1"), cond("b", "2", true), cond("c", "3")]),
{ $or: [{ a: { $eq: "1" } }, { $mustNot: { b: { $eq: "2" } } }, { c: { $eq: "3" } }] },
],
[
group("or", [cond("a", "1"), { ...group("and", [cond("b", "2"), cond("c", "3")]), not: true }]),
{
$or: [{ a: { $eq: "1" } }, { $mustNot: { $and: { b: { $eq: "2" }, c: { $eq: "3" } } } }],
},
],
[group("or", [cond("a", "1", true)], 2), { $or: [{ $mustNot: { a: { $eq: "1" } } }], $boost: 2 }],
[
{ ...group("or", [cond("a", "1"), cond("b", "2", true)]), not: true },
{ $mustNot: [{ $or: [{ a: { $eq: "1" } }, { $mustNot: { b: { $eq: "2" } } }] }] },
],

// Negated groups with more than one key stay array items, since the server excludes
// each key of a $mustNot object separately
[
group("and", [cond("a", "1"), { ...group("and", [cond("b", "2", true)]), not: true }]),
{
$and: { a: { $eq: "1" } },
$mustNot: [{ $and: [{}], $mustNot: { b: { $eq: "2" } } }],
},
],
[
group("and", [
cond("a", "1"),
{ ...group("and", [cond("b", "2"), cond("c", "3", true)]), not: true },
]),
{
$and: { a: { $eq: "1" } },
$mustNot: [{ $and: { b: { $eq: "2" } }, $mustNot: { c: { $eq: "3" } } }],
},
],
]

describe("builder → stringify → parse → stringify is stable", () => {
for (const [root, expected] of builderStates) {
test(JSON.stringify(expected), () => {
const str = stringifyQueryState({ root })
expect(parseJSObjectLiteral<Record<string, unknown>>(str)).toEqual(expected)
expect(stringifyQueryState(parseQueryString(str)!)).toEqual(str)
})
}
})
Loading
Loading