Module: SearchCraft::Model::ClassMethods

Defined in:
lib/searchcraft/model.rb

Instance Method Summary collapse

Instance Method Details

#currently_refreshing?Boolean

Checks the database server to see if the materialized view is currently being refreshed

Returns:

  • (Boolean)


78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/searchcraft/model.rb', line 78

def currently_refreshing?
  # quoted_table_name is table_name, but with double quotes around each chunk
  # e.g. "schema"."table" or "table"
  quoted_table_name = Scenic.database.quote_table_name(table_name)
  dbname = ActiveRecord::Base.connection_db_config.database
  sql = <<~SQL
    SELECT EXISTS (
      SELECT 1
      FROM pg_stat_activity
      WHERE datname = '#{dbname}'
        AND query LIKE '%REFRESH MATERIALIZED VIEW #{quoted_table_name}%'
        AND pid <> pg_backend_pid()
    ) AS is_refresh_running;
  SQL

  warn "Checking if #{table_name} is currently being refreshed..." if SearchCraft.debug?
  if (result = ActiveRecord::Base.connection.execute(sql))
    result.first["is_refresh_running"]
  else
    false
  end
end

#populated?Boolean

Returns:

  • (Boolean)


69
70
71
# File 'lib/searchcraft/model.rb', line 69

def populated?
  Scenic.database.populated?(table_name)
end

#refresh!Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/searchcraft/model.rb', line 52

def refresh!
  refresh_concurrently = @refresh_concurrently && populated?
  unless Rails.env.test?
    if refresh_concurrently
      warn "Refreshing materialized view concurrently #{table_name}..."
    else
      warn "Refreshing materialized view #{table_name}..."
    end
  end

  Scenic.database.refresh_materialized_view(table_name, concurrently: refresh_concurrently, cascade: false)
rescue ActiveRecord::StatementInvalid
  # If populated? lies and returns true; then might get error:
  # PG::FeatureNotSupported: ERROR:  CONCURRENTLY cannot be used when the materialized view is not populated (ActiveRecord::StatementInvalid)
  Scenic.database.refresh_materialized_view(table_name, concurrently: false, cascade: false)
end

#refresh_concurrently=(value) ⇒ Object



73
74
75
# File 'lib/searchcraft/model.rb', line 73

def refresh_concurrently=(value)
  @refresh_concurrently = value
end