Last active
March 29, 2024 14:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It looks like it may return a false positive in case you have a conditional validation, like