wastebin icon indicating copy to clipboard operation
wastebin copied to clipboard

Avoid ID clashes

Open cgzones opened this issue 1 year ago • 3 comments

Currently the the ID for a new paste is randomly generated in the caller of the database insert() function. Then the insert() function tries to insert a new row into the database with that passed ID. There can however already exists a paste in the database with the same ID leading to an insert failure, due to a constraint violation due to the PRIMARY KEY attribute. Checking prior the the INSERT via a SELECT query would open the window for a race condition.

A failure to push a new paste is quite severe, since the user might have spent some some to format the input.

Generate the ID in a loop inside, until the INSERT succeeds.

cgzones avatar Oct 26 '24 14:10 cgzones

An ID clash is indeed an extreme issue but perhaps we can solve it differently by constructing an INSERT query that generates a random primary key?

matze avatar Oct 26 '24 20:10 matze

There exists a sqlite built-in functionrandom(and randomblob), but this would not solve this issue, cause the function might still generate a result already existent in the database. Also we need the ID for the URL path generation, so this approach would require a secondary SQL query to get the ID in all cases (also non-clashing).

cgzones avatar Oct 28 '24 14:10 cgzones

Generate the ID in a loop inside, until the INSERT succeeds.

yes, i think this is the easiest and cleanest solution:

  1. Attempt the INSERT directly with a randomly generated ID.
  2. Catch the error if it fails due to a primary key collision.
  3. Retry with a new ID in a loop until the insert succeeds.

kamaradski avatar May 16 '25 19:05 kamaradski