Method: SQL::Maker::Select#as_sql

Defined in:
lib/sql/maker/select.rb

#as_sqlObject



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
# File 'lib/sql/maker/select.rb', line 155

def as_sql
  sql = ''
  new_line = self.new_line
 
  unless self.select.empty?
    sql += self.prefix
    sql += 'DISTINCT ' if self.distinct
    sql += self.select.map {|col|
      as = self.select_map[col]
      col = col.respond_to?(:as_sql) ? col.as_sql : self._quote(col)
      next col if as.nil?
      as = as.respond_to?(:as_sql) ? as.as_sql : self._quote(as)
      if as && col =~ /(?:^|\.)#{Regexp.escape(as)}$/
        col
      else
        col + ' AS ' +  as
      end
    }.join(', ') + new_line
  end

  sql += 'FROM '

  ## Add any explicit JOIN statements before the non-joined tables.
  unless self.joins.empty?
    initial_table_written = 0
    self.joins.each do |j|
      table = j[:table]
      join  = j[:joins]
      table = self._add_index_hint(table); ## index hint handling
      sql += table if initial_table_written == 0
      initial_table_written += 1
      sql += ' ' + join[:type].upcase if join[:type]
      sql += ' JOIN ' + self._quote(join[:table])
      sql += ' ' + self._quote(join[:alias]) if join[:alias]

      if condition = join[:condition]
        if condition.is_a?(Array)
          sql += ' USING (' + condition.map {|e| self._quote(e) }.join(', ') + ')'
        elsif condition.is_a?(Hash)
          conds = []
          condition.keys.each do |key|
            conds += [self._quote(key) + ' = ' + self._quote(condition[key])]
          end
          sql += ' ON ' + conds.join(' AND ')
        else
          sql += ' ON ' + condition
        end
      end
    end
    sql += ', ' unless self.from.empty?
  end

  unless self.from.empty?
    sql += self.from.map {|e| self._add_index_hint(e[0], e[1]) }.join(', ')
  end

  sql += new_line
  sql += self.as_sql_where     if self.where

  sql += self.as_sql_group_by  if self.group_by
  sql += self.as_sql_having    if self.having
  sql += self.as_sql_order_by  if self.order_by

  sql += self.as_sql_limit     if self.limit

  sql += self.as_sql_for_update
  sql.gsub!(/#{new_line}+$/, '')

  @auto_bind ? bind_param(sql, self.bind) : sql
end