DROP CASCADE in Sql Server

我的梦境 提交于 2019-12-06 03:23:10
Cesar Canassa

I never found an implementation of the DROP CASCADE in python, so I ended up writing my own. Here is how it looks:

def delete_table(self, table_name, cascade=True):
    """
    Deletes the table 'table_name'.
    """
    params = (self.quote_name(table_name), )
    if cascade:
        conn = self._get_connection()

        # Get a list of related tables
        sql = "SELECT T1.TABLE_NAME \
                 FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE AS T1 \
                 JOIN SYS.FOREIGN_KEYS AS F \
                   ON (F.parent_object_id = OBJECT_ID(N'{0}') OR \
                      F.referenced_object_id = OBJECT_ID(N'{0}')) AND \
                      T1.CONSTRAINT_NAME = OBJECT_NAME(F.object_id)"

        related_tables = self.execute(sql.format(params[0]))

        # Drop all the constraints
        constraints = self.execute("SELECT CONSTRAINT_NAME \
                                    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS \
                                    WHERE TABLE_NAME='{0}' AND \
                                    CONSTRAINT_TYPE='FOREIGN KEY';".format(table_name))

        sql = "ALTER TABLE {0} DROP CONSTRAINT {1};"
        for constraint in constraints:
            self.execute(sql.format(params[0], constraint[0]))

        for table in related_tables:
            self.delete_table(table[0], cascade)

        sql = "IF  EXISTS (SELECT * \
                           FROM sys.objects \
                           WHERE object_id = OBJECT_ID(N'{0}') AND \
                           type in (N'U')) \
               DROP TABLE {0}"

        self.execute(sql.format(params[0]))
    else:
        self.execute('DROP TABLE %s;' % params)

What do you mean by "simulate" a DROP CASCADE?

If it means "ignore the cascade parameter for MSSQL" then you can just check the current SQL platform/dialect in use and do whatever you like (I have no idea how/if that's possible). The sqlalchemy dialects implementation might give you some useful ideas, if you need them.

But if you want to actually implement the functionality, you'll have query the system views to build a list of tables to drop and the correct order to drop them in. The documentation for the INFORMATION_SCHEMA views or sys.foreign_keys should help. Once you have a query to get the dependent tables in the right order, you can patch the function to do the actual DROPs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!