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
|
# File 'lib/activerecord-multi-tenant/query_rewriter.rb', line 290
def build_arel(*args)
arel = build_arel_orig(*args)
unless MultiTenant.with_write_only_mode_enabled?
visitor = MultiTenant::ArelTenantVisitor.new(arel)
visitor.contexts.each do |context|
node = context.arel_node
context.unhandled_relations.each do |relation|
model = MultiTenant.multi_tenant_model_for_table(MultiTenant::TableNode.table_name(relation.arel_table))
if MultiTenant.current_tenant_id
enforcement_clause = MultiTenant::TenantEnforcementClause.new(relation.arel_table[model.partition_key])
case node
when Arel::Nodes::Join node.right.expr = node.right.expr.and(enforcement_clause)
when Arel::Nodes::SelectCore
if node.wheres.empty?
node.wheres = [enforcement_clause]
elsif node.wheres[0].is_a?(Arel::Nodes::And)
node.wheres[0].children << enforcement_clause
else
node.wheres[0] = enforcement_clause.and(node.wheres[0])
end
else
raise 'UnknownContext'
end
end
next unless node.is_a?(Arel::Nodes::SelectCore) || node.is_a?(Arel::Nodes::Join)
node_list = if node.is_a? Arel::Nodes::Join
[node]
else
node.source.right
end
node_list.select { |n| n.is_a? Arel::Nodes::Join }.each do |node_join|
next unless node_join.right
relation_right, relation_left = relations_from_node_join(node_join)
next unless relation_right && relation_left
model_right = MultiTenant.multi_tenant_model_for_table(MultiTenant::TableNode.table_name(relation_left))
model_left = MultiTenant.multi_tenant_model_for_table(MultiTenant::TableNode.table_name(relation_right))
next unless model_right && model_left
join_enforcement_clause = MultiTenant::TenantJoinEnforcementClause.new(
relation_right[model_right.partition_key], relation_left
)
node_join.right.expr = node_join.right.expr.and(join_enforcement_clause)
end
end
end
end
arel
end
|