Class: QueryKit::DeleteQuery

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

Overview

DeleteQuery class for building SQL DELETE statements.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table = nil) ⇒ DeleteQuery

Initialize a new DeleteQuery instance.



9
10
11
12
13
# File 'lib/querykit/delete_query.rb', line 9

def initialize(table = nil)
  @table = table
  @wheres = []
  @bindings = []
end

Instance Attribute Details

#bindingsObject (readonly)

Returns the value of attribute bindings.



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

def bindings
  @bindings
end

#tableObject (readonly)

Returns the value of attribute table.



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

def table
  @table
end

#wheresObject (readonly)

Returns the value of attribute wheres.



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

def wheres
  @wheres
end

Instance Method Details

#from(table) ⇒ Object

Set the table to delete from.



16
17
18
19
# File 'lib/querykit/delete_query.rb', line 16

def from(table)
  @table = table
  self
end

#to_sObject

Return the SQL DELETE statement as a string.



50
51
52
# File 'lib/querykit/delete_query.rb', line 50

def to_s
  to_sql
end

#to_sqlObject

Generate the SQL DELETE statement.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/querykit/delete_query.rb', line 34

def to_sql
  raise "No table specified" unless @table

  sql = []
  sql << "DELETE FROM #{@table}"

  unless @wheres.empty?
    sql << "WHERE"
    where_clauses = @wheres.map { |w| "#{w[:column]} #{w[:operator]} ?" }
    sql << where_clauses.join(' AND ')
  end

  sql.join(' ')
end

#where(column, operator = nil, value = nil) ⇒ Object

Add a WHERE condition to the delete query.



22
23
24
25
26
27
28
29
30
31
# File 'lib/querykit/delete_query.rb', line 22

def where(column, operator = nil, value = nil)
  if value.nil? && !operator.nil?
    value = operator
    operator = '='
  end

  @wheres << { type: 'basic', column: column, operator: operator, value: value, boolean: 'AND' }
  @bindings << value
  self
end