scenic icon indicating copy to clipboard operation
scenic copied to clipboard

Add method to return materialized view is populated or not

Open fujimura opened this issue 6 years ago • 1 comments

Added a method which return the view is populated or not.

REFRESH MATERIALIZED VIEW CONCURRENTLY doesn't work for a view which is not populated, even it has unique index. This method is useful to perform concurrent refresh if it's possible.

Real use case in Rails will be like this:

  • Database is loaded from structure.sql to run specs, but the view isn't populated yet so concurrent refresh is not possible. We want to fallback to normal(non-concurrent) refresh in this case.
  • After initial population, views are expected to be refreshed concurrently. It's possible because the view is already populated.

Our team is using a concern below to cope with the case. This pull request is extracted from this.

module MaterializedView
  extend ActiveSupport::Concern

  included do
    class << self
      def materialized_view_populated?
        connection.execute("SELECT relispopulated FROM pg_class WHERE relname = '#{table_name}'").first['relispopulated']
      end

      def refresh_materialized_view(concurrently = true)
        Scenic.database.refresh_materialized_view(table_name, concurrently: materialized_view_populated? && concurrently, cascade: false)
      end
    end
  end
end

fujimura avatar Jul 27 '18 09:07 fujimura

Although I haven't bumped into this problem myself, I think I was just lucky. This looks very useful, any chance it could get merged and released?

tomca32 avatar Oct 08 '18 04:10 tomca32

For whatever reason, I decided today is the day for this 5 year old pull request... I pushed a replacement PR here that is largely the same but resolves some style differences ands adds a populated? method to the model generator.

#396

derekprior avatar Sep 29 '23 21:09 derekprior