From 0502a0b8bb2d573c7e06be693f4366a927d3d5cb Mon Sep 17 00:00:00 2001 From: Jakub Knejzlik Date: Wed, 31 Jan 2024 20:00:05 +0100 Subject: [PATCH] Add math functions --- src/Function.test.ts | 8 ++++++++ src/Function.ts | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/Function.test.ts b/src/Function.test.ts index a8e6c23..d33bddf 100644 --- a/src/Function.test.ts +++ b/src/Function.test.ts @@ -8,6 +8,14 @@ describe("Expression", () => { it("should produce valid SQL", () => { expect(Fn.sum("foo").toSQL(flavor)).toEqual("SUM(`foo`)"); expect(Fn.max("foo").toSQL(flavor)).toEqual("MAX(`foo`)"); + expect(Fn.add("foo", "blah").toSQL(flavor)).toEqual("(`foo` + `blah`)"); + expect(Fn.subtract("foo", "blah").toSQL(flavor)).toEqual( + "(`foo` - `blah`)" + ); + expect(Fn.multiply("foo", "blah").toSQL(flavor)).toEqual( + "(`foo` * `blah`)" + ); + expect(Fn.divide("foo", "blah").toSQL(flavor)).toEqual("(`foo` / `blah`)"); expect(Fn.ifnull("foo", `123`).toSQL(flavor)).toEqual("IFNULL(`foo`,123)"); expect(Fn.ifnull("foo", Q.S`123`).toSQL(flavor)).toEqual( 'IFNULL(`foo`,"123")' diff --git a/src/Function.ts b/src/Function.ts index 8500905..ae68f02 100644 --- a/src/Function.ts +++ b/src/Function.ts @@ -9,6 +9,26 @@ const formatDayjs = (dayjs: Dayjs) => dayjs.format("YYYY-MM-DD"); const defaultFlavor = new MySQLFlavor(); export const Function = { + add: (...columns: ExpressionValue[]) => { + return Q.expr( + `(${columns.map((v) => Expression.escapeExpressionValue(v)).join(" + ")})` + ); + }, + subtract: (...columns: ExpressionValue[]) => { + return Q.expr( + `(${columns.map((v) => Expression.escapeExpressionValue(v)).join(" - ")})` + ); + }, + divide: (...columns: ExpressionValue[]) => { + return Q.expr( + `(${columns.map((v) => Expression.escapeExpressionValue(v)).join(" / ")})` + ); + }, + multiply: (...columns: ExpressionValue[]) => { + return Q.expr( + `(${columns.map((v) => Expression.escapeExpressionValue(v)).join(" * ")})` + ); + }, sum: (column: ExpressionValue) => { return Q.expr(`SUM(${Expression.escapeExpressionValue(column)})`); },