Class: Exwiw::QueryAstBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/exwiw/query_ast_builder.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table_name, table_by_name, dump_target, logger, allow_reverse: true) ⇒ QueryAstBuilder

Returns a new instance of QueryAstBuilder.



11
12
13
14
15
16
17
# File 'lib/exwiw/query_ast_builder.rb', line 11

def initialize(table_name, table_by_name, dump_target, logger, allow_reverse: true)
  @table_name = table_name
  @table_by_name = table_by_name
  @dump_target = dump_target
  @logger = logger
  @allow_reverse = allow_reverse
end

Instance Attribute Details

#dump_targetObject (readonly)

Returns the value of attribute dump_target.



9
10
11
# File 'lib/exwiw/query_ast_builder.rb', line 9

def dump_target
  @dump_target
end

#table_by_nameObject (readonly)

Returns the value of attribute table_by_name.



9
10
11
# File 'lib/exwiw/query_ast_builder.rb', line 9

def table_by_name
  @table_by_name
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



9
10
11
# File 'lib/exwiw/query_ast_builder.rb', line 9

def table_name
  @table_name
end

Class Method Details

.run(table_name, table_by_name, dump_target, logger, allow_reverse: true) ⇒ Object



5
6
7
# File 'lib/exwiw/query_ast_builder.rb', line 5

def self.run(table_name, table_by_name, dump_target, logger, allow_reverse: true)
  new(table_name, table_by_name, dump_target, logger, allow_reverse: allow_reverse).run
end

Instance Method Details

#runObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/exwiw/query_ast_builder.rb', line 19

def run
  table = table_by_name.fetch(table_name)

  where_clauses = build_where_clauses(table, dump_target)
  join_clauses = build_join_clauses(table, table_by_name, dump_target)

  # Reverse / "referenced_by" extraction. A table with no belongs_to path to
  # the dump target produces no where/join clauses and would otherwise dump
  # every row (see the "no relation -> dump all" case). If an extractable
  # child table references it via a foreign key (e.g. active_storage_blobs is
  # referenced by active_storage_attachments.blob_id), constrain it to just
  # the referenced ids instead. Disabled (@allow_reverse=false) while building
  # a child's subquery, so this never recurses.
  if @allow_reverse && table.name != dump_target.table_name &&
     where_clauses.empty? && join_clauses.empty?
    reverse_clause = build_referenced_by_clause(table)
    where_clauses.push(reverse_clause) if reverse_clause
  end

  QueryAst::Select.new.tap do |ast|
    ast.from(table.name)
    if table.rails_managed?
      ast.select_all!
    else
      ast.select(table.columns)
    end
    join_clauses.each { |join_clause| ast.join(join_clause) }
    where_clauses.each { |where_clause| ast.where(where_clause) }
  end
end