Skip to content

Commit

Permalink
#130 Add support for date() (#132)
Browse files Browse the repository at this point in the history
  • Loading branch information
DrewImm authored Jul 9, 2024
1 parent f8955a0 commit 9f3dbe3
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/dml/query-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,10 @@ export class DatabaseQueryBuilder extends StatementBuilder {
this.currentTimestamp(fn);
break;

case DatabaseFunctionKeys.DATE:
this.date(fn);
break;

case DatabaseFunctionKeys.YEAR:
this.year(fn);
break;
Expand Down Expand Up @@ -921,6 +925,22 @@ export class DatabaseQueryBuilder extends StatementBuilder {
return this;
}

public date(fn: DatabaseFunction): this {
this.sql.append('date');
this.sql.openParens();

if (fn.params?.expr) {
this.expression(fn.params.expr);
}
else {
this.expression(DatabaseFunctions.currentTimestamp());
}

this.sql.closeParens();

return this;
}

public year(fn: DatabaseFunction): this {
this.sql.append('year');
this.sql.openParens();
Expand Down
1 change: 1 addition & 0 deletions src/functions/function-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export enum DatabaseFunctionKeys {
MAX,
SUM,
CURRENT_TIMESTAMP,
DATE,
YEAR,
UUID,
}
Expand Down
11 changes: 11 additions & 0 deletions src/functions/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ export class DatabaseFunctions {
};
}

public static date(
expr?: Expression
): DatabaseFunctionToken<ColumnType.DATE> {
return {
riao_expr: ExpressionTokenKey.FUNCTION_CALL,
fn: DatabaseFunctionKeys.DATE,
type: ColumnType.DATE,
params: { expr },
};
}

public static year(
expr?: Expression
): DatabaseFunctionToken<ColumnType.INT> {
Expand Down
42 changes: 42 additions & 0 deletions test/spec/functions/date.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import 'jasmine';
import { DatabaseFunctions } from '../../../src/functions';
import { DatabaseQueryBuilder } from '../../../src/dml';
import { columnName } from '../../../src/tokens';

describe('Function - date()', () => {
it('can select current date', async () => {
const { sql, params } = new DatabaseQueryBuilder()
.select({
columns: [
{
query: DatabaseFunctions.date(
DatabaseFunctions.currentTimestamp()
),
as: 'date',
},
],
})
.toDatabaseQuery();

expect(sql).toEqual('SELECT date(CURRENT_TIMESTAMP) AS "date"');
expect(params).toEqual([]);
});

it('can select from column name', async () => {
const { sql, params } = new DatabaseQueryBuilder()
.select({
columns: [
{
query: DatabaseFunctions.date(
columnName('create_timestamp')
),
as: 'date',
},
],
})
.toDatabaseQuery();

expect(sql).toEqual('SELECT date("create_timestamp") AS "date"');
expect(params).toEqual([]);
});
});

0 comments on commit 9f3dbe3

Please sign in to comment.