Whereas ActiveRecord is a behemoth encompassing a big feature-set, some WTFs pop up every so often. One such WTF is the shortage of help for default values for binary columns in SQLite.
Earlier than
Let’s create a string column in a mannequin that makes use of a SQLite database and add a default worth to it.
# db/migrate/20220821142603_add_string_to_physician.rb
# class AddStringToPhysician < ActiveRecord::Migration[7.0]
# def change
# add_column :physicians, :signature, :string, default: "Regards"
# finish
# finish
irb(major):001:0> doctor = Doctor.create! identify: "Belle"
...
irb(major):002:0> doctor.signature
=> "Regards"
irb(major):003:0> doctor.reload.signature
=> "Regards"
Let’s do the identical with a binary column.
# db/migrate/20220821142330_add_greeting_to_physician.rb
# class AddGreetingToPhysician < ActiveRecord::Migration[7.0]
# def change
# add_column :physicians, :greeting, :binary, default: "Good day!"
# finish
# finish
irb(major):001:0> doctor = Doctor.create! identify: "Belle"
(0.6ms) SELECT sqlite_version(*)
TRANSACTION (0.0ms) start transaction
Doctor Create (0.3ms) INSERT INTO "physicians" ("identify", "created_at", "updated_at", "greeting", "signature") VALUES (?, ?, ?, ?, ?) [["name", "Belle"], ["created_at", "2022-08-21 15:47:44.957101"], ["updated_at", "2022-08-21 15:47:44.957101"], ["greeting", nil], ["signature", "Regards"]]
TRANSACTION (0.4ms) commit transaction
...
irb(major):002:0> doctor.greeting
=> nil
irb(major):003:0> doctor.reload.greeting
=> "Good day!"
This creates an inconsistency within the habits of Sqlite with Rails.
After
Luckily, this PR provides help for studying a binary column’s default values earlier than the its knowledge is learn from the database.
irb(major):001:0> doctor = Doctor.create! identify: "Belle"
(0.6ms) SELECT sqlite_version(*)
TRANSACTION (0.0ms) start transaction
Doctor Create (0.3ms) INSERT INTO "physicians" ("identify", "created_at", "updated_at", "greeting", "signature") VALUES (?, ?, ?, ?, ?) [["name", "Belle"], ["created_at", "2022-08-21 15:47:44.957101"], ["updated_at", "2022-08-21 15:47:44.957101"], ["greeting", "<11 bytes of binary data>"], ["signature", "Regards"]]
TRANSACTION (0.4ms) commit transaction
...
irb(major):002:0> doctor.greeting
=> "Good day!"
irb(major):003:0> doctor.reload.signature
=> "Good day!"