# coding: utf-8


from django.db import connection
from django.db.models.expressions import RawSQL


qn = connection.ops.quote_name


def parametrize_sql(sql, models):
    table_names = {model._meta.object_name: qn(model._meta.db_table) for model in models}
    return sql % table_names


def maybe_subquery(sql, params, models):
    """Возврщает либо корректно сформатированный RawSQL объект, либо список результатов
    """
    sql = parametrize_sql(sql, models)

    if connection.vendor == 'sqlite':
        with connection.cursor() as cursor:
            cursor.execute(sql, params)

            return [r[0] for r in cursor.fetchall()]

    return RawSQL(sql, params)
