1
import type { Knex } from 'knex';
2
import type { FnHelperOptions } from '../types.js';
3
import { FnHelper } from '../types.js';
5
const parseLocaltime = (columnType?: string) => {
6
if (columnType === 'timestamp') {
7
return ` AT TIME ZONE 'UTC'`;
13
export class FnHelperMSSQL extends FnHelper {
14
year(table: string, column: string, options: FnHelperOptions): Knex.Raw {
15
return this.knex.raw(`DATEPART(year, ??.??${parseLocaltime(options?.type)})`, [table, column]);
18
month(table: string, column: string, options: FnHelperOptions): Knex.Raw {
19
return this.knex.raw(`DATEPART(month, ??.??${parseLocaltime(options?.type)})`, [table, column]);
22
week(table: string, column: string, options: FnHelperOptions): Knex.Raw {
23
return this.knex.raw(`DATEPART(week, ??.??${parseLocaltime(options?.type)})`, [table, column]);
26
day(table: string, column: string, options: FnHelperOptions): Knex.Raw {
27
return this.knex.raw(`DATEPART(day, ??.??${parseLocaltime(options?.type)})`, [table, column]);
30
weekday(table: string, column: string, options: FnHelperOptions): Knex.Raw {
31
return this.knex.raw(`DATEPART(weekday, ??.??${parseLocaltime(options?.type)})`, [table, column]);
34
hour(table: string, column: string, options: FnHelperOptions): Knex.Raw {
35
return this.knex.raw(`DATEPART(hour, ??.??${parseLocaltime(options?.type)})`, [table, column]);
38
minute(table: string, column: string, options: FnHelperOptions): Knex.Raw {
39
return this.knex.raw(`DATEPART(minute, ??.??${parseLocaltime(options?.type)})`, [table, column]);
42
second(table: string, column: string, options: FnHelperOptions): Knex.Raw {
43
return this.knex.raw(`DATEPART(second, ??.??${parseLocaltime(options?.type)})`, [table, column]);
46
count(table: string, column: string, options?: FnHelperOptions): Knex.Raw<any> {
47
const collectionName = options?.originalCollectionName || table;
48
const type = this.schema.collections?.[collectionName]?.fields?.[column]?.type ?? 'unknown';
50
if (type === 'json') {
51
return this.knex.raw(`(SELECT COUNT(*) FROM OPENJSON(??.??, '$'))`, [table, column]);
54
if (type === 'alias') {
55
return this._relationalCount(table, column, options);
58
throw new Error(`Couldn't extract type from ${table}.${column}`);