What I would like to ‘have’ is someway to export my tables including the foreign keys. And whenever/whereever re-execute those create table queries.
The problem I am facing though is making sure the right preconditions exist per table.
if table B references A and A references C. Then first C must be created, then A and at last B.
But creating the right order is something that I do not know how to do (yet).
I am currently creating the queries this way: (not the complete code)
class DBManager{
private function createSQLCreateTableDump(){
$query = "SHOW TABLES";
$res = $this->db->prepare($query)->fetchObjectAll();
foreach( $res as $table){
$this->createSQLCreateTableQuery(current(get_object_vars($table)));
}
}
private function createSQLCreateTableQuery($tableName){
$query = "SHOW CREATE TABLE {$tableName}";
$res = $this->db->prepare($query)->fetchObjectOnce();
return $res->{"Create Table"};
}
}
As a reference, $this->db is a class named Database which extends PDO.
fetchObjectOnce and fetchObjectAll returns each row returned as an object. The first argument (which I am not using here) specifies the class type returned. Else stdClass is used.
current(get_object_vars($table)) is used to get the first column returned. Because the column names differ per database used. This seemed the fastest/easiest way.
The problem with this method is that some tables with constraints will be created before the constraint can be created.
the question: What would be a good solution to this problem?
Just thought of this: (which I will try to work out).
I can get the constraints themself from the informatino_schema.table_constraints and key_column_usage tables. Thus I can create a tree of dependancies. Will see how far I can come that way.
Right, I’ve answered my own question and provided an example:
http://pastebin.com/5dg6B0ZF
it is not the cleanest of my work, but it works so far.
it creates two temporary arrays.
One holding the references per table, the other the queries.
I am using table names as keys for the arrays for easy searching.
I won’t accept my own answer till somewhere tomorrow to see if someone else comes up with a better solution.
Let me know what you think.