# -*- coding: utf-8 -*-

from django import db
from django.conf import settings
from django.core.management import base as management


class Command(management.BaseCommand):
    help = """Operations to perform after database
           migration from MySQL to PostgreSQL"""
    
    def handle(self, *args, **options):
        with db.connection.cursor() as cursor:
            self._convert_timestamps(cursor)
            self._convert_constraints(cursor)

    def _convert_timestamps(self, cursor):
            cursor.execute(
                """
                SELECT table_name, column_name, data_type
                FROM information_schema.columns
                WHERE data_type LIKE '%without%'
                """
            )
            for table_name, column_name, _ in cursor.fetchall():
                cursor.execute(
                    """
                    ALTER TABLE %(table)s
                    ALTER %(column)s TYPE timestamptz
                    USING %(column)s AT TIME ZONE '%(timezone)s'
                    """ % {
                        'table': table_name,
                        'column': column_name,
                        'timezone': settings.TIME_ZONE,
                    }
                )
                self.stdout.write(
                    'Alter %s in table %s' % (column_name, table_name))

    def _convert_constraints(self, cursor):
        cursor = db.connection.cursor()
        cursor.execute(
            """
            SELECT table_name, constraint_name
            FROM information_schema.table_constraints
            WHERE constraint_name LIKE '%_fkey'
            """
        )
        for table_name, constraint_name in cursor.fetchall():
            cursor.execute(
                """
                ALTER TABLE %(table)s
                ALTER CONSTRAINT %(constraint)s DEFERRABLE INITIALLY DEFERRED
                """ % {'table': table_name, 'constraint': constraint_name}
            )
            self.stdout.write(
                'Alter constraint %s in table %s' % (constraint_name, table_name))
