Class: Webhookdb::SavedView

Inherits:
Object
  • Object
show all
Defined in:
lib/webhookdb/saved_view.rb

Defined Under Namespace

Classes: InvalidQuery

Constant Summary collapse

DOCS_URL =
"https://docs.webhookdb.com/docs/integrating/saved-views.html"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create_or_replace(organization:, sql:, name:, **kw) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/webhookdb/saved_view.rb', line 20

def self.create_or_replace(organization:, sql:, name:, **kw)
  Webhookdb::DBAdapter.validate_identifier!(name, type: "view")
  self.db.transaction do
    sv = self.find_or_create_or_find(organization:, name:) do |new|
      new.sql = sql
    end
    sv.update(sql:, **kw)

    # Verify that the underlying query is readonly, by running it as a readonly user.
    if (_, errmsg = organization.execute_readonly_query_with_help(sql)) && errmsg.present?
      raise InvalidQuery, errmsg
    end

    # Create the view now that we've asserted it's readonly
    qname = Webhookdb::DBAdapter::PG.new.escape_identifier(name)
    organization.admin_connection do |conn|
      conn << "CREATE OR REPLACE VIEW #{qname} AS (#{sql})"
    end
    return sv
  end
end

.feature_roleObject



14
15
16
17
18
# File 'lib/webhookdb/saved_view.rb', line 14

def self.feature_role
  return Webhookdb.cached_get("saved-view-feature-role") do
    Webhookdb::Role.find_or_create_or_find(name: "saved_views")
  end
end

Instance Method Details

#before_destroyObject



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/webhookdb/saved_view.rb', line 42

def before_destroy
  raise Webhookdb::InvariantViolation, "#{self.inspect} name became invalid somehow" unless
    Webhookdb::DBAdapter.valid_identifier?(self.name)
  if self.organization.admin_connection_url_raw.present?
    qname = Webhookdb::DBAdapter::PG.new.escape_identifier(self.name)
    self.organization.admin_connection do |conn|
      conn << "DROP VIEW IF EXISTS #{qname}"
    end
  end
  super
end