from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.utils.common import format_table

logger = get_logger(__name__)


def format_sql_results_for_log(results):
    if len(results) == 0:
        return messages.SQL_QUERY_RESULT_EMPTY_SET
    else:
        try:
            table_rows = []
            first_row_keys = results[0].keys()
            table_rows.append(first_row_keys)

            for result_row in results:
                table_rows.append([result_row.get(key) for key in first_row_keys])

            return format_table(table_rows)
        except Exception:
            # Log formatting is not essential for migration, so:
            # in case of any error during formatting, log the error and return Python repr of SQL results
            logger.exception()
            return repr(results)

