title: Rails, custom Postgres sequence and possible concurrency issue
body: <p>I have a Postgres photos table, with ids as UUIDs, not INT (primary keys).
  As I store the photos in directories, I created a custom field &quot;file_id&quot;, with it's own sequence to get a uniq id for each record.</p>
  <p><a href="https://i.stack.imgur.com/M63xP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M63xP.png" alt="enter image description here" /></a></p>
  <p>In my rails app (Rails 6.1), the photo model uses this code to get the next folder file_id to create:</p>
  <pre><code>  # need a file_id to store the file in a directory (can't use the uuid)
    before_create :build_file_id
    def build_file_id
      self.file_id = ActiveRecord::Base.connection.execute(&quot;select nextval('usr_photos_file_id_seq')&quot;).first[&quot;nextval&quot;]
    end
  </code></pre>
  <p>Then my photo uploader creates the folders to store the photo using the file_id:</p>
  <pre><code># id path
  id_path = (&quot;%012d&quot;.freeze % record.file_id).scan(/\d{3}/).join(&quot;/&quot;.freeze)   
  </code></pre>
  <p>This works very well for my simple tests:</p>
  <p>this gives for example directories like : <code>000/001/002/003/original/image.jpg</code></p>
  <p>However, I have some doubts about possible concurrency issues when many requests will add photos to the app.</p>
  <p>How to be sure that each photo will be added correctly to the right directory created by the sequence ? Does <code>select nextval('usr_photos_file_id_seq')</code> is sure concurrently and 'reserved' by Postgres when the photo is copied ?</p>
  <p>Thanks,</p>