Skip to content

Commit

Permalink
preserve parens
Browse files Browse the repository at this point in the history
  • Loading branch information
vogievetsky committed Jan 14, 2025
1 parent 4eaee0a commit 66370a9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
6 changes: 6 additions & 0 deletions src/sql/sql-expression.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,12 @@ describe('SqlExpression', () => {
'a AND (b AND c)',
]);

expect(
mapString(
SqlExpression.parse('(a AND (b AND c))').decomposeViaAnd({ preserveParens: true }),
),
).toEqual(['(a AND (b AND c))']);

expect(mapString(SqlExpression.parse('(a AND (b AND c)) And d').decomposeViaAnd())).toEqual([
'a AND (b AND c)',
'd',
Expand Down
1 change: 1 addition & 0 deletions src/sql/sql-expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { SqlBase } from './sql-base';

export interface DecomposeViaOptions {
flatten?: boolean;
preserveParens?: boolean;
}

export abstract class SqlExpression extends SqlBase {
Expand Down
19 changes: 12 additions & 7 deletions src/sql/sql-multi/sql-multi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,14 @@ export class SqlMulti extends SqlExpression {
}

public decomposeViaAnd(options: DecomposeViaOptions = {}): SqlExpression[] {
if (this.op !== 'AND') return super.decomposeViaAnd(options);
const { op, args } = this;
if (op !== 'AND') return super.decomposeViaAnd(options);
if (options.flatten) {
return this.args.values.flatMap(v => v.decomposeViaAnd(options));
return args.values.flatMap(v => v.decomposeViaAnd(options));
} else {
if (this.hasParens()) return [this.changeParens([])];
return this.args.values.map(v => v.changeParens([]));
const { preserveParens } = options;
if (this.hasParens()) return [preserveParens ? this : this.changeParens([])];
return preserveParens ? args.values.slice() : args.values.map(v => v.changeParens([]));
}
}

Expand All @@ -156,11 +158,14 @@ export class SqlMulti extends SqlExpression {
}

public decomposeViaOr(options: DecomposeViaOptions = {}): SqlExpression[] {
if (this.op !== 'OR') return super.decomposeViaOr(options);
const { op, args } = this;
if (op !== 'OR') return super.decomposeViaOr(options);
if (options.flatten) {
return this.args.values.flatMap(v => v.decomposeViaOr(options));
return args.values.flatMap(v => v.decomposeViaOr(options));
} else {
return this.args.values.map(v => v.changeParens([]));
const { preserveParens } = options;
if (this.hasParens()) return [preserveParens ? this : this.changeParens([])];
return preserveParens ? args.values.slice() : args.values.map(v => v.changeParens([]));
}
}

Expand Down

0 comments on commit 66370a9

Please sign in to comment.