Skip to content

Commit

Permalink
feat(functions/subquery): add exists function
Browse files Browse the repository at this point in the history
Add postgres EXISTS(...subquery...) function.
This is required by typeorm exists method.
See: https://github.com/typeorm/typeorm/blob/e7649d2746f907ff36b1efb600402dedd5f5a499/src/query-builder/QueryBuilder.ts#L1273
  • Loading branch information
martini97 authored and oguimbal committed Oct 11, 2024
1 parent a662446 commit 1ff9cb9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/functions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { dateFunctions } from './date';
import { systemFunctions } from './system';
import { sequenceFunctions } from './sequence-fns';
import { numberFunctions } from './numbers';
import { subqueryFunctions } from './subquery';


export const allFunctions = [
Expand All @@ -11,4 +12,5 @@ export const allFunctions = [
, ... systemFunctions
, ... sequenceFunctions
, ... numberFunctions
]
, ... subqueryFunctions
]
14 changes: 14 additions & 0 deletions src/functions/subquery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { FunctionDefinition } from '../interfaces';
import { DataType } from '../interfaces-private';

export const subqueryFunctions: FunctionDefinition[] = [
{
name: 'exists',
args: [DataType.integer],
argsVariadic: DataType.integer,
returns: DataType.bool,
allowNullArguments: true,
impure: true,
implementation: (...items: number[]) => items?.some?.(Boolean) ?? false,
},
];
19 changes: 19 additions & 0 deletions src/tests/subqueries.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ describe('Subqueries', () => {
let db: _IDb;
let many: (str: string) => any[];
let none: (str: string) => void;
let one: (str: string) => any;

beforeEach(() => {
db = newDb() as _IDb;
many = db.public.many.bind(db.public);
none = db.public.none.bind(db.public);
one = db.public.one.bind(db.public);
});

function setupBooks() {
Expand Down Expand Up @@ -90,4 +92,21 @@ describe('Subqueries', () => {

// expect(cnt).toBe(1, 'Was expecting subquery to be simplified');
// })

it('can check if a subquery exists', () => {
setupBooks();

// returns single row, regardless of matches
expect(many(`SELECT EXISTS(SELECT 1 FROM books WHERE created_at < 5) AS x;`))
.toHaveLength(1);

expect(one(`SELECT EXISTS(SELECT 1 FROM books WHERE created_at > 5) AS x;`))
.toEqual({ x: false });

expect(one(`SELECT EXISTS(SELECT 1 FROM books WHERE name = 'one') AS x;`))
.toEqual({ x: true });

expect(one(`SELECT EXISTS(SELECT 1 FROM books WHERE name = 'one') AS x;`))
.toEqual({ x: true });
});
});

0 comments on commit 1ff9cb9

Please sign in to comment.