Class: SqlQuery

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

Defined Under Namespace

Classes: Config

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_name, options = {}) ⇒ SqlQuery

Returns a new instance of SqlQuery.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/sql_query.rb', line 8

def initialize(file_name, options = {})
  unless file_name.is_a?(String) || file_name.is_a?(Symbol)
    raise ArgumentError, 'SQL file name should be String or Symbol'
  end

  @sql_filename = file_name
  @options = options
  @connection = options.try(:delete, :db_connection) ||
                self.class.config.adapter.connection
  prepare_variables
end

Instance Attribute Details

#config=(value) ⇒ Object (writeonly)

Sets the attribute config

Parameters:

  • value

    the value to set the attribute config to.



58
59
60
# File 'lib/sql_query.rb', line 58

def config=(value)
  @config = value
end

#connectionObject (readonly)

Returns the value of attribute connection.



6
7
8
# File 'lib/sql_query.rb', line 6

def connection
  @connection
end

Class Method Details

.configObject



59
60
61
# File 'lib/sql_query.rb', line 59

def self.config
  @config ||= Config.new
end

.configure {|config| ... } ⇒ Object

Yields:



63
64
65
# File 'lib/sql_query.rb', line 63

def self.configure
  yield(config)
end

Instance Method Details

#exec_query(prepare = true) ⇒ Object



31
32
33
34
# File 'lib/sql_query.rb', line 31

def exec_query(prepare = true)
  to_execute = prepare ? prepared_for_logs : sql
  connection.exec_query(to_execute).to_a
end

#execute(prepare = true) ⇒ Object



26
27
28
29
# File 'lib/sql_query.rb', line 26

def execute(prepare = true)
  to_execute = prepare ? prepared_for_logs : sql
  connection.execute(to_execute).entries
end

#explainObject



20
21
22
23
24
# File 'lib/sql_query.rb', line 20

def explain
  msg = "EXPLAIN for: \n#{sql}\n"
  msg += connection.explain(sql)
  pretty(msg)
end

#partial(partial_name, partial_options = {}) ⇒ Object



52
53
54
55
56
# File 'lib/sql_query.rb', line 52

def partial(partial_name, partial_options = {})
  path, file_name = split_to_path_and_name(partial_name)
  self.class.new("#{path}/_#{file_name}",
                 @options.merge(partial_options)).sql
end

#prepared_for_logsObject



48
49
50
# File 'lib/sql_query.rb', line 48

def prepared_for_logs
  sql.gsub(/(\n|\s)+/, ' ')
end

#pretty_sqlObject



40
41
42
# File 'lib/sql_query.rb', line 40

def pretty_sql
  pretty(sql.dup)
end

#quote(value) ⇒ Object



44
45
46
# File 'lib/sql_query.rb', line 44

def quote(value)
  connection.quote(value)
end

#sqlObject



36
37
38
# File 'lib/sql_query.rb', line 36

def sql
  @sql ||= ERB.new(File.read(file_path)).result(binding)
end