Details
-
Type:
Bug
-
Status:
Open
-
Priority:
Major
-
Resolution: Unresolved
-
Affects Version/s: 1.2.2
-
Fix Version/s: None
-
Component/s: Import/Export
-
Labels:None
Description
With 1.2.2 we get errors for our generated PostgreSQL code: "sequence <sequence name> already exists". I tracked down the issue to the following:
Doctrine_Export_Pgsql::createTableSql() has the following new code:
if (isset($options['sequenceName'])) { $sql[] = $this->createSequenceSql($options['sequenceName']); }
This is fine, but this CREATE SEQUENCE code is now added after the CREATE TABLE code. This does not work okay for PostgreSQL, since PostgreSQL will automatically create the index for you if it does not yet exist. If CREATE SEQUENCE is required for some reason, then it should ge before the CREATE TABLE to be useful (it could for example be useful if different increment intervals or starting numbers should be set for the sequence).
I tried moving the new code up, but that did not yet give me the desired results. The issue is that Doctrine_Export::exportClassesSql() collects all the SQL in an array and finally does:
rsort($sql);
return $sql;
This can break any statement set in there that should be run in a specific order. For the PostgreSQL code, this will put all the CREATE TABLE calls in font of the CREATE SEQUENCE calls, resulting in the errors that we see.
Suggested fix options:
1) Do not sort the SQL queries, but accept them as generated by the db specific Export class (but I'm only suggesting this, because I am not aware of the reason to do an rsort() in the first place).
2) Change the PostgreSQL export code to make it immune to the sorting.
We did the latter in our code. The CREATE SEQUENCE and CREATE TABLE are concatenated into one statement string ("<squence>;<table>") that is added to the list of SQL queries. This provides us a work-around for the problem. The first solution is more clean IMO, but I lack knowledge to tell if the rsort() is here for technical or aesthetic reasons.
An additional issue for the PostgreSQL sequence handling: the Doctrine code does create a sequence field in the tables. However, the sequence system seems not to be in use at all for generating new id fields. As a result, the sequences remain at their initial value of 1.
We noticed this when we tried to manually insert a record in the database. Five records were already available. The manual INSERT failed, because of a duplicate index error on the id field. After a few attempts, it did work. That was because the PostgreSQL sequence had reached a value of 6, which was a non-existing id for the table at that point.
I think that a choice has to be made here: either use sequences or don't:
I hope this helps in improving Doctrine.