'Creates the SQL for this query. Returns the SQL string and list of
parameters.
If \'with_limits\' is False, any limit/offset information is not included
in the query.'

def as_sql(self, with_limits=True, with_col_aliases=False):

    if (with_limits and (self.query.low_mark == self.query.high_mark)):
        return ('', ())
    self.pre_sql_setup()
    self.refcounts_before = self.query.alias_refcount.copy()
    out_cols = self.get_columns(with_col_aliases)
    (ordering, ordering_group_by) = self.get_ordering()
    distinct_fields = self.get_distinct()
    (from_, f_params) = self.get_from_clause()
    qn = self.quote_name_unless_alias
    (where, w_params) = self.query.where.as_sql(qn=qn, connection=self.connection)
    (having, h_params) = self.query.having.as_sql(qn=qn, connection=self.connection)
    params = []
    for val in six.itervalues(self.query.extra_select):
        params.extend(val[1])
    result = ['SELECT']
    if self.query.distinct:
        result.append(self.connection.ops.distinct_sql(distinct_fields))
    result.append(',    '.join((out_cols + self.query.ordering_aliases)))
    result.append('FROM')
    result.extend(from_)
    params.extend(f_params)
    if where:
        result.append(('WHERE    %s' % where))
        params.extend(w_params)
    (grouping, gb_params) = self.get_grouping(ordering_group_by)
    if grouping:
        if distinct_fields:
            raise NotImplementedError('annotate()    +    distinct(fields)    not    implemented.')
        if (not ordering):
            ordering = self.connection.ops.force_no_ordering()
        result.append(('GROUP    BY    %s' % ',    '.join(grouping)))
        params.extend(gb_params)
    if having:
        result.append(('HAVING    %s' % having))
        params.extend(h_params)
    if ordering:
        result.append(('ORDER    BY    %s' % ',    '.join(ordering)))
    if with_limits:
        if (self.query.high_mark is not None):
            result.append(('LIMIT    %d' % (self.query.high_mark - self.query.low_mark)))
        if self.query.low_mark:
            if (self.query.high_mark is None):
                val = self.connection.ops.no_limit_value()
                if val:
                    result.append(('LIMIT    %d' % val))
            result.append(('OFFSET    %d' % self.query.low_mark))
    if (self.query.select_for_update and self.connection.features.has_select_for_update):
        nowait = self.query.select_for_update_nowait
        if (nowait and (not self.connection.features.has_select_for_update_nowait)):
            raise DatabaseError('NOWAIT    is    not    supported    on    this    database    backend.')
        result.append(self.connection.ops.for_update_sql(nowait=nowait))
    self.query.reset_refcounts(self.refcounts_before)
    return ('    '.join(result), tuple(params))
