How to disable Foreign Keys to clear database

2,928 views
Skip to first unread message

Greg

unread,
Aug 16, 2012, 10:48:10 PM8/16/12
to sqlal...@googlegroups.com
Hi,

I was naively trying to clear a db earlier in the day and I ran into this problem: 'Cannot delete or update a parent row: a foreign key constraint fails'

So as anyone would do I've been searching online and through the documentation on how to turn the foreign keys off, on delete = Cascade, delete orphan-cascade what have you. So many hours and many stack traces later I'd like to ask your help in this matter

def cleanMapping(self, dbName):
 
      connection =  self.dbEngines[dbName].connect()
      trans = connection.begin()
      
      for my_table in reversed(self.dbMetaData[dbName].tables.values()):
         keys= my_table.foreign_keys
         for column in my_table.columns:
            for key in keys:

               my_table = Table(my_table, self.dbMetaData[dbName],
                           Column(column, Integer,
                           ForeignKey(key, onupdate="CASCADE", ondelete = "CASCADE")
                           ,primary_key=True))   
               connection.execute(my_table.delete())
      
      trans.commit()


So I'm fresh out of ideas; Everytime I try using this code I get "sqlalchemy.exc.ArgumentError: Column object already assigned to Table <col>"


GHZ

unread,
Aug 17, 2012, 7:32:48 AM8/17/12
to sqlal...@googlegroups.com
There is a recipe for dropping FK constraints:


did you find that?

In addition, if you wanted to keep the FKs enabled, there is an example here using Metadata.sorted_tables, to get the table list in dependency order.

Gregory Rehm

unread,
Aug 17, 2012, 2:57:34 PM8/17/12
to sqlal...@googlegroups.com
Thanks so much! that worked great. It seems like google directed me
everywhere except to the recipes.
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/sqlalchemy/-/6EiRPIEPIHAJ.
>
> To post to this group, send email to sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to
> sqlalchemy+...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.
Reply all
Reply to author
Forward
0 new messages