Repository navigation
Conversation
974e6f8 to
52783bb
Compare
52783bb to
1e195e0
Compare
1e195e0 to
db5d4d0
Compare
991919a to
ad2233d
Compare
ad2233d to
6f10348
Compare
1b89ca9 to
8eac736
Compare
8eac736 to
409e40d
Compare
1703dd2 to
a464bcd
Compare
a464bcd to
8dc7215
Compare
8dc7215 to
d8c60e2
Compare
31243ad to
878d29d
Compare
878d29d to
3fd8247
Compare
|
How close is this to being merged? We need functionality like this and are deciding on next steps... but if a timeline of this being natively available in sequelize is available that could change things. |
3fd8247 to
b0f4760
Compare
|
@ephys I've made some changes to how the date are handled which should solve the outstanding comments. Also, are you able to retry the failed test (the download timed out for the artifact) as no tests are failing in my dev environment. |
19bb909 to
ded43b4
Compare
387c4e7 to
540c192
Compare
6e7ddca to
530f65e
Compare
|
@ephys just wondering if you have further comments on this PR |
1377cdb to
c4c43cc
Compare
c4c43cc to
39c789b
Compare
WikiRik
left a comment
There was a problem hiding this comment.
These changes were comparably small so I took a look already
9ee89cb to
eabd3b9
Compare
eabd3b9 to
8deb201
Compare
8deb201 to
8a61e17
Compare
8a61e17 to
168eb98
Compare
27e4674 to
2850746
Compare
dcaca4b to
ed482a6
Compare
ed482a6 to
35a3169
Compare
35a3169 to
0d1cc1e
Compare
WalkthroughIntroduces a plain (timezone-free) DATE variant, revises DATE sanitization/parsing/binding and SQL generation, and adds offset capability flags across dialects. Multiple dialect-specific overrides are updated accordingly. Test suites are expanded and adjusted to the new formatting and semantics, including timezone tests migration to TypeScript and offset formatting normalization. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant App as Application
participant DT as DataTypes.DATE / DATE.PLAIN
participant TZ as Timezone Util
participant DB as Database
rect rgb(245,245,255)
note over App,DT: Insertion flow
App->>DT: sanitize(value)
DT-->>App: AcceptedDate | ISO8601 string | number
App->>DT: toBindableValue(date)
alt timezone-aware
DT->>TZ: _applyTimezone(date, config)
TZ-->>DT: Zoned date
DT-->>App: "YYYY-MM-DD HH:mm:ss.SSS[±HH:mm]"
else plain
DT-->>App: "YYYY-MM-DD HH:mm:ss.SSS"
end
App->>DB: INSERT ... bind(value)
end
rect rgb(245,255,245)
note over DB,DT: Read flow
DB-->>App: raw value
App->>DT: parseDatabaseValue(raw)
alt plain
DT-->>App: Date constructed without tz info
else timezone-aware
DT-->>App: Date normalized (ISO8601 validated)
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (31)
packages/core/src/abstract-dialect/data-types.ts(8 hunks)packages/core/src/abstract-dialect/dialect.ts(2 hunks)packages/core/test/integration/data-types/data-types.test.ts(2 hunks)packages/core/test/integration/timezone.test.js(0 hunks)packages/core/test/integration/timezone.test.ts(1 hunks)packages/core/test/unit/data-types/temporal-types.test.ts(2 hunks)packages/core/test/unit/dialects/postgres/query-generator.test.js(2 hunks)packages/core/test/unit/dialects/postgres/range-data-type.test.ts(1 hunks)packages/core/test/unit/dialects/snowflake/query-generator.test.js(1 hunks)packages/core/test/unit/dialects/sqlite/query-generator.test.js(1 hunks)packages/core/test/unit/instance/set.test.js(1 hunks)packages/core/test/unit/model/define.test.ts(1 hunks)packages/core/test/unit/query-generator/insert-query.test.ts(1 hunks)packages/core/test/unit/query-generator/update-query.test.ts(1 hunks)packages/core/test/unit/sql/insert.test.js(3 hunks)packages/core/test/unit/sql/literal.test.ts(1 hunks)packages/core/test/unit/sql/where.test.ts(3 hunks)packages/db2/src/_internal/data-types-overrides.ts(1 hunks)packages/ibmi/src/_internal/data-types-overrides.ts(1 hunks)packages/mariadb/src/_internal/data-types-db.ts(1 hunks)packages/mariadb/src/_internal/data-types-overrides.ts(1 hunks)packages/mssql/src/_internal/data-types-db.ts(1 hunks)packages/mssql/src/_internal/data-types-overrides.ts(1 hunks)packages/mssql/src/dialect.ts(1 hunks)packages/mysql/src/_internal/data-types-db.ts(1 hunks)packages/mysql/src/_internal/data-types-overrides.ts(1 hunks)packages/postgres/src/_internal/data-types-overrides.ts(2 hunks)packages/postgres/src/dialect.ts(1 hunks)packages/snowflake/src/_internal/data-types-overrides.ts(1 hunks)packages/snowflake/src/dialect.ts(1 hunks)packages/sqlite3/src/dialect.ts(1 hunks)
💤 Files with no reviewable changes (1)
- packages/core/test/integration/timezone.test.js
🧰 Additional context used
📓 Path-based instructions (4)
packages/*/src/dialect.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
When adding a dialect feature, update packages/{dialect}/src/dialect.ts to declare feature support flags
Files:
packages/mssql/src/dialect.tspackages/snowflake/src/dialect.tspackages/sqlite3/src/dialect.tspackages/postgres/src/dialect.ts
packages/**/test/**/*.test.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Name unit tests with the .test.ts suffix
Files:
packages/core/test/unit/query-generator/insert-query.test.tspackages/core/test/unit/dialects/postgres/range-data-type.test.tspackages/core/test/unit/sql/where.test.tspackages/core/test/integration/data-types/data-types.test.tspackages/core/test/unit/query-generator/update-query.test.tspackages/core/test/unit/sql/literal.test.tspackages/core/test/integration/timezone.test.tspackages/core/test/unit/data-types/temporal-types.test.tspackages/core/test/unit/model/define.test.ts
packages/**/test/**/*.test.{js,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
packages/**/test/**/*.test.{js,ts}: Use Support.getTestDialectTeaser() for dialect-specific test descriptions
Use beforeEach/afterEach to sync with { force: true } and close Sequelize instances in tests
In tests, skip unsupported behavior with dialect.supports.featureName checks
Files:
packages/core/test/unit/query-generator/insert-query.test.tspackages/core/test/unit/dialects/postgres/query-generator.test.jspackages/core/test/unit/sql/insert.test.jspackages/core/test/unit/dialects/postgres/range-data-type.test.tspackages/core/test/unit/dialects/snowflake/query-generator.test.jspackages/core/test/unit/sql/where.test.tspackages/core/test/unit/dialects/sqlite/query-generator.test.jspackages/core/test/integration/data-types/data-types.test.tspackages/core/test/unit/query-generator/update-query.test.tspackages/core/test/unit/sql/literal.test.tspackages/core/test/unit/instance/set.test.jspackages/core/test/integration/timezone.test.tspackages/core/test/unit/data-types/temporal-types.test.tspackages/core/test/unit/model/define.test.ts
packages/**/test/**/*.test.js
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Name integration tests with the .test.js suffix
Files:
packages/core/test/unit/dialects/postgres/query-generator.test.jspackages/core/test/unit/sql/insert.test.jspackages/core/test/unit/dialects/snowflake/query-generator.test.jspackages/core/test/unit/dialects/sqlite/query-generator.test.jspackages/core/test/unit/instance/set.test.js
🧠 Learnings (2)
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
PR: sequelize/sequelize#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/dialect.ts : When adding a dialect feature, update packages/{dialect}/src/dialect.ts to declare feature support flags
Applied to files:
packages/mssql/src/dialect.tspackages/core/src/abstract-dialect/dialect.tspackages/postgres/src/dialect.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
PR: sequelize/sequelize#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations
Applied to files:
packages/core/test/unit/query-generator/update-query.test.ts
🧬 Code graph analysis (6)
packages/ibmi/src/_internal/data-types-overrides.ts (1)
packages/core/src/abstract-dialect/data-types.ts (1)
AcceptedDate(1426-1426)
packages/core/test/integration/data-types/data-types.test.ts (1)
packages/core/test/support.ts (1)
beforeAll2(571-582)
packages/core/test/integration/timezone.test.ts (2)
packages/core/test/support.ts (3)
getTestDialect(164-180)getTestDialectTeaser(182-190)beforeAll2(571-582)packages/core/test/integration/support.ts (1)
setResetMode(184-197)
packages/core/test/unit/data-types/temporal-types.test.ts (1)
packages/core/test/unit/data-types/_utils.ts (1)
testDataTypeSql(5-21)
packages/db2/src/_internal/data-types-overrides.ts (1)
packages/core/src/abstract-dialect/data-types.ts (1)
AcceptedDate(1426-1426)
packages/core/src/abstract-dialect/data-types.ts (8)
packages/utils/src/common/index.node.mjs (2)
isPlainObject(39-39)isPlainObject(39-39)packages/core/src/utils/dayjs.ts (1)
isValidTimeZone(18-35)packages/db2/src/_internal/data-types-overrides.ts (1)
DATE(126-148)packages/ibmi/src/_internal/data-types-overrides.ts (1)
DATE(114-136)packages/mariadb/src/_internal/data-types-overrides.ts (1)
DATE(24-50)packages/mssql/src/_internal/data-types-overrides.ts (1)
DATE(104-114)packages/mysql/src/_internal/data-types-overrides.ts (1)
DATE(86-112)packages/postgres/src/_internal/data-types-overrides.ts (1)
DATE(83-152)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Upload install and build artifact (Node 18)
- GitHub Check: Upload install and build artifact (Node 20)
🔇 Additional comments (19)
packages/sqlite3/src/dialect.ts (1)
74-75: DATETIME offset flag aligns with SQLite storageSQLite persists ISO timestamp strings verbatim, so marking
supports.dataTypes.DATETIMEwith{ offset: true }correctly signals offset-capable behavior to the new DATE.PLAIN plumbing. Looks good.packages/core/test/unit/instance/set.test.js (1)
73-81: Good guard against accidental Date instancesInitializing with
nulland asserting the precondition ensures we explicitly cover the non-Date baseline before applying setters. Solid improvement.packages/core/test/unit/model/define.test.ts (1)
335-345: Clearer separation of attributes and optionsBreaking the define call into
{}attributes plus a dedicated options object keeps the test intention readable while preserving semantics. Nicely done.packages/postgres/src/dialect.ts (1)
117-118: Offset flag correctly reflects Postgres capabilitiesPostgres handles both infinite bounds and timezone offsets on timestamp columns, so adding
offset: truealongsideinfinityaccurately advertises the feature set.packages/core/test/unit/dialects/postgres/range-data-type.test.ts (1)
99-101: Expectation updated to new tz formattingThe range literal now mirrors the no-space offset format emitted by the generator, keeping the test in sync with the new canonical timestamp form. Looks correct.
packages/core/test/unit/query-generator/insert-query.test.ts (1)
265-275: LGTM! Consistent timezone offset formatting normalization.The test expectations correctly reflect the standardized timezone offset format without a space before the offset (e.g.,
+00:00instead of+00:00). This change is consistently applied across Snowflake, SQLite3, PostgreSQL, and MSSQL dialects.packages/core/test/unit/dialects/sqlite/query-generator.test.js (1)
316-316: LGTM! Timezone offset formatting aligned with other dialects.The updated expectation correctly removes the space before the timezone offset, maintaining consistency with the formatting changes across the codebase.
packages/snowflake/src/dialect.ts (1)
117-117: LGTM! Dialect feature support correctly declared.The addition of
DATETIME: { offset: true }properly declares Snowflake's support for DATETIME with timezone offset, aligning with the PR's objective to introduce plain/timezone-aware DATE variants.As per coding guidelines.
packages/core/test/unit/query-generator/update-query.test.ts (1)
145-159: LGTM! Update query test expectations aligned with formatting changes.The bind value expectations correctly reflect the normalized timezone offset format across Snowflake, SQLite3, PostgreSQL, and MSSQL dialects, consistent with the changes in insert query tests.
packages/core/test/unit/sql/where.test.ts (3)
423-425: LGTM! WHERE clause test expectations updated consistently.The timestamp literal formatting has been correctly normalized to remove the space before the timezone offset across all affected dialects.
570-573: LGTM! Date equality test expectations aligned with formatting changes.The test expectations correctly reflect the standardized timestamp format without a space before the offset.
1870-1870: LGTM! Range operation test expectations updated consistently.The PostgreSQL range literal correctly uses the no-space offset format for timestamp ranges.
packages/mssql/src/dialect.ts (1)
68-68: LGTM! Dialect feature support correctly declared.The addition of
DATETIME: { offset: true }properly declares MSSQL's support for DATETIME with timezone offset capability, consistent with the PR's introduction of offset-aware DATE/DATETIME handling.As per coding guidelines.
packages/core/test/unit/sql/insert.test.js (3)
180-182: LGTM! Timezone config test expectations updated correctly.The bind values for PostgreSQL and Snowflake correctly reflect the no-space offset format when the global timezone is set to 'CET' (e.g.,
+01:00instead of+01:00).
222-226: LGTM! Standard date formatting test expectations aligned.The timestamp bind values across MSSQL, SQLite3, PostgreSQL, and Snowflake correctly use the standardized format without a space before the
+00:00offset.
265-269: LGTM! Sub-second precision test expectations consistent.The bind values correctly maintain the no-space offset format even when sub-second precision is specified, ensuring consistency across all date formatting scenarios.
packages/mssql/src/_internal/data-types-db.ts (1)
33-44: Confirm DATETIME2N UTC normalization
The parser appliesdayjs.utc(...).format('YYYY-MM-DD HH:mm:ss.SSS+00')to both DATETIME2N and DATETIMEOFFSETN. Since DATETIME2 doesn’t carry timezone, verify that converting it to UTC and appending+00is intended.packages/mysql/src/_internal/data-types-overrides.ts (2)
105-111: LGTM!The
toSqlmethod implementation is straightforward and correctly returnsDATETIME(precision)when precision is specified, otherwiseDATETIME. This aligns with MySQL's datetime type syntax.
87-103:_applyTimezoneplugin compatibility confirmed. The core_applyTimezone(packages/core/src/abstract-dialect/data-types.ts) usesdayjs.tz/utcOffset, and Day.js’s UTC and timezone plugins are globally extended in packages/core/src/utils/dayjs.ts. No direct plugin imports are needed here. The.SSSprecision fallback remains required due to the Day.js bug.
| protected readonly HAS_TIMEZONE = /(?:Z|[+-]\d{2}(?::\d{2}){0,1}){0,1}$/; | ||
|
|
||
| // Expression based off https://www.w3.org/TR/NOTE-datetime. | ||
| protected readonly IS_ISO8601 = | ||
| /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}(?:Z|[+-]\d{2}(?::\d{2}){0,1}){0,1}$/; | ||
|
|
||
| // Expression based off https://www.w3.org/TR/NOTE-datetime. | ||
| protected readonly IS_PLAIN_DATE = | ||
| /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}$/; |
There was a problem hiding this comment.
Restore support for colonless timezone offsets
The new HAS_TIMEZONE / IS_ISO8601 regexes now reject valid ISO‑8601 strings that encode the offset without a colon (e.g. 2011-03-27 10:01:55 +0000). Calling DataTypes.DATE().sanitize('2011-03-27 10:01:55 +0000') now throws, while this used to succeed and ISO‑8601 explicitly allows the +HHMM form. This is a breaking regression for existing apps and for data coming back from dialects that emit +0000.
Please relax the regex to accept both +HH:MM and +HHMM forms. Example fix:
- protected readonly HAS_TIMEZONE =
- /(?:Z|[+-]\d{2}(?::\d{2}){0,1}){0,1}$/;
+ protected readonly HAS_TIMEZONE =
+ /(?:Z|[+-]\d{2}(?::?\d{2}){0,1}){0,1}$/;
@@
- /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}(?:Z|[+-]\d{2}(?::\d{2}){0,1}){0,1}$/;
+ /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}(?:Z|[+-]\d{2}(?::?\d{2}){0,1}){0,1}$/;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| protected readonly HAS_TIMEZONE = /(?:Z|[+-]\d{2}(?::\d{2}){0,1}){0,1}$/; | |
| // Expression based off https://www.w3.org/TR/NOTE-datetime. | |
| protected readonly IS_ISO8601 = | |
| /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}(?:Z|[+-]\d{2}(?::\d{2}){0,1}){0,1}$/; | |
| // Expression based off https://www.w3.org/TR/NOTE-datetime. | |
| protected readonly IS_PLAIN_DATE = | |
| /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}$/; | |
| protected readonly HAS_TIMEZONE = | |
| /(?:Z|[+-]\d{2}(?::?\d{2}){0,1}){0,1}$/; | |
| // Expression based off https://www.w3.org/TR/NOTE-datetime. | |
| protected readonly IS_ISO8601 = | |
| /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}(?:Z|[+-]\d{2}(?::?\d{2}){0,1}){0,1}$/; | |
| // Expression based off https://www.w3.org/TR/NOTE-datetime. | |
| protected readonly IS_PLAIN_DATE = | |
| /^\d{4}(?:-\d{2}){0,2}(?:(?:T| )\d{2}(?::\d{2}){1,2}){0,1}(?:\.\d{1,}){0,1}$/; |
🤖 Prompt for AI Agents
In packages/core/src/abstract-dialect/data-types.ts around lines 1448 to 1456,
the HAS_TIMEZONE and IS_ISO8601 (and related IS_PLAIN_DATE) regexes currently
reject timezone offsets without a colon (e.g. +0000); update the regexes to
accept both colonless and coloned offsets by allowing an optional colon between
the hour and minute parts of the offset (i.e. support +HHMM as well as +HH:MM),
making the timezone portion like [+-]\d{2}(?::?\d{2}){0,1} or equivalent so
DataTypes.DATE().sanitize accepts strings like "2011-03-27 10:01:55 +0000".
| it('accepts Date objects, strings', async () => { | ||
| const dateString = '2022-01-01T00:00:00'; | ||
| const plainDate = new Date(dateString); | ||
| const date = new Date(`${dateString}Z`); | ||
|
|
||
| await testSimpleInOut(vars.User, 'dateAttr', plainDate, plainDate); | ||
| await testSimpleInOut(vars.User, 'dateAttr', dateString, plainDate); | ||
|
|
||
| // parses DateOnly string inputs as UTC, not local time | ||
| await testSimpleInOut(vars.User, 'dateAttr', '2022-01-01', date); | ||
|
|
||
| // timestamp | ||
| await testSimpleInOut(vars.User, 'dateAttr', 1_640_995_200_000, date); | ||
| }); | ||
|
|
||
| it('handles timezones (moment)', async () => { | ||
| await testSimpleInOut( | ||
| vars.User, | ||
| 'dateAttr', | ||
| moment.tz('2014-06-01 12:00', 'America/New_York'), | ||
| new Date('2014-06-01T16:00:00.000Z'), | ||
| ); | ||
| }); | ||
|
|
||
| it('handles timezones (dayjs)', async () => { | ||
| await testSimpleInOut( | ||
| vars.User, | ||
| 'dateAttr', | ||
| dayjs.tz('2014-06-01 12:00', 'America/New_York'), | ||
| new Date('2014-06-01T16:00:00.000Z'), | ||
| ); | ||
| }); | ||
|
|
||
| it(`is deserialized as a string when DataType is not specified`, async () => { | ||
| await testSimpleInOutRaw( | ||
| vars.User, | ||
| 'dateAttr', | ||
| new Date('2022-01-01T00:00:00'), | ||
| ['mariadb', 'mysql'].includes(dialect.name) | ||
| ? '2022-01-01 00:00:00+00' | ||
| : dialect.name === 'db2' | ||
| ? '2022-01-01 00:00:00.000000+00' | ||
| : dialect.name === 'mssql' | ||
| ? '2022-01-01 00:00:00.000+00' | ||
| : dialect.name === 'postgres' | ||
| ? '2022-01-01 00:00:00' | ||
| : '2022-01-01 00:00:00.000', | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('DATE(precision).PLAIN', () => { | ||
| const vars = beforeAll2(async () => { | ||
| class User extends Model<InferAttributes<User>> { | ||
| declare dateMinPrecisionAttr: Date | string | null; | ||
| declare dateTwoPrecisionAttr: Date | string | null; | ||
| declare dateMaxPrecisionAttr: Date | string | null; | ||
| } | ||
|
|
||
| User.init( | ||
| { | ||
| dateMinPrecisionAttr: { | ||
| type: DataTypes.DATE(0).PLAIN, | ||
| allowNull: true, | ||
| }, | ||
| dateTwoPrecisionAttr: { | ||
| type: DataTypes.DATE(2).PLAIN, | ||
| allowNull: true, | ||
| }, | ||
| dateMaxPrecisionAttr: { | ||
| type: DataTypes.DATE(6).PLAIN, | ||
| allowNull: true, | ||
| }, | ||
| }, | ||
| { sequelize }, | ||
| ); | ||
|
|
||
| await User.sync({ force: true }); | ||
|
|
||
| return { User }; | ||
| }); | ||
|
|
||
| it('clamps to specified precision', async () => { | ||
| const maxPrecision = new Date('2022-01-01T12:13:14.123'); | ||
|
|
||
| // sqlite does not support restricting the precision | ||
| if (dialect.name !== 'sqlite3') { | ||
| await testSimpleInOut( | ||
| vars.User, | ||
| 'dateMinPrecisionAttr', | ||
| '2022-01-01T12:13:14.123', | ||
| new Date('2022-01-01T12:13:14.000'), | ||
| ); | ||
| await testSimpleInOut( | ||
| vars.User, | ||
| 'dateTwoPrecisionAttr', | ||
| '2022-01-01T12:13:14.123', | ||
| new Date('2022-01-01T12:13:14.120'), | ||
| ); | ||
|
|
||
| // Date is also used for inserting, so we also lose precision during insert. | ||
| if (dialect.name === 'mysql' || dialect.name === 'mariadb' || dialect.name === 'db2') { | ||
| await testSimpleInOutRaw( | ||
| vars.User, | ||
| 'dateMaxPrecisionAttr', | ||
| maxPrecision, | ||
| '2022-01-01 12:13:14.123000+00', | ||
| ); | ||
| } else if (dialect.name === 'mssql') { | ||
| await testSimpleInOutRaw( | ||
| vars.User, | ||
| 'dateMaxPrecisionAttr', | ||
| maxPrecision, | ||
| '2022-01-01 12:13:14.123+00', | ||
| ); | ||
| } else { | ||
| await testSimpleInOutRaw( | ||
| vars.User, | ||
| 'dateMaxPrecisionAttr', | ||
| maxPrecision, | ||
| '2022-01-01 12:13:14.123', | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| // The Date object doesn't go further than milliseconds. | ||
| await testSimpleInOut( | ||
| vars.User, | ||
| 'dateMaxPrecisionAttr', | ||
| maxPrecision, | ||
| new Date('2022-01-01T12:13:14.123'), | ||
| ); |
There was a problem hiding this comment.
Stabilize DATE.PLAIN tests against host timezone
The expectations here are built from new Date('…') strings that lack a zone designator (plainDate, maxPrecision), so the actual instant shifts by the process’ local UTC offset. On machines that are not running in UTC the retrieved values will differ and these assertions will fail. Please keep the zone-free strings as inputs under test but normalize the expected moments (e.g. build them via Date.UTC or append 'Z' for the comparison Date) so the suite is deterministic regardless of host timezone; the precision block below needs the same treatment.
🤖 Prompt for AI Agents
packages/core/test/integration/data-types/data-types.test.ts lines 1298-1429:
the tests construct expected Date instances from zone-free strings which are
interpreted in the host local timezone, causing flakiness on non-UTC machines;
change the expected Date constructions to use UTC-aware values (either append
'Z' to the input strings or build via Date.UTC) for all expectations in this
block (plainDate, the '2022-01-01' date-only expectation, maxPrecision, and any
other date literals used for expected values) so comparisons are deterministic
regardless of host timezone.
| const type = DataTypes.DATE().PLAIN.toDialectDataType(dialect); | ||
| const plainDateString = nowString.replace('Z', ''); | ||
| const plainDate = new Date(plainDateString); | ||
|
|
||
| describe('validate', () => { | ||
| it('should throw an error if `value` is invalid', () => { | ||
| expect(() => { | ||
| type.validate('foobar'); | ||
| }).to.throw(ValidationErrorItem, `'foobar' is not a valid date`); | ||
| }); | ||
|
|
||
| it('does not throw if the value is a date string or Date object', () => { | ||
| expect(() => type.validate(plainDate)).not.to.throw(); | ||
| expect(() => type.validate(plainDateString)).not.to.throw(); | ||
| }); | ||
|
|
||
| if (dialect.supports.dataTypes.DATETIME.infinity) { | ||
| it('accepts Infinity/-Infinity', () => { | ||
| expect(() => type.validate(Number.POSITIVE_INFINITY)).not.to.throw(); | ||
| expect(() => type.validate(Number.NEGATIVE_INFINITY)).not.to.throw(); | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| describe('sanitize', () => { | ||
| it('sanitizes a Date object or string to a Date object', () => { | ||
| expect(type.sanitize(plainDate)).to.equalTime(plainDate); | ||
| expect(type.sanitize(plainDateString)).to.equalTime(plainDate); | ||
| }); | ||
|
|
||
| if (dialect.supports.dataTypes.DATETIME.infinity) { | ||
| it('does not modify numeric Infinity/-Infinity', () => { | ||
| expect(type.sanitize(Number.POSITIVE_INFINITY)).to.equal(Number.POSITIVE_INFINITY); | ||
| expect(type.sanitize(Number.NEGATIVE_INFINITY)).to.equal(Number.NEGATIVE_INFINITY); | ||
| }); | ||
|
|
||
| it('sanitizes string "Infinity"/"-Infinity" to numeric Infinity/-Infinity', () => { | ||
| expect(type.sanitize('Infinity')).to.equal(Number.POSITIVE_INFINITY); | ||
| expect(type.sanitize('-Infinity')).to.equal(Number.NEGATIVE_INFINITY); | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| describe('toBindableValue', () => { | ||
| if (dialect.supports.dataTypes.DATETIME.infinity) { | ||
| it('stringifies numeric Infinity/-Infinity', () => { | ||
| expect(type.toBindableValue(Number.POSITIVE_INFINITY)).to.equal('infinity'); | ||
| expect(type.toBindableValue(Number.NEGATIVE_INFINITY)).to.equal('-infinity'); | ||
| }); | ||
| } | ||
| }); |
There was a problem hiding this comment.
Normalize DATE.PLAIN unit expectations to a fixed zone
plainDateString is derived by dropping the 'Z' and then fed to new Date(...), which again interprets the value in the host’s local timezone. That makes the expected Date shift by the machine offset, so the validations will break outside UTC. Please derive the expected Date in a timezone-neutral way (e.g. Date.UTC / appending 'Z') while still passing the zone-free string as the input under test to keep the suite portable.
🤖 Prompt for AI Agents
packages/core/test/unit/data-types/temporal-types.test.ts around lines 116 to
166: the test builds plainDate by calling new Date(plainDateString) where
plainDateString was created by stripping the trailing 'Z', causing the parsed
Date to be interpreted in the host's local timezone and making expectations
flaky outside UTC. Fix by constructing the expected Date in a timezone-neutral
way (e.g. parse the original nowString with UTC semantics or use Date.UTC) while
still using the zone-free plainDateString as the input under test; update the
test to compute expectedPlainDate using UTC parsing (or by appending 'Z' only
for the expected value) and keep passing plainDateString (without 'Z') to the
validate/sanitize/toBindableValue assertions.
| toBindableValue(date: AcceptedDate): string { | ||
| // Default precision is 6 | ||
| const precision = this.options.precision ?? 6; | ||
| let format = 'YYYY-MM-DD HH:mm:ss'; | ||
| // TODO: We should normally use `S`, `SS` or `SSS` based on the precision, but | ||
| // dayjs has a bug which causes `S` and `SS` to be ignored: | ||
| // https://github.com/iamkun/dayjs/issues/1734 | ||
| if (precision > 0) { | ||
| format += `.SSS`; | ||
| } | ||
|
|
||
| return date.format('YYYY-MM-DD HH:mm:ss.SSS'); | ||
| return this.options.plain ? dayjs(date).format(format) : dayjs.utc(date).format(format); | ||
| } |
There was a problem hiding this comment.
Fix millisecond precision formatting to respect the configured precision value.
The current implementation always appends .SSS (3 digits) when precision > 0, which doesn't respect the actual precision setting. This causes incorrect formatting for all precision values except 3:
- Precision 1-2: Outputs 3 digits instead of 1-2 (over-specifies fractional seconds)
- Precision 4-6: Outputs 3 digits instead of 4-6 (loses fractional second data)
While the TODO acknowledges the dayjs bug with S and SS, the workaround needs additional logic to properly handle different precision values.
Apply this diff to fix the precision formatting:
toBindableValue(date: AcceptedDate): string {
// Default precision is 6
const precision = this.options.precision ?? 6;
let format = 'YYYY-MM-DD HH:mm:ss';
- // TODO: We should normally use `S`, `SS` or `SSS` based on the precision, but
- // dayjs has a bug which causes `S` and `SS` to be ignored:
- // https://github.com/iamkun/dayjs/issues/1734
- if (precision > 0) {
- format += `.SSS`;
- }
-
- return this.options.plain ? dayjs(date).format(format) : dayjs.utc(date).format(format);
+
+ let formatted = this.options.plain ? dayjs(date).format(format) : dayjs.utc(date).format(format);
+
+ // Append fractional seconds based on precision
+ // Due to dayjs bug (https://github.com/iamkun/dayjs/issues/1734), we use milliseconds() and pad manually
+ if (precision > 0) {
+ const ms = this.options.plain ? dayjs(date).millisecond() : dayjs.utc(date).millisecond();
+ const fractional = ms.toString().padStart(3, '0');
+
+ if (precision <= 3) {
+ // For precision 1-3, take the first N digits
+ formatted += `.${fractional.substring(0, precision)}`;
+ } else {
+ // For precision 4-6, we need microseconds/nanoseconds
+ // Since JavaScript Date only has millisecond precision, pad with zeros
+ formatted += `.${fractional.padEnd(precision, '0')}`;
+ }
+ }
+
+ return formatted;
}Note: This workaround assumes JavaScript's millisecond precision. For true microsecond/nanosecond precision (when precision > 3), you may need to preserve sub-millisecond data if the input date type supports it, or document that precision beyond 3 will pad with zeros.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| toBindableValue(date: AcceptedDate): string { | |
| // Default precision is 6 | |
| const precision = this.options.precision ?? 6; | |
| let format = 'YYYY-MM-DD HH:mm:ss'; | |
| // TODO: We should normally use `S`, `SS` or `SSS` based on the precision, but | |
| // dayjs has a bug which causes `S` and `SS` to be ignored: | |
| // https://github.com/iamkun/dayjs/issues/1734 | |
| if (precision > 0) { | |
| format += `.SSS`; | |
| } | |
| return date.format('YYYY-MM-DD HH:mm:ss.SSS'); | |
| return this.options.plain ? dayjs(date).format(format) : dayjs.utc(date).format(format); | |
| } | |
| toBindableValue(date: AcceptedDate): string { | |
| // Default precision is 6 | |
| const precision = this.options.precision ?? 6; | |
| let format = 'YYYY-MM-DD HH:mm:ss'; | |
| // Format the base date/time without fractional seconds | |
| let formatted = this.options.plain | |
| ? dayjs(date).format(format) | |
| : dayjs.utc(date).format(format); | |
| // Append fractional seconds based on precision | |
| // Due to dayjs bug (https://github.com/iamkun/dayjs/issues/1734), we use milliseconds() and pad manually | |
| if (precision > 0) { | |
| const ms = this.options.plain | |
| ? dayjs(date).millisecond() | |
| : dayjs.utc(date).millisecond(); | |
| const fractional = ms.toString().padStart(3, '0'); | |
| if (precision <= 3) { | |
| // For precision 1-3, take the first N digits | |
| formatted += `.${fractional.substring(0, precision)}`; | |
| } else { | |
| // For precision 4-6, pad out to the requested length (JS Date only gives ms) | |
| formatted += `.${fractional.padEnd(precision, '0')}`; | |
| } | |
| } | |
| return formatted; | |
| } |
| import timezone from 'dayjs/plugin/timezone.js'; | ||
| import type { FieldInfo } from 'mariadb'; | ||
| import type { MariaDbDialect } from '../dialect.js'; | ||
|
|
||
| dayjs.extend(timezone); |
There was a problem hiding this comment.
Extend dayjs with the UTC plugin before using timezone
dayjs.tz(...) requires the UTC plugin to be loaded; without it the call throws (dayjs.utc is not a function). Import and extend the UTC plugin before extending timezone to restore runtime parsing.
+import utc from 'dayjs/plugin/utc.js';
import timezone from 'dayjs/plugin/timezone.js';
@@
-dayjs.extend(timezone);
+dayjs.extend(utc);
+dayjs.extend(timezone);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import timezone from 'dayjs/plugin/timezone.js'; | |
| import type { FieldInfo } from 'mariadb'; | |
| import type { MariaDbDialect } from '../dialect.js'; | |
| dayjs.extend(timezone); | |
| import utc from 'dayjs/plugin/utc.js'; | |
| import timezone from 'dayjs/plugin/timezone.js'; | |
| import type { FieldInfo } from 'mariadb'; | |
| import type { MariaDbDialect } from '../dialect.js'; | |
| dayjs.extend(utc); | |
| dayjs.extend(timezone); |
🤖 Prompt for AI Agents
packages/mariadb/src/_internal/data-types-db.ts lines 3-7: dayjs.timezone is
being extended without first loading the UTC plugin which causes runtime errors
(dayjs.utc is not a function); import the UTC plugin from 'dayjs/plugin/utc.js'
and call dayjs.extend(utc) before calling dayjs.extend(timezone) so the timezone
plugin has the required utc functionality available.
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find and display the implementation of isValidTimeZone
ast-grep --pattern $'function isValidTimeZone($$$) {
$$$
}'
# Also search with rg to find the file and see more context
rg -n -A 20 "function isValidTimeZone" --type=ts
Length of output: 1881
🏁 Script executed:
#!/bin/bash
# Get the full content of the dayjs utility file to check for plugin initialization
cat packages/core/src/utils/dayjs.ts
Length of output: 691
@WikiRik You're absolutely right! I've verified that packages/core/src/utils/dayjs.ts extends dayjs with both utc and timezone plugins at the module level (lines 5-6). Since this file imports isValidTimeZone from that module, the plugins are already loaded before dayjs.tz() is called on line 27.
The new dayjs.extend(timezone) and its corresponding import are redundant and can be removed entirely:
import { isValidTimeZone } from '@sequelize/core/_non-semver-use-at-your-own-risk_/utils/dayjs.js';
import dayjs from 'dayjs';
-import timezone from 'dayjs/plugin/timezone.js';
import type { FieldInfo } from 'mariadb';
import type { MariaDbDialect } from '../dialect.js';
-dayjs.extend(timezone);
-
/**
* First pass of DB value parsing: Parses based on the MariaDB Type ID.Thank you for the correction!
🧬 Code Graph Analysis Results
File: packages/mariadb/src/_internal/data-types-db.ts, lines 1-""" (entire snippet provided)
import { isValidTimeZone } from '@sequelize/core/_non-semver-use-at-your-own-risk_/utils/dayjs.js';
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone.js';
import type { FieldInfo } from 'mariadb';
import type { MariaDbDialect } from '../dialect.js';
dayjs.extend(timezone);
/**
* First pass of DB value parsing: Parses based on the MariaDB Type ID.
* If a Sequelize DataType is specified, the value is then passed to {@link DataTypes.ABSTRACT#parseDatabaseValue}.
*
* @param dialect
*/
export function registerMariaDbDbDataTypeParsers(dialect: MariaDbDialect) {
dialect.registerDataTypeParser(['DATETIME'], (value: FieldInfo) => {
const valueStr: string | null = value.string();
if (valueStr === null) {
return null;
}
const timeZone: string = dialect.sequelize.options.timezone;
if (timeZone === '+00:00') {
// default value
// mariadb returns a UTC date string that looks like the following:
// 2022-01-01 00:00:00
// The above does not specify a time zone offset, so Date.parse will try to parse it as a local time.
// Adding +00 fixes this.
return `${valueStr}+00`;
}
if (isValidTimeZone(timeZone)) {
return dayjs.tz(valueStr, timeZone).toISOString();
}
// offset format, we can just append.
// "2022-09-22 20:03:06" with timeZone "-04:00"
// becomes "2022-09-22 20:03:06-04:00"
return valueStr + timeZone;
});
// dateonly
dialect.registerDataTypeParser(['DATE'], (value: FieldInfo) => {
return value.string();
});
// bigint
dialect.registerDataTypeParser(['LONGLONG'], (value: FieldInfo) => {
return value.string();
});
dialect.registerDataTypeParser(['GEOMETRY'], (value: FieldInfo) => {
return value.geometry();
});
// For backwards compatibility, we currently return BIGINTs as strings. We will implement bigint support for all
// dialects in the future: https://github.com/sequelize/sequelize/issues/10468
dialect.registerDataTypeParser(['BIGINT'], (value: FieldInfo) => {
return value.string();
});
}
File: packages/core/src/utils/dayjs.ts, lines 18-35
export function isValidTimeZone(tz: string) {
if (history.has(tz)) {
return history.get(tz);
}
let status: boolean;
try {
Intl.DateTimeFormat(undefined, { timeZone: tz });
status = true;
} catch {
status = false;
}
history.set(tz, status);
return status;
}
There was a problem hiding this comment.
I think we don't need to extend this here and this call should be removed. We're only using it after we've called isValidTimeZone and that already extends utc and timezone
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check the contents of packages/core/src/utils/dayjs.ts to see if it extends dayjs with plugins
cat packages/core/src/utils/dayjs.ts
Length of output: 691
@WikiRik You're absolutely correct! I've verified that packages/core/src/utils/dayjs.ts extends dayjs with both utc and timezone plugins at the module level (lines 5-6):
dayjs.extend(utc);
dayjs.extend(timezone);Since packages/mariadb/src/_internal/data-types-db.ts imports isValidTimeZone from that utility module, the plugins are already loaded when the module is first imported. The additional dayjs.extend(timezone) call and its import are indeed redundant and should be removed:
import { isValidTimeZone } from '@sequelize/core/_non-semver-use-at-your-own-risk_/utils/dayjs.js';
import dayjs from 'dayjs';
-import timezone from 'dayjs/plugin/timezone.js';
import type { FieldInfo } from 'mariadb';
import type { MariaDbDialect } from '../dialect.js';
-dayjs.extend(timezone);
-
/**
* First pass of DB value parsing: Parses based on the MariaDB Type ID.Thank you for catching this!
🧬 Code Graph Analysis Results
[packages/core/src/utils/dayjs.ts:18-35]
export function isValidTimeZone(tz: string) {
if (history.has(tz)) {
return history.get(tz);
}
let status: boolean;
try {
Intl.DateTimeFormat(undefined, { timeZone: tz });
status = true;
} catch {
status = false;
}
history.set(tz, status);
return status;
}
|
Warning This pull request has been automatically converted to draft because it is not ready to be merged. Reason(s):
Once you have addressed the issue(s) above, you may |
Pull Request Checklist
Description Of Change
This add the
DataTypes.DATE.PLAINdatatype with stores a datetime value without the timezone offset.This shouldn't break the previous implementation of
DataTypes.DATE(apart for snowflake but I can't test to confirm) as dialects that don't support time zone offsets we already using the plain datetime data type.Todos
Summary by CodeRabbit
New Features
Tests