Skip to content

Commit

Permalink
Add math functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jakubknejzlik committed Jan 31, 2024
1 parent ad0e2d7 commit 0502a0b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")'
Expand Down
20 changes: 20 additions & 0 deletions src/Function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)})`);
},
Expand Down

0 comments on commit 0502a0b

Please sign in to comment.