currval has not yet been defined this session, how to get multi-session sequences?

前端 未结 5 1123
再見小時候
再見小時候 2020-12-25 11:38

My objective is to get a primary key field automatically inserted when inserting new row in the table.

How to get a sequence going from session to session in Postg

5条回答
  •  北海茫月
    2020-12-25 11:54

    I will give a practical answer for this matter. My database server is used by my programs and my psql terminal; so there are multiple sessions. currently I am in my psql terminal:

    fooserver=> select currval('fusion_id_seq');
    ERROR:  currval of sequence "fusion_id_seq" is not yet defined in this session
    fooserver=> select nextval('fusion_id_seq');
     nextval 
    ---------
      320032
    (1 row)
    
    fooserver=> select currval('fusion_id_seq');
     currval 
    ---------
      320032
    (1 row)
    

    It looks that you can only see the values in your own session. This will also affect the currval of another session. This is probably related to multi-threading of the server to isolate different session. The counter (serial in psql) is a shared object. In my opinion, this session should be able to get the current value of the counter as long as the counter is properly locked to ensure only a single thread (session) can increment it (atomic operation). But I could be wrong here (not an expert on database server writer).

提交回复
热议问题