Skip to content

Commit

Permalink
Check timestamp columns (created_at, updated_at) are NOT NULL
Browse files Browse the repository at this point in the history
Once the timestamps columns are established on a table, they might as
well be NOT NULL to enforce their existence. All ActiveRecord operations
set these values so they will always exist under normal usage.

Fixes #184
  • Loading branch information
jdufresne committed Sep 2, 2024
1 parent a4f5d7f commit b44c5c6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ class MissingNonNullConstraint < Base # :nodoc:
private

def message(column:, table:)
"add `NOT NULL` to #{table}.#{column} - models validates its presence but it's not non-NULL in the database"
message = "add `NOT NULL` to #{table}.#{column}"
unless ["created_at", "updated_at"].include?(column)
message = "#{messages} - models validates its presence but it's not non-NULL in the database"
end
message
end

def detect
Expand Down Expand Up @@ -50,6 +54,8 @@ def sti_base_model?(model)
end

def non_null_needed?(model, column)
return true if column.name == "created_at" || column.name == "updated_at"

belongs_to = model.reflect_on_all_associations(:belongs_to).find do |reflection|
reflection.foreign_key == column.name ||
(reflection.polymorphic? && reflection.foreign_type == column.name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,4 +310,15 @@ def test_config_ignore_columns

refute_problems
end

def test_timestamps_with_null_are_disallowed
Context.create_table(:users) do |t|
t.timestamps null: true
end.define_model

assert_problems(<<~OUTPUT)
add `NOT NULL` to users.created_at
add `NOT NULL` to users.updated_at
OUTPUT
end
end

0 comments on commit b44c5c6

Please sign in to comment.