Re: Sorting DatabaseTables by FK Constraints

From: Lauri Pietarinen <lauri.pietarinen_at_atbusiness.com>
Date: 25 Dec 2003 14:31:19 -0800
Message-ID: <e9d83568.0312251431.ece649b_at_posting.google.com>


stevengarcia_at_yahoo.com (Steven Garcia) wrote in message news:<7f430eb1.0312230823.35bbace4_at_posting.google.com>...
> I want to sort a collection of database table definitions (in Java) by
> FK dependencies. By sorting I mean that Table A is "less than" Table
> B because Table B has a foreign key constraint that depends on Table
> A.
>
> If you have a simple schema where there are three tables Table A,
> Table B, and Table C, and
>
> Table A has a FK constraint on Table B
> Table B has a FK constraint on Table C
>
> there should only be (theoreticaly) one correct path to insert records
> into this schema. You must insert records into Table C, then Table B,
> then Table A, not in any other order!
>
> I want to make sure that this statement is generally correct.
>
> I've written my own algorithm (I made my Table object in Java
> implement Comparable for those Java savvy folks) but my sorted Lists
> are not always correct. I've determined that given a List of Table
> objects there are many correct "sorted" results and I end up with
> localized sorted sections but my global sorted list is sometimes
> incorrect (and sometimes it's correct.)
>
> Has anyone ever attempted to do this? Any advice?
>
> Thanks, Steve

You will have to look out for circular dependencies, e.g.

Table A has a FK constraint on Table B
Table B has a FK constraint on Table A

regards,
Lauri Pietarinen Received on Thu Dec 25 2003 - 23:31:19 CET

Original text of this message