[Nitro] question about postgresql.rb && last_insert_id and insert_sql

Reid Thompson reid.thompson at ateb.com
Mon Oct 23 20:37:49 EDT 2006


Hi list,
could someone explain to me the reasoning behind the following code in
postgresql.rb.  If the klass.primary_key is a sequence, there is no need
to explicitly set the primary key value in PostgreSQL, PG will
automatically do it. You can do this by either not passing a value for
that column, or by passing default or DEFAULT.  This would make
insert_sql a less costly call.  What am I missing that requires the code
 to be written as it currently is??

--this comment is incorrect -- select nextval() does just that, advances
the sequence and returns the next value ( it could be re-written as #
Return what will become the last inserted row id. )
  # Return the last inserted row id.

  def last_insert_id(klass)
    seq = klass.ann[klass.primary_key][:sequence]

    res = query("SELECT nextval('#{seq}')")
    lid = Integer(res.first_value)

    return lid
  end

  # The insert sql statements.

  def insert_sql(sql, klass)
    str = ''

    if klass.ann[klass.primary_key][:sequence]
      str << "@#{klass.primary_key} = store.last_insert_id(#{klass})\n"
    end

    str << "store.exec \"#{sql}\""

    return str
  end

------example------

test=# \d
                   List of relations
 Schema |          Name           |   Type   |  Owner
--------+-------------------------+----------+----------
 public | seq_test                | table    | rthompso
 public | seq_test_oid_seq        | sequence | rthompso
(14 rows)

test=# \d seq_test
                            Table "public.seq_test"
   Column   |  Type   |                       Modifiers

------------+---------+--------------------------------------------------------
 username   | text    |
 first_name | text    |
 last_name  | text    |
 e_mail     | text    |
 oid        | integer | not null default
nextval('seq_test_oid_seq'::regclass)

test=# insert into seq_test values('uname','fname','lname','emailaddr');
INSERT 0 1
test=# insert into seq_test
values('uname','fname','lname','emailaddr',default);
INSERT 0 1
test=# select * from seq_test;
 username | first_name | last_name |  e_mail   | oid
----------+------------+-----------+-----------+-----
 uname    | fname      | lname     | emailaddr |   1
 uname    | fname      | lname     | emailaddr |   2
(2 rows)

test=#
test=# insert into seq_test
values('uname','fname','lname','emailaddr',DEFAULT);
INSERT 0 1




More information about the Nitro-general mailing list