I am writing a tool for university which is supposed to take a MySQL database and copy it into a PostgreSQL database and vice versa.
I have now read all the relevant information about the tables / columns into Java objects and now want to start making my create statements, however I have one slight problem.
If a table references other tables using a foreign key relation, those other tables need to be created prior to the table, otherwise the DBMS will throw an error. So I have to somehow find a way to sort my table objects, either inside my Java code or by using a clever SQL query.
I have tried using their creation order in the original table:
USE project;
SELECT create_time, table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'project';
However this outputs the creation time only exact to the second, which doesn't help me if they were all created using a script.
This is how I store my tables:
public Table(String name, Column[] columns, ArrayList<String> primaryKeys, ArrayList<String[]> foreignKeys) {
this.name = name;
this.columns = columns;
this.primaryKeys = primaryKeys;
this.foreignKeys = foreignKeys;
}
The foreign key attribute is an ArrayList of String-Arrays of length 3, containing the column with the foreign key constraint and the table + column referencing it.