'Yields the SQL syntax of the query, which can be passed to Database.execute().
The SQL string will be cached for faster reuse.'

def SQL(self):

    g = (((not isinstance(self.group, (list, tuple))) and [self.group]) or self.group)
    g = [abs(self._table.name, f) for f in g if (f is not None)]
    fields = (((not isinstance(self.fields, (list, tuple))) and [self.fields]) or self.fields)
    fields = [(((f in self.aliases) and ('%s    as    %s' % (f, self.aliases[f]))) or f) for f in fields]
    fields = abs(self._table.name, fields)
    if (g and isinstance(self.function, basestring)):
        fields = [(((f in g) and f) or ('%s(%s)' % (self.function, f))) for f in fields]
    if (g and isinstance(self.function, (list, tuple))):
        fields = [(((f in g) and f) or ('%s(%s)' % (F, f))) for (F, f) in zip((self.function + ([FIRST] * len(fields))), fields)]
    q = []
    q.append(('select    %s' % ',    '.join(fields)))
    q.append(('from    `%s`' % self._table.name))
    relations = {}
    for (key1, key2, table, join) in (rel(*r) for r in self.relations):
        table = ((isinstance(table, Table) and table.name) or table)
        relations[table] = (key1, key2, join)
    for (table1, key1, table2, key2, join) in self._table.db.relations:
        if (table1 == self._table.name):
            relations.setdefault(table2, (key1, key2, join))
        if (table2 == self._table.name):
            relations.setdefault(table1, (key1, key2, (((join == LEFT) and RIGHT) or (((join == RIGHT) and LEFT) or join))))
    for (table, (key1, key2, join)) in relations.items():
        for f in fields:
            if ((table + '.') in f):
                q.append(('%sjoin    `%s`' % (((join and (join + '    ')) or ''), table)))
                q.append(('on    %s=%s' % (abs(self._table.name, key1), abs(self._table.db[table].name, key2))))
                break
    if (len(self.filters) > 0):
        q.append(('where    %s' % self.filters.SQL(escape=self._table.db.escape, table=self._table.name)))
    for (clause, value) in (('order', self.sort), ('group', self.group)):
        if (isinstance(value, basestring) and (value != '')):
            q.append(('%s    by    %s' % (clause, abs(self._table.name, value))))
        elif (isinstance(value, (list, tuple)) and (len(value) > 0)):
            q.append(('%s    by    %s' % (clause, ',    '.join(abs(self._table.name, value)))))
        elif isinstance(value, int):
            q.append(('%s    by    %s' % (clause, abs(self._table.name, self._table.fields[value]))))
        if (self.sort and (clause == 'order')):
            if (self.order in (ASCENDING, DESCENDING)):
                q.append(('%s' % self.order))
            elif isinstance(self.order, (list, tuple)):
                q[(-1)] = ','.join(('    '.join(v) for v in zip(q[(-1)].split(','), self.order)))
    if self.range:
        q.append(('limit    %s,    %s' % (str(self.range[0]), str(self.range[1]))))
    q = ('    '.join(q) + ';')
    return q
