google-code-export / yabi

Automatically exported from code.google.com/p/yabi
0 stars 1 forks source link

SQL patch for update to django 1.3 #131

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Retrospectively adding ticket for fixed issue:

Using django 1.3 with postgres database build by older django install can 
result in issues with auto incrementing fields.

Django 1.3 changed the way it gets the last inserted id after a model.save().
More about it in the following post:

http://danostrowski.blogspot.com/2011/08/model-id-not-showing-up-after-save-with
.html#!/2011/08/model-id-not-showing-up-after-save-with.html

In practice this means that if your sequence isn't associated with your primary 
key after a model.save() Django won't set model.pk to the right value. 
This might cause problems like, inserting a second row on a consecutive save or 
FK relationship not being set up properly.

Whenever we move an app to Django 1.3 I think we have to ABSOLUTELY make sure 
that the DB schema is set up correctly.
You will have to find the primary keys that aren't associated with a sequence 
and do 

ALTER SEQUENCE sequencename OWNED BY table.pk

as the blog says.

SELECT               
  pg_tables.tablename,
  pg_attribute.attname,
  COALESCE(pg_get_serial_sequence(pg_tables.tablename, pg_attribute.attname),'DOES NOT EXIST!')
FROM pg_index, pg_class, pg_attribute, pg_tables 
WHERE 
  pg_class.oid = pg_tables.tablename::regclass AND
  indrelid = pg_class.oid AND
  pg_attribute.attrelid = pg_class.oid AND 
  pg_attribute.attnum = any(pg_index.indkey)
  AND indisprimary
  AND pg_tables.tableowner='yabiapp';

Original issue reported on code.google.com by amacgregor on 21 Feb 2012 at 1:46

GoogleCodeExporter commented 9 years ago
Added 
http://code.google.com/p/yabi/source/browse/sql/041_alter_sequence_owner.sql 
for yabi databases on postgres.

Original comment by amacgregor on 21 Feb 2012 at 1:49