Circular Dependencies

time to read 2 min | 266 words

So, I need to copy a set of tables from one database to another, the issue is that the source database keeps changing, so, in a true developer fashion, I added another layer of indirection and instead of writing scripts to copy the database I wrote a program that would write scripts that would copy the database.

I'm pretty proud of it, it uses the SQL Runner tool that I mentioned earlier, and it work in stages, so the first thing that copied is tables with no foreign keys, then the tables that depended on those, and then the tables that depend on those, and so on. The issue is that I've a couple of tables that have circular dependencies (sometimes a dependency on itself). This presents an interesting problem since I don't want to start special casing for each table type.

I can see several options there:

  • Drop the foreign keys, copy the tables and recreate from scratch - On general I don't like this, especially since generating the code to recreate the foreign key is not trivial.
  • Try to copy anyway, maybe I would get lucky or there aren't any real references between the tables.
  • Leave it as a totally manual process (which is a real option, since this is a mostly one off thing).

Ideas?