Class: MiniSql::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/mini_sql/builder.rb

Constant Summary collapse

PREDEFINED_SQL_LITERALS =
(literals1 | literals2).to_set
WHERE_SECTIONS =
[%i[where where_or], %i[where2 where2_or]]

Instance Method Summary collapse

Constructor Details

#initialize(connection, template) ⇒ Builder

Returns a new instance of Builder.



5
6
7
8
9
10
11
12
# File 'lib/mini_sql/builder.rb', line 5

def initialize(connection, template)
  @args = {}
  @sql = template
  @sections = {}
  @connection = connection
  @count_variables = 1
  @is_prepared = false
end

Instance Method Details

#count(field = '*') ⇒ Object



83
84
85
# File 'lib/mini_sql/builder.rb', line 83

def count(field = '*')
  dup.select("count(#{field})").query_single.first
end

#initialize_copy(_original_builder) ⇒ Object



14
15
16
17
# File 'lib/mini_sql/builder.rb', line 14

def initialize_copy(_original_builder)
  @args = @args.transform_values { |v| v.dup }
  @sections = @sections.transform_values { |v| v.dup }
end

#prepared(condition = true) ⇒ Object



73
74
75
76
77
# File 'lib/mini_sql/builder.rb', line 73

def prepared(condition = true)
  @is_prepared = condition

  self
end

#query_decorator(decorator, hash_args = nil) ⇒ Object



69
70
71
# File 'lib/mini_sql/builder.rb', line 69

def query_decorator(decorator, hash_args = nil)
  connection_switcher.query_decorator(decorator, parametrized_sql, union_parameters(hash_args))
end

#sql_literal(literals) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/mini_sql/builder.rb', line 51

def sql_literal(literals)
  literals.each do |name, part_sql|
    if PREDEFINED_SQL_LITERALS.include?(name)
      raise "/*#{name}*/ is predefined, use method `.#{name}` instead `sql_literal`"
    end
    @sections[name] = part_sql.respond_to?(:to_sql) ? part_sql.to_sql : part_sql
  end
  self
end

#to_sql(hash_args = nil) ⇒ Object



79
80
81
# File 'lib/mini_sql/builder.rb', line 79

def to_sql(hash_args = nil)
  @connection.param_encoder.encode(parametrized_sql, union_parameters(hash_args))
end