Skip to content

feat(postgres): add INTERVAL support - #10441

Closed
gabegorelick wants to merge 1 commit into
sequelize:masterfrom
gabegorelick:interval-type
Closed

gabegorelick wants to merge 1 commit into
sequelize:masterfrom
gabegorelick:interval-type

Conversation

@gabegorelick

@gabegorelick gabegorelick commented Feb 13, 2019 •

Copy link
Copy Markdown
Contributor

Pull Request check-list

  • Does npm run test or npm run test-DIALECT pass with this change (including linting)?
  • Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Have you added new tests to prevent regressions?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?
  • Did you follow the commit message conventions explained in CONTRIBUTING.md?

Description of change

Add INTERVAL type for PostgreSQL. Intervals are represented as moment.duration objects.

Usage:

const User = sequelize.define('User', {
  age: Sequelize.INTERVAL(0) // optional precision indicating number of fractional seconds digits 
}

// supports moment.duration objects
User.create({age: moment.duration(1, 'year')}); 

// supports ISO 8601 time interval strings
User.create({age: 'P1Y'});

// Postgres-style interval strings are *not* supported
User.create({age: '1 year'});

const user = await User.findOne();

// returns INTERVALs as moment.duration objects
moment.isDuration(user.age) === true

Closes #4900

Comment thread lib/data-types.js

INTERVAL.prototype.key = INTERVAL.key = 'INTERVAL';
INTERVAL.prototype.validate = function validate() {
return true;

@gabegorelick gabegorelick Feb 13, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've not found a good way to validate intervals.

See https://stackoverflow.com/questions/38692972/how-to-validate-a-moment-js-duration for an example of this not working.

Unfortunately, due to the way moment.duration works this means values like 1 day are silently converted to 0 intervals. But we can probably check if all components of the duration are empty, and then check if the string is a 0 interval.

@gabegorelick gabegorelick Feb 13, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, is validate called by anything? I was halfway through updating this to validate ISO and postgres interval strings when I realized nothing seems to call these functions. I assumed these were called before sending sending data to the DB, but it appears that's not the case?

Or are these only useful for users to reference in their custom validators?

}

if (this.sequelize.config.intervalStyle) {
query += `SET intervalstyle TO ${this.sequelize.config.intervalStyle};`;

@gabegorelick gabegorelick Feb 13, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postgres returns intervals as strings. But we need ISO format to be able to accurately parse them.
See https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-INTERVAL-OUTPUT

This is similar to what Rails does: https://github.com/rails/rails/pull/16919/files#diff-cc31fc1dd1e78db64638200f710b2f59R726

I'm not happy with the need for an intervalStyle setting, but it's the only way to not break backwards compatibility for any consumers currently using intervals like https://www.npmjs.com/package/sequelize-interval-postgres.

Ideally we would detect the format and parse dynamically. But I've yet to see a parser that can do this.

Question: should we just always set intervalstyle to iso_8601 and not even allow it to be configured? That seems to be what the Rails PR does.

@codecov

codecov Bot commented Feb 13, 2019 •

Copy link
Copy Markdown

Codecov Report

Merging #10441 into master will increase coverage by 21.75%.
The diff coverage is 96.29%.

Impacted file tree graph

@@             Coverage Diff             @@
##           master   #10441       +/-   ##
===========================================
+ Coverage   74.54%    96.3%   +21.75%     
===========================================
  Files          85       92        +7     
  Lines        8186     9840     +1654     
===========================================
+ Hits         6102     9476     +3374     
+ Misses       2084      364     -1720
Impacted Files Coverage Δ
lib/dialects/postgres/index.js 100% <ø> (ø)
lib/sequelize.js 96.35% <ø> (+8.3%) ⬆️
lib/dialects/postgres/data-types.js 97.97% <100%> (+78.34%) ⬆️
lib/dialects/postgres/connection-manager.js 94.61% <100%> (ø)
lib/data-types.js 94.83% <88.88%> (+16.78%) ⬆️
lib/utils/logger.js 87.5% <0%> (-12.5%) ⬇️
lib/dialects/mssql/query.js 92.96% <0%> (-2.49%) ⬇️
lib/dialects/mssql/data-types.js 98.13% <0%> (-1.87%) ⬇️
lib/associations/belongs-to-many.js 97.61% <0%> (-0.33%) ⬇️
lib/dialects/mssql/query-generator.js 95.83% <0%> (-0.08%) ⬇️
... and 56 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 30c5ca5...a314571. Read the comment docs.

Comment thread lib/dialects/postgres/data-types.js Outdated

INTERVAL.prototype._sanitize = function _sanitize(value) {
if (typeof value === 'string') {
return moment.duration(value);

@gabegorelick gabegorelick Feb 13, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moment.duration seemed like the best thing to sanitize to. Alternatively, we could normalize to strings, but then we'd potentially need to decide on a format (ISO, SQL, PG). Or we could normalize to number of milliseconds (or seconds).

node-pg returns postgres-interval objects by default. I think returning moment.duration objects is a good way to abstract that.

Comment thread docs/data-types.md
Sequelize.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres
Sequelize.DATE(6) // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision
Sequelize.DATEONLY // DATE without time.
Sequelize.INTERVAL // Duration of time. PostgreSQL only.

@gabegorelick gabegorelick Feb 13, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Other DBs have a notion of an interval or duration type. E.g. Oracle has INTERVAL YEAR [(year_precision)] TO MONTH and INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds)]. This should be generalizable to that.

Note that many DBs, including PG, take a fields option that modifies the interval. For example, INTERVAL YEAR TO MONTH. I think supporting that should be out of scope. Specifying precision should be enough for most use cases.

@papb papb added dialect: postgres For issues and PRs. Things that involve PostgreSQL (and do not involve all dialects). status: awaiting approval type: feature DEPRECATED: replace with the "feature" issue type labels Jul 24, 2019
inherits(INTERVAL, BaseTypes.INTERVAL);

INTERVAL.parse = function parse(value) {
return moment.duration(value);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sdepold

sdepold commented Oct 24, 2021

Copy link
Copy Markdown
Member

Hey there :)

First of all: Thanks a bunch for your contribution to Sequelize! Much appreciated!
Second: Unfortunately we haven't had the chance to look into this ever since you created it. Sorry for that!

A couple of months ago, we have switched from master to main branch as our primary development branch and hence this PR is now outdated :(

If you still think this change is making sense, please consider recreating the PR against main. Thanks in advance and sorry for the additional work.

✌️

@gabegorelick

Copy link
Copy Markdown
Contributor Author

There's still a lot of design decisions that need to be made with this. It also may make sense to wait for https://tc39.es/proposal-temporal/docs/duration.html to stabilize and use that instead of moment durations.

@gabegorelick
gabegorelick deleted the interval-type branch October 25, 2021 16:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dialect: postgres For issues and PRs. Things that involve PostgreSQL (and do not involve all dialects). type: feature DEPRECATED: replace with the "feature" issue type

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for time INTERVAL data type in postgres

4 participants