I am new to postgreSQL, so I really appreciate any pointers from the community.
I am updating some functions in the CMS of a rather old site that I just inherited. Basically, I need an article id before it is inserted into the database. In any case, one way or another, to check the next value that the sequence will use before the start of the database session (insert)?
At first I thought I could use SELECT max(id) from tbl_name
, however, since the identifier is automatically incremented by the sequence, and the articles are often deleted, it obviously will not return the correct identifier for the next value in the sequence.
Since the article is not already in the database and the database session is not running yet, it seems I can not use the currval()
postgreSQL functionality. Also, if I use nextval()
, it automatically increments the sequence before the data is inserted (pasting will also automatically increase the sequence, ending up with the sequence being double increased).
I am currently dealing with this:
function get_next_id() { $SQL = "select nextval('table_id_seq')"; $response = $this->db_query($SQL); $arr = pg_fetch_array($query_response, NULL, PGSQL_ASSOC); $id = (empty($arr['nextval'])) ? 'NULL' : intval($arr['nextval']); $new_id = $id-1; $SQL = "select setval('table_id_seq', {$new_id})"; $this->db_query($SQL); return $id; }
I use SELECT nextval('table_id_seq')
to get the next identifier in the sequence. As this extends the sequence I, immediately use the SELECT setval('table_id_seq',$id)
to return the sequence to its original value. Thus, when the user sends data, and the code finally ends up in the INSERT statement, it automatically increments, and the identifier before and after insertion is identical.
While this works for me, I'm not too hot on postgreSQL and wondering if this might cause any problems on the line, or if this is not the best method? Is there no way to check the next value of a sequence without automatically increasing it?
If this helps, I use postgresql 7.2