简体   繁体   中英

Way to Get Rails to Log *All* Of Postgres Internals?

Is there a way to set sql logging to be super verbose in rails?

I have a uniqueness index check on the primary_key field of this table that doesn't seem to be working. I'd like to see what postgres is actually doing under the hood a bit more. In other words, I see the INSERT statement, but I'd also like to see a list of the checks it performs before the insert.

irb(main):006:0> SampleTable.create(primary_key: 'hi', archived_at: nil)


 (0.2ms)  BEGIN
  SampleTable Create (0.3ms)  INSERT INTO "sample_tables" ("primary_key", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["primary_key", "hi"], ["created_at", "2019-04-23 12:51:00.295952"], ["updated_at", "2019-04-23 12:51:00.295952"]]
   (6.0ms)  COMMIT
=> #<SampleTable id: 2, primary_key: "hi", archived_at: nil, created_at: "2019-04-23 12:51:00", updated_at: "2019-04-23 12:51:00">

If you're talking about unique index - checks are internal to postgres, rails feeds it an sql query and does not know how it is processed.

But note that validates :some_field, uniqueness: true is non-atomic and is prone to race conditions, because between rails' check and actual insert another insert may happen:

  1. Request A starts record creation, checks that record with same key is not present
  2. Request B starts same procedure and also checks that key is not present
  3. Request A proceeds to inserting
  4. Request B proceeds to inserting
  5. Both requests checked that key was not present, but you have a duplicate in db

This validation should be backed by a unique index on database so that in case of race condition postgres will return error and ActiveRecord::RecordNotUnique will be thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM