-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathsqlserver.rb
414 lines (350 loc) · 13.1 KB
/
sqlserver.rb
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# frozen_string_literal: true
module Arel
module Visitors
class SQLServer < Arel::Visitors::ToSql
OFFSET = " OFFSET "
ROWS = " ROWS"
FETCH = " FETCH NEXT "
FETCH0 = " FETCH FIRST (SELECT 0) "
ROWS_ONLY = " ROWS ONLY"
ONE_AS_ONE = ActiveRecord::FinderMethods::ONE_AS_ONE
private
# SQLServer ToSql/Visitor (Overrides)
BIND_BLOCK = proc { |i| "@#{i - 1}" }
private_constant :BIND_BLOCK
def bind_block; BIND_BLOCK; end
def visit_Arel_Nodes_Bin(o, collector)
visit o.expr, collector
collector << " #{ActiveRecord::ConnectionAdapters::SQLServerAdapter.cs_equality_operator} "
end
def visit_Arel_Nodes_Concat(o, collector)
visit o.left, collector
collector << " + "
visit o.right, collector
end
def visit_Arel_Nodes_UpdateStatement(o, collector)
if has_join_and_composite_primary_key?(o)
update_statement_using_join(o, collector)
else
o.limit = Nodes::Limit.new(9_223_372_036_854_775_807) if o.orders.any? && o.limit.nil?
super
end
end
def visit_Arel_Nodes_DeleteStatement(o, collector)
if has_join_and_composite_primary_key?(o)
delete_statement_using_join(o, collector)
else
super
end
end
def has_join_and_composite_primary_key?(o)
has_join_sources?(o) && o.relation.left.instance_variable_get(:@klass).composite_primary_key?
end
def delete_statement_using_join(o, collector)
collector.retryable = false
collector << "DELETE "
visit o.relation.left, collector
collector << " FROM "
visit o.relation, collector
collect_nodes_for o.wheres, collector, " WHERE ", " AND "
end
def update_statement_using_join(o, collector)
collector.retryable = false
collector << "UPDATE "
visit o.relation.left, collector
collect_nodes_for o.values, collector, " SET "
collector << " FROM "
visit o.relation, collector
collect_nodes_for o.wheres, collector, " WHERE ", " AND "
end
def visit_Arel_Nodes_Lock(o, collector)
o.expr = Arel.sql("WITH(UPDLOCK)") if o.expr.to_s =~ /FOR UPDATE/
collector << " "
visit o.expr, collector
end
def visit_Arel_Nodes_Offset(o, collector)
collector << OFFSET
visit o.expr, collector
collector << ROWS
end
def visit_Arel_Nodes_Limit(o, collector)
if node_value(o) == 0
collector << FETCH0
collector << ROWS_ONLY
else
collector << FETCH
visit o.expr, collector
collector << ROWS_ONLY
end
end
def visit_Arel_Nodes_Grouping(o, collector)
remove_invalid_ordering_from_select_statement(o.expr)
super
end
def visit_Arel_Nodes_HomogeneousIn(o, collector)
collector.preparable = false
visit o.left, collector
if o.type == :in
collector << " IN ("
else
collector << " NOT IN ("
end
values = o.casted_values
# Monkey-patch start.
column_name = o.attribute.name
column_type = o.attribute.relation.type_for_attribute(column_name)
column_type = column_type.cast_type if column_type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType) # Use cast_type on encrypted attributes. Don't encrypt them again
if values.empty?
collector << @connection.quote(nil)
elsif @connection.prepared_statements && !column_type.serialized?
# Add query attribute bindings rather than just values.
attrs = values.map { |value| ActiveRecord::Relation::QueryAttribute.new(column_name, value, column_type) }
collector.add_binds(attrs, &bind_block)
else
collector.add_binds(values, o.proc_for_binds, &bind_block)
end
# Monkey-patch end.
collector << ")"
end
def visit_Arel_Nodes_SelectStatement(o, collector)
@select_statement = o
optimizer_hints = nil
distinct_One_As_One_Is_So_Not_Fetch o
if o.with
collector = visit o.with, collector
collector << " "
end
collector = o.cores.inject(collector) do |collect, core|
optimizer_hints = core.optimizer_hints if core.optimizer_hints
visit_Arel_Nodes_SelectCore(core, collect)
end
collector = visit_Orders_And_Let_Fetch_Happen o, collector
collector = visit_Make_Fetch_Happen o, collector
collector = maybe_visit optimizer_hints, collector
collector
ensure
@select_statement = nil
end
def visit_Arel_Nodes_OptimizerHints(o, collector)
hints = o.expr.map { |v| sanitize_as_option_clause(v) }.join(", ")
collector << "OPTION (#{hints})"
end
def visit_Arel_Table(o, collector)
# Apparently, o.engine.connection can actually be a different adapter
# than sqlserver. Can be removed if fixed in ActiveRecord. See:
# github.com/rails-sqlserver/activerecord-sqlserver-adapter/issues/450
table_name =
begin
o.class.engine.with_connection do |connection|
if connection.respond_to?(:sqlserver?) && connection.database_prefix_remote_server?
remote_server_table_name(o)
else
quote_table_name(o.name)
end
end
rescue Exception
quote_table_name(o.name)
end
if o.table_alias
collector << "#{table_name} #{quote_table_name o.table_alias}"
else
collector << table_name
end
end
def visit_Arel_Nodes_JoinSource(o, collector)
if o.left
collector = visit o.left, collector
collector = visit_Arel_Nodes_SelectStatement_SQLServer_Lock collector
end
if o.right.any?
collector << " " if o.left
collector = inject_join o.right, collector, " "
end
collector
end
def visit_Arel_Nodes_InnerJoin(o, collector)
if o.left.is_a?(Arel::Nodes::As) && o.left.left.is_a?(Arel::Nodes::Lateral)
collector << "CROSS "
visit o.left, collector
else
collector << "INNER JOIN "
collector = visit o.left, collector
collector = visit_Arel_Nodes_SelectStatement_SQLServer_Lock collector, space: true
if o.right
collector << " "
visit(o.right, collector)
else
collector
end
end
end
def visit_Arel_Nodes_OuterJoin(o, collector)
if o.left.is_a?(Arel::Nodes::As) && o.left.left.is_a?(Arel::Nodes::Lateral)
collector << "OUTER "
visit o.left, collector
else
collector << "LEFT OUTER JOIN "
collector = visit o.left, collector
collector = visit_Arel_Nodes_SelectStatement_SQLServer_Lock collector, space: true
collector << " "
visit o.right, collector
end
end
def visit_Arel_Nodes_In(o, collector)
if Array === o.right
o.right.each { |node| remove_invalid_ordering_from_select_statement(node) }
else
remove_invalid_ordering_from_select_statement(o.right)
end
super
end
def collect_optimizer_hints(o, collector)
collector
end
def visit_Arel_Nodes_WithRecursive(o, collector)
collector << "WITH "
collect_ctes(o.children, collector)
end
# SQLServer ToSql/Visitor (Additions)
def visit_Arel_Nodes_SelectStatement_SQLServer_Lock(collector, options = {})
if select_statement_lock?
collector = visit @select_statement.lock, collector
collector << " " if options[:space]
end
collector
end
def visit_Orders_And_Let_Fetch_Happen(o, collector)
make_Fetch_Possible_And_Deterministic o
if o.orders.any?
collector << " ORDER BY "
len = o.orders.length - 1
o.orders.each_with_index { |x, i|
collector = visit(x, collector)
collector << ", " unless len == i
}
end
collector
end
def visit_Make_Fetch_Happen(o, collector)
o.offset = Nodes::Offset.new(0) if o.limit && !o.offset
collector = visit o.offset, collector if o.offset
collector = visit o.limit, collector if o.limit
collector
end
def visit_Arel_Nodes_Lateral(o, collector)
collector << "APPLY"
collector << " "
if o.expr.is_a?(Arel::Nodes::SelectStatement)
collector << "("
visit(o.expr, collector)
collector << ")"
else
visit(o.expr, collector)
end
end
# SQLServer Helpers
def node_value(node)
return nil unless node
case node.expr
when NilClass then nil
when Numeric then node.expr
when Arel::Nodes::Unary then node.expr.expr
end
end
def select_statement_lock?
@select_statement && @select_statement.lock
end
# FETCH cannot be used without an order. If an order is not given then try to use the projections for the ordering.
# If no suitable projection are present then fallback to using the primary key of the table.
def make_Fetch_Possible_And_Deterministic(o)
return if o.limit.nil? && o.offset.nil?
return if o.orders.any?
if (projection = projection_to_order_by_for_fetch(o))
o.orders = [projection.asc]
else
pk = primary_Key_From_Table(table_From_Statement(o))
o.orders = [pk.asc] if pk
end
end
# Find the first projection or part of projection that can be used for ordering. Cannot use
# projections with '*' or '1 AS one' in them.
def projection_to_order_by_for_fetch(o)
o.cores.first.projections.each do |projection|
case projection
when Arel::Attributes::Attribute
return projection unless projection.name.include?("*")
when Arel::Nodes::SqlLiteral
projection.split(",").each do |p|
next if p.match?(/#{Regexp.escape(ONE_AS_ONE)}/i) || p.include?("*")
return Arel::Nodes::SqlLiteral.new(remove_last_AS_from_projection(p))
end
end
end
nil
end
# Remove last AS from projection. Example projections:
# - 'name'
# - 'name AS first_name'
# - 'AVG(accounts.credit_limit AS DECIMAL) AS avg_credit_limit)'
def remove_last_AS_from_projection(projection)
parts = projection.split(/\sAS\s/i)
parts.pop if parts.length > 1
parts.join(" AS ")
end
def distinct_One_As_One_Is_So_Not_Fetch(o)
core = o.cores.first
distinct = Nodes::Distinct === core.set_quantifier
one_as_one = core.projections.all? { |x| x == ONE_AS_ONE }
limit_one = [nil, 0, 1].include? node_value(o.limit)
if distinct && one_as_one && limit_one && !o.offset
core.projections = [Arel.sql("TOP(1) 1 AS [one]")]
o.limit = nil
end
end
def table_From_Statement(o)
core = o.cores.first
if Arel::Table === core.from
core.from
elsif Arel::Nodes::SqlLiteral === core.from
Arel::Table.new(core.from)
elsif Arel::Nodes::JoinSource === core.source
Arel::Nodes::SqlLiteral === core.source.left ? Arel::Table.new(core.source.left, @engine) : core.source.left.left
end
end
def primary_Key_From_Table(t)
return unless t
primary_keys = @connection.schema_cache.primary_keys(t.name)
column_name = nil
case primary_keys
when NilClass
column_name = @connection.schema_cache.columns_hash(t.name).first.try(:second).try(:name)
when String
column_name = primary_keys
when Array
candidate_columns = @connection.schema_cache.columns_hash(t.name).slice(*primary_keys).values
candidate_column = candidate_columns.find(&:is_identity?)
candidate_column ||= candidate_columns.first
column_name = candidate_column.try(:name)
end
column_name ? t[column_name] : nil
end
def remote_server_table_name(o)
o.class.engine.with_connection do |connection|
ActiveRecord::ConnectionAdapters::SQLServer::Utils.extract_identifiers(
"#{connection.database_prefix}#{o.name}"
).quoted
end
end
# Need to remove ordering from sub-queries unless TOP/OFFSET also used. Otherwise, SQLServer
# returns error "The ORDER BY clause is invalid in views, inline functions, derived tables,
# sub-queries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified."
def remove_invalid_ordering_from_select_statement(node)
return unless Arel::Nodes::SelectStatement === node
node.orders = [] unless node.offset || node.limit
end
def sanitize_as_option_clause(value)
value.gsub(%r{OPTION \s* \( (.+) \)}xi, "\\1")
end
end
end
end