Class: Gitlab::SQL::Union

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/sql/union.rb

Overview

Class for building SQL UNION statements.

ORDER BYs are dropped from the relations as the final sort order is not guaranteed any way.

Example usage:

union = Gitlab::SQL::Union.new(user.personal_projects, user.projects)
sql   = union.to_sql

Project.where("id IN (#{sql})")

Instance Method Summary collapse

Constructor Details

#initialize(relations) ⇒ Union

Returns a new instance of Union


15
16
17
# File 'lib/gitlab/sql/union.rb', line 15

def initialize(relations)
  @relations = relations
end

Instance Method Details

#to_sqlObject


19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/gitlab/sql/union.rb', line 19

def to_sql
  # Some relations may include placeholders for prepared statements, these
  # aren't incremented properly when joining relations together this way.
  # By using "unprepared_statements" we remove the usage of placeholders
  # (thus fixing this problem), at a slight performance cost.
  fragments = ActiveRecord::Base.connection.unprepared_statement do
    @relations.map do |rel|
      rel.reorder(nil).to_sql
    end
  end

  fragments.join("\nUNION\n")
end