-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathjoin.cr
More file actions
135 lines (112 loc) · 2.77 KB
/
Copy pathjoin.cr
File metadata and controls
135 lines (112 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
require "wordsmith"
module Avram::Join
abstract class SqlClause
getter from : TableName
def initialize(
@from : TableName,
@to : TableName,
@primary_key : Symbol? = nil,
@foreign_key : Symbol? = nil,
@comparison : String? = "=",
@using : Array(Symbol) = [] of Symbol,
@alias_to : TableName? = nil
)
end
abstract def join_type : String
def to_sql : String
String.build do |io|
io << "#{join_type} JOIN "
@to.to_s(io)
if @alias_to
io << " AS #{@alias_to}"
end
if !@using.empty?
io << " USING (#{@using.join(", ")})"
else
io << " ON #{from_column} #{@comparison} #{to_column}"
end
end
end
def to : TableName
@alias_to || @to
end
def from_column : String
"#{@from}.#{@primary_key || "id"}"
end
def to_column : String
"#{to}.#{@foreign_key || default_foreign_key}"
end
def default_foreign_key : String
Wordsmith::Inflector.singularize(@from) + "_id"
end
def clone : self
self
end
end
class Inner < SqlClause
def join_type : String
"INNER"
end
end
class Left < SqlClause
def join_type : String
"LEFT"
end
end
class Right < SqlClause
def join_type : String
"RIGHT"
end
end
class Full < SqlClause
def join_type : String
"FULL"
end
end
class Raw
@clause : String
def self.new(statement : String, *bind_vars)
new(statement, args: bind_vars.to_a)
end
def initialize(statement : String, *, args bind_vars : Array)
ensure_enough_bind_variables_for!(statement, bind_vars)
@clause = build_clause(statement, bind_vars)
end
def prepare(placeholder_supplier : Proc(String)) : String
@clause
end
def to_sql : String
@clause
end
def clone : self
self
end
private def ensure_enough_bind_variables_for!(statement, bind_vars)
bindings = statement.chars.select(&.== '?')
if bindings.size != bind_vars.size
raise "wrong number of bind variables (#{bind_vars.size} for #{bindings.size}) in #{statement}"
end
end
private def build_clause(statement, bind_vars)
bind_vars.each do |arg|
encoded_arg = prepare_for_execution(arg)
statement = statement.sub('?', encoded_arg)
end
statement
end
private def prepare_for_execution(value)
if value.is_a?(Array)
"'#{PQ::Param.encode_array(value)}'"
else
escape_if_needed(value)
end
end
private def escape_if_needed(value)
if value.is_a?(String) || value.is_a?(Slice(UInt8))
PG::EscapeHelper.escape_literal(value)
else
value
end
end
end
end