Skip to content

Instantly share code, notes, and snippets.

@delbetu
Last active March 29, 2024 14:47
Show Gist options
  • Save delbetu/6054dbecd1b1e0133ecb938bdc6f517c to your computer and use it in GitHub Desktop.
Save delbetu/6054dbecd1b1e0133ecb938bdc6f517c to your computer and use it in GitHub Desktop.
Every attribute on a model with 'presence: true' shouldn't allow nulls on db. This script helps identify missing not null constraints. It looks for attributes with presence: true and checks these have NOT NULL on db/structure.sql
# frozen_string_literal: true
require "active_support/all"
def null_on_db?(table_name, col_name)
db_structure = File.read("db/structure.sql")
db_structure.match(/CREATE TABLE public.#{table_name} \((?<cols>.*?)\)/m) || {cols: ""} => { cols: attrs }
attrs.match?(/#{col_name}.*NOT NULL/)
end
Dir.glob("app/models/*.rb").each do |file|
File.read(file).match(/validates (?<attr>:.*),.*presence: true/) || {attr: nil} => {attr:}
next unless attr
table_name = File.basename(file, ".rb").pluralize
cols = attr.delete(":").split(",").map(&:strip)
cols&.each do |col|
puts "#{table_name}.#{col} has presence: true but db allows null" unless null_on_db?(table_name, col)
end
end
@carlos-ghan
Copy link

It looks like it may return a false positive in case you have a conditional validation, like

validates :asset_class, presence: true, if: :lease_accounting_enabled?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment