Module: RailsFields::Utils

Defined in:
lib/rails_fields/utils/helpers.rb,
lib/rails_fields/utils/logging.rb,
lib/rails_fields/utils/mappings.rb

Defined Under Namespace

Classes: AssociationRef

Constant Summary collapse

LOGGER =
begin
  logger = Logger.new($stdout)
  logger.level = Rails.env.production? ? Logger::INFO : Logger::DEBUG
  logger
end
GQL_TO_RAILS_TYPE_MAP =

TODO: mapper can be different or custom

{
  ::GraphQL::Types::String => :string,
  ::GraphQL::Types::Int => :integer,
  ::GraphQL::Types::Float => :float,
  ::GraphQL::Types::Boolean => :boolean,
  ::GraphQL::Types::ID => :integer, # or :string depending on how you handle IDs
  ::GraphQL::Types::ISO8601DateTime => :datetime,
  ::GraphQL::Types::ISO8601Date => :date,
  ::GraphQL::Types::JSON => :json,
  ::GraphQL::Types::BigInt => :bigint
}.freeze
RAILS_TO_GQL_TYPE_MAP =
{
  # id: ::GraphQL::Types::String,
  string: ::GraphQL::Types::String,
  integer: ::GraphQL::Types::Int,
  float: ::GraphQL::Types::Float,
  boolean: ::GraphQL::Types::Boolean,
  datetime: ::GraphQL::Types::ISO8601DateTime,
  date: ::GraphQL::Types::ISO8601Date,
  json: ::GraphQL::Types::JSON,
  bigint: ::GraphQL::Types::BigInt,
  text: ::GraphQL::Types::String
}.freeze

Class Method Summary collapse

Class Method Details

.active_record_modelsObject



16
17
18
19
20
21
22
23
24
25
# File 'lib/rails_fields/utils/helpers.rb', line 16

def active_record_models
  Rails.application.eager_load! # Ensure all models are loaded

  ActiveRecord::Base.descendants.reject do |model|
    !(model.is_a?(Class) && model < ApplicationRecord) ||
      model.abstract_class? ||
      model.name.nil? ||
      model.name == "ActiveRecord::SchemaMigration"
  end
end

.allowed_typesObject



6
7
8
9
# File 'lib/rails_fields/utils/helpers.rb', line 6

def allowed_types
  # TODO: this may depend on the current database adapter or mapper
  ActiveRecord::Base.connection.native_database_types.keys
end

.detect_changes(model) ⇒ Hash, Nil

Detect changes between the ActiveRecord model declared fields and the database structure.

Examples:

model_changes = FieldEnforcement::Utils.detect_changes(User)
# => {
  added: [],
  removed: [],
  renamed: [],
  type_changed: [],
  potential_renames: []
}


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/rails_fields/utils/helpers.rb', line 39

def detect_changes(model)
  # Exclude the primary key (e.g., :id) from comparisons
  primary_key = model.primary_key&.to_sym
  previous_fields = model.attribute_types
                     .to_h { |k, v| [k.to_sym, v.type] }
                     .reject { |name, _| name == primary_key }
  declared_fields = model.declared_fields.to_h do |f|
    [f.name.to_sym, {
      name: f.type.to_sym,
      options: f.options
    }]
  end

  LOGGER.debug "Log: previous_fields: #{previous_fields}"
  LOGGER.debug "Log: declared_fields #{declared_fields}}"

  model_changes = {
    added: [],
    removed: [],
    renamed: [],
    type_changed: [],
    potential_renames: [],
    associations_added: [],
    associations_removed: []
  }

  # Detect added and type-changed fields
  declared_fields.each do |name, type|
    type_name = type[:name]
    if previous_fields[name]
      if previous_fields[name] != type_name
        model_changes[:type_changed] << { name:, from: previous_fields[name], to: type }
      end
    else
      model_changes[:added] << { name:, type: }
    end
  end

  LOGGER.debug "Log: model_changes[:added] before filter #{model_changes[:added]}"
  # Remove added fields that have a defined method in the the model
  model_changes[:added] = model_changes[:added].filter { |f| !model.instance_methods.include?(f[:name]) }
  LOGGER.debug "Log: model_changes[:added] after filter #{model_changes[:added]}"

  # Detect removed fields
  removed_fields = previous_fields.keys - declared_fields.keys
  model_changes[:removed] = removed_fields.map { |name| { name:, type: previous_fields[name] } }

  LOGGER.debug "Log: model_changes[:removed] 1 #{model_changes[:removed]}"

  # Remove foreign keys from removed fields
  associations = model.reflections.values.map(&:foreign_key).map(&:to_sym)
  model_changes[:removed].reject! { |f| associations.include?(f[:name]) }

  LOGGER.debug "Log: model_changes[:removed] 2 #{model_changes[:removed]} | associations #{associations}"

  # Detect potential renames
  potential_renames = []
  model_changes[:removed].each do |removed_field|
    # Match by type name (normalize Hash/Scalar)
    added_field = model_changes[:added].find do |f|
      added_type = f[:type].is_a?(Hash) ? f[:type][:name] : f[:type]
      added_type == removed_field[:type]
    end
    if added_field
      potential_renames << { from: removed_field[:name],
                             to: added_field[:name] }
    end
  end

  LOGGER.debug "Log: potential_renames: #{potential_renames}"

  model_changes[:potential_renames] = potential_renames

  # Filter out incorrect renames (one-to-one mapping)
  potential_renames.each do |rename|
    next unless model_changes[:added].count { |f| f[:name] == rename[:to].to_sym } == 1 &&
      model_changes[:removed].count { |f| f[:name] == rename[:from].to_sym } == 1

    model_changes[:renamed] << rename
    model_changes[:added].reject! { |f| f[:name] == rename[:to].to_sym }
    model_changes[:removed].reject! { |f| f[:name] == rename[:from].to_sym }
  end

  # Handle associations changes
  declared_associations = model.reflections.values.select do |reflection|
    [:belongs_to].include?(reflection.macro)
  end

  declared_foreign_keys = declared_associations.map(&:foreign_key).map(&:to_sym)
  existing_foreign_keys = ActiveRecord::Base.connection
    .foreign_keys(model.table_name)
    .map { |fk| fk.respond_to?(:column) ? fk.column.to_sym : fk.options[:column].to_sym }

  associations_added = declared_associations.select do |reflection|
    !existing_foreign_keys.include?(reflection.foreign_key.to_sym)
  end

  associations_removed = existing_foreign_keys
    .select { |foreign_key| !declared_foreign_keys.include?(foreign_key) }
    .map do |foreign_key|
      model.reflections.values.find { |reflection| reflection.foreign_key == foreign_key.to_s } ||
        AssociationRef.new(foreign_key.to_s.delete_suffix('_id').to_sym)
    end

  model_changes[:associations_added] = associations_added
  model_changes[:associations_removed] = associations_removed

  return model_changes unless model_changes.values.all?(&:empty?)

  nil
end

.generate_migration(model, model_changes, index: 0, write: false) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/rails_fields/utils/helpers.rb', line 151

def generate_migration(model, model_changes, index: 0, write: false)
  return if model_changes.blank?

  model_name = model.name
  timestamp = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i + index
  migration_class_name = "#{model_name}Migration#{timestamp}"

  migration_code = []
  migration_code << "class #{migration_class_name} < ActiveRecord::Migration[#{ActiveRecord::Migration.current_version}]"

  migration_code << "  def change"

  model_changes.dig(:added)&.each do |change|
    field_type = change[:type]
    field_type_for_db = field_type[:name]
    # TODO: custom mapper
    migration_code << "    add_column :#{model.table_name}, :#{change[:name]}, :#{field_type_for_db}"
  end

  # Handle added associations
  model_changes.dig(:associations_added)&.each do |assoc|
    migration_code << "    add_reference :#{model.table_name}, :#{assoc.name}, foreign_key: true"
  end

  # Handle removed associations
  model_changes.dig(:associations_removed)&.each do |assoc|
    migration_code << "    remove_reference :#{model.table_name}, :#{assoc.name}, foreign_key: true"
  end

  # Handle removed fields
  model_changes.dig(:removed)&.each do |change|
    migration_code << "    remove_column :#{model.table_name}, :#{change[:name]}"
  end

  # Handle renamed fields
  model_changes.dig(:renamed)&.each do |change|
    change_to = change[:to]
    migration_code << "    rename_column :#{model.table_name}, :#{change[:from]}, :#{change_to}"
  end

  # Handle fields' type changes
  model_changes.dig(:type_changed)&.each do |change|
    change_to = change[:to][:name]
    migration_code << "    change_column :#{model.table_name}, :#{change[:name]}, :#{change_to}"
  end

  migration_code << "  end"
  migration_code << "end"
  migration_code << ""

  write_migration(migration_code, migration_class_name, timestamp) if write

  migration_code.join("\n")
end

.valid_type?(type) ⇒ Boolean



11
12
13
14
# File 'lib/rails_fields/utils/helpers.rb', line 11

def valid_type?(type)
  # TODO: this may depend on the current database adapter or mapper
  allowed_types.include?(type)
end

.write_migration(migration_code, migration_class_name, timestamp) ⇒ Object



206
207
208
209
210
211
212
# File 'lib/rails_fields/utils/helpers.rb', line 206

def write_migration(migration_code, migration_class_name, timestamp)
  migration_filename = "#{timestamp}_#{migration_class_name.underscore}.rb"
  migration_path = Rails.root.join("db", "migrate", migration_filename)
  File.write(migration_path, migration_code.join("\n"))
  LOGGER.info "Migration saved at #{migration_path}"
  { migration_filename:, migration_path: }
end