Skip to content

Commit 7c6f6f1

Browse files
committed
refactor(driver-sql): move date bucketing out of sql-driver.ts into sql-driver-date-bucket.ts
buildDateBucketExpr's body (the per-dialect GROUP BY expression of a date dimension) moves unedited into a new seam module. The method stays on the class with its docblock and signature, and hands the body exactly the members it reads through DateBucketHost: the dialect flags and the dateGranularityCapabilities getter as getters, temporalFieldKind and sqliteTemporalArg as late-bound closures. Move-only: no behaviour change. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5pPv99puvEK3Nmm1Mc
1 parent 6845035 commit 7c6f6f1

2 files changed

Lines changed: 136 additions & 56 deletions

File tree

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#25521 cut 20] Date bucketing of `SqlDriver`: `buildDateBucketExpr`, the
5+
* per-dialect SQL fragment a date dimension groups by at `day`, `week`,
6+
* `month`, `quarter` or `year` (PostgreSQL `to_char`, MySQL `date_format`,
7+
* SQLite `strftime`, with the #21485 calendar-day arm for a `Field.date` and the
8+
* #21595 Thursday-rule ISO week on SQLite). It moved out of `sql-driver.ts`
9+
* whole.
10+
*
11+
* A MOVE, not a redesign. The function below is the body of the `SqlDriver`
12+
* method of the same name as it stood, re-indented one level and otherwise
13+
* unedited: the same SQL, the same bindings, the same `null` for a granularity
14+
* the dialect does not model.
15+
*
16+
* What did NOT move, and why:
17+
*
18+
* - The method's docblock stays on the class: it is the contract, and the
19+
* published `dist/*.d.ts` carries it with the method.
20+
* - Its callers stay: `aggregate` (the GROUP BY) and `dateBucketSql` (the
21+
* printed form `service-analytics` echoes).
22+
* - `dateGranularityCapabilities`, `temporalFieldKind` and `sqliteTemporalArg`
23+
* are read by members that stay too, and subclasses may override them; the
24+
* body reaches them through the host.
25+
*
26+
* ## How the moved body reaches the class
27+
*
28+
* The shape the other seam modules apply, after #23050. The class keeps the
29+
* method, because the published `dist/*.d.ts` lists its name and position, and
30+
* because an instance spy or a subclass method of the same name must still be
31+
* the one `aggregate` reaches. The method is now one literal of exactly the
32+
* {@link DateBucketHost} members the body reads, plus a `.call`. Methods go as
33+
* closures that call them on the driver at call time, so a subclass override
34+
* or an instance spy is still the one the body reaches; `isPostgres`,
35+
* `isMysql`, `isSqlite` and the `dateGranularityCapabilities` getter go as
36+
* GETTERS, so each is read when the body reads it, as it was on the class.
37+
*
38+
* The module imports `sql-driver.ts` for a type only, so the two modules form
39+
* no evaluation cycle. `index.ts` re-exports nothing from this module, so the
40+
* published surface does not move.
41+
*/
42+
43+
import type { SqlDriver } from './sql-driver.js';
44+
45+
/**
46+
* The `SqlDriver` members the function below reads — every one of them, and
47+
* no other. Each is typed AS the class member (an indexed access on the
48+
* class), so a change to a member's signature on the class is a change here
49+
* too, and naming a member the class does not have is a compile error. See
50+
* the module header for which members are getters.
51+
*/
52+
export interface DateBucketHost {
53+
readonly dateGranularityCapabilities: SqlDriver['dateGranularityCapabilities'];
54+
readonly isMysql: SqlDriver['isMysql'];
55+
readonly isPostgres: SqlDriver['isPostgres'];
56+
readonly isSqlite: SqlDriver['isSqlite'];
57+
sqliteTemporalArg: SqlDriver['sqliteTemporalArg'];
58+
temporalFieldKind: SqlDriver['temporalFieldKind'];
59+
}
60+
61+
/** The body of `SqlDriver#buildDateBucketExpr`; the method's docblock there is its contract. */
62+
export function buildDateBucketExpr(this: Pick<DateBucketHost, 'dateGranularityCapabilities' | 'isMysql' | 'isPostgres' | 'isSqlite' | 'sqliteTemporalArg' | 'temporalFieldKind'>, field: string, granularity: 'day' | 'week' | 'month' | 'quarter' | 'year', table?: string | null): { sql: string; bindings: any[] } | null {
63+
if (!this.dateGranularityCapabilities[granularity]) return null;
64+
65+
const calendarDay = this.temporalFieldKind(table, field) === 'date';
66+
67+
if (this.isPostgres) {
68+
const arg = calendarDay ? `(??)::date::timestamp` : `(??)::timestamptz AT TIME ZONE 'UTC'`;
69+
switch (granularity) {
70+
case 'year': return { sql: `to_char(${arg}, 'YYYY')`, bindings: [field] };
71+
case 'month': return { sql: `to_char(${arg}, 'YYYY-MM')`, bindings: [field] };
72+
case 'day': return { sql: `to_char(${arg}, 'YYYY-MM-DD')`, bindings: [field] };
73+
case 'quarter': return { sql: `to_char(${arg}, 'YYYY"-Q"Q')`, bindings: [field] };
74+
case 'week': return { sql: `to_char(${arg}, 'IYYY"-W"IW')`, bindings: [field] };
75+
}
76+
}
77+
78+
if (this.isMysql) {
79+
const arg = calendarDay ? `??` : `convert_tz(??, @@session.time_zone, '+00:00')`;
80+
switch (granularity) {
81+
case 'year': return { sql: `date_format(${arg}, '%Y')`, bindings: [field] };
82+
case 'month': return { sql: `date_format(${arg}, '%Y-%m')`, bindings: [field] };
83+
case 'day': return { sql: `date_format(${arg}, '%Y-%m-%d')`, bindings: [field] };
84+
case 'quarter': return { sql: `concat(date_format(${arg}, '%Y'), '-Q', quarter(${arg}))`, bindings: [field, field] };
85+
case 'week': return { sql: `date_format(${arg}, '%x-W%v')`, bindings: [field] };
86+
}
87+
}
88+
89+
if (this.isSqlite) {
90+
// `arg` is a bare `??` for a TEXT-stored column and an epoch→julian-day
91+
// normalization for a `Field.datetime` one (#3773).
92+
const { sql: arg, bindings: argBindings } = this.sqliteTemporalArg(field, table);
93+
const fmt = (f: string) => ({ sql: `strftime('${f}', ${arg})`, bindings: [...argBindings] });
94+
switch (granularity) {
95+
case 'year': return fmt('%Y');
96+
case 'month': return fmt('%Y-%m');
97+
case 'day': return fmt('%Y-%m-%d');
98+
case 'quarter': return { sql: `(strftime('%Y', ${arg}) || '-Q' || ((cast(strftime('%m', ${arg}) as integer) - 1) / 3 + 1))`, bindings: [...argBindings, ...argBindings] };
99+
case 'week': {
100+
// [#21595] The ISO 8601 week, `YYYY-Www`: the label the PostgreSQL
101+
// arm's `IYYY"-W"IW` and the MySQL arm's `%x-W%v` answer. A week
102+
// belongs to the year of its Thursday. `'-3 days', 'weekday 4'` moves
103+
// any day to the Thursday of its Monday-start week (a Monday moves
104+
// +3, a Sunday -3), so that Thursday's `%Y` is the week-numbering
105+
// year and `(%j - 1) / 7 + 1` of it is the week number. Both
106+
// modifiers predate every SQLite this platform ships, unlike `%V`
107+
// (see `dateGranularityCapabilities`). No zone is read, so a
108+
// `Field.date` stays its calendar day.
109+
const thursday = (f: string) => `strftime('${f}', ${arg}, '-3 days', 'weekday 4')`;
110+
return {
111+
sql: `(${thursday('%Y')} || '-W' || printf('%02d', (cast(${thursday('%j')} as integer) - 1) / 7 + 1))`,
112+
bindings: [...argBindings, ...argBindings],
113+
};
114+
}
115+
}
116+
}
117+
118+
return null;
119+
}

‎packages/drivers/driver-sql/src/sql-driver.ts‎

Lines changed: 17 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,9 @@ import { aggregateBackendFault, backendStatementFault, distinctBackendFault, unr
192192
// methods of the same names below hand each body what it reads (`PredicateEmitterHost`). The declarations
193193
// imported as types are named by docblocks here.
194194
import { applyEmptyOperator, applyJsonMembership, applyLike, applyLikePattern, applyNormalizedComparison, applyNullSafeNegative, type emptyJsonListPredicate, type emptyListUnsupportedDialectError, type likePatternPredicate, type textMatchPredicate, type undeclaredEmptyOperatorFieldError } from './sql-driver-predicate-emitters.js';
195+
// [#25521 cut 20] Date bucketing (`buildDateBucketExpr`); the method of the same name below hands the body what
196+
// it reads (`DateBucketHost`).
197+
import { buildDateBucketExpr } from './sql-driver-date-bucket.js';
195198
import { makeDatabaseDirectory, probeAbsentSqliteDatabaseFile, SqliteDatabaseFileError } from './sqlite-database-file.js';
196199
import { jsonMembershipPredicate } from '@objectstack/core';
197200
import knex, { Knex } from 'knex';
@@ -5075,62 +5078,20 @@ export class SqlDriver implements IDataDriver {
50755078
granularity: 'day' | 'week' | 'month' | 'quarter' | 'year',
50765079
table?: string | null,
50775080
): { sql: string; bindings: any[] } | null {
5078-
if (!this.dateGranularityCapabilities[granularity]) return null;
5079-
5080-
const calendarDay = this.temporalFieldKind(table, field) === 'date';
5081-
5082-
if (this.isPostgres) {
5083-
const arg = calendarDay ? `(??)::date::timestamp` : `(??)::timestamptz AT TIME ZONE 'UTC'`;
5084-
switch (granularity) {
5085-
case 'year': return { sql: `to_char(${arg}, 'YYYY')`, bindings: [field] };
5086-
case 'month': return { sql: `to_char(${arg}, 'YYYY-MM')`, bindings: [field] };
5087-
case 'day': return { sql: `to_char(${arg}, 'YYYY-MM-DD')`, bindings: [field] };
5088-
case 'quarter': return { sql: `to_char(${arg}, 'YYYY"-Q"Q')`, bindings: [field] };
5089-
case 'week': return { sql: `to_char(${arg}, 'IYYY"-W"IW')`, bindings: [field] };
5090-
}
5091-
}
5092-
5093-
if (this.isMysql) {
5094-
const arg = calendarDay ? `??` : `convert_tz(??, @@session.time_zone, '+00:00')`;
5095-
switch (granularity) {
5096-
case 'year': return { sql: `date_format(${arg}, '%Y')`, bindings: [field] };
5097-
case 'month': return { sql: `date_format(${arg}, '%Y-%m')`, bindings: [field] };
5098-
case 'day': return { sql: `date_format(${arg}, '%Y-%m-%d')`, bindings: [field] };
5099-
case 'quarter': return { sql: `concat(date_format(${arg}, '%Y'), '-Q', quarter(${arg}))`, bindings: [field, field] };
5100-
case 'week': return { sql: `date_format(${arg}, '%x-W%v')`, bindings: [field] };
5101-
}
5102-
}
5103-
5104-
if (this.isSqlite) {
5105-
// `arg` is a bare `??` for a TEXT-stored column and an epoch→julian-day
5106-
// normalization for a `Field.datetime` one (#3773).
5107-
const { sql: arg, bindings: argBindings } = this.sqliteTemporalArg(field, table);
5108-
const fmt = (f: string) => ({ sql: `strftime('${f}', ${arg})`, bindings: [...argBindings] });
5109-
switch (granularity) {
5110-
case 'year': return fmt('%Y');
5111-
case 'month': return fmt('%Y-%m');
5112-
case 'day': return fmt('%Y-%m-%d');
5113-
case 'quarter': return { sql: `(strftime('%Y', ${arg}) || '-Q' || ((cast(strftime('%m', ${arg}) as integer) - 1) / 3 + 1))`, bindings: [...argBindings, ...argBindings] };
5114-
case 'week': {
5115-
// [#21595] The ISO 8601 week, `YYYY-Www`: the label the PostgreSQL
5116-
// arm's `IYYY"-W"IW` and the MySQL arm's `%x-W%v` answer. A week
5117-
// belongs to the year of its Thursday. `'-3 days', 'weekday 4'` moves
5118-
// any day to the Thursday of its Monday-start week (a Monday moves
5119-
// +3, a Sunday -3), so that Thursday's `%Y` is the week-numbering
5120-
// year and `(%j - 1) / 7 + 1` of it is the week number. Both
5121-
// modifiers predate every SQLite this platform ships, unlike `%V`
5122-
// (see `dateGranularityCapabilities`). No zone is read, so a
5123-
// `Field.date` stays its calendar day.
5124-
const thursday = (f: string) => `strftime('${f}', ${arg}, '-3 days', 'weekday 4')`;
5125-
return {
5126-
sql: `(${thursday('%Y')} || '-W' || printf('%02d', (cast(${thursday('%j')} as integer) - 1) / 7 + 1))`,
5127-
bindings: [...argBindings, ...argBindings],
5128-
};
5129-
}
5130-
}
5131-
}
5132-
5133-
return null;
5081+
// [#25521 cut 20] The body moved to `sql-driver-date-bucket.ts` (see `DateBucketHost`).
5082+
const readDateGranularityCapabilities = () => this.dateGranularityCapabilities;
5083+
const readIsMysql = () => this.isMysql;
5084+
const readIsPostgres = () => this.isPostgres;
5085+
const readIsSqlite = () => this.isSqlite;
5086+
const host: ThisParameterType<typeof buildDateBucketExpr> = {
5087+
get dateGranularityCapabilities() { return readDateGranularityCapabilities(); },
5088+
get isMysql() { return readIsMysql(); },
5089+
get isPostgres() { return readIsPostgres(); },
5090+
get isSqlite() { return readIsSqlite(); },
5091+
sqliteTemporalArg: (...a) => this.sqliteTemporalArg(...a),
5092+
temporalFieldKind: (...a) => this.temporalFieldKind(...a),
5093+
};
5094+
return buildDateBucketExpr.call(host, field, granularity, table);
51345095
}
51355096

51365097
/**

0 commit comments

Comments
 (0)