Module: MiniRecord::AutoSchema::ClassMethods

Defined in:
lib/mini_record/auto_schema.rb

Instance Method Summary collapse

Instance Method Details

#add_foreign_keys ⇒ Object

Add foreign keys for indexes with :foreign=>true option, if the key doesn't exists



143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/mini_record/auto_schema.rb', line 143

def add_foreign_keys
  indexes.each do |name, options|
    if options[:foreign]
      column = options[:column].to_s
      unless foreign_keys.detect { |fk| fk[:options][:column] == column }
        to_table = reflect_on_all_associations.detect { |a| a.foreign_key.to_s==column }.table_name
        connection.add_foreign_key(table_name, to_table, options)
        foreign_keys << { :options=> { :column=>column } }
      end
    end
  end
end

#add_index(column_name, options = {}) ⇒ Object Also known as: index



102
103
104
105
106
# File 'lib/mini_record/auto_schema.rb', line 102

def add_index(column_name, options={})
  index_name = connection.index_name(table_name, :column => column_name)
  indexes[index_name] = options.merge(:column => column_name) unless indexes.key?(index_name)
  index_name
end

#auto_upgrade! ⇒ Object



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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/mini_record/auto_schema.rb', line 156

def auto_upgrade!
  return unless connection?

  if self == ActiveRecord::Base
    descendants.each(&:auto_upgrade!)
    clear_tables!
  else
    # If table doesn't exist, create it
    unless connection.tables.include?(table_name)
      # TODO: create_table options
      class << connection; attr_accessor :table_definition; end unless connection.respond_to?(:table_definition=)
      connection.table_definition = table_definition
      connection.create_table(table_name)
      connection.table_definition = ActiveRecord::ConnectionAdapters::TableDefinition.new(connection)
    end

    # Add this to our schema tables
    schema_tables << table_name unless schema_tables.include?(table_name)

    # Generate fields from associations
    if reflect_on_all_associations.any?
      reflect_on_all_associations.each do |association|
        foreign_key = association.options[:foreign_key] || "#{association.name}_id"
        type_key    = "#{association.name.to_s}_type"
        case association.macro
        when :belongs_to
          field foreign_key, :as => :integer unless fields.key?(foreign_key.to_s)
          if association.options[:polymorphic]
            field type_key, :as => :string unless fields.key?(type_key.to_s)
            index [foreign_key, type_key]
          else
            index foreign_key
          end
        when :has_and_belongs_to_many
          table = if name = association.options[:join_table]
                    name.to_s
                  else
                    [table_name, association.name.to_s].sort.join("_")
                  end
          unless connection.tables.include?(table.to_s)
            foreign_key             = association.options[:foreign_key] || association.foreign_key
            association_foreign_key = association.options[:association_foreign_key] || association.association_foreign_key
            connection.create_table(table, :id => false) do |t|
              t.integer foreign_key
              t.integer association_foreign_key
            end
            index_name = connection.index_name(table, :column => [foreign_key, association_foreign_key])
            index_name = index_name[0...connection.index_name_length] if index_name.length > connection.index_name_length
            connection.add_index table, [foreign_key, association_foreign_key], :name => index_name, :unique => true
          end
          # Add join table to our schema tables
          schema_tables << table unless schema_tables.include?(table)
        end
      end
    end

    # Add to schema inheritance column if necessary
    if descendants.present?
      field inheritance_column, :as => :string unless fields.key?(inheritance_column.to_s)
      index inheritance_column
    end

    # Remove fields from db no longer in schema
    (fields_in_db.keys - fields.keys & fields_in_db.keys).each do |field|
      column = fields_in_db[field]
      connection.remove_column table_name, column.name
    end

    # Add fields to db new to schema
    (fields.keys - fields_in_db.keys).each do |field|
      column  = fields[field]
      options = {:limit => column.limit, :precision => column.precision, :scale => column.scale}
      options[:default] = column.default unless column.default.nil?
      options[:null]    = column.null    unless column.null.nil?
      connection.add_column table_name, column.name, column.type.to_sym, options
    end

    # Change attributes of existent columns
    (fields.keys & fields_in_db.keys).each do |field|
      if field != primary_key #ActiveRecord::Base.get_primary_key(table_name)
        changed  = false  # flag
        new_type = fields[field].type.to_sym
        new_attr = {}

        # First, check if the field type changed
        if fields[field].sql_type.to_s.downcase != fields_in_db[field].sql_type.to_s.downcase
          logger.debug "[MiniRecord] Detected schema change for #{table_name}.#{field}#type from " +
                       "#{fields[field].sql_type.to_s.downcase.inspect} in #{fields_in_db[field].sql_type.to_s.downcase.inspect}" if logger
          changed = true
        end

        # Special catch for precision/scale, since *both* must be specified together
        # Always include them in the attr struct, but they'll only get applied if changed = true
        new_attr[:precision] = fields[field][:precision]
        new_attr[:scale]     = fields[field][:scale]

        # If we have precision this is also the limit
        fields[field][:limit] ||= fields[field][:precision]

        # Next, iterate through our extended attributes, looking for any differences
        # This catches stuff like :null, :precision, etc
        fields[field].each_pair do |att,value|
          next if att == :type or att == :base or att == :name # special cases
          value = true if att == :null && value.nil?
          if value != fields_in_db[field].send(att)
            logger.debug "[MiniRecord] Detected schema change for #{table_name}.#{field}##{att} "+
                         "from #{fields_in_db[field].send(att).inspect} in #{value.inspect}" if logger
            new_attr[att] = value
            changed = true
          end
        end

        # Change the column if applicable
        connection.change_column table_name, field, new_type, new_attr if changed
      end
    end

    remove_foreign_keys if connection.respond_to?(:foreign_keys)

    # Remove old index
    (indexes_in_db.keys - indexes.keys).each do |name|
      connection.remove_index(table_name, :name => name)
    end

    # Add indexes
    indexes.each do |name, options|
      options = options.dup
      unless connection.indexes(table_name).detect { |i| i.name == name }
        connection.add_index(table_name, options.delete(:column), options)
      end
    end

    add_foreign_keys if connection.respond_to?(:foreign_keys)

    # Reload column information
    reset_column_information
  end
end

#clear_tables! ⇒ Object



116
117
118
119
120
121
# File 'lib/mini_record/auto_schema.rb', line 116

def clear_tables!
  (connection.tables - schema_tables).each do |name|
    connection.drop_table(name)
    schema_tables.delete(name)
  end
end

#connection? ⇒ Boolean

Returns:

  • (Boolean)


109
110
111
112
113
114
# File 'lib/mini_record/auto_schema.rb', line 109

def connection?
  !!connection
rescue Exception => e
  puts "\e[31m%s\e[0m" % e.message.strip
  false
end

#field(*args) ⇒ Object Also known as: key, property, col



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
# File 'lib/mini_record/auto_schema.rb', line 50

def field(*args)
  return unless connection?

  options    = args.extract_options!
  type       = options.delete(:as) || options.delete(:type) || :string
  index      = options.delete(:index)

  args.each do |column_name|

    # Allow custom types like:
    #   t.column :type, "ENUM('EMPLOYEE','CLIENT','SUPERUSER','DEVELOPER')"
    if type.is_a?(String)
      # will be converted in: t.column :type, "ENUM('EMPLOYEE','CLIENT')"
      table_definition.column(column_name, type, options.reverse_merge(:limit => 0))
    else
      # wil be converted in: t.string :name
      table_definition.send(type, column_name, options)
    end

    # Get the correct column_name i.e. in field :category, :as => :references
    column_name = table_definition.columns[-1].name

    # Parse indexes
    case index
    when Hash
      add_index(options.delete(:column) || column_name, index)
    when TrueClass
      add_index(column_name)
    when String, Symbol, Array
      add_index(index)
    end
  end
end

#fields ⇒ Object



36
37
38
39
40
41
# File 'lib/mini_record/auto_schema.rb', line 36

def fields
  table_definition.columns.inject({}) do |hash, column|
    hash[column.name] = column
    hash
  end
end

#fields_in_db ⇒ Object



43
44
45
46
47
48
# File 'lib/mini_record/auto_schema.rb', line 43

def fields_in_db
  connection.columns(table_name).inject({}) do |hash, column|
    hash[column.name] = column
    hash
  end
end

#foreign_keys ⇒ Object



123
124
125
126
127
# File 'lib/mini_record/auto_schema.rb', line 123

def foreign_keys
  # fk cache to minimize quantity of sql queries
  @foreign_keys ||= {}
  @foreign_keys[:table_name] ||= connection.foreign_keys(table_name)
end

#indexes ⇒ Object



23
24
25
26
27
# File 'lib/mini_record/auto_schema.rb', line 23

def indexes
  return superclass.indexes unless superclass == ActiveRecord::Base

  @_indexes ||= {}
end

#indexes_in_db ⇒ Object



29
30
31
32
33
34
# File 'lib/mini_record/auto_schema.rb', line 29

def indexes_in_db
  connection.indexes(table_name).inject({}) do |hash, index|
    hash[index.name] = index
    hash
  end
end

#remove_foreign_keys ⇒ Object

Remove foreign keys for indexes with :foreign=>false option



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/mini_record/auto_schema.rb', line 130

def remove_foreign_keys
  indexes.each do |name, options|
    if options[:foreign]==false
      foreign_key = foreign_keys.detect { |fk| fk.options[:column] == options[:column].to_s }
      if foreign_key
        connection.remove_foreign_key(table_name, :name => foreign_key.options[:name])
        foreign_keys.delete(foreign_key)
      end
    end
  end
end

#reset_table_definition! ⇒ Object Also known as: reset_schema!



91
92
93
# File 'lib/mini_record/auto_schema.rb', line 91

def reset_table_definition!
  @_table_definition = nil
end

#schema {|table_definition| ... } ⇒ Object

Yields:



96
97
98
99
100
# File 'lib/mini_record/auto_schema.rb', line 96

def schema
  reset_table_definition!
  yield table_definition
  table_definition
end

#schema_tables ⇒ Object



9
10
11
# File 'lib/mini_record/auto_schema.rb', line 9

def schema_tables
  @@_schema_tables ||= []
end

#table_definition ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/mini_record/auto_schema.rb', line 13

def table_definition
  return superclass.table_definition unless superclass == ActiveRecord::Base

  @_table_definition ||= begin
                           tb = ActiveRecord::ConnectionAdapters::TableDefinition.new(connection)
                           tb.primary_key(primary_key)
                           tb
                         end
end

#timestamps ⇒ Object



87
88
89
# File 'lib/mini_record/auto_schema.rb', line 87

def timestamps
  field :created_at, :updated_at, :as => :datetime, :null => false
end