Read my latest article: Announcing RailsDeveloper (posted Wed, 01 Sep 2010 17:01:00 GMT)

PostgreSQL sequences in Rails

Posted by Robby Russell Sat, 20 Aug 2005 07:05:00 GMT

23 comments Latest by fake watches Thu, 02 Sep 2010 05:51:33 GMT

Rails doesn’t support legacy or custom named sequences at the moment. (as far as I am aware). It’s kind of tricky to have it detect the SEQUENCE name automatically (every time).

In PHP, I used this big ugly query to detect this info:
$sql = $db->prepare("SELECT seq.relname::text
                        FROM pg_class src, pg_class seq, pg_namespace, pg_attribute,
                        pg_depend
                        WHERE
                            pg_depend.refobjsubid = pg_attribute.attnum AND
                            pg_depend.refobjid = src.oid AND
                            seq.oid = pg_depend.objid AND
                            src.relnamespace = pg_namespace.oid AND
                            pg_attribute.attrelid = src.oid AND
                            pg_namespace.nspname = ? AND
                            src.relname = ? AND
                            pg_attribute.attname = ?");

I used this to mimmick the mysql_insert_id function in PHP for PostgreSQL… ( pg_insert_id )

Well, with Rails, I thought that I would build a similar patch, as the current code just assumes the value would be {column}_id_seq.

After hours of playing around and thinking that I figured it all out ... I decided to run a quick test with a non standard sequence name… like this one:

testingdb=# \d legacy.foobar
                                     Table "legacy.foobar" 
  Column   |         Type          |                         Modifiers                          
-----------+-----------------------+------------------------------------------------------------
 foobar_id | integer               | not null default nextval('legacy.old_sequence_name'::text)
 name      | character varying(40) | 
Indexes:
    "foobar_pkey" PRIMARY KEY, btree (foobar_id)

testingdb=# INSERT INTO legacy.foobar (name) VALUES ('abc')
testingdb-# ;
INSERT 17514 1
testingdb=# SELECT * FROM legacy.foobar ;
 foobar_id | name 
-----------+------
       106 | abc
(1 row)

My patch wouldn’t figure that out because the sequence was not created by SERIAL. So, my patch started to feel lame and a total waste of time, because I thought that it was fixing a problem.. that works pretty much as effectively as assuming it is _seq.. but without needing to run a SQL query to determine that. We all (should) know that the field will be named like that when working with SERIAL. So, my patch didn’t buy us anything.

However, Active Record still doesn’t support those funky sequence names. So, I found this ticket #1273.

Their approach was very similar to what caused me to use my long SQL query in the first place because this was suggested to me well over a year ago and I found it to not work in the following situation.

If I have two seperate schemas with the same table name in each like so:

=# \d legacy.people
                                       Table "legacy.people" 
  Column   |         Type          |                           Modifiers                           
-----------+-----------------------+---------------------------------------------------------------
 people_id | integer               | not null default nextval('legacy.people_people_id_seq'::text)
 name      | character varying(50) | 
Indexes:
    "people_pkey" PRIMARY KEY, btree (people_id)

=# \d foo.people
                                       Table "foo.people" 
  Column   |         Type          |                         Modifiers                          
-----------+-----------------------+------------------------------------------------------------
 people_id | integer               | not null default nextval('foo.people_people_id_seq'::text)
 name      | character varying(50) | 
Indexes:
    "people_pkey" PRIMARY KEY, btree (people_id)      

That patch will not work because you can’t call the following query:

# SELECT adsrc FROM pg_attrdef WHERE adrelid = (SELECT oid FROM pg_class WHERE relname = 'people');
ERROR:  more than one row returned by a subquery used as an expression  

... because there are two tables with the same name! (fun, huh?)

Mine would work… but why bother with that huge query? So, I took my ticket out of [PATCH] and decided that I thought it would be best to just assume that sequences are generated with SERIAL ( link ) by default in AR.

Okay, so what can we do about custom SEQUENCE names?

Well, I am proposing the following (and mentioned this in the ticket #2016)...

class LegacyTable < ActiveRecord::Base
  def self.table_name() "legacy.foobar" end

  # new option for this
  set_primary_key "foobar_id", :sequence => "legacy.old_sequence_name" 
end

(or something along those lines)

With this, I can work around these legacy database scenarios with a quick option. Thoughts/opinions?

I decided to post this on my blog as well, because I do know that there are a few skeptical PostgreSQL people out there who read my blog… I want you to know that I am looking out for you. ;-)

I am sick and tired.. and going to sleep now.

Subscribe to my RSS feed Enjoying the content? Be sure to subscribe to my RSS feed.
Comments

Leave a response

  1. Avatar
    schnitzel@vr-web.de //kargers.org Fri, 12 Jan 2007 22:13:14 GMT

    I have got the same problem.

    I want to use hibernate generated databases and from web ruby.

    I ‘ve got no idea to influence the sequences. Have You got an idea (meanwhile) ??

    Erhard

  2. Avatar
    eduludi Tue, 06 Mar 2007 16:49:46 GMT

    Me too… I have a view instead a table (for postgres, both are relations). How can I do? There aren’t sequences for a view. And if I try to create the sequence, postgres say something like “PGError: ERROR: currval of sequence “table_id_seq” is not yet defined in this session”. Thanks…

  3. Avatar
    btrewern Wed, 07 Mar 2007 12:07:34 GMT

    eduludi,

    Use nextval instead on currval should work.

    Ben

  4. Avatar
    eduludi Mon, 19 Mar 2007 14:06:39 GMT

    Thanks, but this don’t is useful to me. I ‘m using nextval. I never used curval (i check out my functions, views, tables, etc.).

  5. Avatar
    maybe Mon, 03 Sep 2007 06:30:04 GMT

    stop using ActiveRecord would help… not joking!

  6. Avatar
    Alcohol Abuse Thu, 22 Apr 2010 10:49:29 GMT

    writing skill and ability to make reader to read the while thing to the end. I would like to read more of your blogs and I recently came across your blog and have been reading along. I want to express my admiration of your to share my thoughts with you.

  7. Avatar
    Intuit checks Sat, 01 May 2010 07:27:39 GMT

    This is a good piece of writing mate for this particular topic. I was wondering if I could use this write-up on my website, I will link it back to your website though. If this is a problem please let me know and I will take it down right away.

  8. Avatar
    air max ltd white black Wed, 02 Jun 2010 07:35:53 GMT

    TYU TYU

  9. Avatar
    nike dunk Wed, 02 Jun 2010 07:36:07 GMT

    TYU TYU TYU

  10. Avatar
    nike air ltd Sat, 05 Jun 2010 02:56:22 GMT

    er te

  11. Avatar
    mbt shuguli gtx Sat, 05 Jun 2010 02:56:31 GMT

    tr ytr

  12. Avatar
    designer handbags reviews Sat, 12 Jun 2010 10:03:08 GMT

    I ‘ve got no idea to influence the sequences. Have You got an idea (meanwhile) ??

  13. Avatar
    coach rain boots Mon, 21 Jun 2010 04:37:07 GMT

    Thanks for the very helpful information.. I dont know much about this.! And im glad for your help..

  14. Avatar
    drug rehabilitation      Wed, 07 Jul 2010 13:41:39 GMT

    Thanks for this very useful info you have provided us. I will bookmark this for future reference and refer it to my friends. More power to your blog.

  15. Avatar
    replica bvlgari watches Mon, 02 Aug 2010 09:10:56 GMT
  16. Avatar
    replica bvlgari watches Mon, 02 Aug 2010 09:12:07 GMT
  17. Avatar
    ugg boots Sat, 07 Aug 2010 00:54:33 GMT
  18. Avatar
    http://www.bestretroshoes.com Tue, 10 Aug 2010 08:55:49 GMT
    Air Jordan Retro 22,Air Jordan Retro 22
    Air Jordan Retro 23,Air Jordan Retro 23
    Air Jordan 9.5,Air Jordan 9.5
    Air Jordan 15,Air Jordan 15
    Air Jordan 6 rings,Air Jordan 6 rings
    Air Jordan 19,Air Jordan 19
    Air Jordan Retro 2,Air Jordan Retro 2
    Air Jordan Retro 6,Air Jordan Retro 6
    Air Jordan 5 Retro Shoes,Air Jordan 5 Retro Shoes
  19. Avatar
    http://www.bestretroshoes.com Tue, 10 Aug 2010 08:56:30 GMT
    Air Jordan XIX For Sale,Air Jordan XIX For Sale
    Nike 977 Shoes For Sale,Nike 977 Shoes For Sale
    News jordans For Sale,News jordans For Sale
    air jordan dmp retro defining moments,air jordan dmp retro defining moments
    air jordan fusion,air jordan fusion
    air jordan fusion 3,air jordan fusion 3
    air jordan force 4,air jordan force 4
    air jordan force 5,air jordan force 5
    Nike boot For Sale,Nike boot For Sale
  20. Avatar
    Herve leger Thu, 12 Aug 2010 08:23:36 GMT

    We are a professional exporter and wholesaler of brand fashion products,Herve Leger Boatneck Red Dress Herve Leger Bandage Double Shoulder Purple Dress Herve Leger Bandage One Shoulder Off-white Dress Herve Leger Bronze Beaded Dress Herve Leger Bandage Mini Red Skirt,All products have good quality,fast and safe delivery without shipping fee. Our primary goal is to meet our clients’ requirement and establish mutually pleasant business relationships with you.If you are interested, please do not hesitate to contact us.

  21. Avatar
    Coach Handbags Fri, 13 Aug 2010 01:13:53 GMT

    We are a professional exporter and wholesaler of brand fashion products,Coach Poppy Signature Sateen Pocket HOBO 14570 Apricot Coach Poppy Signature Spotlight Tote 13843 Apricot Coach Poppy Signature Spotlight Tote 13843 Black Coach Poppy Signature Spotlight Tote 13843 Blue Coach Poppy Signature Spotlight Tote 13843 Brown,All products have good quality,fast and safe delivery without shipping fee. Our primary goal is to meet our clients’ requirement and establish mutually pleasant business relationships with you.If you are interested, please do not hesitate to contact us.

  22. Avatar
    pandora jewelry Thu, 19 Aug 2010 14:33:31 GMT

    our clients’ requirement and establish mutually pleasant business relationships with you.If you are interested, please do not hesitate to contact us.

  23. Avatar
    fake watches Thu, 02 Sep 2010 05:51:33 GMT

Share your thoughts... (really...I want to hear them)

Comments