# -*- coding: UTF-8 -*-
from django.core.management import BaseCommand
from django.db import connection


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        cursor = connection.cursor()
        talos_tables = [
            "api_topicvote",
            "api_diaryoperate",
            "api_diaryfavor",
            "api_live_stream",
            "api_problemtag",
            "api_topicreply",
            "api_reply_collect",
            "api_columntabtag",
            "api_votepk",
            "api_wechatmaterial",
            "api_topicreplyvote",
            "api_live_white_list",
            "api_video_white_list",
            "api_problemfavor",
            "api_diary",
            "api_pgcclassify",
            "api_article",
            "api_live_msg",
            "api_topicrankingscore",
            "api_topicimage",
            "api_streamtag",
            "api_diarycheck",
            "api_diaryvote",
            "api_columnist",
            "api_preoperationimage",
            "api_problem_operations",
            "api_activity",
            "api_replyheadline",
            "api_problem",
            "api_live_channel",
            "api_columntab",
            "api_diarymessage",
            "api_columncard",
            "api_zhiboconfig",
            "api_diary_tags",
            "api_topic_video",
            "api_draft",
            "api_diaryrank",
            "api_topicscore",
            "api_activitywinlist",
            "api_report",
            "api_filterword",
            "api_shortvideo_black_list",

            "community_article",
            "community_topic_sticky",

            "relation_usertagrelation",
            "social_userfollow",
            "social_feed",

            "api_question_vote",
            "api_questiontag",
            "api_question",
            "api_answer_vote",
            "api_overheadquestion",
            "api_question_image",
            "api_answer_top",
            "api_answerreply_vote",
            "api_answer",
            "api_answer_reply",
            "api_overheadanswer",
            "api_answer_image",
            "api_user_question_answer",
        ]
        sql = '''
SELECT `TABLE_NAME`, `CONSTRAINT_NAME`
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE `CONSTRAINT_SCHEMA`='zhengxing_test'
  AND `REFERENCED_COLUMN_NAME` != 'null'
  AND (`REFERENCED_TABLE_NAME` in ({talos_tables})
  OR `TABLE_NAME` in ({talos_tables}))
  ;
'''.format(talos_tables=",".join(map(lambda x: "'{}'".format(x), talos_tables)))
        print sql
        cursor.execute(sql)
        row = cursor.fetchall()
        with open("del_fk.sql", "w") as f:
            for i in row:
                sql = "ALTER TABLE `{}` DROP FOREIGN KEY {};\n".format(*i)
                print i
                print sql
                f.write(sql)
