Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mlomnicki committed Oct 22, 2009
0 parents commit 6175ff3
Show file tree
Hide file tree
Showing 12 changed files with 329 additions and 0 deletions.
109 changes: 109 additions & 0 deletions CHANGELOG
@@ -0,0 +1,109 @@
[REVISION 20080131]

[FIXED] Stack-level too deep.

[NEW] Generate foreign keys for databases that currently have none. Doesn't check to see if the foreign key already exists, nor does it drop the foreign keys yet.

[REVISION 20071128]

[FIXED] Workaround to ensure plugin is only ever loaded once.

[REVISION 20070905]

[FIXED] "some_column_name" referenced in foreign key constraint does not exist.

[REVISION 20070904]

[NEW] Support :references keyword when calling primary_key().

[NEW] [#11995] the parameter :references needs the second argument referencing the field name.

[REVISION 20070707]

[NEW] Support acts_as_tree convention: if a column is named parent_id it will be treated as a circular reference to the table in which it is defined.

[REVISION 20070703]

[FIXED] Foreign-keys not created when using add_column.

[REVISION 20070628]

[FIXED] Stack level too deep in 'add_column_without_foreign_key_migrations' (Ronen Barzel).

[REVISION 20070503]

[NEW] Support for SQL92 [NOT] DEFERRABLE on foreign keys.

[REVISION 20061202]

[CHANGED] Use Rails 1.2 alias_method_chain.

[CHANGED] Separate modules into individual files.

[REVISION 20061013]

[NEW] install.rb informs user of missing dependencies.

[REVISION 20060909]

[CHANGED] Replaced dependence on defunct Foreign Key Support and Schema Defining plugins with a single dependece on RedHill on Rails Core.

[REVISION 20060831]

[CHANGED] Separated out generic foreign-key functionality into new foreign key support plugin.

[REVISION 20060629]

[NEW] Added foreign_key method to table to allow t.foreign_key(columns, references_table_name, references_column_names, options).

[NEW] Support foreign keys in add_column as we do for initial table columns.

[NEW] Support :on_update and :on_delete as options--with values of :set_null, :cascade, or :restrict--for all foreign key creation mechanisms.

[REVISION 20060627]

[CHANGED] Reverted to overloaded column method with optional :references as the preferred mechanism with belongs_to a "nicety". This is really as a result of using it in a large-scale production application where belongs_to just didn't feel right in many cases and was semantically ambiguous.

[REVISION 20060824]

[CHANGED] Replaced method and column option :references with :belongs_to in keeping with the rails model keywords. The references variations are still available but have been deprecated and will be removed.

[NEW] Added options :dependent => :nullify to SET NULL or :dependent => :delete_all | :destroy to CASCADE DELETE.

[REVISION 20060812]

[NEW] Added new table method references(table, options) which is essentially an alias for column(:table_id, :integer, options).

[REVISION 20060803]

[FIXED] The method proper_pluralized_table_name tries to call pluralize_table_name where it should call pluralized_table_name.

[REVISION 20060623]

[FIXED] Another try at a hack-around for a "feature" of pluralize that when called to pluralize a word that is already in the plural, acts as singularize.

[REVISION 20060616]

[FIXED] Hack-around for a "feature" of pluralize that when called to pluralize a word that is already in the plural, acts as singularize. Ie. "countries".pluralize becomes "country"!

[REVISION 200606004]

[CHANGED] This plugin now depends on Schema Defining!

[REVISION 20060602]

[CHANGED] Simplified static method overriding thanks to Ryan Tomayko.

[REVISION 20060525]

[CHANGED] Disabled foreign-key generation when executing a schema dump. This is a temporary measure until I get around to batching up the foreign keys at the end of the script.

[REVISION 20060523]

[NEW] Support :references => nil to prevent unwanted foreign-keys.

[FIXED] Pluralization.

[REVISION 20060522]

[FIXED] Infinite recursion caused by bug in 1.8.4 method_alias on windows.
20 changes: 20 additions & 0 deletions MIT-LICENSE
@@ -0,0 +1,20 @@
Copyright (c) 2006 RedHill Consulting, Pty. Ltd.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
91 changes: 91 additions & 0 deletions README
@@ -0,0 +1,91 @@
= Foreign Key Migrations

Foreign Key Migrations is a plugin that automatically generates foreign-key
constraints when creating tables. It uses SQL-92 syntax and as such should be
compatible with most databases that support foreign-key constraints.

In the simplest case, the plugin assumes that if you have a column named
+customer_id+ that you want a foreign-key constraint generated that references
the +id+ column in the +customers+ table:

create_table :orders do |t|
t.column :customer_id, :integer, :null => false
...
end

If you have multiple columns referencing a table or for whatever reason, your
column name isn't the same as the referenced table name, you can use the
<code>:references</code> option:

create_table :orders do |t|
t.column :ordered_by_id, :integer, :null => false, :references => :customers
...
end

If you have a column with a name ending in +_id+ for which you do not wish a
foreign-key to be generated, you can use <code>:references => nil</code>:

create_table :orders do |t|
t.column :external_id, :integer, :null => false, :references => nil
...
end

Sometimes you may (for legacy reasons) need to reference a primary key column that is
named something other than +id+. In this case you can specify the name of the column:

create_table :orders do |t|
t.column :ordered_by_pk, :integer, :null => false, :references => [:customers, :pk]
...
end

You also have the option of specifying what to do on delete/update using
<code>:on_delete</code>/<code>:on_update</code>, respectively to one of:
<code>:cascade</code>; <code>:restrict</code>; and <code>:set_null</code>:

create_table :orders do |t|
t.column :customer_id, :integer, :on_delete => :set_null, :on_update => :cascade
...
end

If your database supports it (for example PostgreSQL) you can also mark the constraint as deferrable:

create_table :orders do |t|
t.column :customer_id, :integer, :deferrable => true
...
end

By convention, if a column is named +parent_id+ it will be treated as a circular reference to
the table in which it is defined.

Sometimes you may (for legacy reasons) need to name your primary key column such that it
would be misinterpreted as a foreign-key (say for example if you named the primary key
+order_id+). In this case you can manually create the primary key as follows:

create_table :orders, :id => false do |t|
...
t.primary_key :order_id, :references => nil
end

There is also a generator for creating foreign keys on a database that currently has none:

ruby script/generate foreign_key_migration

The plugin fully supports and understands the following active-record
configuration properties:

* <code>config.active_record.pluralize_table_names</code>
* <code>config.active_record.table_name_prefix</code>
* <code>config.active_record.table_name_suffix</code>

=== Dependencies

* RedHill on Rails Core (redhillonrails_core).

=== See Also

* Foreign Key Associations (foreign_key_associations).

=== License

This plugin is copyright 2006 by RedHill Consulting, Pty. Ltd. and is released
under the MIT license.
5 changes: 5 additions & 0 deletions about.yml
@@ -0,0 +1,5 @@
author: simon@redhillconsulting.com.au
summary: Automatically generates foreign-key constraints when creating tables.
homepage: http://www.redhillonrails.org
license: MIT
rails_version: EDGE
@@ -0,0 +1,24 @@
class ForeignKeyMigrationGenerator < Rails::Generator::NamedBase
def initialize(runtime_args, runtime_options = {})
runtime_args << 'create_foreign_keys' if runtime_args.empty?
super
end

def manifest
foreign_keys = []

connection = ActiveRecord::Base.connection
connection.tables.each do |table_name|
connection.columns(table_name).each do |column|
references = ActiveRecord::Base.references(table_name, column.name)
foreign_keys << RedHillConsulting::Core::ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(nil, table_name, column.name, references.first, references.last) if references
end
end

record do |m|
m.migration_template 'migration.rb', 'db/migrate', :assigns => {
:migration_name => class_name, :foreign_keys => foreign_keys
}, :migration_file_name => file_name
end
end
end
10 changes: 10 additions & 0 deletions generators/foreign_key_migration/templates/migration.rb
@@ -0,0 +1,10 @@
class <%= migration_name %> < ActiveRecord::Migration
def self.up
<% foreign_keys.each do |foreign_key| -%>
<%= foreign_key.to_dump %>
<% end -%>
end

def self.down
end
end
1 change: 1 addition & 0 deletions init.rb
@@ -0,0 +1 @@
require 'foreign_key_migrations' unless defined?(RedHillConsulting::ForeignKeyMigrations)
1 change: 1 addition & 0 deletions install.rb
@@ -0,0 +1 @@
puts "WARNING: You also need to install redhillonrails_core" unless File.exists?(File.join(File.dirname(__FILE__), "..", "redhillonrails_core"))
3 changes: 3 additions & 0 deletions lib/foreign_key_migrations.rb
@@ -0,0 +1,3 @@
ActiveRecord::Base.send(:include, RedHillConsulting::ForeignKeyMigrations::ActiveRecord::Base)
ActiveRecord::Migration.send(:include, RedHillConsulting::ForeignKeyMigrations::ActiveRecord::Migration)
ActiveRecord::ConnectionAdapters::TableDefinition.send(:include, RedHillConsulting::ForeignKeyMigrations::ActiveRecord::ConnectionAdapters::TableDefinition)
@@ -0,0 +1,22 @@
module RedHillConsulting::ForeignKeyMigrations::ActiveRecord
module Base
def self.included(base)
base.extend(ClassMethods)
end

module ClassMethods
def references(table_name, column_name, options = {})
column_name = column_name.to_s
if options.has_key?(:references)
references = options[:references]
references = [references, :id] unless references.nil? || references.is_a?(Array)
references
elsif column_name == 'parent_id'
[table_name, :id]
elsif column_name =~ /^(.*)_id$/
[pluralized_table_name($1), :id]
end
end
end
end
end
@@ -0,0 +1,28 @@
module RedHillConsulting::ForeignKeyMigrations::ActiveRecord::ConnectionAdapters
module TableDefinition
def self.included(base)
base.class_eval do
alias_method_chain :column, :foreign_key_migrations
alias_method_chain :primary_key, :foreign_key_migrations
end
end

def primary_key_with_foreign_key_migrations(name, options = {})
column(name, :primary_key, options)
end

def column_with_foreign_key_migrations(name, type, options = {})
column_without_foreign_key_migrations(name, type, options)
references = ActiveRecord::Base.references(self.name, name, options)
foreign_key(name, references.first, references.last, options) if references
self
end

# Some people liked this; personally I've decided against using it but I'll keep it nonetheless
def belongs_to(table, options = {})
options = options.merge(:references => table)
options[:on_delete] = options.delete(:dependent) if options.has_key?(:dependent)
column("#{table.to_s.singularize}_id".to_sym, :integer, options)
end
end
end
@@ -0,0 +1,15 @@
module RedHillConsulting::ForeignKeyMigrations::ActiveRecord
module Migration
def self.included(base)
base.extend(ClassMethods)
end

module ClassMethods
def add_column(table_name, column_name, type, options = {})
super
references = ActiveRecord::Base.references(table_name, column_name, options)
add_foreign_key(table_name, column_name, references.first, references.last, options) if references
end
end
end
end

0 comments on commit 6175ff3

Please sign in to comment.