Skip to content

PostgreSQL interval datatype support - #16919

Closed
Envek wants to merge 1 commit into
rails:masterfrom
Envek:pg_interval_support
Closed

Envek wants to merge 1 commit into
rails:masterfrom
Envek:pg_interval_support

Conversation

@Envek

@Envek Envek commented Sep 14, 2014 •

Copy link
Copy Markdown
Contributor

Add native support for PostgreSQL interval datatype with conversion from all PostgreSQL formats to ActiveSupport::Duration on record load and transformation from ActiveSupport::Duration to ISO 8601 on save (no more strings). Also added support to define column in migrations and get it in schema dump, optional column precision is supported.

  • Parses ISO 8601 duration format, tells Postgres to use it (see Output formats)
  • Constructs ActiveSupport::Duration value (that magic 2.days)
  • Converts ActiveSupport::Duration to ISO 8601 duration format on save
  • Do not allows to use old raw values on save — you must ensure you're feeding correct ISO strings to model object.
  • Allows to use Numeric values, treating them as number of seconds (as some calculations with Time objects returns not durations but floats)

Example:

create_table :events do |t|
  t.string   :name
  t.interval :duration
end

Event.create!(name: 'Rock Fest', duration: 2.days)
Event.last.duration # => 2 days
Event.last.duration.iso8601 # => "P2D"

I've proposed this in Rails-core Google Group here: https://groups.google.com/forum/#!topic/rubyonrails-core/zcscu1p4ucA

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could extract this implementation (and the regexp constants) to a standalone PostgreSQLIntervalParser

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.

It was extracted into #16917 and merged a long, long time ago. For some reason this thread wasn't marked as stale.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Guessing the interval output format every time is expensive.

How about checking intervalstyle to see what output to expect? http://www.postgresql.org/docs/9.4/static/datatype-datetime.html#DATATYPE-INTERVAL-OUTPUT

Or setting intervalstyle to iso8601 when we connect.

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.

Setting intervalstyle is much better idea, this can be achieved on connecting issuing command SET intervalstyle = iso_8601; (seems like it take effect on entire session until disconnect).
Where this command's issue should be placed?

@Envek

Envek commented Sep 15, 2014

Copy link
Copy Markdown
Contributor Author

Changed implementation to set output format to ISO 8601 on connect. Removed all stuff that became unnecessary.

@seuros seuros added this to the 5.0.0 milestone Sep 16, 2014
@ollym

ollym commented Dec 6, 2014

Copy link
Copy Markdown
Contributor

I wish this could make it into 4.2, I use interval columns regularly

@Envek

Envek commented Dec 19, 2014

Copy link
Copy Markdown
Contributor Author

@ollym This PR isn't backward compatible and would not be merged in 4.x
But today I've updated my app that uses intervals to rails 4.2 and during upgrade have extracted this pull request changes into initializer, you can grab it here: https://gist.github.com/Envek/7077bfc36b17233f60ad#file-pg_interval_support_4_2-rb
Hope it helps.

@ollym

ollym commented Dec 19, 2014

Copy link
Copy Markdown
Contributor

@Envek amazing work. Thanks!

Right now I'm storing my interval columns as strings. What steps do you recommend for upgrading to using native interval column types using this patch?

Also any chance you might turn it into a gem?

@Envek

Envek commented Dec 19, 2014

Copy link
Copy Markdown
Contributor Author

@ollym if your interval columns are indeed have interval type in database your need only to insert this initializer in app, run rake db:schema:dump to update db/schema.rb and restart server.

But you will be faced with another problem: How to work with durations between HTML, JS and Rails app. ISO 8601 Durations support is still inconsistent and requires quite a lot of effort to organize interchange between backend and frontend.

Currently, as I'm need short durations in my app (hours) I'm use usual <input type="value"> tags in HTML and convert ActiveSupport::Duration's to strings like HH:mm:ss and vice versa.

@ollym

ollym commented Dec 19, 2014

Copy link
Copy Markdown
Contributor

@Envek what's wrong with the ISO8601 duration specification? That's the format I'm storing them in the database at the moment (as strings), and that's the format they're being sent to the API (my application).

@Envek

Envek commented Dec 19, 2014

Copy link
Copy Markdown
Contributor Author

Everything is fine with specification, but implementation on browser side (js libraries) is still weak and inconsistent.

And it's up to you to handle values coming from clients — string values are currently not parsed and passed to database as is:

Event.new(duration: "PT5H10M") # => #<Event:0x007fcfe6358a78 id: nil, duration: "PT5H10M">
Event.new(duration: ActiveSupport::Duration.parse("PT5H10M")) # => #<Event:0x007fcfe6358a78 id: nil, duration: 5 hours and 10 minutes>

If you know better approach to handle values from scary real world — please tell it here.

@ollym

ollym commented Dec 20, 2014

Copy link
Copy Markdown
Contributor

@Envek I would type cast value from the user as well as from the database. I assume this will involve creating a new type here:

https://github.com/rails/rails/tree/master/activerecord/lib/active_record/type

And then raising an exception if the format is invalid.

@Envek

Envek commented Jan 12, 2015

Copy link
Copy Markdown
Contributor Author

Implemented type_cast_from_user method in activerecord/lib/active_record/connection_adapters/postgresql/oid/interval.rb
Updated a gist initializer for 4.2 accordingly.

@voltechs

Copy link
Copy Markdown

@Envek which gist did you update? Can't seem to get the 4.2 initializer (you posted earlier) working...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Unfortunately this is a breaking change, so we can't actually do this without a deprecation cycle. We should continue to treat it as a string and emit a warning, since w/ the attributes API you can now specify manually in the mean time.

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.

Can you point me on some example how to do that (deprecation warning and some kind of switch to enable this feature immediately)?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Basically, do this:

m.register_type 'interval' do |*args, sql_type|
  unless ActiveRecord::Base.real_interval_types
    ActiveSupport::Deprecation.warn(<<-MSG.squish)
      blah blah blah deprecated
    MSG
    m.lookup(varchar, *args)
  else
    # what you have now
  end
end

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.

@sgrif Pushed deprecation warning in bc366e1, is it good for you?

@Envek

Envek commented Oct 1, 2015

Copy link
Copy Markdown
Contributor Author

@voltechs I have tested initializer today in 4.2.4 app, it's working. Here it's current version: https://gist.githubusercontent.com/Envek/7077bfc36b17233f60ad/raw/25d12443c0fdf0dccf0f51275688c1e0264c55ec/pg_interval_support_4_2.rb

If you still can't get it working, please contact me directly, as this conversation is for pull request related staff only. Thanks.

@sgrif

sgrif commented Nov 2, 2015

Copy link
Copy Markdown
Contributor

@Envek are you still interested in working on this? It'll need some more work to be mergeable into master.

@Envek

Envek commented Nov 3, 2015

Copy link
Copy Markdown
Contributor Author

@sgrif sure I still interested in all my PRs. Will add deprecation warning tomorrow.

Please note that this PR is based on top of #16917, so it should be merged first (I have split ActiveSupport and ActiveRecord stuff on separate PRs). Could you please take a look on it? I will do my best to finish both these PRs. Let's merge them! 😄

@ollym

ollym commented Nov 3, 2015

Copy link
Copy Markdown
Contributor

This is really important for me too, have a load of hacks in our code base that's keeping this together.

@ollym

ollym commented Nov 4, 2015

Copy link
Copy Markdown
Contributor

@Envek I highly recommend you check out the excellent work @jeremyevans is has done with the PG interval column within sequel here:
https://github.com/jeremyevans/sequel/blob/master/lib/sequel/extensions/pg_interval.rb

It even contains a full PostgreSQL Interval parser.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do we expect values other than a string or nil here? I'd rather not let those slip through. What do you think of changing to this instead?

def type_cast_from_database(value)
  return if value.nil?
  ::ActiveSupport::Duration.parse(value)
end

@rafaelfranca rafaelfranca removed this from the 5.0.0 [temp] milestone Apr 5, 2016
@Envek

Envek commented Apr 19, 2016

Copy link
Copy Markdown
Contributor Author

@sgrif #16917 has landed to the master branch and that's a good time to ressurect this pull request!

I've applied your notes, rebased on top of current master (more than 10 000 commits forward!) and changed implementation to match current ActiveRecord.

Please review again.

@marnen

marnen commented Jul 19, 2019

Copy link
Copy Markdown

I’d like to get interval support into Rails. How can I help get this pull request ready to merge?

@rails-bot

rails-bot Bot commented Dec 17, 2019

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
Thank you for your contributions.

@rails-bot rails-bot Bot added the stale label Dec 17, 2019
@marnen

marnen commented Dec 17, 2019

Copy link
Copy Markdown

It would still be nice to get this merged (once conflicts are resolved). This is a fairly important outstanding issue, so I don't really want the bots to close it.

@rails-bot rails-bot Bot removed the stale label Dec 17, 2019
@rafaelfranca

Copy link
Copy Markdown
Member

We will need a volunteer to resolve the conflicts and push the PR to the finish line, otherwise in 3 months the bot will mark the PR as stale again and we'll have to close.

@marnen

marnen commented Dec 18, 2019 •

Copy link
Copy Markdown

@rafaelfranca Now that you’ve clarified that, perhaps we stand a better chance of having it happen. :) (I might give it a try, but I’m already overcommitted, so I may not get to it soon...)

@voltechs

voltechs commented Dec 18, 2019 •

Copy link
Copy Markdown

It seems as though we need some dedicated support/eyes from the internal rails core team. I'm sensing rebase fatigue from the contributors here. Feels a little tone-deaf to doom this PR to the dustbin simply because there hasn't been a lot of support from the merge guardians. Is anyone prepared to review/accept this PR if contributors step up? Nobody likes wasting other people's time, let alone their own.

Thanks for stepping up, @marnen. I too am considering helping with this, but I'm also fairly overcommitted. I at least wanted to chime in and refresh my support (for what little it's worth) for this.

@marnen

marnen commented Dec 18, 2019

Copy link
Copy Markdown

@voltechs I agree. Note that I'm trying not to have to step up, first because I don't actually have time, and second because I'm putting a little more effort into crashtech/torque-postgresql#41 , which sort of covers the same ground.

But I do need this functionality in my Rails applications, and so I will ultimately attempt to deal with this if no one with more time (and more skill hacking ActiveRecord!) comes forward to do it.

@rails-bot rails-bot Bot added the docs label Jan 20, 2020
@Envek

Envek commented Jan 20, 2020

Copy link
Copy Markdown
Contributor Author

I have refreshed this pull request. Can someone review it again? @rafaelfranca, or can you maybe recommend someone to ask for a review?

Due to many merge conflicts, I had to squash all commits (that addressed previous reviews) into one, or it was seemed to be impossible to resolve all the conflicts. However, none of the conflicts required significant changes, so in reality, this pull request stayed mostly the same. I even restored some tests that I deleted earlier. And, sure, I bumped version numbers in deprecation warning and changelog.

Thanks everyone for your support comments – they helped me not to forget about this change, and I returned to it as soon as there was a spare minute.

@Envek

Envek commented Jan 23, 2020

Copy link
Copy Markdown
Contributor Author

Updated gist with initializers for adding support for interval data type into existing applications. Added initializer for both Rails 5.2 and 6.0: https://gist.github.com/Envek/7077bfc36b17233f60ad#file-pg_interval_support_6_0-rb

@AgentAntelope

Copy link
Copy Markdown

Hey there, me and @h-lame were looking at using this and found that when using the gist example, we needed to add a little more code to support schema dumping for default values. We added:

          def type_cast_for_schema(value)
            serialize(value).inspect
          end

to ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Interval in order to support this. Hope this helps get this in! Would definitely like to see this support in core Rails.

@Envek

Envek commented Feb 1, 2020

Copy link
Copy Markdown
Contributor Author

@AgentAntelope, nice catch, thank you! Added method from you to the datatype along with a test case.

@rails-bot

rails-bot Bot commented May 1, 2020

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
Thank you for your contributions.

@rails-bot rails-bot Bot added the stale label May 1, 2020
@marnen

marnen commented May 1, 2020

Copy link
Copy Markdown

Ongoing issue, should still be open.

@rails-bot

rails-bot Bot commented Sep 18, 2020

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
Thank you for your contributions.

@rails-bot rails-bot Bot added the stale label Sep 18, 2020
@jeremy jeremy added this to the 6.1.0 milestone Sep 18, 2020
@rails-bot rails-bot Bot removed the stale label Sep 18, 2020
@jeremy

jeremy commented Sep 18, 2020

Copy link
Copy Markdown
Member

Let's get this in. This effort is old enough to be entering grade school. Thank you for your patience & persistence @Envek.

Add support for PostgreSQL `interval` data type with conversion to
`ActiveSupport::Duration` when loading records from database and
serialization to ISO 8601 formatted duration string on save.
Add support to define a column in migrations and get it in a schema dump.
Optional column precision is supported.

To use this in 6.1, you need to place the next string to your model file:

    attribute :duration, :interval

To keep old behavior until 6.2 is released:

    attribute :duration, :string
@Envek

Envek commented Sep 21, 2020

Copy link
Copy Markdown
Contributor Author

Let's get this in.

This is fantastic! 🥳 Thank you!

I rebased PR on top of current master branch, fixed conflicts, checked that Rails version in deprecation warning is up to date. Just in case 😉

@jeremy

jeremy commented Sep 30, 2020

Copy link
Copy Markdown
Member

Merged @ 0475215

@jeremy jeremy closed this Sep 30, 2020
@Envek
Envek deleted the pg_interval_support branch February 26, 2021 12:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.