in reply to Re^2: Perl DBI and Foreign Keys
in thread Perl DBI and Foreign Keys

And if you do not like last_insert_id, you can always build an index generator yourself, like max( index_column ) + 1.

Replies are listed 'Best First'.
Re^4: Perl DBI and Foreign Keys
by Marshall (Canon) on Apr 08, 2019 at 12:45 UTC
    I don't think that would work as a substitute for last_insert_id due to race conditions with multiple writers.

    I can read a table. Calculate the number of rows. And wind up with a different number of rows than you read doing the same thing if somebody else inserted a row during this process.

      what if it's wrapped within a transaction?
        what if it's wrapped within a transaction?

        Still a race. This is really a FAQ. The only clean way is to use what the database offers, either sequences or their crippled replacement, auto-generated IDs. See Re^2: Perl DBI and Foreign Keys.

        Of course, you could build your own service to generate unique IDs without race conditions and add that on top. (Quite a challenge if you want it to work with high load ...) But as already explained, this service is already provided by almost any SQL database at no extra cost.

        (And please don't come up with UUIDs. They come in different classes, with different properties (see UUID), and some of them are actually quite unlikely to collide. Others are more likely to collide. IDs generated by the database are guaranteed not to collide, and you don't need anything else but the existing database engine.)


        Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)