UNPKG

@neo4j/cypher-builder

Version:

A programmatic API for building Cypher queries for Neo4j

106 lines (105 loc) 3.02 kB
"use strict"; /* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] */ Object.defineProperty(exports, "__esModule", { value: true }); exports.BooleanOp = void 0; exports.and = and; exports.not = not; exports.or = or; exports.xor = xor; const CypherASTNode_1 = require("../../CypherASTNode"); const filter_truthy_1 = require("../../utils/filter-truthy"); /** * @group Operators * @category Boolean */ class BooleanOp extends CypherASTNode_1.CypherASTNode { operator; /** @internal */ constructor(operator) { super(); this.operator = operator; } } exports.BooleanOp = BooleanOp; class BinaryOp extends BooleanOp { children; /** @internal */ constructor(operator, predicates) { super(operator); this.children = predicates; this.addChildren(...this.children); } /** * @internal */ getCypher(env) { const childrenStrs = this.children.map((c) => c.getCypher(env)).filter(Boolean); if (childrenStrs.length <= 1) { throw new Error(`Boolean operation ${this.operator} does not have predicates`); } const operatorStr = ` ${this.operator} `; return `(${childrenStrs.join(operatorStr)})`; } } class NotOp extends BooleanOp { child; constructor(child) { super("NOT"); this.child = child; this.addChildren(this.child); } /** * @internal */ getCypher(env) { const childStr = this.child.getCypher(env); // This check is just to avoid double parenthesis (e.g. "NOT ((a AND b))" ), both options are valid cypher if (this.child instanceof BinaryOp) { return `${this.operator} ${childStr}`; } return `${this.operator} (${childStr})`; } } function and(...ops) { const filteredPredicates = (0, filter_truthy_1.filterTruthy)(ops); if (filteredPredicates[0] && filteredPredicates[1]) { return new BinaryOp("AND", filteredPredicates); } return filteredPredicates[0]; } /** Generates an `NOT` operator before the given predicate * @see {@link https://neo4j.com/docs/cypher-manual/current/syntax/operators/#query-operators-boolean | Cypher Documentation} * @group Operators * @category Boolean * @example * ```ts * console.log("Test", Cypher.not( * Cypher.eq(new Cypher.Literal("Hi"), new Cypher.Literal("Hi")) * ); * ``` * Translates to * ```cypher * NOT "Hi" = "Hi" * ``` * */ function not(child) { return new NotOp(child); } function or(...ops) { const filteredPredicates = (0, filter_truthy_1.filterTruthy)(ops); if (filteredPredicates[0] && filteredPredicates[1]) { return new BinaryOp("OR", filteredPredicates); } return filteredPredicates[0]; } function xor(...ops) { const filteredPredicates = (0, filter_truthy_1.filterTruthy)(ops); if (filteredPredicates[0] && filteredPredicates[1]) { return new BinaryOp("XOR", filteredPredicates); } return filteredPredicates[0]; }