Class: Json2sql::WhereModel

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

Overview

Builds a SQL WHERE clause from a Hash describing the conditions.

Input structure mirrors the JSON format used in the C++ backend:

{
  "and" => {
    "name"   => "john",           # implicit LIKE '%john%'
    "age"    => 30,               # implicit equality
    "status" => { "in" => [1,2] },
    "score"  => { ">=" => 4.5 },
    "col"    => { "null" => true },  # IS NULL / IS NOT NULL
    "ref"    => { "=" => "$.table.col" }  # column reference
  },
  "or" => { ... }
}

Supported operators: = < > <= >= != <>

in  !in  like  !like

String pseudo-actions: contains (LIKE %v%), first (LIKE v%), last (LIKE %v)

Instance Method Summary collapse

Constructor Details

#initialize(sql, table, relation) ⇒ WhereModel

Returns a new instance of WhereModel.



25
26
27
28
29
30
31
32
# File 'lib/json2sql/where_model.rb', line 25

def initialize(sql, table, relation)

  @sql = sql

  @table = table.to_s

  @relation = relation
end

Instance Method Details

#build(params) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/json2sql/where_model.rb', line 34

def build(params)

  has_relation  = @relation.kind != WhereRelation::NONE

  has_where_and = params["and"].is_a?(Hash)

  has_where_or  = params["or"].is_a?(Hash)

  return unless has_relation || has_where_and || has_where_or

  @sql << " WHERE "

  if has_relation

    @relation.build_table_relation(@sql, @table)

    @sql << " AND " if has_where_and || has_where_or
  end

  if has_where_and

    build_column_group(params["and"], " AND ")

    return
  end

  if has_where_or

    build_column_group(params["or"], " OR ")
  end
end