Search code examples
postgresqlrose-db-object

Rose::DB doesn't seem to recognize Postgres sequence


My code is simple:

eval {
    my $item = $_table1_class->new(
        field1 => $val1,
        field2 => $val2,
        field3 => $val3,
    );
    $item->save;
};
if ($@) {
   .
   .
   .
   # Error handling stuff.
   .
   .
   .
}

When the code runs, I get the error message, "ERROR: null value in column "id" violates not-null constraint". The error message also indicates that the line that the error is in is the "$item->save;" line.

The PostgreSQL database table that I am trying to write to has an id field in addition to field1, field2, and field3. The id field is defined as:

id | integer | not null default | nextval('table1_id_seq'::regclass)

This is reflected in the code for the class that I define for Rose::DB for this table. For the id field for this table I have the code:

id => { 
     type => 'serial', 
     not_null => 1, 
     primary_key => 1, 
     sequence => 'table1_id_seq', 
},

What in the world could be wrong here?

The strange thing is that this was all working this morning. I changed stuff that shouldn't effect this at all and it has just stopped working. I have been pulling my hair out all day. It seems pretty clear to me that Rose::DB should be getting PostgreSQL to create the id from the sequence. But, it seems not to be doing this. I use this straightforward way of updating other tables exactly the same as this particular table (mutatis mutandis) and it works fine for these other tables. But, here it is simply not working.

Does anybody have any ideas about this? Looking on the net, I see that others have had what seem to be related problems, but I cannot find any remedy in posts elsewhere on the net.

Anybody?


Solution

  • I figured it out. The problem was that in my class for the table, a different field was specified as the primary key from "id". The code read:

    primary_key_columns => [ qw( col2 ) ],
    

    (I hadn't written this code.) When I changed this to:

    primary_key_columns => [ qw( id ) ],
    

    It worked again. What bothers me is why this worked in the first place. It was definitely working, then stuff I did elsewhere in the code seemed to wake up Rose::DB that something was wrong here and it stopped working.

    So, the fault was NOT with Rose::DB here really, but with our code.