Class: PgCanary::Rules::QueryContext::Scope

Inherits:
Object
  • Object
show all
Includes:
PgQuerySupport
Defined in:
lib/pg_canary/rules/query_context.rb

Overview

One SELECT scope (top-level statement, CTE, subquery, ...) with its own FROM-clause alias resolution.

Constant Summary

Constants included from PgQuerySupport

PgQuerySupport::COMPARISON_OPS

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stmt) ⇒ Scope

Returns a new instance of Scope.



18
19
20
21
22
# File 'lib/pg_canary/rules/query_context.rb', line 18

def initialize(stmt)
  @stmt = stmt
  @aliases = {}
  collect_aliases(stmt.from_clause)
end

Instance Attribute Details

#aliasesObject (readonly)

Returns the value of attribute aliases.



16
17
18
# File 'lib/pg_canary/rules/query_context.rb', line 16

def aliases
  @aliases
end

#stmtObject (readonly)

Returns the value of attribute stmt.



16
17
18
# File 'lib/pg_canary/rules/query_context.rb', line 16

def stmt
  @stmt
end

Instance Method Details

#limited?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/pg_canary/rules/query_context.rb', line 33

def limited?
  !stmt.limit_count.nil?
end

#resolve(column_ref) ⇒ Object

Resolves a ColumnRef to [table, column]. Returns nil when the ref cannot be attributed to a real table unambiguously (unknown alias, subquery output, multiple candidate tables for an unqualified ref).



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/pg_canary/rules/query_context.rb', line 45

def resolve(column_ref)
  fields = column_ref_fields(column_ref)
  return nil if fields.nil? || fields.empty?

  column = fields.last
  if fields.length >= 2
    table = @aliases[fields[-2]]
    table ? [table, column] : nil
  else
    tables.length == 1 ? [tables.first, column] : nil
  end
end

#sort_itemsObject

=> [PgQuery::SortBy]



29
30
31
# File 'lib/pg_canary/rules/query_context.rb', line 29

def sort_items
  stmt.sort_clause.map { |n| unwrap_node(n) }.grep(PgQuery::SortBy)
end

#tablesObject

Real table names referenced directly in this scope's FROM clause.



38
39
40
# File 'lib/pg_canary/rules/query_context.rb', line 38

def tables
  @aliases.values.compact.uniq
end

#where_clauseObject



24
25
26
# File 'lib/pg_canary/rules/query_context.rb', line 24

def where_clause
  stmt.where_clause
end