Skip to content

Support for time INTERVAL data type in postgres #4900

Description

@mark-lester

I have times > 24 hours, which just broke upon moving to postrgres, so I think I need to implement an INTERVAL data type in data-types.js.

Activity

  1. changed the title [-]Support for time INTERVAL data type in postgress[/-] [+]Support for time INTERVAL data type in postgres[/+] on Nov 20, 2015
  2. mark-lester commented on Nov 21, 2015

    @mark-lester
    Author

    I added the obvious

    /**
     * A time interval column
     * @property INTERVAL
     */
    
    var INTERVAL = function() {
      if (!(this instanceof INTERVAL)) return new INTERVAL();
      ABSTRACT.apply(this, arguments);
    };
    util.inherits(INTERVAL, ABSTRACT);
    
    INTERVAL.prototype.key = INTERVAL.key = 'INTERVAL';
    INTERVAL.prototype.toSql = function() {
      return 'INTERVAL';
    };
    

    and the entry in module.exports.
    Unless I get told otherwise I'll submit that shortly. I cant fully test yet as I have a weird bug on constraints and block inserts (it goes away when I bring the block size down so I need to have a proper look at what is being said to postrgres)

  3. added
    type: feature
    on Nov 21, 2015
  4. mickhansen commented on Nov 21, 2015

    @mickhansen
    Contributor

    The newer version uses ABSTRACT.inherts(cb) afaik, but @janmeier is more knowledgeable here.

  5. janmeier commented on Nov 24, 2015

    @janmeier
    Member
  6. janmeier commented on Dec 4, 2015

    @janmeier
    Member

    ping @mark-lester :)

  7. mark-lester commented on Dec 4, 2015

    @mark-lester
    Author

    Hey. where did I get to ?, I think I gave up, yes, I aborted and went for strings, because ...,
    https://groups.google.com/forum/#!topic/sequelize/IBoT8wf72tg
    I am just in the middle of critical phase in today's cooking, let me remember why I bottled out, ..., brb

  8. janmeier commented on Dec 4, 2015

    @janmeier
    Member

    While other dialects use strings to identify their types (e.g. INTEGER, GEOMETRY etc), postgres uses oids, which are numbers. The oid for interval is 1186, and interval[] is 1187. Most oids are static, but those for user created types / types you have to manually enable, fx geometry and hstore are dynamic.

    (You can check for an oid using `select typname, oid, typarray from pg_type where typtype = 'b')

  9. mark-lester commented on Dec 4, 2015

    @mark-lester
    Author

    ok, thanks,
    I am about to return to the server and so will have another punt, I need to to implement a sequence manager, something that does this kind of thing (all totally untested).

    sequenceManage:function(offset){
        var self=this;
        var query = "UPDATE "+this.tableName+
            " SET "+this.sequenceName+" = "+this.sequenceName+"+"+offset+
            " WHERE "+this.sequenceName +" >= "+this.get(this.sequenceName);
        _.each(this.seqIndexes,function(seqIndex){
            query+=" AND "+seqIndex+"="+self.get(seqIndex);
        });
        return this.sequelize.query(query);
    },
    

    and this

                modelDef.hooks={
                    beforeInsert: function(record, options) {
                        this.sequenceManage(1);
                    },
                        afterDelete: function(record, options) {
                        this.sequenceManage(-1);
                    }
                },
    

    and obviously give your def a sequenceName (name of field that holds the sequence) and sequencIndex[], list of fields to sequence across.
    If there's a thing to do that pray tell, but I will go back now and attempt to return to using INTERVAL

  10. mark-lester commented on Dec 4, 2015

    @mark-lester
    Author

    I need guidance.
    I am trying to bend an INTERVAL into a timey thing that returns a string of the form H:m:s
    I made this parse method, but to no avail, interval is a "H:m:s" string already, but I am getting an object from my query .

     INTERVAL.parse  = INTERVAL.prototype.parse=function(interval) {
        _.each( ['hours','minutes','seconds'],function(arg){
           if (interval[arg].length === 1)
              interval[arg]="0"+interval[arg];
        });
    
        return interval.hours+":"+interval.minutes+":"+interval.seconds;
      };
    

    any clues on where I am supposed to stop an INTERVAL field from returning an object consisting of hours,minutes and seconds.,
    and is this what we really want anyway ?. The object form might be what we should have. What I myself want is just an H:m:s string where H can be > 24. is that fair ?.

  11. janmeier commented on Dec 7, 2015

    @janmeier
    Member

    I don't have any strong feelings about the returned type for interval, since you are the one implementing it, feel free to write it to suit your needs.

    Adding a .parse method should be all that's required - Is that method being called at all? Perhaps you can create a pull request with what you have so far, that would make it easier for me to offer some guidance

  12. mark-lester commented on Dec 18, 2015

    @mark-lester
    Author

    OK, I let this slip as I went off back into the client. I have some other stuff now, namely I want to do things like select "name",earth_distance (ll_to_earth(88.9761,24.621281) , ll_to_earth("lon","lat")) from "Stops"; so that would be a cool thing to have.
    I did some work previously on epilogue so it could do aggregates like max and min, and you can append $lt etc so you can do afield$lt=, so I got near to this stuff, at least using the interface.
    I'll have another look first and then post an issue. If someone has done any gis stuff and I just cant see it please say.

  13. 19 remaining items

  14. abelosorio commented on Feb 13, 2019

    @abelosorio
  15. gunar commented on Feb 14, 2019

    @gunar

    Thank you for your work @abelosorio @gabegorelick . Excited about getting this merged.

  16. abelosorio commented on Feb 14, 2019

    @abelosorio

    Yeah... so do I. Finally closing a 3-year issue 💪

  17. gabegorelick commented on Feb 14, 2019

    @gabegorelick
    Contributor

    If you'd like to help out, please provide feedback on #10441. There are still some open questions that need to be answered about the design of that approach.

  18. stale commented on Jul 23, 2019

    @stale
  19. gabegorelick commented on Jul 24, 2019

    @gabegorelick
    Contributor

    Still an issue. I will rebase #10441 when I get a chance.

  20. jbdevelop commented on Jan 28, 2021

    @jbdevelop

    I was trying to insert data...

    I got it just like that

    await TransferDevice.create({
              device_id: item.device_id,
              transfer_id: item.transfer_id,
              transfer_route_id: item.transfer_route_id,
              start_date: null,
              end_date: null,
              last_update: null,
              tracking_token: null,
              created_at: Sequelize.literal(`NOW() - INTERVAL '3h'`),
              updated_at: Sequelize.literal(`NOW() - INTERVAL '3h'`),
            }) 
    

    https://stackoverflow.com/questions/43634819/how-to-use-interval-in-sequelizejs

  21. sfroskos commented on Aug 31, 2021

    @sfroskos

    Are PostgreSQL intervals now supported in sequelize? Is there any guidance on how to do create a model and query it using intervals?

  22. jthoward64 commented on Jun 14, 2023

    @jthoward64

    Just for anyone who comes looking, I think this issue is essentially blocked behind the new temporal support (#14295)

  23. ephys commented on Jun 14, 2023

    @ephys
    Member

    I think so too. I'd prefer to map the interval data type to Temporal.Duration (rather than our own representation), as they're both ISO 8601 compatible

  24. jthoward64 commented on Jun 14, 2023

    @jthoward64

    I think so too. I'd prefer to map the interval data type to Temporal.Duration (rather than our own representation), as they're both ISO 8601 compatible

    On that, I have been using a custom data type in the meantime that others may find helpful, it uses Luxon's duration under the hood. I haven't tested it exhaustively, but I haven't run into issue so far.

    import { DataTypes } from "@sequelize/core";
    import type { DurationLikeObject } from "luxon";
    import { Duration } from "luxon";
    
    export class DurationDataType extends DataTypes.ABSTRACT<Duration> {
      toSql() {
        return "interval";
      }
    
      validate(value: unknown): value is Duration {
        return value instanceof Duration;
      }
    
      areValuesEqual(
        value: Duration | null | undefined,
        originalValue: Duration | null | undefined
      ): boolean {
        return value == null || originalValue == null
          ? value === originalValue
          : value.equals(originalValue);
      }
    
      escape(value: Duration): string {
        const stringified = value.toISO();
        if (stringified == null) {
          throw new Error("Could not serialize Duration to ISO string");
        }
        return stringified;
      }
    
      toBindableValue(value: Duration): string {
        return this.escape(value);
      }
    
      parseDatabaseValue(value: unknown): unknown {
        try {
          if (typeof value === "string") {
            return Duration.fromISO(value);
          }
          if (typeof value === "number") {
            return Duration.fromMillis(value);
          }
          if (typeof value === "object") {
            return Duration.fromObject(value as DurationLikeObject);
          }
          throw new Error("Could not parse Duration from database value");
        } catch (error) {
          const message = error instanceof Error ? error.message : "Unknown error";
          throw new Error(
            `Could not parse Duration from database value: ${message}`
          );
        }
      }
    }
  25. added theissue type on Mar 9, 2025
  26. removed
    type: feature
    on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

dialect: postgres

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions