Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add object support for 'and' and 'or' functions. Closes #344 #583

Merged
merged 5 commits into from
Jul 14, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 15,7 @@ import {

import {
orWhere
} from './0030-or-where'
} from './0040-or-where'

<div style={{ marginBottom: '1em' }}>
<Playground code={orWhere} setupCode={exampleSetup} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 13,7 @@ import {

import {
conditionalWhereCalls
} from './0040-conditional-where-calls'
} from './0050-conditional-where-calls'

<div style={{ marginBottom: '1em' }}>
<Playground code={conditionalWhereCalls} setupCode={exampleSetup} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 14,7 @@ import {

import {
complexWhereClause
} from './0050-complex-where-clause'
} from './0060-complex-where-clause'

<div style={{ marginBottom: '1em' }}>
<Playground code={complexWhereClause} setupCode={exampleSetup} />
Expand Down
114 changes: 73 additions & 41 deletions src/expression/expression-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 29,15 @@ import { QueryExecutor } from '../query-executor/query-executor.js'
import {
BinaryOperatorExpression,
ComparisonOperatorExpression,
FilterObject,
OperandValueExpression,
OperandValueExpressionOrList,
parseFilterList,
parseFilterObject,
parseValueBinaryOperation,
parseValueBinaryOperationOrExpression,
} from '../parser/binary-operation-parser.js'
import { Expression } from './expression.js'
import { AndNode } from '../operation-node/and-node.js'
import { OrNode } from '../operation-node/or-node.js'
import { ParensNode } from '../operation-node/parens-node.js'
import { ExpressionWrapper } from './expression-wrapper.js'
import {
Expand All @@ -51,10 52,9 @@ import {
parseValueExpressionOrList,
} from '../parser/value-parser.js'
import { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js'
import { ValueNode } from '../operation-node/value-node.js'
import { CaseBuilder } from '../query-builder/case-builder.js'
import { CaseNode } from '../operation-node/case-node.js'
import { isUndefined } from '../util/object-utils.js'
import { isReadonlyArray, isUndefined } from '../util/object-utils.js'
import { JSONPathBuilder } from '../query-builder/json-path-builder.js'

export interface ExpressionBuilder<DB, TB extends keyof DB> {
Expand Down Expand Up @@ -577,15 577,42 @@ export interface ExpressionBuilder<DB, TB extends keyof DB> {
* ```sql
* select "person".*
* from "person"
* where "first_name" = $1
* and "first_name" = $2
* and "first_name" = $3
* where (
* "first_name" = $1
* and "first_name" = $2
* and "first_name" = $3
* )
* ```
*
* Optionally you can use the simpler object notation if you only need
* equality comparisons:
*
* ```ts
* db.selectFrom('person')
* .selectAll('person')
* .where((eb) => eb.and({
* first_name: 'Jennifer',
* last_name: 'Aniston'
* }))
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "person".*
* from "person"
* where (
* "first_name" = $1
* and "last_name" = $2
* )
* ```
*/
and(
exprs: ReadonlyArray<Expression<SqlBool>>
): ExpressionWrapper<DB, TB, SqlBool>

and(exprs: Readonly<FilterObject<DB, TB>>): ExpressionWrapper<DB, TB, SqlBool>

/**
* Combines two or more expressions using the logical `or` operator.
*
Expand All @@ -600,7 627,7 @@ export interface ExpressionBuilder<DB, TB extends keyof DB> {
* ```ts
* db.selectFrom('person')
* .selectAll('person')
* .where((eb) => or([
* .where((eb) => eb.or([
* eb('first_name', '=', 'Jennifer'),
* eb('fist_name', '=', 'Arnold'),
* eb('fist_name', '=', 'Sylvester')
Expand All @@ -612,15 639,42 @@ export interface ExpressionBuilder<DB, TB extends keyof DB> {
* ```sql
* select "person".*
* from "person"
* where "first_name" = $1
* or "first_name" = $2
* or "first_name" = $3
* where (
* "first_name" = $1
* or "first_name" = $2
* or "first_name" = $3
* )
* ```
*
* Optionally you can use the simpler object notation if you only need
* equality comparisons:
*
* ```ts
* db.selectFrom('person')
* .selectAll('person')
* .where((eb) => eb.or({
* first_name: 'Jennifer',
* last_name: 'Aniston'
* }))
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "person".*
* from "person"
* where (
* "first_name" = $1
* or "last_name" = $2
* )
* ```
*/
or(
exprs: ReadonlyArray<Expression<SqlBool>>
): ExpressionWrapper<DB, TB, SqlBool>

or(exprs: Readonly<FilterObject<DB, TB>>): ExpressionWrapper<DB, TB, SqlBool>

/**
* Wraps the expression in parentheses.
*
Expand Down Expand Up @@ -812,45 866,23 @@ export function createExpressionBuilder<DB, TB extends keyof DB>(
},

and(
exprs: ReadonlyArray<Expression<SqlBool>>
exprs: ReadonlyArray<Expression<SqlBool>> | Readonly<FilterObject<DB, TB>>
): ExpressionWrapper<DB, TB, SqlBool> {
if (exprs.length === 0) {
return new ExpressionWrapper(ValueNode.createImmediate(true))
} else if (exprs.length === 1) {
return new ExpressionWrapper(exprs[0].toOperationNode())
}

let node = AndNode.create(
exprs[0].toOperationNode(),
exprs[1].toOperationNode()
)

for (let i = 2; i < exprs.length; i) {
node = AndNode.create(node, exprs[i].toOperationNode())
if (isReadonlyArray(exprs)) {
return new ExpressionWrapper(parseFilterList(exprs, 'and'))
}

return new ExpressionWrapper(ParensNode.create(node))
return new ExpressionWrapper(parseFilterObject(exprs, 'and'))
},

or(
exprs: ReadonlyArray<Expression<SqlBool>>
exprs: ReadonlyArray<Expression<SqlBool>> | Readonly<FilterObject<DB, TB>>
): ExpressionWrapper<DB, TB, SqlBool> {
if (exprs.length === 0) {
return new ExpressionWrapper(ValueNode.createImmediate(false))
} else if (exprs.length === 1) {
return new ExpressionWrapper(exprs[0].toOperationNode())
}

let node = OrNode.create(
exprs[0].toOperationNode(),
exprs[1].toOperationNode()
)

for (let i = 2; i < exprs.length; i) {
node = OrNode.create(node, exprs[i].toOperationNode())
if (isReadonlyArray(exprs)) {
return new ExpressionWrapper(parseFilterList(exprs, 'or'))
}

return new ExpressionWrapper(ParensNode.create(node))
return new ExpressionWrapper(parseFilterObject(exprs, 'or'))
},

parens(...args: any[]) {
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,5 244,6 @@ export {
ComparisonOperatorExpression,
OperandValueExpression,
OperandValueExpressionOrList,
FilterObject,
} from './parser/binary-operation-parser.js'
export { ExistsExpression } from './parser/unary-operation-parser.js'
79 changes: 71 additions & 8 deletions src/parser/binary-operation-parser.ts
Original file line number Diff line number Diff line change
@@ -1,18 1,27 @@
import { BinaryOperationNode } from '../operation-node/binary-operation-node.js'
import { isBoolean, isNull, isString } from '../util/object-utils.js'
import { isOperationNodeSource } from '../operation-node/operation-node-source.js'
import {
isBoolean,
isNull,
isString,
isUndefined,
} from '../util/object-utils.js'
import {
OperationNodeSource,
isOperationNodeSource,
} from '../operation-node/operation-node-source.js'
import {
OperatorNode,
ComparisonOperator,
ArithmeticOperator,
BinaryOperator,
Operator,
OPERATORS,
} from '../operation-node/operator-node.js'
import {
ExtractTypeFromReferenceExpression,
ExtractTypeFromStringReference,
parseReferenceExpression,
ReferenceExpression,
StringReference,
} from './reference-parser.js'
import {
parseValueExpression,
Expand All @@ -23,6 32,10 @@ import {
import { ValueNode } from '../operation-node/value-node.js'
import { OperationNode } from '../operation-node/operation-node.js'
import { Expression } from '../expression/expression.js'
import { SelectType } from '../util/column-type.js'
import { AndNode } from '../operation-node/and-node.js'
import { ParensNode } from '../operation-node/parens-node.js'
import { OrNode } from '../operation-node/or-node.js'

export type OperandValueExpression<
DB,
Expand All @@ -47,9 60,13 @@ export type ComparisonOperatorExpression =
| ComparisonOperator
| Expression<unknown>

export type ArithmeticOperatorExpression =
| ArithmeticOperator
| Expression<unknown>
export type FilterObject<DB, TB extends keyof DB> = {
[R in StringReference<DB, TB>]?: ValueExpressionOrList<
DB,
TB,
SelectType<ExtractTypeFromStringReference<DB, TB, R>>
>
}

export function parseValueBinaryOperationOrExpression(
args: any[]
Expand All @@ -68,7 85,7 @@ export function parseValueBinaryOperation(
operator: BinaryOperatorExpression,
right: OperandValueExpressionOrList<any, any, any>
): BinaryOperationNode {
if (isIsOperator(operator) && isNullOrBoolean(right)) {
if (isIsOperator(operator) && needsIsOperator(right)) {
return BinaryOperationNode.create(
parseReferenceExpression(left),
parseOperator(operator),
Expand All @@ -82,6 99,7 @@ export function parseValueBinaryOperation(
parseValueExpressionOrList(right)
)
}

export function parseReferentialBinaryOperation(
left: ReferenceExpression<any, any>,
operator: BinaryOperatorExpression,
Expand All @@ -94,13 112,50 @@ export function parseReferentialBinaryOperation(
)
}

export function parseFilterObject(
obj: Readonly<FilterObject<any, any>>,
combinator: 'and' | 'or'
): OperationNode {
return parseFilterList(
Object.entries(obj)
.filter(([, v]) => !isUndefined(v))
.map(([k, v]) =>
parseValueBinaryOperation(k, needsIsOperator(v) ? 'is' : '=', v)
),
koskimas marked this conversation as resolved.
Show resolved Hide resolved
combinator
)
}

export function parseFilterList(
list: ReadonlyArray<OperationNodeSource | OperationNode>,
combinator: 'and' | 'or'
): OperationNode {
const combine = combinator === 'and' ? AndNode.create : OrNode.create

if (list.length === 0) {
return ValueNode.createImmediate(combinator === 'and')
}

let node = toOperationNode(list[0])

for (let i = 1; i < list.length; i) {
node = combine(node, toOperationNode(list[i]))
}

if (list.length > 1) {
return ParensNode.create(node)
}

return node
}

function isIsOperator(
operator: BinaryOperatorExpression
): operator is 'is' | 'is not' {
return operator === 'is' || operator === 'is not'
}

function isNullOrBoolean(value: unknown): value is null | boolean {
function needsIsOperator(value: unknown): value is null | boolean {
return isNull(value) || isBoolean(value)
}

Expand All @@ -115,3 170,11 @@ function parseOperator(operator: OperatorExpression): OperationNode {

throw new Error(`invalid operator ${JSON.stringify(operator)}`)
}

function toOperationNode(
nodeOrSource: OperationNode | OperationNodeSource
): OperationNode {
return isOperationNodeSource(nodeOrSource)
? nodeOrSource.toOperationNode()
: nodeOrSource
}
Loading
Loading