Skip to content

Commit

Permalink
feat(binary-operators): Added date minus date (#388)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexnortung authored Jul 31, 2024
1 parent ba67048 commit 2027196
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/schema/pg-catalog/binary-operators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ function registerNumericOperators(schema: _ISchema) {


function registerDatetimeOperators(schema: _ISchema) {
// ======= date "-" date =======
schema.registerOperator({
operator: '-',
commutative: false,
left: Types.date,
right: Types.date,
returns: Types.interval,
implementation: (a, b) => moment(a).diff(moment(b), 'days'),
})

// ======= date/time "+ -" timestamp =======
for (const dt of dateTypes) {
for (const [operator, f] of [['+', 1], ['-', -1]] as const) {
Expand Down
17 changes: 17 additions & 0 deletions src/tests/operators.queries.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,23 @@ describe('Operators', () => {
expect(dt.toString()).to.equal(moment.utc().startOf('day').add(1, 'day').toDate().toString());
});

it('date - date', () => {
const result = many(`select '2020-01-02'::date - '2020-01-01'::date as dt`);
expect(result[0]?.dt).to.equal(1);
const result2 = many(`select '2020-01-03'::date - '2020-01-01'::date as dt`);
expect(result2[0]?.dt).to.equal(2);
const result3 = many(`select '2022-01-01'::date - '2020-01-01'::date as dt`);
expect(result3[0]?.dt).to.equal(731);

const nullResult1 = many(`select '2020-01-03'::date - null::date as dt`);
expect(nullResult1[0]?.dt).to.equal(null);

const nullResult2 = many(`select null::date - '2020-01-03'::date as dt`);
expect(nullResult2[0]?.dt).to.equal(null);

const nullResult3 = many(`select null::date - null::date as dt`);
expect(nullResult3[0]?.dt).to.equal(null);
});

it('timestamp + interval', () => {
const result = many(`select now() + interval '1 day' as dt`);
Expand Down

0 comments on commit 2027196

Please sign in to comment.