activerecord-creating_foreign_keys 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +53 -0
  4. data/Rakefile +36 -0
  5. data/lib/active_record/creating_foreign_keys.rb +13 -0
  6. data/lib/active_record/creating_foreign_keys/schema_creation.rb +36 -0
  7. data/lib/active_record/creating_foreign_keys/schema_statements.rb +41 -0
  8. data/lib/active_record/creating_foreign_keys/version.rb +7 -0
  9. data/test/creating_foreign_keys_test.rb +87 -0
  10. data/test/dummy/README.rdoc +28 -0
  11. data/test/dummy/Rakefile +6 -0
  12. data/test/dummy/app/assets/javascripts/application.js +13 -0
  13. data/test/dummy/app/assets/stylesheets/application.css +15 -0
  14. data/test/dummy/app/controllers/application_controller.rb +5 -0
  15. data/test/dummy/app/helpers/application_helper.rb +2 -0
  16. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  17. data/test/dummy/bin/bundle +3 -0
  18. data/test/dummy/bin/rails +4 -0
  19. data/test/dummy/bin/rake +4 -0
  20. data/test/dummy/bin/setup +29 -0
  21. data/test/dummy/config.ru +4 -0
  22. data/test/dummy/config/application.rb +26 -0
  23. data/test/dummy/config/boot.rb +5 -0
  24. data/test/dummy/config/database.yml +16 -0
  25. data/test/dummy/config/environment.rb +5 -0
  26. data/test/dummy/config/environments/development.rb +41 -0
  27. data/test/dummy/config/environments/production.rb +79 -0
  28. data/test/dummy/config/environments/test.rb +42 -0
  29. data/test/dummy/config/initializers/assets.rb +11 -0
  30. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  31. data/test/dummy/config/initializers/cookies_serializer.rb +3 -0
  32. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  33. data/test/dummy/config/initializers/inflections.rb +16 -0
  34. data/test/dummy/config/initializers/mime_types.rb +4 -0
  35. data/test/dummy/config/initializers/session_store.rb +3 -0
  36. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  37. data/test/dummy/config/locales/en.yml +23 -0
  38. data/test/dummy/config/routes.rb +56 -0
  39. data/test/dummy/config/secrets.yml +22 -0
  40. data/test/dummy/public/404.html +67 -0
  41. data/test/dummy/public/422.html +67 -0
  42. data/test/dummy/public/500.html +66 -0
  43. data/test/dummy/public/favicon.ico +0 -0
  44. data/test/test_helper.rb +27 -0
  45. metadata +236 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: d793ee206e5cd56d2a8ce657cdfe3c10cbc8849a
4
+ data.tar.gz: 7e03014b0adac230210fcb8daea1833ecaf908ae
5
+ SHA512:
6
+ metadata.gz: ddf9ef6336460563a25d8990b5b7fe26c30e4c046bd1d7c1a3fb7e920510fc44bfbc0f9e10b05ad54e90e25d501c2919dcf595e4cc680719b1c09ffe979b7e9c
7
+ data.tar.gz: c815f7517ec76a3b113af81dc482feb2ea7b6f8f5b3cdd70b576dc61d924f6b9a1c23bb0ca502023c47c286b553fd38e36ea807f1f30ff53c8451cb6169f4114
@@ -0,0 +1,20 @@
1
+ Copyright 2020 hamuyuuki
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,53 @@
1
+ [![Build Status](https://travis-ci.com/hamuyuuki/activerecord-creating_foreign_keys.svg?branch=master)](https://travis-ci.com/hamuyuuki/activerecord-creating_foreign_keys)
2
+ [![Maintainability](https://api.codeclimate.com/v1/badges/3cac3284bb083ea1f9cd/maintainability)](https://codeclimate.com/github/hamuyuuki/activerecord-creating_foreign_keys/maintainability)
3
+ [![Test Coverage](https://api.codeclimate.com/v1/badges/3cac3284bb083ea1f9cd/test_coverage)](https://codeclimate.com/github/hamuyuuki/activerecord-creating_foreign_keys/test_coverage)
4
+
5
+ # activerecord-creating_foreign_keys
6
+ `activerecord-creating_foreign_keys` defines FOREIGN KEY Constraints in a CREATE TABLE Statement.
7
+
8
+ Rails 4.2 [supports adding and removing foreign keys](https://guides.rubyonrails.org/v4.2/4_2_release_notes.html#foreign-key-support). And Rails 4.2.1 [supports adding a `:foreign_key` option to `references`](https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md#rails-421-march-19-2015).
9
+ But it defines FOREIGN KEY Constraints in a ALTER TABLE Statement as an additional DDL when you define a `:foreign_key` option to `references`.
10
+
11
+ Rails 5 [supports defining FOREIGN KEY Constraints in a CREATE TABLE Statement](https://github.com/rails/rails/pull/20009/files). So `activerecord-creating_foreign_keys` backports that into Rails 4.2.
12
+
13
+ ## Getting Started
14
+ Install `activerecord-creating_foreign_keys` at the command prompt:
15
+ ```sh
16
+ gem install activerecord-creating_foreign_keys
17
+ ```
18
+
19
+ Or add `activerecord-creating_foreign_keys` to your Gemfile:
20
+ ```ruby
21
+ gem "activerecord-creating_foreign_keys"
22
+ ```
23
+
24
+ ## How to use
25
+ You don't need to do anything after installing `activerecord-creating_foreign_keys`.
26
+
27
+ You can know **Before** and **After** if `articles` is created.
28
+
29
+ ```
30
+ create_table :articles do |t|
31
+ t.references :author, foreign_key: true
32
+ end
33
+ ```
34
+
35
+ **Before**
36
+ ```sql
37
+ CREATE TABLE `articles` (`id` int(11) auto_increment PRIMARY KEY, `author_id` int(11));
38
+ ALTER TABLE `articles` ADD CONSTRAINT `fk_rails_e74ce85cbc` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`);
39
+ ```
40
+
41
+ **After**
42
+ ```sql
43
+ CREATE TABLE `articles` (`id` int(11) auto_increment PRIMARY KEY, `author_id` int(11), CONSTRAINT `fk_rails_e74ce85cbc` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`));
44
+ ```
45
+
46
+ ## Limitation
47
+ At this time, only the `mysql2` adapter support this function.
48
+
49
+ ## Contributing
50
+ Bug reports and pull requests are welcome on GitHub at https://github.com/hamuyuuki/activerecord-creating_foreign_keys. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
51
+
52
+ ## License
53
+ `activerecord-creating_foreign_keys` is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ begin
4
+ require "bundler/setup"
5
+ rescue LoadError
6
+ puts "You must `gem install bundler` and `bundle install` to run rake tasks"
7
+ end
8
+
9
+ require "rdoc/task"
10
+
11
+ RDoc::Task.new(:rdoc) do |rdoc|
12
+ rdoc.rdoc_dir = "rdoc"
13
+ rdoc.title = "ActiveRecord::CreatingForeignKeys"
14
+ rdoc.options << "--line-numbers"
15
+ rdoc.rdoc_files.include("README.md")
16
+ rdoc.rdoc_files.include("lib/**/*.rb")
17
+ end
18
+
19
+
20
+
21
+
22
+
23
+
24
+ Bundler::GemHelper.install_tasks
25
+
26
+ require "rake/testtask"
27
+
28
+ Rake::TestTask.new(:test) do |t|
29
+ t.libs << "lib"
30
+ t.libs << "test"
31
+ t.pattern = "test/**/*_test.rb"
32
+ t.verbose = false
33
+ end
34
+
35
+
36
+ task default: :test
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/lazy_load_hooks"
4
+
5
+ ActiveSupport.on_load(:active_record) do
6
+ require "active_record/creating_foreign_keys/schema_creation"
7
+ require "active_record/creating_foreign_keys/schema_statements"
8
+ # TODO: Should research the not `require` way
9
+ require "active_record/connection_adapters/abstract_mysql_adapter"
10
+
11
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::SchemaCreation.prepend(ActiveRecord::CreatingForeignKeys::SchemaCreation)
12
+ ActiveRecord::ConnectionAdapters::AbstractAdapter.prepend(ActiveRecord::CreatingForeignKeys::SchemaStatements)
13
+ end
@@ -0,0 +1,36 @@
1
+
2
+ module ActiveRecord
3
+ module CreatingForeignKeys
4
+ module SchemaCreation
5
+ def visit_TableDefinition(o)
6
+ name = o.name
7
+ create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE #{quote_table_name(name)} "
8
+
9
+ statements = o.columns.map { |c| accept c }
10
+ statements.concat(o.indexes.map { |column_name, options| index_in_create(name, column_name, options) })
11
+ statements.concat(o.foreign_keys.map { |to_table, options| foreign_key_in_create(o.name, to_table, options) })
12
+
13
+ create_sql << "(#{statements.join(', ')}) " if statements.present?
14
+ create_sql << "#{o.options}"
15
+ create_sql << " AS #{@conn.to_sql(o.as)}" if o.as
16
+ create_sql
17
+ end
18
+
19
+ def visit_ForeignKeyDefinition(o)
20
+ sql = <<-SQL.strip_heredoc
21
+ CONSTRAINT #{quote_column_name(o.name)}
22
+ FOREIGN KEY (#{quote_column_name(o.column)})
23
+ REFERENCES #{quote_table_name(o.to_table)} (#{quote_column_name(o.primary_key)})
24
+ SQL
25
+ sql << " #{action_sql('DELETE', o.on_delete)}" if o.on_delete
26
+ sql << " #{action_sql('UPDATE', o.on_update)}" if o.on_update
27
+ sql
28
+ end
29
+
30
+ def foreign_key_in_create(from_table, to_table, options)
31
+ options = @conn.foreign_key_options(from_table, to_table, options)
32
+ accept ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(from_table, to_table, options)
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,41 @@
1
+
2
+ module ActiveRecord
3
+ module CreatingForeignKeys
4
+ module SchemaStatements
5
+ def create_table(table_name, options = {})
6
+ td = create_table_definition table_name, options[:temporary], options[:options], options[:as]
7
+
8
+ if options[:id] != false && !options[:as]
9
+ pk = options.fetch(:primary_key) do
10
+ Base.get_primary_key table_name.to_s.singularize
11
+ end
12
+
13
+ td.primary_key pk, options.fetch(:id, :primary_key), options
14
+ end
15
+
16
+ yield td if block_given?
17
+
18
+ if options[:force] && table_exists?(table_name)
19
+ drop_table(table_name, options)
20
+ end
21
+
22
+ result = execute schema_creation.accept td
23
+
24
+ unless supports_indexes_in_create?
25
+ td.indexes.each_pair do |column_name, index_options|
26
+ add_index(table_name, column_name, index_options)
27
+ end
28
+ end
29
+
30
+ result
31
+ end
32
+
33
+ def foreign_key_options(from_table, to_table, options) # :nodoc:
34
+ options = options.dup
35
+ options[:column] ||= foreign_key_column_for(to_table)
36
+ options[:name] ||= foreign_key_name(from_table, options)
37
+ options
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module CreatingForeignKeys
5
+ VERSION = "0.0.1"
6
+ end
7
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "test_helper"
4
+ require "active_support/test_case"
5
+
6
+ class CreatingForeignKeysTest < ActiveSupport::TestCase
7
+ # ref: https://github.com/rails/rails/blob/4-2-stable/activerecord/test/cases/test_case.rb#L82L120
8
+ class SQLCounter
9
+ class << self
10
+ attr_accessor :ignored_sql, :log, :log_all
11
+ def clear_log; self.log = []; self.log_all = []; end
12
+ end
13
+
14
+ self.clear_log
15
+
16
+ self.ignored_sql = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/, /^BEGIN/, /^COMMIT/]
17
+
18
+ # FIXME: this needs to be refactored so specific database can add their own
19
+ # ignored SQL, or better yet, use a different notification for the queries
20
+ # instead examining the SQL content.
21
+ oracle_ignored = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im, /^\s*select .* from all_constraints/im, /^\s*select .* from all_tab_cols/im]
22
+ mysql_ignored = [/^SHOW TABLES/i, /^SHOW FULL FIELDS/, /^SHOW CREATE TABLE /i, /^SHOW VARIABLES /, /^\s*SELECT column_name\b.*\bFROM information_schema\.key_column_usage\b/im]
23
+ postgresql_ignored = [/^\s*select\b.*\bfrom\b.*pg_namespace\b/im, /^\s*select tablename\b.*from pg_tables\b/im, /^\s*select\b.*\battname\b.*\bfrom\b.*\bpg_attribute\b/im, /^SHOW search_path/i]
24
+ sqlite3_ignored = [/^\s*SELECT name\b.*\bFROM sqlite_master/im, /^\s*SELECT sql\b.*\bFROM sqlite_master/im]
25
+
26
+ [oracle_ignored, mysql_ignored, postgresql_ignored, sqlite3_ignored].each do |db_ignored_sql|
27
+ ignored_sql.concat db_ignored_sql
28
+ end
29
+
30
+ attr_reader :ignore
31
+
32
+ def initialize(ignore = Regexp.union(self.class.ignored_sql))
33
+ @ignore = ignore
34
+ end
35
+
36
+ def call(name, start, finish, message_id, values)
37
+ sql = values[:sql]
38
+
39
+ # FIXME: this seems bad. we should probably have a better way to indicate
40
+ # the query was cached
41
+ return if 'CACHE' == values[:name]
42
+
43
+ self.class.log_all << sql
44
+ self.class.log << sql unless ignore =~ sql
45
+ end
46
+ end
47
+
48
+ # ref: https://github.com/rails/rails/blob/4-2-stable/activerecord/test/cases/test_case.rb#L122
49
+ ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new)
50
+
51
+ # ref: https://github.com/rails/rails/blob/4-2-stable/activerecord/test/cases/test_case.rb#L49L61
52
+ def assert_queries(num = 1, options = {})
53
+ ignore_none = options.fetch(:ignore_none) { num == :any }
54
+ SQLCounter.clear_log
55
+ x = yield
56
+ the_log = ignore_none ? SQLCounter.log_all : SQLCounter.log
57
+ if num == :any
58
+ assert_operator the_log.size, :>=, 1, "1 or more queries expected, but none were executed."
59
+ else
60
+ mesg = "#{the_log.size} instead of #{num} queries were executed.#{the_log.size == 0 ? '' : "\nQueries:\n#{the_log.join("\n")}"}"
61
+ assert_equal num, the_log.size, mesg
62
+ end
63
+ x
64
+ end
65
+
66
+ # ref: https://github.com/rails/rails/blob/4-2-stable/activerecord/test/cases/migration/references_foreign_key_test.rb#L12L15
67
+ # https://github.com/rails/rails/blob/4-2-stable/activerecord/test/cases/test_case.rb#L8L10
68
+ teardown do
69
+ @connection.drop_table "testings", if_exists: true
70
+ @connection.drop_table "testing_parents", if_exists: true
71
+ SQLCounter.clear_log
72
+ end
73
+
74
+ # ref: https://github.com/rails/rails/blob/4-2-stable/activerecord/test/cases/migration/references_foreign_key_test.rb#L7L10
75
+ # https://github.com/rails/rails/pull/20009/files#diff-753b84de930c3ef1f329af181b7fd7b21957e5c022765ca81748cda3002eb58dR35-R42
76
+ test "foreign keys can be created in one query with MySQL" do
77
+ ActiveRecord::Base.establish_connection :mysql
78
+ @connection = ActiveRecord::Base.connection
79
+ @connection.create_table(:testing_parents, force: true)
80
+
81
+ assert_queries(1) do
82
+ @connection.create_table :testings do |t|
83
+ t.references :testing_parent, foreign_key: true
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,28 @@
1
+ == README
2
+
3
+ This README would normally document whatever steps are necessary to get the
4
+ application up and running.
5
+
6
+ Things you may want to cover:
7
+
8
+ * Ruby version
9
+
10
+ * System dependencies
11
+
12
+ * Configuration
13
+
14
+ * Database creation
15
+
16
+ * Database initialization
17
+
18
+ * How to run the test suite
19
+
20
+ * Services (job queues, cache servers, search engines, etc.)
21
+
22
+ * Deployment instructions
23
+
24
+ * ...
25
+
26
+
27
+ Please feel free to use a different markup language if you do not plan to run
28
+ <tt>rake doc:app</tt>.
@@ -0,0 +1,6 @@
1
+ # Add your own tasks in files placed in lib/tasks ending in .rake,
2
+ # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3
+
4
+ require File.expand_path('../config/application', __FILE__)
5
+
6
+ Rails.application.load_tasks
@@ -0,0 +1,13 @@
1
+ // This is a manifest file that'll be compiled into application.js, which will include all the files
2
+ // listed below.
3
+ //
4
+ // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5
+ // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6
+ //
7
+ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8
+ // compiled file.
9
+ //
10
+ // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
11
+ // about supported directives.
12
+ //
13
+ //= require_tree .
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any styles
10
+ * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
11
+ * file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,5 @@
1
+ class ApplicationController < ActionController::Base
2
+ # Prevent CSRF attacks by raising an exception.
3
+ # For APIs, you may want to use :null_session instead.
4
+ protect_from_forgery with: :exception
5
+ end
@@ -0,0 +1,2 @@
1
+ module ApplicationHelper
2
+ end
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Dummy</title>
5
+ <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6
+ <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7
+ <%= csrf_meta_tags %>
8
+ </head>
9
+ <body>
10
+
11
+ <%= yield %>
12
+
13
+ </body>
14
+ </html>
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3
+ load Gem.bin_path('bundler', 'bundle')
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
3
+ require_relative '../config/boot'
4
+ require 'rails/commands'
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require_relative '../config/boot'
3
+ require 'rake'
4
+ Rake.application.run
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+ require 'pathname'
3
+
4
+ # path to your application root.
5
+ APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
6
+
7
+ Dir.chdir APP_ROOT do
8
+ # This script is a starting point to setup your application.
9
+ # Add necessary setup steps to this file:
10
+
11
+ puts "== Installing dependencies =="
12
+ system "gem install bundler --conservative"
13
+ system "bundle check || bundle install"
14
+
15
+ # puts "\n== Copying sample files =="
16
+ # unless File.exist?("config/database.yml")
17
+ # system "cp config/database.yml.sample config/database.yml"
18
+ # end
19
+
20
+ puts "\n== Preparing database =="
21
+ system "bin/rake db:setup"
22
+
23
+ puts "\n== Removing old logs and tempfiles =="
24
+ system "rm -f log/*"
25
+ system "rm -rf tmp/cache"
26
+
27
+ puts "\n== Restarting application server =="
28
+ system "touch tmp/restart.txt"
29
+ end