|
| 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 | +} |
0 commit comments