Auto-create check constraints for text fields with limit

Move column defaults from migration strategy to migrations.
Compact index creation inside migrations.
Disable database schema generation.
This commit is contained in:
2026-11-26 02:32:09 +01:00
parent 74f9a09098
commit b6d2c19b0b
9 changed files with 148 additions and 210 deletions
+4
View File
@@ -2,6 +2,10 @@
# for a full overview on how database connection configuration can be specified.
default: &default
pool: <%= ENV.fetch('RAILS_MAX_THREADS', 3) %>
# Disable schema dump. It is redundant with regard to migration files and
# buggy (as of Rails 8.1.4 adds foreign key constraints multiple times after
# repeated db:schema:load).
schema_dump: false
production:
<<: *default
+1 -2
View File
@@ -1,11 +1,10 @@
class CreateUsers < ActiveRecord::Migration[8.1]
def change
create_table :users do |t|
t.string :email, null: false, limit: 64
t.string :email, null: false, limit: 2**6, index: {unique: true}
t.integer :status, null: false, default: 0
t.timestamps
end
add_index :users, :email
end
end
@@ -1,24 +1,24 @@
class AddDeviseToUsers < ActiveRecord::Migration[8.1]
def change
change_table :users do |t|
## NOTE: commented fields left for reference/inclusion in future migrations
## Commented fields left for reference/inclusion in future migrations.
## Database authenticatable
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.string :reset_password_token, index: {unique: true}
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Confirmable
t.string :confirmation_token
t.string :confirmation_token, index: {unique: true}
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
# Only if using reconfirmable
t.string :unconfirmed_email, limit: 64
# Only if using reconfirmable.
t.string :unconfirmed_email, limit: 2**6
## Trackable
# t.integer :sign_in_count, default: 0, null: false
@@ -28,14 +28,11 @@ class AddDeviseToUsers < ActiveRecord::Migration[8.1]
# t.string :last_sign_in_ip
## Lockable
# t.string :unlock_token # Only if unlock strategy is :email or :both
# Only if unlock strategy is :email or :both.
# t.string :unlock_token, index: {unique: true}
# t.datetime :locked_at
# Only if lock strategy is :failed_attempts
# Only if lock strategy is :failed_attempts.
# t.integer :failed_attempts, default: 0, null: false
end
add_index :users, :reset_password_token
add_index :users, :confirmation_token
# add_index :users, :unlock_token, unique: true
end
end
+8 -5
View File
@@ -2,14 +2,17 @@ class CreateUnits < ActiveRecord::Migration[8.1]
def change
create_table :units do |t|
t.references :user, foreign_key: {on_delete: :cascade}
t.string :symbol, null: false, limit: 15
t.text :description
t.string :symbol, null: false, limit: 2**4
t.text :description, limit: 2**16
t.float :multiplier, null: false, limit: Float::MANT_DIG, default: 1.0
t.references :base, foreign_key: {to_table: :units, on_delete: :cascade}
t.timestamps
# Constraints:
# * symbol has to be unique
t.index [:user_id, :symbol], unique: true
# * unit has to belong to the same user as quantity (used by :readouts)
t.index [:id, :user_id], unique: true
end
add_index :units, [:user_id, :symbol]
add_index :units, [:id, :user_id]
end
end
+11 -8
View File
@@ -2,17 +2,20 @@ class CreateQuantities < ActiveRecord::Migration[8.1]
def change
create_table :quantities do |t|
t.references :user, foreign_key: {on_delete: :cascade}
t.string :name, null: false, limit: 31
t.text :description
t.string :name, null: false, limit: 2**5
t.text :description, limit: 2**16
t.references :parent, foreign_key: {to_table: :quantities, on_delete: :cascade}
t.timestamps
# Caches; can be computed from other attributes
t.integer :depth, null: false, default: 0
# Cached, computed from other attributes. NULL default to ensure value
# has been properly initialized.
t.integer :depth, null: false
t.string :pathname, null: false, limit: 511
# Constraints:
# * name has to be unique
t.index [:user_id, :parent_id, :name], unique: true
# * quantity has to belong to the same user as unit (used by :readouts)
t.index [:id, :user_id], unique: true
end
add_index :quantities, [:user_id, :parent_id, :name]
add_index :quantities, [:id, :user_id]
end
end
+10 -11
View File
@@ -1,20 +1,17 @@
class CreateReadouts < ActiveRecord::Migration[8.1]
def change
create_table :notes do |t|
t.text :text, null: false
t.text :text, null: false, limit: 2**16
t.timestamps
end
create_table :measurements do |t|
t.datetime :taken_at, null: false
t.datetime :taken_at, null: false, index: {unique: true}
#t.references :collector, foreign_key: true
#t.references :device, foreign_key: true
t.references :note, foreign_key: {on_delete: :nullify}
t.timestamps
end
add_index :measurements, :taken_at
# Defining Readouts as a super-/subclass polymorphic relations for different
# subclass data types (numeric, string, file) is not possible with proper
@@ -40,14 +37,16 @@ class CreateReadouts < ActiveRecord::Migration[8.1]
# t.references :file
# Possibly mutually exclusive with :unit or check constraint for:
# :unit is not null <=> :value is not null
t.timestamps
# Constraints:
# * quantity + category has to be unique within measurement
t.index [:measurement_id, :quantity_id, :category], unique: true
# * quantity and unit has to belong to the same user as readout
t.foreign_key :quantities, column: [:quantity_id, :user_id],
primary_key: [:id, :user_id]
t.foreign_key :units, column: [:unit_id, :user_id], primary_key: [:id, :user_id]
end
add_index :readouts, [:measurement_id, :quantity_id, :category]
add_foreign_key :readouts, :quantities, column: [:quantity_id, :user_id],
primary_key: [:id, :user_id]
add_foreign_key :readouts, :units, column: [:unit_id, :user_id],
primary_key: [:id, :user_id]
# TODO: remove below tables after current setup verified
#create_table :numeric_values do |t|
-123
View File
@@ -1,123 +0,0 @@
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_11_07_214900) do
create_table "measurements", force: :cascade do |t|
t.datetime "taken_at", null: false
t.integer "note_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["note_id"], name: "index_measurements_on_note_id"
t.index ["taken_at"], name: "index_measurements_on_taken_at", unique: true
end
create_table "notes", force: :cascade do |t|
t.text "text", limit: 65535, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "quantities", force: :cascade do |t|
t.integer "user_id"
t.string "name", limit: 31, null: false
t.text "description", limit: 65535
t.integer "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "depth", default: 0, null: false
t.string "pathname", limit: 511, null: false
t.index ["id", "user_id"], name: "index_quantities_on_id_and_user_id", unique: true
t.index ["parent_id"], name: "index_quantities_on_parent_id"
t.index ["user_id", "parent_id", "name"], name: "index_quantities_on_user_id_and_parent_id_and_name", unique: true
t.index ["user_id"], name: "index_quantities_on_user_id"
end
create_table "readouts", force: :cascade do |t|
t.integer "user_id", null: false
t.integer "measurement_id"
t.integer "quantity_id", null: false
t.integer "category", default: 0, null: false
t.float "value", limit: 53, null: false
t.integer "unit_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["measurement_id", "quantity_id", "category"], name: "index_readouts_on_measurement_id_and_quantity_id_and_category", unique: true
t.index ["measurement_id"], name: "index_readouts_on_measurement_id"
t.index ["quantity_id"], name: "index_readouts_on_quantity_id"
t.index ["unit_id"], name: "index_readouts_on_unit_id"
t.index ["user_id"], name: "index_readouts_on_user_id"
end
create_table "tags", force: :cascade do |t|
t.integer "user_id", null: false
t.string "label", limit: 32, null: false
t.text "description", limit: 65536
t.integer "supertag_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "depth", null: false
t.index ["id", "user_id"], name: "index_tags_on_id_and_user_id", unique: true
t.index ["supertag_id"], name: "index_tags_on_supertag_id"
t.index ["user_id", "label"], name: "index_tags_on_user_id_and_label", unique: true
t.index ["user_id"], name: "index_tags_on_user_id"
t.check_constraint "id != supertag_id", name: "self_reference"
t.check_constraint "length(description) <= 65536", name: "description_length"
t.check_constraint "length(label) <= 32", name: "label_length"
end
create_table "units", force: :cascade do |t|
t.integer "user_id"
t.string "symbol", limit: 15, null: false
t.text "description", limit: 65535
t.float "multiplier", limit: 53, default: 1.0, null: false
t.integer "base_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["base_id"], name: "index_units_on_base_id"
t.index ["id", "user_id"], name: "index_units_on_id_and_user_id", unique: true
t.index ["user_id", "symbol"], name: "index_units_on_user_id_and_symbol", unique: true
t.index ["user_id"], name: "index_units_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", limit: 64, null: false
t.integer "status", default: 0, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email", limit: 64
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "measurements", "notes", on_delete: :nullify
add_foreign_key "quantities", "quantities", column: "parent_id", on_delete: :cascade
add_foreign_key "quantities", "users", on_delete: :cascade
add_foreign_key "readouts", "measurements", on_delete: :cascade
add_foreign_key "readouts", "quantities", column: ["quantity_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "readouts", "quantities", on_delete: :cascade
add_foreign_key "readouts", "units", column: ["unit_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "readouts", "units", on_delete: :cascade
add_foreign_key "readouts", "users", on_delete: :cascade
add_foreign_key "tags", "tags", column: "supertag_id", on_delete: :cascade
add_foreign_key "tags", "tags", column: ["supertag_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "tags", "users", on_delete: :cascade
add_foreign_key "units", "units", column: "base_id", on_delete: :cascade
add_foreign_key "units", "users", on_delete: :cascade
end
+104 -48
View File
@@ -1,60 +1,116 @@
class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy
COLUMN_DEFAULTS = {
# TODO: all types `null: false` ?
# TODO: references `foreign_key: {on_delete: :cascade}` ?
# `timestamps` - Rails defaults to `null: false, precision: true`, which is
# expected.
text: {limit: 2**16 - 1}
}
COLUMN_DEFAULTS.default = {}
COLUMN_DEFAULTS.freeze
# Strategy methods can be invoked differently depending on whether changes are
# applied from migration files in up or down direction (e.g. `change_table`
# can be run as series of `remove_column` during #down) or from schema file.
# Strategy has to be verified at least using:
# db:migrate + db:migrate VERSION=0
# db:reset + (multiple) db:schema:load (if schema file is used)
module ColumnSettingsStrategy
def column(name, type, **options)
super(name, type, **COLUMN_DEFAULTS[type].merge(options))
# SQLite does not enforce `limit` on string/text columns by default.
# `text` can be theoretically up to 1GB or longer, so roughly unlimited
# for practical purposes. But the actual usable length depends on
# additional factors, like compile time limits (`SQLITE_MAX_LENGTH` in
# SQLite) and probably other.
# TODO: remove after commit
#def create_table(table_name, **options, &)
# result = super(table_name, **apply_defaults(:create_table, options), &)
# add_constraints(table_name, columns(table_name)) unless migration.reverting?
# result
#end
#def change_table(table_name, **options)
# return super if migration.reverting?
# before, result, after = columns(table_name), super, columns(table_name)
# add_constraints(table_name, after - before)
# remove_constraints(table_name, (before - after).map(&:name))
# result
#end
#def drop_table(*table_names, **options)
# super(*table_names, **apply_defaults(:drop_table, options))
#end
#def remove_column(table_name, column_name, type = nil, **options)
# remove_constraints(table_name, [column_name])
# super
#end
def method_missing(method, *args, **kwargs, &)
return super if migration.reverting?
# SchemaDumper#table has hardcoded: `tbl.puts ", force: :cascade do |t|"`.
# It collides with `if_not_exists`. Drop #except(*conflicts) after
# https://github.com/rails/rails/issues/37392 is fixed.
defaults = MIGRATION_DEFAULTS[method.to_sym]
conflicts = defaults.has_key?(:if_not_exists) ? [:force] : []
result = nil
process_method(method, *args, **kwargs) do
result = super(method, *args, **defaults.merge(kwargs.except(*conflicts)), &)
end
return result
end
def process_method(method, *args, **kwargs)
case method.to_sym
when :create_table
yield
add_constraints(args.first, columns(args.first))
when :change_table
before, _, after = columns(args.first), yield, columns(args.first)
add_constraints(args.first, after - before)
remove_constraints(args.first, (before - after).map(&:name))
when :remove_column
remove_constraints(args.first, [args.second])
yield
else
yield
end
end
private
# `if_not_exists: true`/`if_exists: true` - are necessary fo every top level
# migration statement. Without these options it's impossible to change
# migration status once it fails in the middle. If migration is only applied
# partially, its status is not updated. Then it's impossible to:
# a) migrate, because some objects have alredy been created/dropped and
# b) rollback, due to migration status.
# `timestamps` - Rails defaults to `null: false, precision: true`, as expected.
MIGRATION_DEFAULTS = {
add_check_constraint: {if_not_exists: true},
create_table: {if_not_exists: true},
drop_table: {if_exists: true},
remove_check_constraint: {if_exists: true},
}
MIGRATION_DEFAULTS.default = {}
MIGRATION_DEFAULTS.freeze
# SQLite does not enforce `limit` on string/text columns by default. `text`
# can be theoretically up to 1GB or longer, so roughly unlimited for practical
# purposes. But the actual usable length depends on additional factors, like
# compile time limits (`SQLITE_MAX_LENGTH` in SQLite) and probably other.
# Limit is explicitly set to:
# a) be used by views/UI (Rails does not report limit for `text` column
# types, unless it is explicitly set) and
# b) be enforced by database constraint (below).
# Length constraint is measured in codepoints (not bytes).
if options[:limit] && [:string, :text].include?(type)
check_constraint("length(#{name}) <= #{options[:limit]}", name: "#{name}_length")
def add_constraints(table_name, columns)
# Do not run on db:schema:load, as constraints are dumped explicitly.
return unless migration.name
columns.select { |column| column.limit && [:string, :text].include?(column.type) }
.each do |column|
expression = "length(#{column.name}) <= #{column.limit}"
name = "#{column.name}_length"
add_check_constraint(table_name, expression, name: name)
end
end
end
ActiveRecord::ConnectionAdapters::TableDefinition.prepend ColumnSettingsStrategy
# `if_not_exists: true`/`if_exists: true` - without these options it's impossible
# to change migration status once migration fails partially. If `up` migration
# creates some, but not all objects, its status is not updated from `down` to
# `up`. Then it's impossible to migrate: a) up - due to `already exists`
# errors and b) down - due to migration status. Similarily for `down`.
MIGRATION_DEFAULTS = {
add_check_constraint: {if_not_exists: true},
add_column: {if_not_exists: true},
add_foreign_key: {if_not_exists: true},
add_index: {if_not_exists: true, unique: true},
add_timestamps: {if_not_exists: true},
create_join_table: {force: :cascade},
create_table: {force: :cascade},
drop_table: {force: :cascade},
remove_check_constraint: {if_exists: true},
remove_column: {if_exists: true},
remove_foreign_key: {if_exists: true},
remove_index: {if_exists: true},
remove_timestamps: {if_exists: true},
}
MIGRATION_DEFAULTS.default = {}
MIGRATION_DEFAULTS.freeze
def method_missing(method, *args, **kwargs, &)
conflicts = kwargs.has_key?(:force) ? [:if_not_exists, :if_exists] : []
defaults = MIGRATION_DEFAULTS[method.to_sym].except(*conflicts)
super(method, *args, **defaults.merge(kwargs), &)
def remove_constraints(table_name, column_names)
column_names.each do |column_name|
remove_check_constraint(table_name, name: "#{column_name}_length")
end
end
# TODO: remove after commit
#def apply_defaults(method, options)
# defaults = MIGRATION_DEFAULTS[method]
# conflicts = defaults.has_key?(:if_not_exists) ? [:force] : []
# defaults.merge(options.except(*conflicts))
#end
end