Class: MatViews::Services::CreateView

Inherits:
BaseService show all
Defined in:
lib/mat_views/services/create_view.rb

Overview

Service responsible for creating PostgreSQL materialised views.

The service validates the view definition, handles existence checks, executes ‘CREATE MATERIALIZED VIEW … WITH DATA`, and, when the refresh strategy is `:concurrent`, ensures a supporting UNIQUE index.

Options:

  • ‘force:` (Boolean, default: false) → drop and recreate if the view already exists

  • ‘row_count_strategy:` (Symbol, default: :none) → one of `:estimated`, `:exact`, or `:none or nil` to control row count reporting

Returns a MatViews::ServiceResponse

Examples:

Create a new matview (no force)

svc = MatViews::Services::CreateView.new(defn, **options)
response = svc.call
response.status # => :created or :skipped

Force recreate an existing matview

svc = MatViews::Services::CreateView.new(defn, force: true)
svc.call

via job, this is the typical usage and will create a run record in the DB

MatViews::Jobs::Adapter.enqueue(MatViews::Services::CreateViewJob, definition.id, **options)

See Also:

Constant Summary

Constants inherited from BaseService

BaseService::ALLOWED_ROW_STRATEGIES, BaseService::DEFAULT_NIL_STRATEGY, BaseService::DEFAULT_ROW_STRATEGY, BaseService::UNKNOWN_ROW_COUNT

Instance Attribute Summary collapse

Attributes inherited from BaseService

#definition, #request, #response, #row_count_strategy, #use_transaction

Instance Method Summary collapse

Methods inherited from BaseService

#call

Constructor Details

#initialize(definition, force: false, row_count_strategy: :estimated) ⇒ CreateView

Supports optional row count strategies:

  • ‘:estimated` → approximate, using `pg_class.reltuples`

  • ‘:exact` → accurate, using `COUNT(*)`

  • ‘nil` → skip row count

Parameters:

  • definition (MatViews::MatViewDefinition)
  • force (Boolean) (defaults to: false)

    Whether to drop+recreate an existing matview.

  • row_count_strategy (Symbol, nil) (defaults to: :estimated)

    one of ‘:estimated`, `:exact`, or `nil` (default: `:estimated`)



54
55
56
57
58
59
60
61
# File 'lib/mat_views/services/create_view.rb', line 54

def initialize(definition, force: false, row_count_strategy: :estimated)
  super(definition, row_count_strategy: row_count_strategy)
  @force = force
  # Transactions are disabled if unique_index_columns are present because
  # PostgreSQL does not allow creating a UNIQUE INDEX CONCURRENTLY inside a transaction block.
  # If a unique index is required (for concurrent refresh), we must avoid wrapping the operation in a transaction.
  @use_transaction = definition.unique_index_columns.none?
end

Instance Attribute Details

#forceBoolean (readonly)

Whether to force recreation (drop+create if exists).

Returns:

  • (Boolean)


43
44
45
# File 'lib/mat_views/services/create_view.rb', line 43

def force
  @force
end