sql - Transactional isolation level needed for safely incrementing ids -


i'm writing small piece of software insert records database used commercial application. unique primary keys (ids) in relevant table(s) sequential, not seem set "auto increment". thus, assume, have find largest id, increment , use value record i'm inserting.

in pseudo-code brevity:

id = select max(id) some_table id++ insert some_table values(id, othervalues...) 

now, if thread started same transaction before first 1 finished insert, 2 identical ids , failure when trying insert last one. check failure , retry, simpler solution might setting isolation level on transaction. this, need serializable or lower level?

additionally, this, generally, sound way of solving problem? other ways of doing it?

one way of doing merge first 2 lines insert statement:

insert some_table values ((select max(id) + 1 some_table),othervalues...)

or

insert some_table select st2.id, othervalues (select max(id)+1 some_table) st2

otherwise, want lock in transaction , prevent else reading in first line, , ending duplicate id's... blocking reads, open larger can of worms.

in other systems, i've seen table used stored max keys - way lock max_keys table when incrementing , problem goes away - sounds stuck vendor's table structure.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -